]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/irc-login.c
Send a PING at the end of the server sync to detect it
[ngircd-alex.git] / src / ngircd / irc-login.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001-2011 Alexander Barton (alex@barton.de) and Contributors.
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 "class.h"
31 #include "conf.h"
32 #include "channel.h"
33 #include "io.h"
34 #include "log.h"
35 #include "messages.h"
36 #include "pam.h"
37 #include "parse.h"
38 #include "irc.h"
39 #include "irc-info.h"
40 #include "irc-write.h"
41
42 #include "exp.h"
43 #include "irc-login.h"
44
45
46 static bool Hello_User PARAMS(( CLIENT *Client ));
47 static bool Hello_User_PostAuth PARAMS(( CLIENT *Client ));
48 static void Kill_Nick PARAMS(( char *Nick, char *Reason ));
49 static void Introduce_Client PARAMS((CLIENT *To, CLIENT *Client, int Type));
50
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 #ifndef STRICT_RFC
275                         if (Conf_AuthPing) {
276                                 Conn_SetAuthPing(Client_Conn(Client), rand());
277                                 IRC_WriteStrClient(Client, "PING :%ld",
278                                         Conn_GetAuthPing(Client_Conn(Client)));
279                                 LogDebug("Connection %d: sent AUTH PING %ld ...",
280                                         Client_Conn(Client),
281                                         Conn_GetAuthPing(Client_Conn(Client)));
282                         }
283 #endif
284
285                         /* If we received a valid USER command already then
286                          * register the new client! */
287                         if( Client_Type( Client ) == CLIENT_GOTUSER )
288                                 return Hello_User( Client );
289                         else
290                                 Client_SetType( Client, CLIENT_GOTNICK );
291                 } else {
292                         /* Nickname change */
293                         if (Client_Conn(target) > NONE) {
294                                 /* Local client */
295                                 Log(LOG_INFO,
296                                     "%s \"%s\" changed nick (connection %d): \"%s\" -> \"%s\".",
297                                     Client_TypeText(target), Client_Mask(target),
298                                     Client_Conn(target), Client_ID(target),
299                                     Req->argv[0]);
300                                 Conn_UpdateIdle(Client_Conn(target));
301                         } else {
302                                 /* Remote client */
303                                 LogDebug("%s \"%s\" changed nick: \"%s\" -> \"%s\".",
304                                          Client_TypeText(target),
305                                          Client_Mask(target), Client_ID(target),
306                                          Req->argv[0]);
307                         }
308
309                         /* Inform all users and servers (which have to know)
310                          * of this nickname change */
311                         if( Client_Type( Client ) == CLIENT_USER )
312                                 IRC_WriteStrClientPrefix( Client, Client,
313                                                           "NICK :%s",
314                                                           Req->argv[0] );
315                         IRC_WriteStrServersPrefix( Client, target,
316                                                    "NICK :%s", Req->argv[0] );
317                         IRC_WriteStrRelatedPrefix( target, target, false,
318                                                    "NICK :%s", Req->argv[0] );
319
320                         /* Register old nickname for WHOWAS queries */
321                         Client_RegisterWhowas( target );
322
323                         /* Save new nickname */
324                         Client_SetID( target, Req->argv[0] );
325
326                         IRC_SetPenalty( target, 2 );
327                 }
328
329                 return CONNECTED;
330         } else if(Client_Type(Client) == CLIENT_SERVER ||
331                   Client_Type(Client) == CLIENT_SERVICE) {
332                 /* Server or service introduces new client */
333
334                 /* Bad number of parameters? */
335                 if (Req->argc != 2 && Req->argc != 7)
336                         return IRC_WriteStrClient(Client, ERR_NEEDMOREPARAMS_MSG,
337                                                   Client_ID(Client), Req->command);
338
339                 if (Req->argc >= 7) {
340                         /* RFC 2813 compatible syntax */
341                         nick = Req->argv[0];
342                         hops = atoi(Req->argv[1]);
343                         user = Req->argv[2];
344                         hostname = Req->argv[3];
345                         token = atoi(Req->argv[4]);
346                         modes = Req->argv[5] + 1;
347                         info = Req->argv[6];
348                 } else {
349                         /* RFC 1459 compatible syntax */
350                         nick = Req->argv[0];
351                         hops = 1;
352                         user = Req->argv[0];
353                         hostname = Client_ID(Client);
354                         token = atoi(Req->argv[1]);
355                         modes = "";
356                         info = Req->argv[0];
357                 }
358
359                 c = Client_Search(nick);
360                 if(c) {
361                         /*
362                          * the new nick is already present on this server:
363                          * the new and the old one have to be disconnected now.
364                          */
365                         Log( LOG_ERR, "Server %s introduces already registered nick \"%s\"!", Client_ID( Client ), Req->argv[0] );
366                         Kill_Nick( Req->argv[0], "Nick collision" );
367                         return CONNECTED;
368                 }
369
370                 /* Find the Server this client is connected to */
371                 intr_c = Client_GetFromToken(Client, token);
372                 if( ! intr_c )
373                 {
374                         Log( LOG_ERR, "Server %s introduces nick \"%s\" on unknown server!?", Client_ID( Client ), Req->argv[0] );
375                         Kill_Nick( Req->argv[0], "Unknown server" );
376                         return CONNECTED;
377                 }
378
379                 c = Client_NewRemoteUser(intr_c, nick, hops, user, hostname,
380                                          token, modes, info, true);
381                 if( ! c )
382                 {
383                         /* out of memory, need to disconnect client to keep network state consistent */
384                         Log( LOG_ALERT, "Can't create client structure! (on connection %d)", Client_Conn( Client ));
385                         Kill_Nick( Req->argv[0], "Server error" );
386                         return CONNECTED;
387                 }
388
389                 /* RFC 2813: client is now fully registered, inform all the
390                  * other servers about the new user.
391                  * RFC 1459: announce the new client only after receiving the
392                  * USER command, first we need more information! */
393                 if (Req->argc < 7) {
394                         LogDebug("Client \"%s\" is being registered (RFC 1459) ...",
395                                  Client_Mask(c));
396                         Client_SetType(c, CLIENT_GOTNICK);
397                 } else
398                         Introduce_Client(Client, c, CLIENT_USER);
399
400                 return CONNECTED;
401         }
402         else return IRC_WriteStrClient( Client, ERR_ALREADYREGISTRED_MSG, Client_ID( Client ));
403 } /* IRC_NICK */
404
405
406 /**
407  * Handler for the IRC "USER" command.
408  *
409  * See RFC 2812, 3.1.3 "User message".
410  *
411  * @param Client        The client from which this command has been received.
412  * @param Req           Request structure with prefix and all parameters.
413  * @returns             CONNECTED or DISCONNECTED.
414  */
415 GLOBAL bool
416 IRC_USER(CLIENT * Client, REQUEST * Req)
417 {
418         CLIENT *c;
419 #ifdef IDENTAUTH
420         char *ptr;
421 #endif
422
423         assert(Client != NULL);
424         assert(Req != NULL);
425
426         if (Client_Type(Client) == CLIENT_GOTNICK ||
427 #ifndef STRICT_RFC
428             Client_Type(Client) == CLIENT_UNKNOWN ||
429 #endif
430             Client_Type(Client) == CLIENT_GOTPASS)
431         {
432                 /* New connection */
433                 if (Req->argc != 4)
434                         return IRC_WriteStrClient(Client,
435                                                   ERR_NEEDMOREPARAMS_MSG,
436                                                   Client_ID(Client),
437                                                   Req->command);
438
439                 /* User name */
440 #ifdef IDENTAUTH
441                 ptr = Client_User(Client);
442                 if (!ptr || !*ptr || *ptr == '~')
443                         Client_SetUser(Client, Req->argv[0], false);
444 #else
445                 Client_SetUser(Client, Req->argv[0], false);
446 #endif
447                 Client_SetOrigUser(Client, Req->argv[0]);
448
449                 /* "Real name" or user info text: Don't set it to the empty
450                  * string, the original ircd can't deal with such "real names"
451                  * (e. g. "USER user * * :") ... */
452                 if (*Req->argv[3])
453                         Client_SetInfo(Client, Req->argv[3]);
454                 else
455                         Client_SetInfo(Client, "-");
456
457                 LogDebug("Connection %d: got valid USER command ...",
458                     Client_Conn(Client));
459                 if (Client_Type(Client) == CLIENT_GOTNICK)
460                         return Hello_User(Client);
461                 else
462                         Client_SetType(Client, CLIENT_GOTUSER);
463                 return CONNECTED;
464
465         } else if (Client_Type(Client) == CLIENT_SERVER ||
466                    Client_Type(Client) == CLIENT_SERVICE) {
467                 /* Server/service updating an user */
468                 if (Req->argc != 4)
469                         return IRC_WriteStrClient(Client,
470                                                   ERR_NEEDMOREPARAMS_MSG,
471                                                   Client_ID(Client),
472                                                   Req->command);
473                 c = Client_Search(Req->prefix);
474                 if (!c)
475                         return IRC_WriteStrClient(Client, ERR_NOSUCHNICK_MSG,
476                                                   Client_ID(Client),
477                                                   Req->prefix);
478
479                 Client_SetUser(c, Req->argv[0], true);
480                 Client_SetOrigUser(c, Req->argv[0]);
481                 Client_SetHostname(c, Req->argv[1]);
482                 Client_SetInfo(c, Req->argv[3]);
483
484                 LogDebug("Connection %d: got valid USER command for \"%s\".",
485                          Client_Conn(Client), Client_Mask(c));
486
487                 /* RFC 1459 style user registration?
488                  * Introduce client to network: */
489                 if (Client_Type(c) == CLIENT_GOTNICK)
490                         Introduce_Client(Client, c, CLIENT_USER);
491
492                 return CONNECTED;
493         } else if (Client_Type(Client) == CLIENT_USER) {
494                 /* Already registered connection */
495                 return IRC_WriteStrClient(Client, ERR_ALREADYREGISTRED_MSG,
496                                           Client_ID(Client));
497         } else {
498                 /* Unexpected/invalid connection state? */
499                 return IRC_WriteStrClient(Client, ERR_NOTREGISTERED_MSG,
500                                           Client_ID(Client));
501         }
502 } /* IRC_USER */
503
504
505 /**
506  * Handler for the IRC "SERVICE" command.
507  *
508  * This function implements IRC Services registration using the SERVICE command
509  * defined in RFC 2812 3.1.6 and RFC 2813 4.1.4.
510  *
511  * At the moment ngIRCd doesn't support directly linked services, so this
512  * function returns ERR_ERRONEUSNICKNAME when the SERVICE command has not been
513  * received from a peer server.
514  *
515  * @param Client        The client from which this command has been received.
516  * @param Req           Request structure with prefix and all parameters.
517  * @returns             CONNECTED or DISCONNECTED..
518  */
519 GLOBAL bool
520 IRC_SERVICE(CLIENT *Client, REQUEST *Req)
521 {
522         CLIENT *c, *intr_c;
523         char *nick, *user, *host, *info, *modes, *ptr;
524         int token, hops;
525
526         assert(Client != NULL);
527         assert(Req != NULL);
528
529         if (Client_Type(Client) != CLIENT_GOTPASS &&
530             Client_Type(Client) != CLIENT_SERVER)
531                 return IRC_WriteStrClient(Client, ERR_ALREADYREGISTRED_MSG,
532                                           Client_ID(Client));
533
534         if (Req->argc != 6)
535                 return IRC_WriteStrClient(Client, ERR_NEEDMOREPARAMS_MSG,
536                                           Client_ID(Client), Req->command);
537
538         if (Client_Type(Client) != CLIENT_SERVER)
539                 return IRC_WriteStrClient(Client, ERR_ERRONEUSNICKNAME_MSG,
540                                   Client_ID(Client), Req->argv[0]);
541
542         /* Bad number of parameters? */
543         if (Req->argc != 6)
544                 return IRC_WriteStrClient(Client, ERR_NEEDMOREPARAMS_MSG,
545                                           Client_ID(Client), Req->command);
546
547         nick = Req->argv[0];
548         user = NULL; host = NULL;
549         token = atoi(Req->argv[1]);
550         hops = atoi(Req->argv[4]);
551         info = Req->argv[5];
552
553         /* Validate service name ("nick name") */
554         c = Client_Search(nick);
555         if(c) {
556                 /* Nick name collission: disconnect (KILL) both clients! */
557                 Log(LOG_ERR, "Server %s introduces already registered service \"%s\"!",
558                     Client_ID(Client), nick);
559                 Kill_Nick(nick, "Nick collision");
560                 return CONNECTED;
561         }
562
563         /* Get the server to which the service is connected */
564         intr_c = Client_GetFromToken(Client, token);
565         if (! intr_c) {
566                 Log(LOG_ERR, "Server %s introduces service \"%s\" on unknown server!?",
567                     Client_ID(Client), nick);
568                 Kill_Nick(nick, "Unknown server");
569                 return CONNECTED;
570         }
571
572         /* Get user and host name */
573         ptr = strchr(nick, '@');
574         if (ptr) {
575                 *ptr = '\0';
576                 host = ++ptr;
577         }
578         if (!host)
579                 host = Client_Hostname(intr_c);
580         ptr = strchr(nick, '!');
581         if (ptr) {
582                 *ptr = '\0';
583                 user = ++ptr;
584         }
585         if (!user)
586                 user = nick;
587
588         /* According to RFC 2812/2813 parameter 4 <type> "is currently reserved
589          * for future usage"; but we use it to transfer the modes and check
590          * that the first character is a '+' sign and ignore it otherwise. */
591         modes = (Req->argv[3][0] == '+') ? ++Req->argv[3] : "";
592
593         c = Client_NewRemoteUser(intr_c, nick, hops, user, host,
594                                  token, modes, info, true);
595         if (! c) {
596                 /* Couldn't create client structure, so KILL the service to
597                  * keep network status consistent ... */
598                 Log(LOG_ALERT, "Can't create client structure! (on connection %d)",
599                     Client_Conn(Client));
600                 Kill_Nick(nick, "Server error");
601                 return CONNECTED;
602         }
603
604         Introduce_Client(Client, c, CLIENT_SERVICE);
605         return CONNECTED;
606 } /* IRC_SERVICE */
607
608
609 /**
610  * Handler for the IRC "WEBIRC" command.
611  *
612  * See doc/Protocol.txt, section II.4:
613  * "Update webchat/proxy client information".
614  *
615  * @param Client        The client from which this command has been received.
616  * @param Req           Request structure with prefix and all parameters.
617  * @returns             CONNECTED or DISCONNECTED.
618  */
619 GLOBAL bool
620 IRC_WEBIRC(CLIENT *Client, REQUEST *Req)
621 {
622         /* Exactly 4 parameters are requited */
623         if (Req->argc != 4)
624                 return IRC_WriteStrClient(Client, ERR_NEEDMOREPARAMS_MSG,
625                                           Client_ID(Client), Req->command);
626
627         if (!Conf_WebircPwd[0] || strcmp(Req->argv[0], Conf_WebircPwd) != 0)
628                 return IRC_WriteStrClient(Client, ERR_PASSWDMISMATCH_MSG,
629                                           Client_ID(Client));
630
631         LogDebug("Connection %d: got valid WEBIRC command: user=%s, host=%s, ip=%s",
632                  Client_Conn(Client), Req->argv[1], Req->argv[2], Req->argv[3]);
633
634         Client_SetUser(Client, Req->argv[1], true);
635         Client_SetOrigUser(Client, Req->argv[1]);
636         Client_SetHostname(Client, Req->argv[2]);
637         return CONNECTED;
638 } /* IRC_WEBIRC */
639
640
641 /**
642  * Handler for the IRC "QUIT" command.
643  *
644  * See RFC 2812, 3.1.7 "Quit", and RFC 2813, 4.1.5 "Quit".
645  *
646  * @param Client        The client from which this command has been received.
647  * @param Req           Request structure with prefix and all parameters.
648  * @returns             CONNECTED or DISCONNECTED.
649  */
650 GLOBAL bool
651 IRC_QUIT( CLIENT *Client, REQUEST *Req )
652 {
653         CLIENT *target;
654         char quitmsg[LINE_LEN];
655
656         assert(Client != NULL);
657         assert(Req != NULL);
658
659         /* Wrong number of arguments? */
660         if (Req->argc > 1)
661                 return IRC_WriteStrClient(Client, ERR_NEEDMOREPARAMS_MSG,
662                                           Client_ID(Client), Req->command);
663
664         if (Req->argc == 1)
665                 strlcpy(quitmsg, Req->argv[0], sizeof quitmsg);
666
667         if (Client_Type(Client) == CLIENT_SERVER) {
668                 /* Server */
669                 target = Client_Search(Req->prefix);
670                 if (!target) {
671                         Log(LOG_WARNING,
672                             "Got QUIT from %s for unknown client!?",
673                             Client_ID(Client));
674                         return CONNECTED;
675                 }
676
677                 if (target != Client) {
678                         Client_Destroy(target, "Got QUIT command.",
679                                        Req->argc == 1 ? quitmsg : NULL, true);
680                         return CONNECTED;
681                 } else {
682                         Conn_Close(Client_Conn(Client), "Got QUIT command.",
683                                    Req->argc == 1 ? quitmsg : NULL, true);
684                         return DISCONNECTED;
685                 }
686         } else {
687                 if (Req->argc == 1 && quitmsg[0] != '\"') {
688                         /* " " to avoid confusion */
689                         strlcpy(quitmsg, "\"", sizeof quitmsg);
690                         strlcat(quitmsg, Req->argv[0], sizeof quitmsg-1);
691                         strlcat(quitmsg, "\"", sizeof quitmsg );
692                 }
693
694                 /* User, Service, or not yet registered */
695                 Conn_Close(Client_Conn(Client), "Got QUIT command.",
696                            Req->argc == 1 ? quitmsg : NULL, true);
697
698                 return DISCONNECTED;
699         }
700 } /* IRC_QUIT */
701
702
703 #ifndef STRICT_RFC
704
705 /**
706  * Handler for HTTP command, e.g. GET and POST
707  *
708  * We handle these commands here to avoid the quite long timeout when
709  * some user tries to access this IRC daemon using an web browser ...
710  *
711  * @param Client        The client from which this command has been received.
712  * @param Req           Request structure with prefix and all parameters.
713  * @returns             CONNECTED or DISCONNECTED.
714  */
715 GLOBAL bool
716 IRC_QUIT_HTTP( CLIENT *Client, REQUEST *Req )
717 {
718         Req->argc = 1;
719         Req->argv[0] = "Oops, HTTP request received? This is IRC!";
720         return IRC_QUIT(Client, Req);
721 } /* IRC_QUIT_HTTP */
722
723 #endif
724
725
726 /**
727  * Handler for the IRC "PING" command.
728  *
729  * See RFC 2812, 3.7.2 "Ping message".
730  *
731  * @param Client        The client from which this command has been received.
732  * @param Req           Request structure with prefix and all parameters.
733  * @returns             CONNECTED or DISCONNECTED.
734  */
735 GLOBAL bool
736 IRC_PING(CLIENT *Client, REQUEST *Req)
737 {
738         CLIENT *target, *from;
739
740         assert(Client != NULL);
741         assert(Req != NULL);
742
743         if (Req->argc < 1)
744                 return IRC_WriteStrClient(Client, ERR_NOORIGIN_MSG,
745                                           Client_ID(Client));
746 #ifdef STRICT_RFC
747         /* Don't ignore additional arguments when in "strict" mode */
748         if (Req->argc > 2)
749                  return IRC_WriteStrClient(Client, ERR_NEEDMOREPARAMS_MSG,
750                                            Client_ID(Client), Req->command);
751 #endif
752
753         if (Req->argc > 1) {
754                 /* A target has been specified ... */
755                 target = Client_Search(Req->argv[1]);
756
757                 if (!target || Client_Type(target) != CLIENT_SERVER)
758                         return IRC_WriteStrClient(Client, ERR_NOSUCHSERVER_MSG,
759                                         Client_ID(Client), Req->argv[1]);
760
761                 if (target != Client_ThisServer()) {
762                         /* Ok, we have to forward the PING */
763                         if (Client_Type(Client) == CLIENT_SERVER)
764                                 from = Client_Search(Req->prefix);
765                         else
766                                 from = Client;
767                         if (!from)
768                                 return IRC_WriteStrClient(Client,
769                                                 ERR_NOSUCHSERVER_MSG,
770                                                 Client_ID(Client), Req->prefix);
771
772                         return IRC_WriteStrClientPrefix(target, from,
773                                         "PING %s :%s", Req->argv[0],
774                                         Req->argv[1] );
775                 }
776         }
777
778         if (Client_Type(Client) == CLIENT_SERVER) {
779                 if (Req->prefix)
780                         from = Client_Search(Req->prefix);
781                 else
782                         from = Client;
783         } else
784                 from = Client_ThisServer();
785         if (!from)
786                 return IRC_WriteStrClient(Client, ERR_NOSUCHSERVER_MSG,
787                                         Client_ID(Client), Req->prefix);
788
789         Log(LOG_DEBUG, "Connection %d: got PING, sending PONG ...",
790             Client_Conn(Client));
791
792 #ifdef STRICT_RFC
793         return IRC_WriteStrClient(Client, "PONG %s :%s",
794                 Client_ID(from), Client_ID(Client));
795 #else
796         /* Some clients depend on the argument being returned in the PONG
797          * reply (not mentioned in any RFC, though) */
798         return IRC_WriteStrClient(Client, "PONG %s :%s",
799                 Client_ID(from), Req->argv[0]);
800 #endif
801 } /* IRC_PING */
802
803
804 /**
805  * Handler for the IRC "PONG" command.
806  *
807  * See RFC 2812, 3.7.3 "Pong message".
808  *
809  * @param Client        The client from which this command has been received.
810  * @param Req           Request structure with prefix and all parameters.
811  * @returns             CONNECTED or DISCONNECTED.
812  */
813 GLOBAL bool
814 IRC_PONG(CLIENT *Client, REQUEST *Req)
815 {
816         CLIENT *target, *from;
817         CONN_ID conn;
818 #ifndef STRICT_RFC
819         long auth_ping;
820 #endif
821         char *s;
822
823         assert(Client != NULL);
824         assert(Req != NULL);
825
826         /* Wrong number of arguments? */
827         if (Req->argc < 1) {
828                 if (Client_Type(Client) == CLIENT_USER)
829                         return IRC_WriteStrClient(Client, ERR_NOORIGIN_MSG,
830                                                   Client_ID(Client));
831                 else
832                         return CONNECTED;
833         }
834         if (Req->argc > 2) {
835                 if (Client_Type(Client) == CLIENT_USER)
836                         return IRC_WriteStrClient(Client,
837                                                   ERR_NEEDMOREPARAMS_MSG,
838                                                   Client_ID(Client),
839                                                   Req->command);
840                 else
841                         return CONNECTED;
842         }
843
844         /* Forward? */
845         if (Req->argc == 2 && Client_Type(Client) == CLIENT_SERVER) {
846                 target = Client_Search(Req->argv[0]);
847                 if (!target)
848                         return IRC_WriteStrClient(Client, ERR_NOSUCHSERVER_MSG,
849                                         Client_ID(Client), Req->argv[0]);
850
851                 from = Client_Search(Req->prefix);
852
853                 if (target != Client_ThisServer() && target != from) {
854                         /* Ok, we have to forward the message. */
855                         if (!from)
856                                 return IRC_WriteStrClient(Client,
857                                                 ERR_NOSUCHSERVER_MSG,
858                                                 Client_ID(Client), Req->prefix);
859
860                         if (Client_Type(Client_NextHop(target)) != CLIENT_SERVER)
861                                 s = Client_ID(from);
862                         else
863                                 s = Req->argv[0];
864                         return IRC_WriteStrClientPrefix(target, from,
865                                  "PONG %s :%s", s, Req->argv[1]);
866                 }
867         }
868
869         /* The connection timestamp has already been updated when the data has
870          * been read from so socket, so we don't need to update it here. */
871
872         conn = Client_Conn(Client);
873
874 #ifndef STRICT_RFC
875         /* Check authentication PING-PONG ... */
876         auth_ping = Conn_GetAuthPing(conn);
877         if (auth_ping) {
878                 LogDebug("AUTH PONG: waiting for token \"%ld\", got \"%s\" ...",
879                          auth_ping, Req->argv[0]);
880                 if (auth_ping == atoi(Req->argv[0])) {
881                         Conn_SetAuthPing(conn, 0);
882                         if (Client_Type(Client) == CLIENT_WAITAUTHPING)
883                                 Hello_User(Client);
884                 } else
885                         if (!IRC_WriteStrClient(Client,
886                                         "To connect, type /QUOTE PONG %ld",
887                                         auth_ping))
888                                 return DISCONNECTED;
889         }
890 #endif
891
892         if (Client_Type(Client) == CLIENT_SERVER && Conn_LastPing(conn) == 0) {
893                 Log(LOG_INFO,
894                     "Synchronization with \"%s\" done (connection %d): %ld seconds [%ld users, %ld channels]",
895                     Client_ID(Client), conn, time(NULL) - Conn_GetSignon(conn),
896                     Client_UserCount(), Channel_CountVisible(NULL));
897                 Conn_UpdatePing(conn);
898         } else
899                 LogDebug("Connection %d: received PONG. Lag: %ld seconds.",
900                          conn, time(NULL) - Conn_LastPing(conn));
901
902         return CONNECTED;
903 } /* IRC_PONG */
904
905
906 /**
907  * Initiate client registration.
908  *
909  * This function is called after the daemon received the required NICK and
910  * USER commands of a new client. If the daemon is compiled with support for
911  * PAM, the authentication sub-processs is forked; otherwise the global server
912  * password is checked.
913  *
914  * @param Client        The client logging in.
915  * @returns             CONNECTED or DISCONNECTED.
916  */
917 static bool
918 Hello_User(CLIENT * Client)
919 {
920 #ifdef PAM
921         int pipefd[2], result;
922         pid_t pid;
923 #endif
924         CONN_ID conn;
925
926         assert(Client != NULL);
927         conn = Client_Conn(Client);
928
929 #ifndef STRICT_RFC
930         if (Conf_AuthPing) {
931                 /* Did we receive the "auth PONG" already? */
932                 if (Conn_GetAuthPing(conn)) {
933                         Client_SetType(Client, CLIENT_WAITAUTHPING);
934                         LogDebug("Connection %d: Waiting for AUTH PONG ...", conn);
935                         return CONNECTED;
936                 }
937         }
938 #endif
939
940 #ifdef PAM
941         if (!Conf_PAM) {
942                 /* Don't do any PAM authentication at all, instead emulate
943                  * the beahiour of the daemon compiled without PAM support:
944                  * because there can't be any "server password", all
945                  * passwords supplied are classified as "wrong". */
946                 if(Client_Password(Client)[0] == '\0')
947                         return Hello_User_PostAuth(Client);
948                 Client_Reject(Client, "Non-empty password", false);
949                 return DISCONNECTED;
950         }
951
952         if (Conf_PAMIsOptional && strcmp(Client_Password(Client), "") == 0) {
953                 /* Clients are not required to send a password and to be PAM-
954                  * authenticated at all. If not, they won't become "identified"
955                  * and keep the "~" in their supplied user name.
956                  * Therefore it is sensible to either set Conf_PAMisOptional or
957                  * to enable IDENT lookups -- not both. */
958                 return Hello_User_PostAuth(Client);
959         }
960
961         /* Fork child process for PAM authentication; and make sure that the
962          * process timeout is set higher than the login timeout! */
963         pid = Proc_Fork(Conn_GetProcStat(conn), pipefd,
964                         cb_Read_Auth_Result, Conf_PongTimeout + 1);
965         if (pid > 0) {
966                 LogDebug("Authenticator for connection %d created (PID %d).",
967                          conn, pid);
968                 return CONNECTED;
969         } else {
970                 /* Sub process */
971                 Log_Init_Subprocess("Auth");
972                 Conn_CloseAllSockets(NONE);
973                 result = PAM_Authenticate(Client);
974                 if (write(pipefd[1], &result, sizeof(result)) != sizeof(result))
975                         Log_Subprocess(LOG_ERR,
976                                        "Failed to pipe result to parent!");
977                 Log_Exit_Subprocess("Auth");
978                 exit(0);
979         }
980 #else
981         /* Check global server password ... */
982         if (strcmp(Client_Password(Client), Conf_ServerPwd) != 0) {
983                 /* Bad password! */
984                 Client_Reject(Client, "Bad server password", false);
985                 return DISCONNECTED;
986         }
987         return Hello_User_PostAuth(Client);
988 #endif
989 }
990
991
992 #ifdef PAM
993
994 /**
995  * Read result of the authenticatior sub-process from pipe
996  *
997  * @param r_fd          File descriptor of the pipe.
998  * @param events        (ignored IO specification)
999  */
1000 static void
1001 cb_Read_Auth_Result(int r_fd, UNUSED short events)
1002 {
1003         CONN_ID conn;
1004         CLIENT *client;
1005         int result;
1006         size_t len;
1007         PROC_STAT *proc;
1008
1009         LogDebug("Auth: Got callback on fd %d, events %d", r_fd, events);
1010         conn = Conn_GetFromProc(r_fd);
1011         if (conn == NONE) {
1012                 /* Ops, none found? Probably the connection has already
1013                  * been closed!? We'll ignore that ... */
1014                 io_close(r_fd);
1015                 LogDebug("Auth: Got callback for unknown connection!?");
1016                 return;
1017         }
1018         proc = Conn_GetProcStat(conn);
1019         client = Conn_GetClient(conn);
1020
1021         /* Read result from pipe */
1022         len = Proc_Read(proc, &result, sizeof(result));
1023         Proc_Close(proc);
1024         if (len == 0)
1025                 return;
1026
1027         if (len != sizeof(result)) {
1028                 Log(LOG_CRIT, "Auth: Got malformed result!");
1029                 Client_Reject(client, "Internal error", false);
1030                 return;
1031         }
1032
1033         if (result == true) {
1034                 Client_SetUser(client, Client_OrigUser(client), true);
1035                 (void)Hello_User_PostAuth(client);
1036         } else
1037                 Client_Reject(client, "Bad password", false);
1038 }
1039
1040 #endif
1041
1042
1043 /**
1044  * Finish client registration.
1045  *
1046  * Introduce the new client to the network and send all "hello messages"
1047  * to it after authentication has been succeeded.
1048  *
1049  * @param Client        The client logging in.
1050  * @returns             CONNECTED or DISCONNECTED.
1051  */
1052 static bool
1053 Hello_User_PostAuth(CLIENT *Client)
1054 {
1055         assert(Client != NULL);
1056
1057         if (Class_HandleServerBans(Client) != CONNECTED)
1058                 return DISCONNECTED;
1059
1060         Introduce_Client(NULL, Client, CLIENT_USER);
1061
1062         if (!IRC_WriteStrClient
1063             (Client, RPL_WELCOME_MSG, Client_ID(Client), Client_Mask(Client)))
1064                 return false;
1065         if (!IRC_WriteStrClient
1066             (Client, RPL_YOURHOST_MSG, Client_ID(Client),
1067              Client_ID(Client_ThisServer()), PACKAGE_VERSION, TARGET_CPU,
1068              TARGET_VENDOR, TARGET_OS))
1069                 return false;
1070         if (!IRC_WriteStrClient
1071             (Client, RPL_CREATED_MSG, Client_ID(Client), NGIRCd_StartStr))
1072                 return false;
1073         if (!IRC_WriteStrClient
1074             (Client, RPL_MYINFO_MSG, Client_ID(Client),
1075              Client_ID(Client_ThisServer()), PACKAGE_VERSION, USERMODES,
1076              CHANMODES))
1077                 return false;
1078
1079         /* Features supported by this server (005 numeric, ISUPPORT),
1080          * see <http://www.irc.org/tech_docs/005.html> for details. */
1081         if (!IRC_Send_ISUPPORT(Client))
1082                 return DISCONNECTED;
1083
1084         if (!IRC_Send_LUSERS(Client))
1085                 return DISCONNECTED;
1086         if (!IRC_Show_MOTD(Client))
1087                 return DISCONNECTED;
1088
1089         /* Suspend the client for a second ... */
1090         IRC_SetPenalty(Client, 1);
1091
1092         return CONNECTED;
1093 }
1094
1095
1096 /**
1097  * Kill all users with a specific nick name in the network.
1098  *
1099  * @param Nick          Nick name.
1100  * @param Reason        Reason for the KILL.
1101  */
1102 static void
1103 Kill_Nick(char *Nick, char *Reason)
1104 {
1105         REQUEST r;
1106
1107         assert (Nick != NULL);
1108         assert (Reason != NULL);
1109
1110         r.prefix = NULL;
1111         r.argv[0] = Nick;
1112         r.argv[1] = Reason;
1113         r.argc = 2;
1114
1115         Log(LOG_ERR, "User(s) with nick \"%s\" will be disconnected: %s",
1116             Nick, Reason);
1117
1118         IRC_KILL(Client_ThisServer(), &r);
1119 } /* Kill_Nick */
1120
1121
1122 /**
1123  * Introduce a new user or service client in the network.
1124  *
1125  * @param From          Remote server introducing the client or NULL (local).
1126  * @param Client        New client.
1127  * @param Type          Type of the client (CLIENT_USER or CLIENT_SERVICE).
1128  */
1129 static void
1130 Introduce_Client(CLIENT *From, CLIENT *Client, int Type)
1131 {
1132         /* Set client type (user or service) */
1133         Client_SetType(Client, Type);
1134
1135         if (From) {
1136                 if (Conf_IsService(Conf_GetServer(Client_Conn(From)),
1137                                    Client_ID(Client)))
1138                         Client_SetType(Client, CLIENT_SERVICE);
1139                 LogDebug("%s \"%s\" (+%s) registered (via %s, on %s, %d hop%s).",
1140                          Client_TypeText(Client), Client_Mask(Client),
1141                          Client_Modes(Client), Client_ID(From),
1142                          Client_ID(Client_Introducer(Client)),
1143                          Client_Hops(Client), Client_Hops(Client) > 1 ? "s": "");
1144         } else {
1145                 Log(LOG_NOTICE, "%s \"%s\" registered (connection %d).",
1146                     Client_TypeText(Client), Client_Mask(Client),
1147                     Client_Conn(Client));
1148                 Log_ServerNotice('c', "Client connecting: %s (%s@%s) [%s] - %s",
1149                                  Client_ID(Client), Client_User(Client),
1150                                  Client_Hostname(Client),
1151                                  Conn_IPA(Client_Conn(Client)),
1152                                  Client_TypeText(Client));
1153         }
1154
1155         /* Inform other servers */
1156         IRC_WriteStrServersPrefixFlag_CB(From,
1157                                 From != NULL ? From : Client_ThisServer(),
1158                                 '\0', cb_introduceClient, (void *)Client);
1159 } /* Introduce_Client */
1160
1161
1162 /**
1163  * Introduce a new user or service client to a remote server.
1164  *
1165  * This function differentiates between RFC1459 and RFC2813 server links and
1166  * generates the appropriate commands to register the new user or service.
1167  *
1168  * @param To            The remote server to inform.
1169  * @param Prefix        Prefix for the generated commands.
1170  * @param data          CLIENT structure of the new client.
1171  */
1172 static void
1173 cb_introduceClient(CLIENT *To, CLIENT *Prefix, void *data)
1174 {
1175         CLIENT *c = (CLIENT *)data;
1176         CONN_ID conn;
1177         char *modes, *user, *host;
1178
1179         modes = Client_Modes(c);
1180         user = Client_User(c) ? Client_User(c) : "-";
1181         host = Client_Hostname(c) ? Client_Hostname(c) : "-";
1182
1183         conn = Client_Conn(To);
1184         if (Conn_Options(conn) & CONN_RFC1459) {
1185                 /* RFC 1459 mode: separate NICK and USER commands */
1186                 Conn_WriteStr(conn, "NICK %s :%d", Client_ID(c),
1187                               Client_Hops(c) + 1);
1188                 Conn_WriteStr(conn, ":%s USER %s %s %s :%s",
1189                               Client_ID(c), user, host,
1190                               Client_ID(Client_Introducer(c)), Client_Info(c));
1191                 if (modes[0])
1192                         Conn_WriteStr(conn, ":%s MODE %s +%s",
1193                                       Client_ID(c), Client_ID(c), modes);
1194         } else {
1195                 /* RFC 2813 mode: one combined NICK or SERVICE command */
1196                 if (Client_Type(c) == CLIENT_SERVICE
1197                     && strchr(Client_Flags(To), 'S'))
1198                         IRC_WriteStrClientPrefix(To, Prefix,
1199                                          "SERVICE %s %d * +%s %d :%s",
1200                                          Client_Mask(c),
1201                                          Client_MyToken(Client_Introducer(c)),
1202                                          Client_Modes(c), Client_Hops(c) + 1,
1203                                          Client_Info(c));
1204                 else
1205                         IRC_WriteStrClientPrefix(To, Prefix,
1206                                          "NICK %s %d %s %s %d +%s :%s",
1207                                          Client_ID(c), Client_Hops(c) + 1,
1208                                          user, host,
1209                                          Client_MyToken(Client_Introducer(c)),
1210                                          modes, Client_Info(c));
1211         }
1212 } /* cb_introduceClient */
1213
1214
1215 /* -eof- */