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