]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/irc-login.c
Merge branches 'CloakUserHost', 'QuitOnHTTP' and 'bug72-WHOIS-List'
[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 #ifndef STRICT_RFC
687
688 /**
689  * Handler for HTTP command, e.g. GET and POST
690  *
691  * We handle these commands here to avoid the quite long timeout when
692  * some user tries to access this IRC daemon using an web browser ...
693  *
694  * @param Client        The client from which this command has been received.
695  * @param Req           Request structure with prefix and all parameters.
696  * @returns             CONNECTED or DISCONNECTED.
697  */
698 GLOBAL bool
699 IRC_QUIT_HTTP( CLIENT *Client, REQUEST *Req )
700 {
701         Req->argc = 1;
702         Req->argv[0] = "Oops, HTTP request received? This is IRC!";
703         return IRC_QUIT(Client, Req);
704 } /* IRC_QUIT_HTTP */
705
706 #endif
707
708
709 /**
710  * Handler for the IRC "PING" command.
711  *
712  * See RFC 2812, 3.7.2 "Ping message".
713  *
714  * @param Client        The client from which this command has been received.
715  * @param Req           Request structure with prefix and all parameters.
716  * @returns             CONNECTED or DISCONNECTED.
717  */
718 GLOBAL bool
719 IRC_PING(CLIENT *Client, REQUEST *Req)
720 {
721         CLIENT *target, *from;
722
723         assert(Client != NULL);
724         assert(Req != NULL);
725
726         if (Req->argc < 1)
727                 return IRC_WriteStrClient(Client, ERR_NOORIGIN_MSG,
728                                           Client_ID(Client));
729 #ifdef STRICT_RFC
730         /* Don't ignore additional arguments when in "strict" mode */
731         if (Req->argc > 2)
732                  return IRC_WriteStrClient(Client, ERR_NEEDMOREPARAMS_MSG,
733                                            Client_ID(Client), Req->command);
734 #endif
735
736         if (Req->argc > 1) {
737                 /* A target has been specified ... */
738                 target = Client_Search(Req->argv[1]);
739
740                 if (!target || Client_Type(target) != CLIENT_SERVER)
741                         return IRC_WriteStrClient(Client, ERR_NOSUCHSERVER_MSG,
742                                         Client_ID(Client), Req->argv[1]);
743
744                 if (target != Client_ThisServer()) {
745                         /* Ok, we have to forward the PING */
746                         if (Client_Type(Client) == CLIENT_SERVER)
747                                 from = Client_Search(Req->prefix);
748                         else
749                                 from = Client;
750                         if (!from)
751                                 return IRC_WriteStrClient(Client,
752                                                 ERR_NOSUCHSERVER_MSG,
753                                                 Client_ID(Client), Req->prefix);
754
755                         return IRC_WriteStrClientPrefix(target, from,
756                                         "PING %s :%s", Req->argv[0],
757                                         Req->argv[1] );
758                 }
759         }
760
761         if (Client_Type(Client) == CLIENT_SERVER) {
762                 if (Req->prefix)
763                         from = Client_Search(Req->prefix);
764                 else
765                         from = Client;
766         } else
767                 from = Client_ThisServer();
768         if (!from)
769                 return IRC_WriteStrClient(Client, ERR_NOSUCHSERVER_MSG,
770                                         Client_ID(Client), Req->prefix);
771
772         Log(LOG_DEBUG, "Connection %d: got PING, sending PONG ...",
773             Client_Conn(Client));
774
775 #ifdef STRICT_RFC
776         return IRC_WriteStrClient(Client, "PONG %s :%s",
777                 Client_ID(from), Client_ID(Client));
778 #else
779         /* Some clients depend on the argument being returned in the PONG
780          * reply (not mentioned in any RFC, though) */
781         return IRC_WriteStrClient(Client, "PONG %s :%s",
782                 Client_ID(from), Req->argv[0]);
783 #endif
784 } /* IRC_PING */
785
786
787 /**
788  * Handler for the IRC "PONG" command.
789  *
790  * See RFC 2812, 3.7.3 "Pong message".
791  *
792  * @param Client        The client from which this command has been received.
793  * @param Req           Request structure with prefix and all parameters.
794  * @returns             CONNECTED or DISCONNECTED.
795  */
796 GLOBAL bool
797 IRC_PONG(CLIENT *Client, REQUEST *Req)
798 {
799         CLIENT *target, *from;
800         char *s;
801
802         assert(Client != NULL);
803         assert(Req != NULL);
804
805         /* Wrong number of arguments? */
806         if (Req->argc < 1)
807                 return IRC_WriteStrClient(Client, ERR_NOORIGIN_MSG,
808                                           Client_ID(Client));
809         if (Req->argc > 2)
810                 return IRC_WriteStrClient(Client, ERR_NEEDMOREPARAMS_MSG,
811                                           Client_ID(Client), Req->command);
812
813         /* Forward? */
814         if (Req->argc == 2 && Client_Type(Client) == CLIENT_SERVER) {
815                 target = Client_Search(Req->argv[0]);
816                 if (!target)
817                         return IRC_WriteStrClient(Client, ERR_NOSUCHSERVER_MSG,
818                                         Client_ID(Client), Req->argv[0]);
819
820                 from = Client_Search(Req->prefix);
821
822                 if (target != Client_ThisServer() && target != from) {
823                         /* Ok, we have to forward the message. */
824                         if (!from)
825                                 return IRC_WriteStrClient(Client,
826                                                 ERR_NOSUCHSERVER_MSG,
827                                                 Client_ID(Client), Req->prefix);
828
829                         if (Client_Type(Client_NextHop(target)) != CLIENT_SERVER)
830                                 s = Client_ID(from);
831                         else
832                                 s = Req->argv[0];
833                         return IRC_WriteStrClientPrefix(target, from,
834                                  "PONG %s :%s", s, Req->argv[1]);
835                 }
836         }
837
838         /* The connection timestamp has already been updated when the data has
839          * been read from so socket, so we don't need to update it here. */
840 #ifdef DEBUG
841         if (Client_Conn(Client) > NONE)
842                 Log(LOG_DEBUG,
843                         "Connection %d: received PONG. Lag: %ld seconds.",
844                         Client_Conn(Client),
845                         time(NULL) - Conn_LastPing(Client_Conn(Client)));
846         else
847                  Log(LOG_DEBUG,
848                         "Connection %d: received PONG.", Client_Conn(Client));
849 #endif
850         return CONNECTED;
851 } /* IRC_PONG */
852
853
854 /**
855  * Initiate client registration.
856  *
857  * This function is called after the daemon received the required NICK and
858  * USER commands of a new client. If the daemon is compiled with support for
859  * PAM, the authentication sub-processs is forked; otherwise the global server
860  * password is checked.
861  *
862  * @param Client        The client logging in.
863  * @returns             CONNECTED or DISCONNECTED.
864  */
865 static bool
866 Hello_User(CLIENT * Client)
867 {
868 #ifdef PAM
869         int pipefd[2], result;
870         CONN_ID conn;
871         pid_t pid;
872
873         assert(Client != NULL);
874         conn = Client_Conn(Client);
875
876         if (!Conf_PAM) {
877                 /* Don't do any PAM authentication at all, instead emulate
878                  * the beahiour of the daemon compiled without PAM support:
879                  * because there can't be any "server password", all
880                  * passwords supplied are classified as "wrong". */
881                 if(Client_Password(Client)[0] == '\0')
882                         return Hello_User_PostAuth(Client);
883                 Reject_Client(Client);
884                 return DISCONNECTED;
885         }
886
887         /* Fork child process for PAM authentication; and make sure that the
888          * process timeout is set higher than the login timeout! */
889         pid = Proc_Fork(Conn_GetProcStat(conn), pipefd,
890                         cb_Read_Auth_Result, Conf_PongTimeout + 1);
891         if (pid > 0) {
892                 LogDebug("Authenticator for connection %d created (PID %d).",
893                          conn, pid);
894                 return CONNECTED;
895         } else {
896                 /* Sub process */
897                 Log_Init_Subprocess("Auth");
898                 result = PAM_Authenticate(Client);
899                 if (write(pipefd[1], &result, sizeof(result)) != sizeof(result))
900                         Log_Subprocess(LOG_ERR,
901                                        "Failed to pipe result to parent!");
902                 Log_Exit_Subprocess("Auth");
903                 exit(0);
904         }
905 #else
906         assert(Client != NULL);
907
908         /* Check global server password ... */
909         if (strcmp(Client_Password(Client), Conf_ServerPwd) != 0) {
910                 /* Bad password! */
911                 Reject_Client(Client);
912                 return DISCONNECTED;
913         }
914         return Hello_User_PostAuth(Client);
915 #endif
916 }
917
918
919 #ifdef PAM
920
921 /**
922  * Read result of the authenticatior sub-process from pipe
923  *
924  * @param r_fd          File descriptor of the pipe.
925  * @param events        (ignored IO specification)
926  */
927 static void
928 cb_Read_Auth_Result(int r_fd, UNUSED short events)
929 {
930         CONN_ID conn;
931         CLIENT *client;
932         int result;
933         size_t len;
934         PROC_STAT *proc;
935
936         LogDebug("Auth: Got callback on fd %d, events %d", r_fd, events);
937         conn = Conn_GetFromProc(r_fd);
938         if (conn == NONE) {
939                 /* Ops, none found? Probably the connection has already
940                  * been closed!? We'll ignore that ... */
941                 io_close(r_fd);
942                 LogDebug("Auth: Got callback for unknown connection!?");
943                 return;
944         }
945         proc = Conn_GetProcStat(conn);
946         client = Conn_GetClient(conn);
947
948         /* Read result from pipe */
949         len = Proc_Read(proc, &result, sizeof(result));
950         if (len == 0)
951                 return;
952
953         if (len != sizeof(result)) {
954                 Log(LOG_CRIT, "Auth: Got malformed result!");
955                 Reject_Client(client);
956                 return;
957         }
958
959         if (result == true) {
960                 Client_SetUser(client, Client_OrigUser(client), true);
961                 (void)Hello_User_PostAuth(client);
962         } else
963                 Reject_Client(client);
964 }
965
966 #endif
967
968
969 /**
970  * Reject a client because of wrong password.
971  *
972  * This function is called either when the global server password or a password
973  * checked using PAM has been wrong.
974  *
975  * @param Client        The client to reject.
976  */
977 static void
978 Reject_Client(CLIENT *Client)
979 {
980         Log(LOG_ERR,
981             "User \"%s\" rejected (connection %d): Access denied!",
982             Client_Mask(Client), Client_Conn(Client));
983         Conn_Close(Client_Conn(Client), NULL,
984                    "Access denied! Bad password?", true);
985 }
986
987
988 /**
989  * Finish client registration.
990  *
991  * Introduce the new client to the network and send all "hello messages"
992  * to it after authentication has been succeeded.
993  *
994  * @param Client        The client logging in.
995  * @returns             CONNECTED or DISCONNECTED.
996  */
997 static bool
998 Hello_User_PostAuth(CLIENT *Client)
999 {
1000         Introduce_Client(NULL, Client, CLIENT_USER);
1001
1002         if (!IRC_WriteStrClient
1003             (Client, RPL_WELCOME_MSG, Client_ID(Client), Client_Mask(Client)))
1004                 return false;
1005         if (!IRC_WriteStrClient
1006             (Client, RPL_YOURHOST_MSG, Client_ID(Client),
1007              Client_ID(Client_ThisServer()), PACKAGE_VERSION, TARGET_CPU,
1008              TARGET_VENDOR, TARGET_OS))
1009                 return false;
1010         if (!IRC_WriteStrClient
1011             (Client, RPL_CREATED_MSG, Client_ID(Client), NGIRCd_StartStr))
1012                 return false;
1013         if (!IRC_WriteStrClient
1014             (Client, RPL_MYINFO_MSG, Client_ID(Client),
1015              Client_ID(Client_ThisServer()), PACKAGE_VERSION, USERMODES,
1016              CHANMODES))
1017                 return false;
1018
1019         /* Features supported by this server (005 numeric, ISUPPORT),
1020          * see <http://www.irc.org/tech_docs/005.html> for details. */
1021         if (!IRC_Send_ISUPPORT(Client))
1022                 return DISCONNECTED;
1023
1024         if (!IRC_Send_LUSERS(Client))
1025                 return DISCONNECTED;
1026         if (!IRC_Show_MOTD(Client))
1027                 return DISCONNECTED;
1028
1029         /* Suspend the client for a second ... */
1030         IRC_SetPenalty(Client, 1);
1031
1032         return CONNECTED;
1033 }
1034
1035
1036 /**
1037  * Kill all users with a specific nick name in the network.
1038  *
1039  * @param Nick          Nick name.
1040  * @param Reason        Reason for the KILL.
1041  */
1042 static void
1043 Kill_Nick( char *Nick, char *Reason )
1044 {
1045         REQUEST r;
1046
1047         assert( Nick != NULL );
1048         assert( Reason != NULL );
1049
1050         r.prefix = (char *)Client_ThisServer( );
1051         r.argv[0] = Nick;
1052         r.argv[1] = Reason;
1053         r.argc = 2;
1054
1055         Log( LOG_ERR, "User(s) with nick \"%s\" will be disconnected: %s", Nick, Reason );
1056         IRC_KILL( Client_ThisServer( ), &r );
1057 } /* Kill_Nick */
1058
1059
1060 /**
1061  * Introduce a new user or service client in the network.
1062  *
1063  * @param From          Remote server introducing the client or NULL (local).
1064  * @param Client        New client.
1065  * @param Type          Type of the client (CLIENT_USER or CLIENT_SERVICE).
1066  */
1067 static void
1068 Introduce_Client(CLIENT *From, CLIENT *Client, int Type)
1069 {
1070         /* Set client type (user or service) */
1071         Client_SetType(Client, Type);
1072
1073         if (From) {
1074                 if (Conf_IsService(Conf_GetServer(Client_Conn(From)),
1075                                    Client_ID(Client)))
1076                         Client_SetType(Client, CLIENT_SERVICE);
1077                 LogDebug("%s \"%s\" (+%s) registered (via %s, on %s, %d hop%s).",
1078                          Client_TypeText(Client), Client_Mask(Client),
1079                          Client_Modes(Client), Client_ID(From),
1080                          Client_ID(Client_Introducer(Client)),
1081                          Client_Hops(Client), Client_Hops(Client) > 1 ? "s": "");
1082         } else {
1083                 Log(LOG_NOTICE, "%s \"%s\" registered (connection %d).",
1084                     Client_TypeText(Client), Client_Mask(Client),
1085                     Client_Conn(Client));
1086                 Log_ServerNotice('c', "Client connecting: %s (%s@%s) [%s] - %s",
1087                                  Client_ID(Client), Client_User(Client),
1088                                  Client_Hostname(Client),
1089                                  Conn_IPA(Client_Conn(Client)),
1090                                  Client_TypeText(Client));
1091         }
1092
1093         /* Inform other servers */
1094         IRC_WriteStrServersPrefixFlag_CB(From,
1095                                 From != NULL ? From : Client_ThisServer(),
1096                                 '\0', cb_introduceClient, (void *)Client);
1097 } /* Introduce_Client */
1098
1099
1100 /**
1101  * Introduce a new user or service client to a remote server.
1102  *
1103  * This function differentiates between RFC1459 and RFC2813 server links and
1104  * generates the appropriate commands to register the new user or service.
1105  *
1106  * @param To            The remote server to inform.
1107  * @param Prefix        Prefix for the generated commands.
1108  * @param data          CLIENT structure of the new client.
1109  */
1110 static void
1111 cb_introduceClient(CLIENT *To, CLIENT *Prefix, void *data)
1112 {
1113         CLIENT *c = (CLIENT *)data;
1114         CONN_ID conn;
1115         char *modes, *user, *host;
1116
1117         modes = Client_Modes(c);
1118         user = Client_User(c) ? Client_User(c) : "-";
1119         host = Client_Hostname(c) ? Client_Hostname(c) : "-";
1120
1121         conn = Client_Conn(To);
1122         if (Conn_Options(conn) & CONN_RFC1459) {
1123                 /* RFC 1459 mode: separate NICK and USER commands */
1124                 Conn_WriteStr(conn, "NICK %s :%d", Client_ID(c),
1125                               Client_Hops(c) + 1);
1126                 Conn_WriteStr(conn, ":%s USER %s %s %s :%s",
1127                               Client_ID(c), user, host,
1128                               Client_ID(Client_Introducer(c)), Client_Info(c));
1129                 if (modes[0])
1130                         Conn_WriteStr(conn, ":%s MODE %s +%s",
1131                                       Client_ID(c), Client_ID(c), modes);
1132         } else {
1133                 /* RFC 2813 mode: one combined NICK or SERVICE command */
1134                 if (Client_Type(c) == CLIENT_SERVICE
1135                     && strchr(Client_Flags(To), 'S'))
1136                         IRC_WriteStrClientPrefix(To, Prefix,
1137                                          "SERVICE %s %d * +%s %d :%s",
1138                                          Client_Mask(c),
1139                                          Client_MyToken(Client_Introducer(c)),
1140                                          Client_Modes(c), Client_Hops(c) + 1,
1141                                          Client_Info(c));
1142                 else
1143                         IRC_WriteStrClientPrefix(To, Prefix,
1144                                          "NICK %s %d %s %s %d +%s :%s",
1145                                          Client_ID(c), Client_Hops(c) + 1,
1146                                          user, host,
1147                                          Client_MyToken(Client_Introducer(c)),
1148                                          modes, Client_Info(c));
1149         }
1150 } /* cb_introduceClient */
1151
1152
1153 /* -eof- */