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