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