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