]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/irc-login.c
eeecf96d82d88b40af7b4693ec1edbc3056bb6c8
[ngircd-alex.git] / src / ngircd / irc-login.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001-2011 Alexander Barton (alex@barton.de) and Contributors.
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  * Please read the file COPYING, README and AUTHORS for more information.
10  */
11
12 #include "portab.h"
13
14 /**
15  * @file
16  * Login and logout
17  */
18
19 #include "imp.h"
20 #include <assert.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <strings.h>
25 #include <signal.h>
26 #include <unistd.h>
27
28 #include "ngircd.h"
29 #include "conn-func.h"
30 #include "class.h"
31 #include "conf.h"
32 #include "channel.h"
33 #include "io.h"
34 #include "log.h"
35 #include "messages.h"
36 #include "pam.h"
37 #include "parse.h"
38 #include "irc.h"
39 #include "irc-info.h"
40 #include "irc-write.h"
41
42 #include "exp.h"
43 #include "irc-login.h"
44
45
46 static bool Hello_User PARAMS(( CLIENT *Client ));
47 static bool Hello_User_PostAuth PARAMS(( CLIENT *Client ));
48 static void Kill_Nick PARAMS(( char *Nick, char *Reason ));
49 static void Introduce_Client PARAMS((CLIENT *To, CLIENT *Client, int Type));
50 static void Reject_Client PARAMS((CLIENT *Client));
51
52 static void cb_introduceClient PARAMS((CLIENT *Client, CLIENT *Prefix,
53                                        void *i));
54
55 #ifdef PAM
56 static void cb_Read_Auth_Result PARAMS((int r_fd, UNUSED short events));
57 #endif
58
59 /**
60  * Handler for the IRC "PASS" command.
61  *
62  * See RFC 2813 section 4.1.1, and RFC 2812 section 3.1.1.
63  *
64  * @param Client        The client from which this command has been received.
65  * @param Req           Request structure with prefix and all parameters.
66  * @returns             CONNECTED or DISCONNECTED.
67  */
68 GLOBAL bool
69 IRC_PASS( CLIENT *Client, REQUEST *Req )
70 {
71         char *type, *orig_flags;
72         int protohigh, protolow;
73
74         assert( Client != NULL );
75         assert( Req != NULL );
76
77         /* Return an error if this is not a local client */
78         if (Client_Conn(Client) <= NONE)
79                 return IRC_WriteStrClient(Client, ERR_UNKNOWNCOMMAND_MSG,
80                                           Client_ID(Client), Req->command);
81
82         if (Client_Type(Client) == CLIENT_UNKNOWN && Req->argc == 1) {
83                 /* Not yet registered "unknown" connection, PASS with one
84                  * argument: either a regular client, service, or server
85                  * using the old RFC 1459 section 4.1.1 syntax. */
86                 LogDebug("Connection %d: got PASS command (RFC 1459) ...",
87                          Client_Conn(Client));
88         } else if ((Client_Type(Client) == CLIENT_UNKNOWN ||
89                     Client_Type(Client) == CLIENT_UNKNOWNSERVER) &&
90                    (Req->argc == 3 || Req->argc == 4)) {
91                 /* Not yet registered "unknown" connection or outgoing server
92                  * link, PASS with three or four argument: server using the
93                  * RFC 2813 section 4.1.1 syntax. */
94                 LogDebug("Connection %d: got PASS command (RFC 2813, new server link) ...",
95                          Client_Conn(Client));
96         } else if (Client_Type(Client) == CLIENT_UNKNOWN ||
97                    Client_Type(Client) == CLIENT_UNKNOWNSERVER) {
98                 /* Unregistered connection, but wrong number of arguments: */
99                 return IRC_WriteStrClient(Client, ERR_NEEDMOREPARAMS_MSG,
100                                           Client_ID(Client), Req->command);
101         } else {
102                 /* Registered connection, PASS command is not allowed! */
103                 return IRC_WriteStrClient(Client, ERR_ALREADYREGISTRED_MSG,
104                                           Client_ID(Client));
105         }
106
107         Client_SetPassword(Client, Req->argv[0]);
108
109         /* Protocol version */
110         if (Req->argc >= 2 && strlen(Req->argv[1]) >= 4) {
111                 int c2, c4;
112
113                 c2 = Req->argv[1][2];
114                 c4 = Req->argv[1][4];
115
116                 Req->argv[1][4] = '\0';
117                 protolow = atoi(&Req->argv[1][2]);
118                 Req->argv[1][2] = '\0';
119                 protohigh = atoi(Req->argv[1]);
120
121                 Req->argv[1][2] = c2;
122                 Req->argv[1][4] = c4;
123
124                 Client_SetType(Client, CLIENT_GOTPASS_2813);
125         } else {
126                 protohigh = protolow = 0;
127                 Client_SetType(Client, CLIENT_GOTPASS);
128         }
129
130         /* Protocol type, see doc/Protocol.txt */
131         if (Req->argc >= 2 && strlen(Req->argv[1]) > 4)
132                 type = &Req->argv[1][4];
133         else
134                 type = NULL;
135
136         /* Protocol flags/options */
137         if (Req->argc >= 4)
138                 orig_flags = Req->argv[3];
139         else
140                 orig_flags = "";
141
142         /* Implementation, version and IRC+ flags */
143         if (Req->argc >= 3) {
144                 char *impl, *ptr, *serverver, *flags;
145
146                 impl = Req->argv[2];
147                 ptr = strchr(impl, '|');
148                 if (ptr)
149                         *ptr = '\0';
150
151                 if (type && strcmp(type, PROTOIRCPLUS) == 0) {
152                         /* The peer seems to be a server which supports the
153                          * IRC+ protocol (see doc/Protocol.txt). */
154                         serverver = ptr ? ptr + 1 : "?";
155                         flags = strchr(ptr ? serverver : impl, ':');
156                         if (flags) {
157                                 *flags = '\0';
158                                 flags++;
159                         } else
160                                 flags = "";
161                         Log(LOG_INFO,
162                             "Peer on conenction %d announces itself as %s-%s using protocol %d.%d/IRC+ (flags: \"%s\").",
163                             Client_Conn(Client), impl, serverver,
164                             protohigh, protolow, flags);
165                 } else {
166                         /* The peer seems to be a server supporting the
167                          * "original" IRC protocol (RFC 2813). */
168                         if (strchr(orig_flags, 'Z'))
169                                 flags = "Z";
170                         else
171                                 flags = "";
172                         Log(LOG_INFO,
173                             "Peer on connection %d announces itself as \"%s\" using protocol %d.%d (flags: \"%s\").",
174                             Client_Conn(Client), impl,
175                             protohigh, protolow, flags);
176                 }
177                 Client_SetFlags(Client, flags);
178         }
179
180         return CONNECTED;
181 } /* IRC_PASS */
182
183
184 /**
185  * Handler for the IRC "NICK" command.
186  *
187  * See RFC 2812, 3.1.2 "Nick message", and RFC 2813, 4.1.3 "Nick".
188  *
189  * This function implements the IRC command "NICK" which is used to register
190  * with the server, to change already registered nicknames and to introduce
191  * new users which are connected to other servers.
192  *
193  * @param Client        The client from which this command has been received.
194  * @param Req           Request structure with prefix and all parameters.
195  * @returns             CONNECTED or DISCONNECTED.
196  */
197 GLOBAL bool
198 IRC_NICK( CLIENT *Client, REQUEST *Req )
199 {
200         CLIENT *intr_c, *target, *c;
201         char *nick, *user, *hostname, *modes, *info;
202         int token, hops;
203
204         assert( Client != NULL );
205         assert( Req != NULL );
206
207         /* Some IRC clients, for example BitchX, send the NICK and USER
208          * commands in the wrong order ... */
209         if(Client_Type(Client) == CLIENT_UNKNOWN
210             || Client_Type(Client) == CLIENT_GOTPASS
211             || Client_Type(Client) == CLIENT_GOTNICK
212 #ifndef STRICT_RFC
213             || Client_Type(Client) == CLIENT_GOTUSER
214 #endif
215             || Client_Type(Client) == CLIENT_USER
216             || Client_Type(Client) == CLIENT_SERVICE
217             || (Client_Type(Client) == CLIENT_SERVER && Req->argc == 1))
218         {
219                 /* User registration or change of nickname */
220
221                 /* Wrong number of arguments? */
222                 if( Req->argc != 1 )
223                         return IRC_WriteStrClient( Client, ERR_NEEDMOREPARAMS_MSG,
224                                                    Client_ID( Client ),
225                                                    Req->command );
226
227                 /* Search "target" client */
228                 if( Client_Type( Client ) == CLIENT_SERVER )
229                 {
230                         target = Client_Search( Req->prefix );
231                         if( ! target )
232                                 return IRC_WriteStrClient( Client,
233                                                            ERR_NOSUCHNICK_MSG,
234                                                            Client_ID( Client ),
235                                                            Req->argv[0] );
236                 }
237                 else
238                 {
239                         /* Is this a restricted client? */
240                         if( Client_HasMode( Client, 'r' ))
241                                 return IRC_WriteStrClient( Client,
242                                                            ERR_RESTRICTED_MSG,
243                                                            Client_ID( Client ));
244
245                         target = Client;
246                 }
247
248 #ifndef STRICT_RFC
249                 /* If the clients tries to change to its own nickname we won't
250                  * do anything. This is how the original ircd behaves and some
251                  * clients (for example Snak) expect it to be like this.
252                  * But I doubt that this is "really the right thing" ... */
253                 if( strcmp( Client_ID( target ), Req->argv[0] ) == 0 )
254                         return CONNECTED;
255 #endif
256
257                 /* Check that the new nickname is available. Special case:
258                  * the client only changes from/to upper to lower case. */
259                 if( strcasecmp( Client_ID( target ), Req->argv[0] ) != 0 )
260                 {
261                         if( ! Client_CheckNick( target, Req->argv[0] ))
262                                 return CONNECTED;
263                 }
264
265                 if (Client_Type(target) != CLIENT_USER &&
266                     Client_Type(target) != CLIENT_SERVICE &&
267                     Client_Type(target) != CLIENT_SERVER) {
268                         /* New client */
269                         LogDebug("Connection %d: got valid NICK command ...",
270                              Client_Conn( Client ));
271
272                         /* Register new nickname of this client */
273                         Client_SetID( target, Req->argv[0] );
274
275 #ifndef STRICT_RFC
276                         if (Conf_AuthPing) {
277                                 Conn_SetAuthPing(Client_Conn(Client), rand());
278                                 IRC_WriteStrClient(Client, "PING :%ld",
279                                         Conn_GetAuthPing(Client_Conn(Client)));
280                                 LogDebug("Connection %d: sent AUTH PING %ld ...",
281                                         Client_Conn(Client),
282                                         Conn_GetAuthPing(Client_Conn(Client)));
283                         }
284 #endif
285
286                         /* If we received a valid USER command already then
287                          * register the new client! */
288                         if( Client_Type( Client ) == CLIENT_GOTUSER )
289                                 return Hello_User( Client );
290                         else
291                                 Client_SetType( Client, CLIENT_GOTNICK );
292                 } else {
293                         /* Nickname change */
294                         if (Client_Conn(target) > NONE) {
295                                 /* Local client */
296                                 Log(LOG_INFO,
297                                     "%s \"%s\" changed nick (connection %d): \"%s\" -> \"%s\".",
298                                     Client_TypeText(target), Client_Mask(target),
299                                     Client_Conn(target), Client_ID(target),
300                                     Req->argv[0]);
301                                 Conn_UpdateIdle(Client_Conn(target));
302                         } else {
303                                 /* Remote client */
304                                 LogDebug("%s \"%s\" changed nick: \"%s\" -> \"%s\".",
305                                          Client_TypeText(target),
306                                          Client_Mask(target), Client_ID(target),
307                                          Req->argv[0]);
308                         }
309
310                         /* Inform all users and servers (which have to know)
311                          * of this nickname change */
312                         if( Client_Type( Client ) == CLIENT_USER )
313                                 IRC_WriteStrClientPrefix( Client, Client,
314                                                           "NICK :%s",
315                                                           Req->argv[0] );
316                         IRC_WriteStrServersPrefix( Client, target,
317                                                    "NICK :%s", Req->argv[0] );
318                         IRC_WriteStrRelatedPrefix( target, target, false,
319                                                    "NICK :%s", Req->argv[0] );
320
321                         /* Register old nickname for WHOWAS queries */
322                         Client_RegisterWhowas( target );
323
324                         /* Save new nickname */
325                         Client_SetID( target, Req->argv[0] );
326
327                         IRC_SetPenalty( target, 2 );
328                 }
329
330                 return CONNECTED;
331         } else if(Client_Type(Client) == CLIENT_SERVER ||
332                   Client_Type(Client) == CLIENT_SERVICE) {
333                 /* Server or service introduces new client */
334
335                 /* Bad number of parameters? */
336                 if (Req->argc != 2 && Req->argc != 7)
337                         return IRC_WriteStrClient(Client, ERR_NEEDMOREPARAMS_MSG,
338                                                   Client_ID(Client), Req->command);
339
340                 if (Req->argc >= 7) {
341                         /* RFC 2813 compatible syntax */
342                         nick = Req->argv[0];
343                         hops = atoi(Req->argv[1]);
344                         user = Req->argv[2];
345                         hostname = Req->argv[3];
346                         token = atoi(Req->argv[4]);
347                         modes = Req->argv[5] + 1;
348                         info = Req->argv[6];
349                 } else {
350                         /* RFC 1459 compatible syntax */
351                         nick = Req->argv[0];
352                         hops = 1;
353                         user = Req->argv[0];
354                         hostname = Client_ID(Client);
355                         token = atoi(Req->argv[1]);
356                         modes = "";
357                         info = Req->argv[0];
358                 }
359
360                 c = Client_Search(nick);
361                 if(c) {
362                         /*
363                          * the new nick is already present on this server:
364                          * the new and the old one have to be disconnected now.
365                          */
366                         Log( LOG_ERR, "Server %s introduces already registered nick \"%s\"!", Client_ID( Client ), Req->argv[0] );
367                         Kill_Nick( Req->argv[0], "Nick collision" );
368                         return CONNECTED;
369                 }
370
371                 /* Find the Server this client is connected to */
372                 intr_c = Client_GetFromToken(Client, token);
373                 if( ! intr_c )
374                 {
375                         Log( LOG_ERR, "Server %s introduces nick \"%s\" on unknown server!?", Client_ID( Client ), Req->argv[0] );
376                         Kill_Nick( Req->argv[0], "Unknown server" );
377                         return CONNECTED;
378                 }
379
380                 c = Client_NewRemoteUser(intr_c, nick, hops, user, hostname,
381                                          token, modes, info, true);
382                 if( ! c )
383                 {
384                         /* out of memory, need to disconnect client to keep network state consistent */
385                         Log( LOG_ALERT, "Can't create client structure! (on connection %d)", Client_Conn( Client ));
386                         Kill_Nick( Req->argv[0], "Server error" );
387                         return CONNECTED;
388                 }
389
390                 /* RFC 2813: client is now fully registered, inform all the
391                  * other servers about the new user.
392                  * RFC 1459: announce the new client only after receiving the
393                  * USER command, first we need more information! */
394                 if (Req->argc < 7) {
395                         LogDebug("Client \"%s\" is being registered (RFC 1459) ...",
396                                  Client_Mask(c));
397                         Client_SetType(c, CLIENT_GOTNICK);
398                 } else
399                         Introduce_Client(Client, c, CLIENT_USER);
400
401                 return CONNECTED;
402         }
403         else return IRC_WriteStrClient( Client, ERR_ALREADYREGISTRED_MSG, Client_ID( Client ));
404 } /* IRC_NICK */
405
406
407 /**
408  * Handler for the IRC "USER" command.
409  *
410  * See RFC 2812, 3.1.3 "User message".
411  *
412  * @param Client        The client from which this command has been received.
413  * @param Req           Request structure with prefix and all parameters.
414  * @returns             CONNECTED or DISCONNECTED.
415  */
416 GLOBAL bool
417 IRC_USER(CLIENT * Client, REQUEST * Req)
418 {
419         CLIENT *c;
420 #ifdef IDENTAUTH
421         char *ptr;
422 #endif
423
424         assert(Client != NULL);
425         assert(Req != NULL);
426
427         if (Client_Type(Client) == CLIENT_GOTNICK ||
428 #ifndef STRICT_RFC
429             Client_Type(Client) == CLIENT_UNKNOWN ||
430 #endif
431             Client_Type(Client) == CLIENT_GOTPASS)
432         {
433                 /* New connection */
434                 if (Req->argc != 4)
435                         return IRC_WriteStrClient(Client,
436                                                   ERR_NEEDMOREPARAMS_MSG,
437                                                   Client_ID(Client),
438                                                   Req->command);
439
440                 /* User name */
441 #ifdef IDENTAUTH
442                 ptr = Client_User(Client);
443                 if (!ptr || !*ptr || *ptr == '~')
444                         Client_SetUser(Client, Req->argv[0], false);
445 #else
446                 Client_SetUser(Client, Req->argv[0], false);
447 #endif
448                 Client_SetOrigUser(Client, Req->argv[0]);
449
450                 /* "Real name" or user info text: Don't set it to the empty
451                  * string, the original ircd can't deal with such "real names"
452                  * (e. g. "USER user * * :") ... */
453                 if (*Req->argv[3])
454                         Client_SetInfo(Client, Req->argv[3]);
455                 else
456                         Client_SetInfo(Client, "-");
457
458                 LogDebug("Connection %d: got valid USER command ...",
459                     Client_Conn(Client));
460                 if (Client_Type(Client) == CLIENT_GOTNICK)
461                         return Hello_User(Client);
462                 else
463                         Client_SetType(Client, CLIENT_GOTUSER);
464                 return CONNECTED;
465
466         } else if (Client_Type(Client) == CLIENT_SERVER ||
467                    Client_Type(Client) == CLIENT_SERVICE) {
468                 /* Server/service updating an user */
469                 if (Req->argc != 4)
470                         return IRC_WriteStrClient(Client,
471                                                   ERR_NEEDMOREPARAMS_MSG,
472                                                   Client_ID(Client),
473                                                   Req->command);
474                 c = Client_Search(Req->prefix);
475                 if (!c)
476                         return IRC_WriteStrClient(Client, ERR_NOSUCHNICK_MSG,
477                                                   Client_ID(Client),
478                                                   Req->prefix);
479
480                 Client_SetUser(c, Req->argv[0], true);
481                 Client_SetOrigUser(c, Req->argv[0]);
482                 Client_SetHostname(c, Req->argv[1]);
483                 Client_SetInfo(c, Req->argv[3]);
484
485                 LogDebug("Connection %d: got valid USER command for \"%s\".",
486                          Client_Conn(Client), Client_Mask(c));
487
488                 /* RFC 1459 style user registration?
489                  * Introduce client to network: */
490                 if (Client_Type(c) == CLIENT_GOTNICK)
491                         Introduce_Client(Client, c, CLIENT_USER);
492
493                 return CONNECTED;
494         } else if (Client_Type(Client) == CLIENT_USER) {
495                 /* Already registered connection */
496                 return IRC_WriteStrClient(Client, ERR_ALREADYREGISTRED_MSG,
497                                           Client_ID(Client));
498         } else {
499                 /* Unexpected/invalid connection state? */
500                 return IRC_WriteStrClient(Client, ERR_NOTREGISTERED_MSG,
501                                           Client_ID(Client));
502         }
503 } /* IRC_USER */
504
505
506 /**
507  * Handler for the IRC "SERVICE" command.
508  *
509  * This function implements IRC Services registration using the SERVICE command
510  * defined in RFC 2812 3.1.6 and RFC 2813 4.1.4.
511  *
512  * At the moment ngIRCd doesn't support directly linked services, so this
513  * function returns ERR_ERRONEUSNICKNAME when the SERVICE command has not been
514  * received from a peer server.
515  *
516  * @param Client        The client from which this command has been received.
517  * @param Req           Request structure with prefix and all parameters.
518  * @returns             CONNECTED or DISCONNECTED..
519  */
520 GLOBAL bool
521 IRC_SERVICE(CLIENT *Client, REQUEST *Req)
522 {
523         CLIENT *c, *intr_c;
524         char *nick, *user, *host, *info, *modes, *ptr;
525         int token, hops;
526
527         assert(Client != NULL);
528         assert(Req != NULL);
529
530         if (Client_Type(Client) != CLIENT_GOTPASS &&
531             Client_Type(Client) != CLIENT_SERVER)
532                 return IRC_WriteStrClient(Client, ERR_ALREADYREGISTRED_MSG,
533                                           Client_ID(Client));
534
535         if (Req->argc != 6)
536                 return IRC_WriteStrClient(Client, ERR_NEEDMOREPARAMS_MSG,
537                                           Client_ID(Client), Req->command);
538
539         if (Client_Type(Client) != CLIENT_SERVER)
540                 return IRC_WriteStrClient(Client, ERR_ERRONEUSNICKNAME_MSG,
541                                   Client_ID(Client), Req->argv[0]);
542
543         /* Bad number of parameters? */
544         if (Req->argc != 6)
545                 return IRC_WriteStrClient(Client, ERR_NEEDMOREPARAMS_MSG,
546                                           Client_ID(Client), Req->command);
547
548         nick = Req->argv[0];
549         user = NULL; host = NULL;
550         token = atoi(Req->argv[1]);
551         hops = atoi(Req->argv[4]);
552         info = Req->argv[5];
553
554         /* Validate service name ("nick name") */
555         c = Client_Search(nick);
556         if(c) {
557                 /* Nick name collission: disconnect (KILL) both clients! */
558                 Log(LOG_ERR, "Server %s introduces already registered service \"%s\"!",
559                     Client_ID(Client), nick);
560                 Kill_Nick(nick, "Nick collision");
561                 return CONNECTED;
562         }
563
564         /* Get the server to which the service is connected */
565         intr_c = Client_GetFromToken(Client, token);
566         if (! intr_c) {
567                 Log(LOG_ERR, "Server %s introduces service \"%s\" on unknown server!?",
568                     Client_ID(Client), nick);
569                 Kill_Nick(nick, "Unknown server");
570                 return CONNECTED;
571         }
572
573         /* Get user and host name */
574         ptr = strchr(nick, '@');
575         if (ptr) {
576                 *ptr = '\0';
577                 host = ++ptr;
578         }
579         if (!host)
580                 host = Client_Hostname(intr_c);
581         ptr = strchr(nick, '!');
582         if (ptr) {
583                 *ptr = '\0';
584                 user = ++ptr;
585         }
586         if (!user)
587                 user = nick;
588
589         /* According to RFC 2812/2813 parameter 4 <type> "is currently reserved
590          * for future usage"; but we use it to transfer the modes and check
591          * that the first character is a '+' sign and ignore it otherwise. */
592         modes = (Req->argv[3][0] == '+') ? ++Req->argv[3] : "";
593
594         c = Client_NewRemoteUser(intr_c, nick, hops, user, host,
595                                  token, modes, info, true);
596         if (! c) {
597                 /* Couldn't create client structure, so KILL the service to
598                  * keep network status consistent ... */
599                 Log(LOG_ALERT, "Can't create client structure! (on connection %d)",
600                     Client_Conn(Client));
601                 Kill_Nick(nick, "Server error");
602                 return CONNECTED;
603         }
604
605         Introduce_Client(Client, c, CLIENT_SERVICE);
606         return CONNECTED;
607 } /* IRC_SERVICE */
608
609
610 /**
611  * Handler for the IRC "WEBIRC" command.
612  *
613  * See doc/Protocol.txt, section II.4:
614  * "Update webchat/proxy client information".
615  *
616  * @param Client        The client from which this command has been received.
617  * @param Req           Request structure with prefix and all parameters.
618  * @returns             CONNECTED or DISCONNECTED.
619  */
620 GLOBAL bool
621 IRC_WEBIRC(CLIENT *Client, REQUEST *Req)
622 {
623         /* Exactly 4 parameters are requited */
624         if (Req->argc != 4)
625                 return IRC_WriteStrClient(Client, ERR_NEEDMOREPARAMS_MSG,
626                                           Client_ID(Client), Req->command);
627
628         if (!Conf_WebircPwd[0] || strcmp(Req->argv[0], Conf_WebircPwd) != 0)
629                 return IRC_WriteStrClient(Client, ERR_PASSWDMISMATCH_MSG,
630                                           Client_ID(Client));
631
632         LogDebug("Connection %d: got valid WEBIRC command: user=%s, host=%s, ip=%s",
633                  Client_Conn(Client), Req->argv[1], Req->argv[2], Req->argv[3]);
634
635         Client_SetUser(Client, Req->argv[1], true);
636         Client_SetOrigUser(Client, Req->argv[1]);
637         Client_SetHostname(Client, Req->argv[2]);
638         return CONNECTED;
639 } /* IRC_WEBIRC */
640
641
642 /**
643  * Handler for the IRC "QUIT" command.
644  *
645  * See RFC 2812, 3.1.7 "Quit", and RFC 2813, 4.1.5 "Quit".
646  *
647  * @param Client        The client from which this command has been received.
648  * @param Req           Request structure with prefix and all parameters.
649  * @returns             CONNECTED or DISCONNECTED.
650  */
651 GLOBAL bool
652 IRC_QUIT( CLIENT *Client, REQUEST *Req )
653 {
654         CLIENT *target;
655         char quitmsg[LINE_LEN];
656
657         assert(Client != NULL);
658         assert(Req != NULL);
659
660         /* Wrong number of arguments? */
661         if (Req->argc > 1)
662                 return IRC_WriteStrClient(Client, ERR_NEEDMOREPARAMS_MSG,
663                                           Client_ID(Client), Req->command);
664
665         if (Req->argc == 1)
666                 strlcpy(quitmsg, Req->argv[0], sizeof quitmsg);
667
668         if (Client_Type(Client) == CLIENT_SERVER) {
669                 /* Server */
670                 target = Client_Search(Req->prefix);
671                 if (!target) {
672                         Log(LOG_WARNING,
673                             "Got QUIT from %s for unknown client!?",
674                             Client_ID(Client));
675                         return CONNECTED;
676                 }
677
678                 if (target != Client) {
679                         Client_Destroy(target, "Got QUIT command.",
680                                        Req->argc == 1 ? quitmsg : NULL, true);
681                         return CONNECTED;
682                 } else {
683                         Conn_Close(Client_Conn(Client), "Got QUIT command.",
684                                    Req->argc == 1 ? quitmsg : NULL, true);
685                         return DISCONNECTED;
686                 }
687         } else {
688                 if (Req->argc == 1 && quitmsg[0] != '\"') {
689                         /* " " to avoid confusion */
690                         strlcpy(quitmsg, "\"", sizeof quitmsg);
691                         strlcat(quitmsg, Req->argv[0], sizeof quitmsg-1);
692                         strlcat(quitmsg, "\"", sizeof quitmsg );
693                 }
694
695                 /* User, Service, or not yet registered */
696                 Conn_Close(Client_Conn(Client), "Got QUIT command.",
697                            Req->argc == 1 ? quitmsg : NULL, true);
698
699                 return DISCONNECTED;
700         }
701 } /* IRC_QUIT */
702
703
704 #ifndef STRICT_RFC
705
706 /**
707  * Handler for HTTP command, e.g. GET and POST
708  *
709  * We handle these commands here to avoid the quite long timeout when
710  * some user tries to access this IRC daemon using an web browser ...
711  *
712  * @param Client        The client from which this command has been received.
713  * @param Req           Request structure with prefix and all parameters.
714  * @returns             CONNECTED or DISCONNECTED.
715  */
716 GLOBAL bool
717 IRC_QUIT_HTTP( CLIENT *Client, REQUEST *Req )
718 {
719         Req->argc = 1;
720         Req->argv[0] = "Oops, HTTP request received? This is IRC!";
721         return IRC_QUIT(Client, Req);
722 } /* IRC_QUIT_HTTP */
723
724 #endif
725
726
727 /**
728  * Handler for the IRC "PING" command.
729  *
730  * See RFC 2812, 3.7.2 "Ping message".
731  *
732  * @param Client        The client from which this command has been received.
733  * @param Req           Request structure with prefix and all parameters.
734  * @returns             CONNECTED or DISCONNECTED.
735  */
736 GLOBAL bool
737 IRC_PING(CLIENT *Client, REQUEST *Req)
738 {
739         CLIENT *target, *from;
740
741         assert(Client != NULL);
742         assert(Req != NULL);
743
744         if (Req->argc < 1)
745                 return IRC_WriteStrClient(Client, ERR_NOORIGIN_MSG,
746                                           Client_ID(Client));
747 #ifdef STRICT_RFC
748         /* Don't ignore additional arguments when in "strict" mode */
749         if (Req->argc > 2)
750                  return IRC_WriteStrClient(Client, ERR_NEEDMOREPARAMS_MSG,
751                                            Client_ID(Client), Req->command);
752 #endif
753
754         if (Req->argc > 1) {
755                 /* A target has been specified ... */
756                 target = Client_Search(Req->argv[1]);
757
758                 if (!target || Client_Type(target) != CLIENT_SERVER)
759                         return IRC_WriteStrClient(Client, ERR_NOSUCHSERVER_MSG,
760                                         Client_ID(Client), Req->argv[1]);
761
762                 if (target != Client_ThisServer()) {
763                         /* Ok, we have to forward the PING */
764                         if (Client_Type(Client) == CLIENT_SERVER)
765                                 from = Client_Search(Req->prefix);
766                         else
767                                 from = Client;
768                         if (!from)
769                                 return IRC_WriteStrClient(Client,
770                                                 ERR_NOSUCHSERVER_MSG,
771                                                 Client_ID(Client), Req->prefix);
772
773                         return IRC_WriteStrClientPrefix(target, from,
774                                         "PING %s :%s", Req->argv[0],
775                                         Req->argv[1] );
776                 }
777         }
778
779         if (Client_Type(Client) == CLIENT_SERVER) {
780                 if (Req->prefix)
781                         from = Client_Search(Req->prefix);
782                 else
783                         from = Client;
784         } else
785                 from = Client_ThisServer();
786         if (!from)
787                 return IRC_WriteStrClient(Client, ERR_NOSUCHSERVER_MSG,
788                                         Client_ID(Client), Req->prefix);
789
790         Log(LOG_DEBUG, "Connection %d: got PING, sending PONG ...",
791             Client_Conn(Client));
792
793 #ifdef STRICT_RFC
794         return IRC_WriteStrClient(Client, "PONG %s :%s",
795                 Client_ID(from), Client_ID(Client));
796 #else
797         /* Some clients depend on the argument being returned in the PONG
798          * reply (not mentioned in any RFC, though) */
799         return IRC_WriteStrClient(Client, "PONG %s :%s",
800                 Client_ID(from), Req->argv[0]);
801 #endif
802 } /* IRC_PING */
803
804
805 /**
806  * Handler for the IRC "PONG" command.
807  *
808  * See RFC 2812, 3.7.3 "Pong message".
809  *
810  * @param Client        The client from which this command has been received.
811  * @param Req           Request structure with prefix and all parameters.
812  * @returns             CONNECTED or DISCONNECTED.
813  */
814 GLOBAL bool
815 IRC_PONG(CLIENT *Client, REQUEST *Req)
816 {
817         CLIENT *target, *from;
818         CONN_ID conn;
819 #ifndef STRICT_RFC
820         long auth_ping;
821 #endif
822         char *s;
823
824         assert(Client != NULL);
825         assert(Req != NULL);
826
827         /* Wrong number of arguments? */
828         if (Req->argc < 1) {
829                 if (Client_Type(Client) == CLIENT_USER)
830                         return IRC_WriteStrClient(Client, ERR_NOORIGIN_MSG,
831                                                   Client_ID(Client));
832                 else
833                         return CONNECTED;
834         }
835         if (Req->argc > 2) {
836                 if (Client_Type(Client) == CLIENT_USER)
837                         return IRC_WriteStrClient(Client,
838                                                   ERR_NEEDMOREPARAMS_MSG,
839                                                   Client_ID(Client),
840                                                   Req->command);
841                 else
842                         return CONNECTED;
843         }
844
845         /* Forward? */
846         if (Req->argc == 2 && Client_Type(Client) == CLIENT_SERVER) {
847                 target = Client_Search(Req->argv[0]);
848                 if (!target)
849                         return IRC_WriteStrClient(Client, ERR_NOSUCHSERVER_MSG,
850                                         Client_ID(Client), Req->argv[0]);
851
852                 from = Client_Search(Req->prefix);
853
854                 if (target != Client_ThisServer() && target != from) {
855                         /* Ok, we have to forward the message. */
856                         if (!from)
857                                 return IRC_WriteStrClient(Client,
858                                                 ERR_NOSUCHSERVER_MSG,
859                                                 Client_ID(Client), Req->prefix);
860
861                         if (Client_Type(Client_NextHop(target)) != CLIENT_SERVER)
862                                 s = Client_ID(from);
863                         else
864                                 s = Req->argv[0];
865                         return IRC_WriteStrClientPrefix(target, from,
866                                  "PONG %s :%s", s, Req->argv[1]);
867                 }
868         }
869
870         /* The connection timestamp has already been updated when the data has
871          * been read from so socket, so we don't need to update it here. */
872
873         conn = Client_Conn(Client);
874
875 #ifndef STRICT_RFC
876         /* Check authentication PING-PONG ... */
877         auth_ping = Conn_GetAuthPing(conn);
878         if (auth_ping) {
879                 LogDebug("AUTH PONG: waiting for token \"%ld\", got \"%s\" ...",
880                          auth_ping, Req->argv[0]);
881                 if (auth_ping == atoi(Req->argv[0])) {
882                         Conn_SetAuthPing(conn, 0);
883                         if (Client_Type(Client) == CLIENT_WAITAUTHPING)
884                                 Hello_User(Client);
885                 } else
886                         if (!IRC_WriteStrClient(Client,
887                                         "To connect, type /QUOTE PONG %ld",
888                                         auth_ping))
889                                 return DISCONNECTED;
890         }
891 #endif
892
893 #ifdef DEBUG
894         if (conn > NONE)
895                 Log(LOG_DEBUG,
896                         "Connection %d: received PONG. Lag: %ld seconds.", conn,
897                         time(NULL) - Conn_LastPing(Client_Conn(Client)));
898         else
899                  Log(LOG_DEBUG,
900                         "Connection %d: received PONG.", conn);
901 #endif
902         return CONNECTED;
903 } /* IRC_PONG */
904
905
906 /**
907  * Initiate client registration.
908  *
909  * This function is called after the daemon received the required NICK and
910  * USER commands of a new client. If the daemon is compiled with support for
911  * PAM, the authentication sub-processs is forked; otherwise the global server
912  * password is checked.
913  *
914  * @param Client        The client logging in.
915  * @returns             CONNECTED or DISCONNECTED.
916  */
917 static bool
918 Hello_User(CLIENT * Client)
919 {
920 #ifdef PAM
921         int pipefd[2], result;
922         pid_t pid;
923 #endif
924         CONN_ID conn;
925
926         assert(Client != NULL);
927         conn = Client_Conn(Client);
928
929 #ifndef STRICT_RFC
930         if (Conf_AuthPing) {
931                 /* Did we receive the "auth PONG" already? */
932                 if (Conn_GetAuthPing(conn)) {
933                         Client_SetType(Client, CLIENT_WAITAUTHPING);
934                         LogDebug("Connection %d: Waiting for AUTH PONG ...", conn);
935                         return CONNECTED;
936                 }
937         }
938 #endif
939
940         if (Class_IsMember(CLASS_GLINE, Client) ||
941             Class_IsMember(CLASS_KLINE, Client)) {
942                 Reject_Client(Client);
943                 return DISCONNECTED;
944         }
945
946 #ifdef PAM
947         if (!Conf_PAM) {
948                 /* Don't do any PAM authentication at all, instead emulate
949                  * the beahiour of the daemon compiled without PAM support:
950                  * because there can't be any "server password", all
951                  * passwords supplied are classified as "wrong". */
952                 if(Client_Password(Client)[0] == '\0')
953                         return Hello_User_PostAuth(Client);
954                 Reject_Client(Client);
955                 return DISCONNECTED;
956         }
957
958         /* Fork child process for PAM authentication; and make sure that the
959          * process timeout is set higher than the login timeout! */
960         pid = Proc_Fork(Conn_GetProcStat(conn), pipefd,
961                         cb_Read_Auth_Result, Conf_PongTimeout + 1);
962         if (pid > 0) {
963                 LogDebug("Authenticator for connection %d created (PID %d).",
964                          conn, pid);
965                 return CONNECTED;
966         } else {
967                 /* Sub process */
968                 Log_Init_Subprocess("Auth");
969                 Conn_CloseAllSockets(NONE);
970                 result = PAM_Authenticate(Client);
971                 if (write(pipefd[1], &result, sizeof(result)) != sizeof(result))
972                         Log_Subprocess(LOG_ERR,
973                                        "Failed to pipe result to parent!");
974                 Log_Exit_Subprocess("Auth");
975                 exit(0);
976         }
977 #else
978         /* Check global server password ... */
979         if (strcmp(Client_Password(Client), Conf_ServerPwd) != 0) {
980                 /* Bad password! */
981                 Reject_Client(Client);
982                 return DISCONNECTED;
983         }
984         return Hello_User_PostAuth(Client);
985 #endif
986 }
987
988
989 #ifdef PAM
990
991 /**
992  * Read result of the authenticatior sub-process from pipe
993  *
994  * @param r_fd          File descriptor of the pipe.
995  * @param events        (ignored IO specification)
996  */
997 static void
998 cb_Read_Auth_Result(int r_fd, UNUSED short events)
999 {
1000         CONN_ID conn;
1001         CLIENT *client;
1002         int result;
1003         size_t len;
1004         PROC_STAT *proc;
1005
1006         LogDebug("Auth: Got callback on fd %d, events %d", r_fd, events);
1007         conn = Conn_GetFromProc(r_fd);
1008         if (conn == NONE) {
1009                 /* Ops, none found? Probably the connection has already
1010                  * been closed!? We'll ignore that ... */
1011                 io_close(r_fd);
1012                 LogDebug("Auth: Got callback for unknown connection!?");
1013                 return;
1014         }
1015         proc = Conn_GetProcStat(conn);
1016         client = Conn_GetClient(conn);
1017
1018         /* Read result from pipe */
1019         len = Proc_Read(proc, &result, sizeof(result));
1020         Proc_Close(proc);
1021         if (len == 0)
1022                 return;
1023
1024         if (len != sizeof(result)) {
1025                 Log(LOG_CRIT, "Auth: Got malformed result!");
1026                 Reject_Client(client);
1027                 return;
1028         }
1029
1030         if (result == true) {
1031                 Client_SetUser(client, Client_OrigUser(client), true);
1032                 (void)Hello_User_PostAuth(client);
1033         } else
1034                 Reject_Client(client);
1035 }
1036
1037 #endif
1038
1039
1040 /**
1041  * Reject a client because of wrong password.
1042  *
1043  * This function is called either when the global server password or a password
1044  * checked using PAM has been wrong.
1045  *
1046  * @param Client        The client to reject.
1047  */
1048 static void
1049 Reject_Client(CLIENT *Client)
1050 {
1051         Log(LOG_ERR,
1052             "User \"%s\" rejected (connection %d): Access denied!",
1053             Client_Mask(Client), Client_Conn(Client));
1054         Conn_Close(Client_Conn(Client), NULL,
1055                    "Access denied! Bad password?", true);
1056 }
1057
1058
1059 /**
1060  * Finish client registration.
1061  *
1062  * Introduce the new client to the network and send all "hello messages"
1063  * to it after authentication has been succeeded.
1064  *
1065  * @param Client        The client logging in.
1066  * @returns             CONNECTED or DISCONNECTED.
1067  */
1068 static bool
1069 Hello_User_PostAuth(CLIENT *Client)
1070 {
1071         Introduce_Client(NULL, Client, CLIENT_USER);
1072
1073         if (!IRC_WriteStrClient
1074             (Client, RPL_WELCOME_MSG, Client_ID(Client), Client_Mask(Client)))
1075                 return false;
1076         if (!IRC_WriteStrClient
1077             (Client, RPL_YOURHOST_MSG, Client_ID(Client),
1078              Client_ID(Client_ThisServer()), PACKAGE_VERSION, TARGET_CPU,
1079              TARGET_VENDOR, TARGET_OS))
1080                 return false;
1081         if (!IRC_WriteStrClient
1082             (Client, RPL_CREATED_MSG, Client_ID(Client), NGIRCd_StartStr))
1083                 return false;
1084         if (!IRC_WriteStrClient
1085             (Client, RPL_MYINFO_MSG, Client_ID(Client),
1086              Client_ID(Client_ThisServer()), PACKAGE_VERSION, USERMODES,
1087              CHANMODES))
1088                 return false;
1089
1090         /* Features supported by this server (005 numeric, ISUPPORT),
1091          * see <http://www.irc.org/tech_docs/005.html> for details. */
1092         if (!IRC_Send_ISUPPORT(Client))
1093                 return DISCONNECTED;
1094
1095         if (!IRC_Send_LUSERS(Client))
1096                 return DISCONNECTED;
1097         if (!IRC_Show_MOTD(Client))
1098                 return DISCONNECTED;
1099
1100         /* Suspend the client for a second ... */
1101         IRC_SetPenalty(Client, 1);
1102
1103         return CONNECTED;
1104 }
1105
1106
1107 /**
1108  * Kill all users with a specific nick name in the network.
1109  *
1110  * @param Nick          Nick name.
1111  * @param Reason        Reason for the KILL.
1112  */
1113 static void
1114 Kill_Nick(char *Nick, char *Reason)
1115 {
1116         REQUEST r;
1117
1118         assert (Nick != NULL);
1119         assert (Reason != NULL);
1120
1121         r.prefix = NULL;
1122         r.argv[0] = Nick;
1123         r.argv[1] = Reason;
1124         r.argc = 2;
1125
1126         Log(LOG_ERR, "User(s) with nick \"%s\" will be disconnected: %s",
1127             Nick, Reason);
1128
1129         IRC_KILL(Client_ThisServer(), &r);
1130 } /* Kill_Nick */
1131
1132
1133 /**
1134  * Introduce a new user or service client in the network.
1135  *
1136  * @param From          Remote server introducing the client or NULL (local).
1137  * @param Client        New client.
1138  * @param Type          Type of the client (CLIENT_USER or CLIENT_SERVICE).
1139  */
1140 static void
1141 Introduce_Client(CLIENT *From, CLIENT *Client, int Type)
1142 {
1143         /* Set client type (user or service) */
1144         Client_SetType(Client, Type);
1145
1146         if (From) {
1147                 if (Conf_IsService(Conf_GetServer(Client_Conn(From)),
1148                                    Client_ID(Client)))
1149                         Client_SetType(Client, CLIENT_SERVICE);
1150                 LogDebug("%s \"%s\" (+%s) registered (via %s, on %s, %d hop%s).",
1151                          Client_TypeText(Client), Client_Mask(Client),
1152                          Client_Modes(Client), Client_ID(From),
1153                          Client_ID(Client_Introducer(Client)),
1154                          Client_Hops(Client), Client_Hops(Client) > 1 ? "s": "");
1155         } else {
1156                 Log(LOG_NOTICE, "%s \"%s\" registered (connection %d).",
1157                     Client_TypeText(Client), Client_Mask(Client),
1158                     Client_Conn(Client));
1159                 Log_ServerNotice('c', "Client connecting: %s (%s@%s) [%s] - %s",
1160                                  Client_ID(Client), Client_User(Client),
1161                                  Client_Hostname(Client),
1162                                  Conn_IPA(Client_Conn(Client)),
1163                                  Client_TypeText(Client));
1164         }
1165
1166         /* Inform other servers */
1167         IRC_WriteStrServersPrefixFlag_CB(From,
1168                                 From != NULL ? From : Client_ThisServer(),
1169                                 '\0', cb_introduceClient, (void *)Client);
1170 } /* Introduce_Client */
1171
1172
1173 /**
1174  * Introduce a new user or service client to a remote server.
1175  *
1176  * This function differentiates between RFC1459 and RFC2813 server links and
1177  * generates the appropriate commands to register the new user or service.
1178  *
1179  * @param To            The remote server to inform.
1180  * @param Prefix        Prefix for the generated commands.
1181  * @param data          CLIENT structure of the new client.
1182  */
1183 static void
1184 cb_introduceClient(CLIENT *To, CLIENT *Prefix, void *data)
1185 {
1186         CLIENT *c = (CLIENT *)data;
1187         CONN_ID conn;
1188         char *modes, *user, *host;
1189
1190         modes = Client_Modes(c);
1191         user = Client_User(c) ? Client_User(c) : "-";
1192         host = Client_Hostname(c) ? Client_Hostname(c) : "-";
1193
1194         conn = Client_Conn(To);
1195         if (Conn_Options(conn) & CONN_RFC1459) {
1196                 /* RFC 1459 mode: separate NICK and USER commands */
1197                 Conn_WriteStr(conn, "NICK %s :%d", Client_ID(c),
1198                               Client_Hops(c) + 1);
1199                 Conn_WriteStr(conn, ":%s USER %s %s %s :%s",
1200                               Client_ID(c), user, host,
1201                               Client_ID(Client_Introducer(c)), Client_Info(c));
1202                 if (modes[0])
1203                         Conn_WriteStr(conn, ":%s MODE %s +%s",
1204                                       Client_ID(c), Client_ID(c), modes);
1205         } else {
1206                 /* RFC 2813 mode: one combined NICK or SERVICE command */
1207                 if (Client_Type(c) == CLIENT_SERVICE
1208                     && strchr(Client_Flags(To), 'S'))
1209                         IRC_WriteStrClientPrefix(To, Prefix,
1210                                          "SERVICE %s %d * +%s %d :%s",
1211                                          Client_Mask(c),
1212                                          Client_MyToken(Client_Introducer(c)),
1213                                          Client_Modes(c), Client_Hops(c) + 1,
1214                                          Client_Info(c));
1215                 else
1216                         IRC_WriteStrClientPrefix(To, Prefix,
1217                                          "NICK %s %d %s %s %d +%s :%s",
1218                                          Client_ID(c), Client_Hops(c) + 1,
1219                                          user, host,
1220                                          Client_MyToken(Client_Introducer(c)),
1221                                          modes, Client_Info(c));
1222         }
1223 } /* cb_introduceClient */
1224
1225
1226 /* -eof- */