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