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