Fix inverted test in previous commit.
[ircu2.10.12-pk.git] / ircd / s_auth.c
1 /************************************************************************
2  *   IRC - Internet Relay Chat, src/s_auth.c
3  *   Copyright (C) 1992 Darren Reed
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 1, or (at your option)
8  *   any later version.
9  *
10  *   This program is distributed in the hope that it will be useful,
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *   GNU General Public License for more details.
14  *
15  *   You should have received a copy of the GNU General Public License
16  *   along with this program; if not, write to the Free Software
17  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  *
19  * Changes:
20  *   July 6, 1999 - Rewrote most of the code here. When a client connects
21  *     to the server and passes initial socket validation checks, it
22  *     is owned by this module (auth) which returns it to the rest of the
23  *     server when dns and auth queries are finished. Until the client is
24  *     released, the server does not know it exists and does not process
25  *     any messages from it.
26  *     --Bleep  Thomas Helvey <tomh@inxpress.net>
27  *
28  *  December 26, 2005 - Rewrite the flag handling and integrate that with
29  *     an IRCnet-style IAuth protocol.
30  *     -- Michael Poole
31  */
32 /** @file
33  * @brief Implementation of DNS and ident lookups.
34  * @version $Id$
35  */
36 #include "config.h"
37
38 #include "s_auth.h"
39 #include "class.h"
40 #include "client.h"
41 #include "IPcheck.h"
42 #include "ircd.h"
43 #include "ircd_alloc.h"
44 #include "ircd_chattr.h"
45 #include "ircd_events.h"
46 #include "ircd_features.h"
47 #include "ircd_log.h"
48 #include "ircd_osdep.h"
49 #include "ircd_reply.h"
50 #include "ircd_snprintf.h"
51 #include "ircd_string.h"
52 #include "list.h"
53 #include "msg.h"        /* for MAXPARA */
54 #include "numeric.h"
55 #include "querycmds.h"
56 #include "random.h"
57 #include "res.h"
58 #include "s_bsd.h"
59 #include "s_conf.h"
60 #include "s_debug.h"
61 #include "s_misc.h"
62 #include "s_user.h"
63 #include "send.h"
64
65 #include <errno.h>
66 #include <string.h>
67 #include <stdlib.h>
68 #include <unistd.h>
69 #include <fcntl.h>
70 #include <sys/socket.h>
71 #include <sys/ioctl.h>
72
73 /** Pending operations during registration. */
74 enum AuthRequestFlag {
75     AR_AUTH_PENDING,    /**< ident connecting or waiting for response */
76     AR_DNS_PENDING,     /**< dns request sent, waiting for response */
77     AR_CAP_PENDING,     /**< in middle of CAP negotiations */
78     AR_NEEDS_PONG,      /**< user has not PONGed */
79     AR_NEEDS_USER,      /**< user must send USER command */
80     AR_NEEDS_NICK,      /**< user must send NICK command */
81     AR_LAST_SCAN = AR_NEEDS_NICK, /**< maximum flag to scan through */
82     AR_IAUTH_PENDING,   /**< iauth request sent, waiting for response */
83     AR_IAUTH_HURRY,     /**< we told iauth to hurry up */
84     AR_IAUTH_USERNAME,  /**< iauth sent a username (preferred or forced) */
85     AR_IAUTH_FUSERNAME, /**< iauth sent a forced username */
86     AR_PASSWORD_CHECKED, /**< client password already checked */
87     AR_NUM_FLAGS
88 };
89
90 DECLARE_FLAGSET(AuthRequestFlags, AR_NUM_FLAGS);
91
92 /** Stores registration state of a client. */
93 struct AuthRequest {
94   struct AuthRequest* next;       /**< linked list node ptr */
95   struct AuthRequest* prev;       /**< linked list node ptr */
96   struct Client*      client;     /**< pointer to client struct for request */
97   struct irc_sockaddr local;      /**< local endpoint address */
98   struct irc_in_addr  original;   /**< original client IP address */
99   struct Socket       socket;     /**< socket descriptor for auth queries */
100   struct Timer        timeout;    /**< timeout timer for ident and dns queries */
101   struct AuthRequestFlags flags;  /**< current state of request */
102   unsigned int        cookie;     /**< cookie the user must PONG */
103   unsigned short      port;       /**< client's remote port number */
104 };
105
106 /** Array of message text (with length) pairs for AUTH status
107  * messages.  Indexed using #ReportType.
108  */
109 static struct {
110   const char*  message;
111   unsigned int length;
112 } HeaderMessages [] = {
113 #define MSG(STR) { STR, sizeof(STR) - 1 }
114   MSG("NOTICE AUTH :*** Looking up your hostname\r\n"),
115   MSG("NOTICE AUTH :*** Found your hostname\r\n"),
116   MSG("NOTICE AUTH :*** Couldn't look up your hostname\r\n"),
117   MSG("NOTICE AUTH :*** Checking Ident\r\n"),
118   MSG("NOTICE AUTH :*** Got ident response\r\n"),
119   MSG("NOTICE AUTH :*** No ident response\r\n"),
120   MSG("NOTICE AUTH :*** \r\n"),
121   MSG("NOTICE AUTH :*** Your forward and reverse DNS do not match, "
122     "ignoring hostname.\r\n"),
123   MSG("NOTICE AUTH :*** Invalid hostname\r\n")
124 #undef MSG
125 };
126
127 /** Enum used to index messages in the HeaderMessages[] array. */
128 typedef enum {
129   REPORT_DO_DNS,
130   REPORT_FIN_DNS,
131   REPORT_FAIL_DNS,
132   REPORT_DO_ID,
133   REPORT_FIN_ID,
134   REPORT_FAIL_ID,
135   REPORT_FAIL_IAUTH,
136   REPORT_IP_MISMATCH,
137   REPORT_INVAL_DNS
138 } ReportType;
139
140 /** Sends response \a r (from #ReportType) to client \a c. */
141 #define sendheader(c, r) \
142    send(cli_fd(c), HeaderMessages[(r)].message, HeaderMessages[(r)].length, 0)
143
144 /** Enumeration of IAuth connection flags. */
145 enum IAuthFlag
146 {
147   IAUTH_BLOCKED,                        /**< socket buffer full */
148   IAUTH_CLOSING,                        /**< candidate to be disposed */
149   /* The following flags are controlled by iauth's "O" options command. */
150   IAUTH_ADDLINFO,                       /**< Send additional info
151                                          * (password and username). */
152   IAUTH_FIRST_OPTION = IAUTH_ADDLINFO,  /**< First flag that is a policy option. */
153   IAUTH_REQUIRED,                       /**< IAuth completion required for registration. */
154   IAUTH_TIMEOUT,                        /**< Refuse new connections if IAuth is behind. */
155   IAUTH_EXTRAWAIT,                      /**< Give IAuth extra time to answer. */
156   IAUTH_UNDERNET,                       /**< Enable Undernet extensions. */
157   IAUTH_LAST_FLAG                       /**< total number of flags */
158 };
159 /** Declare a bitset structure indexed by IAuthFlag. */
160 DECLARE_FLAGSET(IAuthFlags, IAUTH_LAST_FLAG);
161
162 /** Describes state of an IAuth connection. */
163 struct IAuth {
164   struct MsgQ i_sendQ;                  /**< messages queued to send */
165   struct Socket i_socket;               /**< main socket to iauth */
166   struct Socket i_stderr;               /**< error socket for iauth */
167   struct IAuthFlags i_flags;            /**< connection state/status/flags */
168   uint64_t i_recvB;                     /**< bytes received */
169   uint64_t i_sendB;                     /**< bytes sent */
170   time_t started;                       /**< time that this instance was started */
171   unsigned int i_recvM;                 /**< messages received */
172   unsigned int i_sendM;                 /**< messages sent */
173   unsigned int i_count;                 /**< characters used in i_buffer */
174   unsigned int i_errcount;              /**< characters used in i_errbuf */
175   int i_debug;                          /**< debug level */
176   char i_buffer[BUFSIZE+1];             /**< partial unprocessed line from server */
177   char i_errbuf[BUFSIZE+1];             /**< partial unprocessed error line */
178   char *i_version;                      /**< iauth version string */
179   struct SLink *i_config;               /**< configuration string list */
180   struct SLink *i_stats;                /**< statistics string list */
181   char **i_argv;                        /**< argument list */
182 };
183
184 /** Return whether flag \a flag is set on \a iauth. */
185 #define IAuthHas(iauth, flag) ((iauth) && FlagHas(&(iauth)->i_flags, flag))
186 /** Set flag \a flag on \a iauth. */
187 #define IAuthSet(iauth, flag) FlagSet(&(iauth)->i_flags, flag)
188 /** Clear flag \a flag from \a iauth. */
189 #define IAuthClr(iauth, flag) FlagClr(&(iauth)->i_flags, flag)
190 /** Get connected flag for \a iauth. */
191 #define i_GetConnected(iauth) ((iauth) && s_fd(i_socket(iauth)) > -1)
192
193 /** Return socket event generator for \a iauth. */
194 #define i_socket(iauth) (&(iauth)->i_socket)
195 /** Return stderr socket for \a iauth. */
196 #define i_stderr(iauth) (&(iauth)->i_stderr)
197 /** Return outbound message queue for \a iauth. */
198 #define i_sendQ(iauth) (&(iauth)->i_sendQ)
199 /** Return debug level for \a iauth. */
200 #define i_debug(iauth) ((iauth)->i_debug)
201
202 /** Active instance of IAuth. */
203 struct IAuth *iauth;
204
205 static void iauth_sock_callback(struct Event *ev);
206 static void iauth_stderr_callback(struct Event *ev);
207 static int sendto_iauth(struct Client *cptr, const char *format, ...);
208 static int preregister_user(struct Client *cptr);
209 typedef int (*iauth_cmd_handler)(struct IAuth *iauth, struct Client *cli,
210                                  int parc, char **params);
211
212 /** Set username for user associated with \a auth.
213  * @param[in] auth Client authorization request to work on.
214  * @return Zero if client is kept, CPTR_KILLED if client rejected.
215  */
216 static int auth_set_username(struct AuthRequest *auth)
217 {
218   struct Client *sptr = auth->client;
219   struct User   *user = cli_user(sptr);
220   char *d;
221   char *s;
222   int   rlen = USERLEN;
223   int   killreason;
224   short upper = 0;
225   short lower = 0;
226   short pos = 0;
227   short leadcaps = 0;
228   short other = 0;
229   short digits = 0;
230   short digitgroups = 0;
231   char  ch;
232   char  last;
233
234   if (FlagHas(&auth->flags, AR_IAUTH_USERNAME))
235   {
236       ircd_strncpy(cli_user(sptr)->username, cli_username(sptr), USERLEN);
237   }
238   else
239   {
240     /* Copy username from source to destination.  Since they may be the
241      * same, and we may prefix with a '~', use a buffer character (ch)
242      * to hold the next character to copy.
243      */
244     s = IsIdented(sptr) ? cli_username(sptr) : user->username;
245     last = *s++;
246     d = user->username;
247     if (HasFlag(sptr, FLAG_DOID) && !IsIdented(sptr))
248     {
249       *d++ = '~';
250       --rlen;
251     }
252     while (last && !IsCntrl(last) && rlen--)
253     {
254       ch = *s++;
255       *d++ = IsUserChar(last) ? last : '_';
256       last = (ch != '~') ? ch : '_';
257     }
258     *d = 0;
259   }
260
261   /* If username is empty or just ~, reject. */
262   if ((user->username[0] == '\0')
263       || ((user->username[0] == '~') && (user->username[1] == '\0')))
264     return exit_client(sptr, sptr, &me, "USER: Bogus userid.");
265
266   /* Check for K- or G-line. */
267   killreason = find_kill(sptr);
268   if (killreason) {
269     ServerStats->is_ref++;
270     return exit_client(sptr, sptr, &me,
271                        (killreason == -1 ? "K-lined" : "G-lined"));
272   }
273
274   if (!FlagHas(&auth->flags, AR_IAUTH_FUSERNAME))
275   {
276     /* Check for mixed case usernames, meaning probably hacked.  Jon2 3-94
277      * Explanations of rules moved to where it is checked     Entrope 2-06
278      */
279     s = d = user->username + (user->username[0] == '~');
280     for (last = '\0';
281          (ch = *d++) != '\0';
282          pos++, last = ch)
283     {
284       if (IsLower(ch))
285       {
286         lower++;
287       }
288       else if (IsUpper(ch))
289       {
290         upper++;
291         /* Accept caps as leading if we haven't seen lower case or digits yet. */
292         if ((leadcaps || pos == 0) && !lower && !digits)
293           leadcaps++;
294       }
295       else if (IsDigit(ch))
296       {
297         digits++;
298         if (pos == 0 || !IsDigit(last))
299         {
300           digitgroups++;
301           /* If more than two groups of digits, reject. */
302           if (digitgroups > 2)
303             goto badid;
304         }
305       }
306       else if (ch == '-' || ch == '_' || ch == '.')
307       {
308         other++;
309         /* If -_. exist at start, consecutively, or more than twice, reject. */
310         if (pos == 0 || last == '-' || last == '_' || last == '.' || other > 2)
311           goto badid;
312       }
313       else /* All other punctuation is rejected. */
314         goto badid;
315     }
316
317     /* If mixed case, first must be capital, but no more than three;
318      * but if three capitals, they must all be leading. */
319     if (lower && upper && (!leadcaps || leadcaps > 3 ||
320                            (upper > 2 && upper > leadcaps)))
321       goto badid;
322     /* If two different groups of digits, one must be either at the
323      * start or end. */
324     if (digitgroups == 2 && !(IsDigit(s[0]) || IsDigit(ch)))
325       goto badid;
326     /* Must have at least one letter. */
327     if (!lower && !upper)
328       goto badid;
329     /* Final character must not be punctuation. */
330     if (!IsAlnum(last))
331       goto badid;
332   }
333
334   return 0;
335
336 badid:
337   /* If we confirmed their username, and it is what they claimed,
338    * accept it. */
339   if (IsIdented(sptr) && !strcmp(cli_username(sptr), user->username))
340     return 0;
341
342   ServerStats->is_ref++;
343   send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
344              ":Your username is invalid.");
345   send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
346              ":Connect with your real username, in lowercase.");
347   send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
348              ":If your mail address were foo@bar.com, your username "
349              "would be foo.");
350   return exit_client(sptr, sptr, &me, "USER: Bad username");
351 }
352
353 /** Check whether an authorization request is complete.
354  * This means that no flags from 0 to #AR_LAST_SCAN are set on \a auth.
355  * If #AR_IAUTH_PENDING is set, optionally go into "hurry" state.  If
356  * 0 through #AR_LAST_SCAN and #AR_IAUTH_PENDING are all clear,
357  * destroy \a auth, clear the password, set the username, and register
358  * the client.
359  * @param[in] auth Authorization request to check.
360  * @return Zero if client is kept, CPTR_KILLED if client rejected.
361  */
362 static int check_auth_finished(struct AuthRequest *auth)
363 {
364   enum AuthRequestFlag flag;
365   int res;
366
367   /* Check non-iauth registration blocking flags. */
368   for (flag = 0; flag <= AR_LAST_SCAN; ++flag)
369     if (FlagHas(&auth->flags, flag))
370     {
371       Debug((DEBUG_INFO, "Auth %p [%d] still has flag %d", auth,
372              cli_fd(auth->client), flag));
373       return 0;
374     }
375
376   /* If appropriate, do preliminary assignment to connection class. */
377   if (IsUserPort(auth->client)
378       && !FlagHas(&auth->flags, AR_IAUTH_HURRY)
379       && preregister_user(auth->client))
380     return CPTR_KILLED;
381
382   /* If we have not done so, check client password.  Do this as soon
383    * as possible so that iauth's challenge/response (which uses PASS
384    * for responses) is not confused with the client's password.
385    */
386   if (IsUserPort(auth->client)
387       && !FlagHas(&auth->flags, AR_PASSWORD_CHECKED))
388   {
389     struct ConfItem *aconf;
390
391     aconf = cli_confs(auth->client)->value.aconf;
392     if (aconf
393         && !EmptyString(aconf->passwd)
394         && strcmp(cli_passwd(auth->client), aconf->passwd))
395     {
396       ServerStats->is_ref++;
397       send_reply(auth->client, ERR_PASSWDMISMATCH);
398       return exit_client(auth->client, auth->client, &me, "Bad Password");
399     }
400     FlagSet(&auth->flags, AR_PASSWORD_CHECKED);
401   }
402
403   /* Check if iauth is done. */
404   if (FlagHas(&auth->flags, AR_IAUTH_PENDING))
405   {
406     /* Switch auth request to hurry-up state. */
407     if (!FlagHas(&auth->flags, AR_IAUTH_HURRY))
408     {
409       /* Set "hurry" flag in auth request. */
410       FlagSet(&auth->flags, AR_IAUTH_HURRY);
411
412       /* If iauth wants it, send notification. */
413       if (IAuthHas(iauth, IAUTH_UNDERNET))
414         sendto_iauth(auth->client, "H %s", get_client_class(auth->client));
415
416       /* If iauth wants it, give client more time. */
417       if (IAuthHas(iauth, IAUTH_EXTRAWAIT))
418         cli_firsttime(auth->client) = CurrentTime;
419     }
420
421     Debug((DEBUG_INFO, "Auth %p [%d] still has flag %d", auth,
422            cli_fd(auth->client), AR_IAUTH_PENDING));
423     return 0;
424   }
425   else
426     FlagSet(&auth->flags, AR_IAUTH_HURRY);
427
428   destroy_auth_request(auth);
429   if (IsUserPort(auth->client))
430   {
431     memset(cli_passwd(auth->client), 0, sizeof(cli_passwd(auth->client)));
432     res = auth_set_username(auth);
433     if (res == 0)
434       res = register_user(auth->client, auth->client);
435   }
436   else
437     res = 0;
438   MyFree(auth);
439   return res;
440 }
441
442 /** Verify that a hostname is valid, i.e., only contains characters
443  * valid for a hostname and that a hostname is not too long.
444  * @param host Hostname to check.
445  * @param maxlen Maximum length of hostname, not including NUL terminator.
446  * @return Non-zero if the hostname is valid.
447  */
448 static int
449 auth_verify_hostname(const char *host, int maxlen)
450 {
451   int i;
452
453   /* Walk through the host name */
454   for (i = 0; host[i]; i++)
455     /* If it's not a hostname character or if it's too long, return false */
456     if (!IsHostChar(host[i]) || i >= maxlen)
457       return 0;
458
459   return 1; /* it's a valid hostname */
460 }
461
462 /** Assign a client to a connection class.
463  * @param[in] cptr Client to assign to a class.
464  * @return Zero if client is kept, CPTR_KILLED if rejected.
465  */
466 static int preregister_user(struct Client *cptr)
467 {
468   static time_t last_too_many1;
469   static time_t last_too_many2;
470
471   ircd_strncpy(cli_user(cptr)->host, cli_sockhost(cptr), HOSTLEN);
472   ircd_strncpy(cli_user(cptr)->realhost, cli_sockhost(cptr), HOSTLEN);
473
474   switch (conf_check_client(cptr))
475   {
476   case ACR_OK:
477     break;
478   case ACR_NO_AUTHORIZATION:
479     sendto_opmask_butone(0, SNO_UNAUTH, "Unauthorized connection from %s.",
480                          get_client_name(cptr, HIDE_IP));
481     ++ServerStats->is_ref;
482     return exit_client(cptr, cptr, &me,
483                        "No Authorization - use another server");
484   case ACR_TOO_MANY_IN_CLASS:
485     sendto_opmask_butone_ratelimited(0, SNO_TOOMANY, &last_too_many1,
486                                      "Too many connections in class %s for %s.",
487                                      get_client_class(cptr),
488                                      get_client_name(cptr, SHOW_IP));
489     ++ServerStats->is_ref;
490     return exit_client(cptr, cptr, &me,
491                        "Sorry, your connection class is full - try "
492                        "again later or try another server");
493   case ACR_TOO_MANY_FROM_IP:
494     sendto_opmask_butone_ratelimited(0, SNO_TOOMANY, &last_too_many2,
495                                      "Too many connections from same IP for %s.",
496                                      get_client_name(cptr, SHOW_IP));
497     ++ServerStats->is_ref;
498     return exit_client(cptr, cptr, &me,
499                        "Too many connections from your host");
500   case ACR_ALREADY_AUTHORIZED:
501     /* Can this ever happen? */
502   case ACR_BAD_SOCKET:
503     ++ServerStats->is_ref;
504     IPcheck_connect_fail(cptr);
505     return exit_client(cptr, cptr, &me, "Unknown error -- Try again");
506   }
507   return 0;
508 }
509
510 /** Send the ident server a query giving "theirport , ourport". The
511  * write is only attempted *once* so it is deemed to be a fail if the
512  * entire write doesn't write all the data given.  This shouldn't be a
513  * problem since the socket should have a write buffer far greater
514  * than this message to store it in should problems arise. -avalon
515  * @param[in] auth The request to send.
516  */
517 static void send_auth_query(struct AuthRequest* auth)
518 {
519   char               authbuf[32];
520   unsigned int       count;
521
522   assert(0 != auth);
523
524   ircd_snprintf(0, authbuf, sizeof(authbuf), "%hu , %hu\r\n",
525                 auth->port, auth->local.port);
526
527   if (IO_SUCCESS != os_send_nonb(s_fd(&auth->socket), authbuf, strlen(authbuf), &count)) {
528     close(s_fd(&auth->socket));
529     socket_del(&auth->socket);
530     s_fd(&auth->socket) = -1;
531     ++ServerStats->is_abad;
532     if (IsUserPort(auth->client))
533       sendheader(auth->client, REPORT_FAIL_ID);
534     FlagClr(&auth->flags, AR_AUTH_PENDING);
535     check_auth_finished(auth);
536   }
537 }
538
539 /** Enum used to index ident reply fields in a human-readable way. */
540 enum IdentReplyFields {
541   IDENT_PORT_NUMBERS,
542   IDENT_REPLY_TYPE,
543   IDENT_OS_TYPE,
544   IDENT_INFO,
545   USERID_TOKEN_COUNT
546 };
547
548 /** Parse an ident reply line and extract the userid from it.
549  * @param[in] reply The ident reply line.
550  * @return The userid, or NULL on parse failure.
551  */
552 static char* check_ident_reply(char* reply)
553 {
554   char* token;
555   char* end;
556   char* vector[USERID_TOKEN_COUNT];
557   int count = token_vector(reply, ':', vector, USERID_TOKEN_COUNT);
558
559   if (USERID_TOKEN_COUNT != count)
560     return 0;
561   /*
562    * second token is the reply type
563    */
564   token = vector[IDENT_REPLY_TYPE];
565   if (EmptyString(token))
566     return 0;
567
568   while (IsSpace(*token))
569     ++token;
570
571   if (0 != strncmp(token, "USERID", 6))
572     return 0;
573
574   /*
575    * third token is the os type
576    */
577   token = vector[IDENT_OS_TYPE];
578   if (EmptyString(token))
579     return 0;
580   while (IsSpace(*token))
581    ++token;
582
583   /*
584    * Unless "OTHER" is specified as the operating system
585    * type, the server is expected to return the "normal"
586    * user identification of the owner of this connection.
587    * "Normal" in this context may be taken to mean a string
588    * of characters which uniquely identifies the connection
589    * owner such as a user identifier assigned by the system
590    * administrator and used by such user as a mail
591    * identifier, or as the "user" part of a user/password
592    * pair used to gain access to system resources.  When an
593    * operating system is specified (e.g., anything but
594    * "OTHER"), the user identifier is expected to be in a
595    * more or less immediately useful form - e.g., something
596    * that could be used as an argument to "finger" or as a
597    * mail address.
598    */
599   if (0 == strncmp(token, "OTHER", 5))
600     return 0;
601   /*
602    * fourth token is the username
603    */
604   token = vector[IDENT_INFO];
605   if (EmptyString(token))
606     return 0;
607   while (IsSpace(*token))
608     ++token;
609   /*
610    * look for the end of the username, terminators are '\0, @, <SPACE>, :'
611    */
612   for (end = token; *end; ++end) {
613     if (IsSpace(*end) || '@' == *end || ':' == *end)
614       break;
615   }
616   *end = '\0';
617   return token;
618 }
619
620 /** Read the reply (if any) from the ident server we connected to.  We
621  * only give it one shot, if the reply isn't good the first time fail
622  * the authentication entirely. --Bleep
623  * @param[in] auth The request to read.
624  */
625 static void read_auth_reply(struct AuthRequest* auth)
626 {
627   char*        username = 0;
628   unsigned int len;
629   /*
630    * rfc1453 sez we MUST accept 512 bytes
631    */
632   char   buf[BUFSIZE + 1];
633
634   assert(0 != auth);
635   assert(0 != auth->client);
636   assert(auth == cli_auth(auth->client));
637
638   if (IO_SUCCESS == os_recv_nonb(s_fd(&auth->socket), buf, BUFSIZE, &len)) {
639     buf[len] = '\0';
640     Debug((DEBUG_INFO, "Auth %p [%d] reply: %s", auth, cli_fd(auth->client), buf));
641     username = check_ident_reply(buf);
642     Debug((DEBUG_INFO, "Username: %s", username));
643   }
644
645   Debug((DEBUG_INFO, "Deleting auth [%d] socket %p", auth, cli_fd(auth->client)));
646   close(s_fd(&auth->socket));
647   socket_del(&auth->socket);
648   s_fd(&auth->socket) = -1;
649
650   if (EmptyString(username)) {
651     if (IsUserPort(auth->client))
652       sendheader(auth->client, REPORT_FAIL_ID);
653     ++ServerStats->is_abad;
654   } else {
655     if (IsUserPort(auth->client))
656       sendheader(auth->client, REPORT_FIN_ID);
657     ++ServerStats->is_asuc;
658     if (!FlagHas(&auth->flags, AR_IAUTH_USERNAME)) {
659       ircd_strncpy(cli_username(auth->client), username, USERLEN);
660       SetGotId(auth->client);
661     }
662     if (IAuthHas(iauth, IAUTH_UNDERNET))
663       sendto_iauth(auth->client, "u %s", username);
664   }
665
666   FlagClr(&auth->flags, AR_AUTH_PENDING);
667   check_auth_finished(auth);
668 }
669
670 /** Handle socket I/O activity.
671  * @param[in] ev A socket event whos associated data is the active
672  *   struct AuthRequest.
673  */
674 static void auth_sock_callback(struct Event* ev)
675 {
676   struct AuthRequest* auth;
677
678   assert(0 != ev_socket(ev));
679   assert(0 != s_data(ev_socket(ev)));
680
681   auth = (struct AuthRequest*) s_data(ev_socket(ev));
682
683   switch (ev_type(ev)) {
684   case ET_DESTROY: /* being destroyed */
685     break;
686
687   case ET_CONNECT: /* socket connection completed */
688     Debug((DEBUG_INFO, "Connection completed for auth %p [%d]; sending query",
689            auth, cli_fd(auth->client)));
690     socket_state(&auth->socket, SS_CONNECTED);
691     send_auth_query(auth);
692     break;
693
694   case ET_READ: /* socket is readable */
695   case ET_EOF: /* end of file on socket */
696   case ET_ERROR: /* error on socket */
697     Debug((DEBUG_INFO, "Auth socket %p [%p] readable", auth, ev_socket(ev)));
698     read_auth_reply(auth);
699     break;
700
701   default:
702     assert(0 && "Unrecognized event in auth_socket_callback().");
703     break;
704   }
705 }
706
707 /** Stop an auth request completely.
708  * @param[in] auth The struct AuthRequest to cancel.
709  */
710 void destroy_auth_request(struct AuthRequest* auth)
711 {
712   Debug((DEBUG_INFO, "Deleting auth request for %p", auth->client));
713
714   if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
715     delete_resolver_queries(auth);
716   }
717
718   if (-1 < s_fd(&auth->socket)) {
719     close(s_fd(&auth->socket));
720     socket_del(&auth->socket);
721     s_fd(&auth->socket) = -1;
722   }
723
724   if (t_active(&auth->timeout))
725     timer_del(&auth->timeout);
726   cli_auth(auth->client) = NULL;
727 }
728
729 /** Handle a 'ping' (authorization) timeout for a client.
730  * @param[in] cptr The client whose session authorization has timed out.
731  * @return Zero if client is kept, CPTR_KILLED if client rejected.
732  */
733 int auth_ping_timeout(struct Client *cptr)
734 {
735   struct AuthRequest *auth;
736   enum AuthRequestFlag flag;
737
738   auth = cli_auth(cptr);
739
740   /* Check whether the auth request is gone (more likely, it never
741    * existed, as in an outbound server connection). */
742   if (!auth)
743       return exit_client_msg(cptr, cptr, &me, "Registration Timeout");
744
745   /* Check for a user-controlled timeout. */
746   for (flag = 0; flag <= AR_LAST_SCAN; ++flag) {
747     if (FlagHas(&auth->flags, flag)) {
748       /* Display message if they have sent a NICK and a USER but no
749        * nospoof PONG.
750        */
751       if (*(cli_name(cptr)) && cli_user(cptr) && *(cli_user(cptr))->username) {
752         send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
753                    ":Your client may not be compatible with this server.");
754         send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
755                    ":Compatible clients are available at %s",
756                    feature_str(FEAT_URL_CLIENTS));
757       }
758       return exit_client_msg(cptr, cptr, &me, "Registration Timeout");
759     }
760   }
761
762   /* Check for iauth timeout. */
763   if (FlagHas(&auth->flags, AR_IAUTH_PENDING)) {
764     sendto_iauth(cptr, "T");
765     if (IAuthHas(iauth, IAUTH_REQUIRED)) {
766       sendheader(cptr, REPORT_FAIL_IAUTH);
767       return exit_client_msg(cptr, cptr, &me, "Authorization Timeout");
768     }
769     FlagClr(&auth->flags, AR_IAUTH_PENDING);
770     return check_auth_finished(auth);
771   }
772
773   assert(0 && "Unexpectedly reached end of auth_ping_timeout()");
774   return 0;
775 }
776
777 /** Timeout a given auth request.
778  * @param[in] ev A timer event whose associated data is the expired
779  *   struct AuthRequest.
780  */
781 static void auth_timeout_callback(struct Event* ev)
782 {
783   struct AuthRequest* auth;
784
785   assert(0 != ev_timer(ev));
786   assert(0 != t_data(ev_timer(ev)));
787
788   auth = (struct AuthRequest*) t_data(ev_timer(ev));
789
790   if (ev_type(ev) == ET_EXPIRE) {
791     /* Report the timeout in the log. */
792     log_write(LS_RESOLVER, L_INFO, 0, "Registration timeout %s",
793               get_client_name(auth->client, HIDE_IP));
794
795     /* Notify client if ident lookup failed. */
796     if (FlagHas(&auth->flags, AR_AUTH_PENDING)) {
797       FlagClr(&auth->flags, AR_AUTH_PENDING);
798       if (IsUserPort(auth->client))
799         sendheader(auth->client, REPORT_FAIL_ID);
800     }
801
802     /* Likewise if dns lookup failed. */
803     if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
804       FlagClr(&auth->flags, AR_DNS_PENDING);
805       delete_resolver_queries(auth);
806       if (IsUserPort(auth->client))
807         sendheader(auth->client, REPORT_FAIL_DNS);
808     }
809
810     /* Try to register the client. */
811     check_auth_finished(auth);
812   }
813 }
814
815 /** Handle a complete DNS lookup.  Send the client on it's way to a
816  * connection completion, regardless of success or failure -- unless
817  * there was a mismatch and KILL_IPMISMATCH is set.
818  * @param[in] vptr The pending struct AuthRequest.
819  * @param[in] addr IP address being resolved.
820  * @param[in] h_name Resolved name, or NULL if lookup failed.
821  */
822 static void auth_dns_callback(void* vptr, const struct irc_in_addr *addr, const char *h_name)
823 {
824   struct AuthRequest* auth = (struct AuthRequest*) vptr;
825   assert(0 != auth);
826
827   FlagClr(&auth->flags, AR_DNS_PENDING);
828   if (!addr) {
829     /* DNS entry was missing for the IP. */
830     if (IsUserPort(auth->client))
831       sendheader(auth->client, REPORT_FAIL_DNS);
832     sendto_iauth(auth->client, "d");
833   } else if (!irc_in_addr_valid(addr)
834              || (irc_in_addr_cmp(&cli_ip(auth->client), addr)
835                  && irc_in_addr_cmp(&auth->original, addr))) {
836     /* IP for hostname did not match client's IP. */
837     sendto_opmask_butone(0, SNO_IPMISMATCH, "IP# Mismatch: %s != %s[%s]",
838                          cli_sock_ip(auth->client), h_name,
839                          ircd_ntoa(addr));
840     if (IsUserPort(auth->client))
841       sendheader(auth->client, REPORT_IP_MISMATCH);
842     if (feature_bool(FEAT_KILL_IPMISMATCH)) {
843       exit_client(auth->client, auth->client, &me, "IP mismatch");
844       return;
845     }
846   } else if (!auth_verify_hostname(h_name, HOSTLEN)) {
847     /* Hostname did not look valid. */
848     if (IsUserPort(auth->client))
849       sendheader(auth->client, REPORT_INVAL_DNS);
850     sendto_iauth(auth->client, "d");
851   } else {
852     /* Hostname and mappings checked out. */
853     if (IsUserPort(auth->client))
854       sendheader(auth->client, REPORT_FIN_DNS);
855     ircd_strncpy(cli_sockhost(auth->client), h_name, HOSTLEN);
856     sendto_iauth(auth->client, "N %s", h_name);
857   }
858   check_auth_finished(auth);
859 }
860
861 /** Flag the client to show an attempt to contact the ident server on
862  * the client's host.  Should the connect or any later phase of the
863  * identifying process fail, it is aborted and the user is given a
864  * username of "unknown".
865  * @param[in] auth The request for which to start the ident lookup.
866  */
867 static void start_auth_query(struct AuthRequest* auth)
868 {
869   struct irc_sockaddr remote_addr;
870   struct irc_sockaddr local_addr;
871   int                 fd;
872   IOResult            result;
873
874   assert(0 != auth);
875   assert(0 != auth->client);
876
877   /*
878    * get the local address of the client and bind to that to
879    * make the auth request.  This used to be done only for
880    * ifdef VIRTUAL_HOST, but needs to be done for all clients
881    * since the ident request must originate from that same address--
882    * and machines with multiple IP addresses are common now
883    */
884   memcpy(&local_addr, &auth->local, sizeof(local_addr));
885   local_addr.port = 0;
886   memcpy(&remote_addr.addr, &cli_ip(auth->client), sizeof(remote_addr.addr));
887   remote_addr.port = 113;
888   fd = os_socket(&local_addr, SOCK_STREAM, "auth query", 0);
889   if (fd < 0) {
890     ++ServerStats->is_abad;
891     if (IsUserPort(auth->client))
892       sendheader(auth->client, REPORT_FAIL_ID);
893     return;
894   }
895   if (IsUserPort(auth->client))
896     sendheader(auth->client, REPORT_DO_ID);
897
898   if ((result = os_connect_nonb(fd, &remote_addr)) == IO_FAILURE ||
899       !socket_add(&auth->socket, auth_sock_callback, (void*) auth,
900                   result == IO_SUCCESS ? SS_CONNECTED : SS_CONNECTING,
901                   SOCK_EVENT_READABLE, fd)) {
902     ++ServerStats->is_abad;
903     if (IsUserPort(auth->client))
904       sendheader(auth->client, REPORT_FAIL_ID);
905     close(fd);
906     return;
907   }
908
909   FlagSet(&auth->flags, AR_AUTH_PENDING);
910   if (result == IO_SUCCESS)
911     send_auth_query(auth);
912 }
913
914 /** Initiate DNS lookup for a client.
915  * @param[in] auth The auth request for which to start the DNS lookup.
916  */
917 static void start_dns_query(struct AuthRequest *auth)
918 {
919   if (feature_bool(FEAT_NODNS)) {
920     sendto_iauth(auth->client, "d");
921     return;
922   }
923
924   if (irc_in_addr_is_loopback(&cli_ip(auth->client))) {
925     strcpy(cli_sockhost(auth->client), cli_name(&me));
926     sendto_iauth(auth->client, "N %s", cli_sockhost(auth->client));
927     return;
928   }
929
930   if (IsUserPort(auth->client))
931     sendheader(auth->client, REPORT_DO_DNS);
932
933   FlagSet(&auth->flags, AR_DNS_PENDING);
934   gethost_byaddr(&cli_ip(auth->client), auth_dns_callback, auth);
935 }
936
937 /** Initiate IAuth check for a client.
938  * @param[in] auth The auth request for which to star the IAuth check.
939  */
940 static void start_iauth_query(struct AuthRequest *auth)
941 {
942   FlagSet(&auth->flags, AR_IAUTH_PENDING);
943   if (!sendto_iauth(auth->client, "C %s %hu %s %hu",
944                     cli_sock_ip(auth->client), auth->port,
945                     ircd_ntoa(&auth->local.addr), auth->local.port))
946     FlagClr(&auth->flags, AR_IAUTH_PENDING);
947 }
948
949 /** Starts auth (identd) and dns queries for a client.
950  * @param[in] client The client for which to start queries.
951  */
952 void start_auth(struct Client* client)
953 {
954   struct irc_sockaddr remote;
955   struct AuthRequest* auth;
956
957   assert(0 != client);
958   Debug((DEBUG_INFO, "Beginning auth request on client %p", client));
959
960   /* Register with event handlers. */
961   cli_lasttime(client) = CurrentTime;
962   cli_since(client) = CurrentTime;
963   if (cli_fd(client) > HighestFd)
964     HighestFd = cli_fd(client);
965   LocalClientArray[cli_fd(client)] = client;
966   socket_events(&(cli_socket(client)), SOCK_ACTION_SET | SOCK_EVENT_READABLE);
967
968   /* Allocate the AuthRequest. */
969   auth = MyCalloc(1, sizeof(*auth));
970   assert(0 != auth);
971   auth->client = client;
972   cli_auth(client) = auth;
973   s_fd(&auth->socket) = -1;
974   timer_add(timer_init(&auth->timeout), auth_timeout_callback, (void*) auth,
975             TT_RELATIVE, feature_int(FEAT_AUTH_TIMEOUT));
976
977   /* Try to get socket endpoint addresses. */
978   if (!os_get_sockname(cli_fd(client), &auth->local)
979       || !os_get_peername(cli_fd(client), &remote)) {
980     ++ServerStats->is_abad;
981     if (IsUserPort(auth->client))
982       sendheader(auth->client, REPORT_FAIL_ID);
983     exit_client(auth->client, auth->client, &me, "Socket local/peer lookup failed");
984     return;
985   }
986   auth->port = remote.port;
987
988   /* Try to start DNS lookup. */
989   start_dns_query(auth);
990
991   /* Try to start ident lookup. */
992   start_auth_query(auth);
993
994   /* Set required client inputs for users. */
995   if (IsUserPort(client)) {
996     cli_user(client) = make_user(client);
997     cli_user(client)->server = &me;
998     FlagSet(&auth->flags, AR_NEEDS_USER);
999     FlagSet(&auth->flags, AR_NEEDS_NICK);
1000
1001     /* Try to start iauth lookup. */
1002     start_iauth_query(auth);
1003   }
1004
1005   /* Add client to GlobalClientList. */
1006   add_client_to_list(client);
1007
1008   /* Check which auth events remain pending. */
1009   check_auth_finished(auth);
1010 }
1011
1012 /** Mark that a user has PONGed while unregistered.
1013  * @param[in] auth Authorization request for client.
1014  * @param[in] cookie PONG cookie value sent by client.
1015  * @return Zero if client should be kept, CPTR_KILLED if rejected.
1016  */
1017 int auth_set_pong(struct AuthRequest *auth, unsigned int cookie)
1018 {
1019   assert(auth != NULL);
1020   if (!FlagHas(&auth->flags, AR_NEEDS_PONG))
1021     return 0;
1022   if (cookie != auth->cookie)
1023   {
1024     send_reply(auth->client, SND_EXPLICIT | ERR_BADPING,
1025                ":To connect, type /QUOTE PONG %u", auth->cookie);
1026     return 0;
1027   }
1028   cli_lasttime(auth->client) = CurrentTime;
1029   FlagClr(&auth->flags, AR_NEEDS_PONG);
1030   return check_auth_finished(auth);
1031 }
1032
1033 /** Record a user's claimed username and userinfo.
1034  * @param[in] auth Authorization request for client.
1035  * @param[in] username Client's asserted username.
1036  * @param[in] userinfo Client's asserted self-description.
1037  * @return Zero if client should be kept, CPTR_KILLED if rejected.
1038  */
1039 int auth_set_user(struct AuthRequest *auth, const char *username, const char *userinfo)
1040 {
1041   struct Client *cptr;
1042
1043   assert(auth != NULL);
1044   if (FlagHas(&auth->flags, AR_IAUTH_HURRY))
1045     return 0;
1046   FlagClr(&auth->flags, AR_NEEDS_USER);
1047   cptr = auth->client;
1048   ircd_strncpy(cli_info(cptr), userinfo, REALLEN);
1049   ircd_strncpy(cli_user(cptr)->username, username, USERLEN);
1050   ircd_strncpy(cli_user(cptr)->host, cli_sockhost(cptr), HOSTLEN);
1051   if (IAuthHas(iauth, IAUTH_UNDERNET))
1052     sendto_iauth(cptr, "U %s :%s", username, userinfo);
1053   else if (IAuthHas(iauth, IAUTH_ADDLINFO))
1054     sendto_iauth(cptr, "U %s", username);
1055   return check_auth_finished(auth);
1056 }
1057
1058 /** Handle authorization-related aspects of initial nickname selection.
1059  * This is called after verifying that the nickname is available.
1060  * @param[in] auth Authorization request for client.
1061  * @param[in] nickname Client's requested nickname.
1062  * @return Zero if client should be kept, CPTR_KILLED if rejected.
1063  */
1064 int auth_set_nick(struct AuthRequest *auth, const char *nickname)
1065 {
1066   assert(auth != NULL);
1067   FlagClr(&auth->flags, AR_NEEDS_NICK);
1068   /*
1069    * If the client hasn't gotten a cookie-ping yet,
1070    * choose a cookie and send it. -record!jegelhof@cloud9.net
1071    */
1072   if (!auth->cookie) {
1073     do {
1074       auth->cookie = ircrandom();
1075     } while (!auth->cookie);
1076     sendrawto_one(auth->client, "PING :%u", auth->cookie);
1077     FlagSet(&auth->flags, AR_NEEDS_PONG);
1078   }
1079   if (IAuthHas(iauth, IAUTH_UNDERNET))
1080     sendto_iauth(auth->client, "n %s", nickname);
1081   return check_auth_finished(auth);
1082 }
1083
1084 /** Record a user's password.
1085  * @param[in] auth Authorization request for client.
1086  * @param[in] password Client's password.
1087  * @return Zero if client should be kept, CPTR_KILLED if rejected.
1088  */
1089 int auth_set_password(struct AuthRequest *auth, const char *password)
1090 {
1091   assert(auth != NULL);
1092   if (IAuthHas(iauth, IAUTH_ADDLINFO))
1093     sendto_iauth(auth->client, "P :%s", password);
1094   return 0;
1095 }
1096
1097 /** Send exit notification for \a cptr to iauth.
1098  * @param[in] cptr Client who is exiting.
1099  */
1100 void auth_send_exit(struct Client *cptr)
1101 {
1102   sendto_iauth(cptr, "D");
1103 }
1104
1105 /** Mark that a user has started capabilities negotiation.
1106  * This blocks authorization until auth_cap_done() is called.
1107  * @param[in] auth Authorization request for client.
1108  * @return Zero if client should be kept, CPTR_KILLED if rejected.
1109  */
1110 int auth_cap_start(struct AuthRequest *auth)
1111 {
1112   assert(auth != NULL);
1113   FlagSet(&auth->flags, AR_CAP_PENDING);
1114   return 0;
1115 }
1116
1117 /** Mark that a user has completed capabilities negotiation.
1118  * This unblocks authorization if auth_cap_start() was called.
1119  * @param[in] auth Authorization request for client.
1120  * @return Zero if client should be kept, CPTR_KILLED if rejected.
1121  */
1122 int auth_cap_done(struct AuthRequest *auth)
1123 {
1124   assert(auth != NULL);
1125   FlagClr(&auth->flags, AR_CAP_PENDING);
1126   return check_auth_finished(auth);
1127 }
1128
1129 /** Attempt to spawn the process for an IAuth instance.
1130  * @param[in] iauth IAuth descriptor.
1131  * @param[in] automatic If non-zero, apply sanity checks against
1132  *   excessive automatic restarts.
1133  * @return 0 on success, non-zero on failure.
1134  */
1135 int iauth_do_spawn(struct IAuth *iauth, int automatic)
1136 {
1137   pid_t cpid;
1138   int s_io[2];
1139   int s_err[2];
1140   int res;
1141
1142   if (automatic && CurrentTime - iauth->started < 5)
1143   {
1144     sendto_opmask_butone(NULL, SNO_AUTH, "IAuth crashed fast, leaving it dead.");
1145     return -1;
1146   }
1147
1148   /* Record time we tried to spawn the iauth process. */
1149   iauth->started = CurrentTime;
1150
1151   /* Attempt to allocate a pair of sockets. */
1152   res = os_socketpair(s_io);
1153   if (res)
1154     return errno;
1155
1156   /* Mark the parent's side of the pair (element 0) as non-blocking. */
1157   res = os_set_nonblocking(s_io[0]);
1158   if (!res) {
1159     res = errno;
1160     close(s_io[1]);
1161     close(s_io[0]);
1162     return res;
1163   }
1164
1165   /* Initialize the socket structure to talk to the child. */
1166   res = socket_add(i_socket(iauth), iauth_sock_callback, iauth,
1167                    SS_CONNECTED, SOCK_EVENT_READABLE, s_io[0]);
1168   if (!res) {
1169     res = errno;
1170     close(s_io[1]);
1171     close(s_io[0]);
1172     return res;
1173   }
1174
1175   /* Allocate another pair for stderr. */
1176   res = os_socketpair(s_err);
1177   if (res) {
1178     res = errno;
1179     socket_del(i_socket(iauth));
1180     close(s_io[1]);
1181     close(s_io[0]);
1182     return res;
1183   }
1184
1185   /* Mark parent side of this pair non-blocking, too. */
1186   res = os_set_nonblocking(s_err[0]);
1187   if (!res) {
1188     res = errno;
1189     close(s_err[1]);
1190     close(s_err[0]);
1191     socket_del(i_socket(iauth));
1192     close(s_io[1]);
1193     close(s_io[0]);
1194     return res;
1195   }
1196
1197   /* And set up i_stderr(iauth). */
1198   res = socket_add(i_stderr(iauth), iauth_stderr_callback, iauth,
1199                    SS_CONNECTED, SOCK_EVENT_READABLE, s_err[0]);
1200   if (!res) {
1201     res = errno;
1202     close(s_err[1]);
1203     close(s_err[0]);
1204     socket_del(i_socket(iauth));
1205     close(s_io[1]);
1206     close(s_io[0]);
1207     return res;
1208   }
1209
1210   /* Attempt to fork a child process. */
1211   cpid = fork();
1212   if (cpid < 0) {
1213     /* Error forking the child, still in parent. */
1214     res = errno;
1215     socket_del(i_stderr(iauth));
1216     close(s_err[1]);
1217     close(s_err[0]);
1218     socket_del(i_socket(iauth));
1219     close(s_io[1]);
1220     close(s_io[0]);
1221     return res;
1222   }
1223
1224   if (cpid > 0) {
1225     /* We are the parent process.  Close the child's sockets. */
1226     close(s_io[1]);
1227     close(s_err[1]);
1228     /* Send our server name (supposedly for proxy checking purposes)
1229      * and maximum number of connections (for allocation hints).
1230      * Need to use conf_get_local() since &me may not be fully
1231      * initialized the first time we run.
1232      */
1233     sendto_iauth(NULL, "M %s %d", conf_get_local()->name, MAXCONNECTIONS);
1234     /* Indicate success (until the child dies). */
1235     return 0;
1236   }
1237
1238   /* We are the child process.
1239    * Duplicate our end of the socket to stdin, stdout and stderr.
1240    * Then close all the higher-numbered FDs and exec the process.
1241    */
1242   if (dup2(s_io[1], 0) == 0
1243       && dup2(s_io[1], 1) == 1
1244       && dup2(s_err[1], 2) == 2) {
1245     close_connections(0);
1246     execvp(iauth->i_argv[0], iauth->i_argv);
1247   }
1248
1249   /* If we got here, something was seriously wrong. */
1250   exit(EXIT_FAILURE);
1251 }
1252
1253 /** See if an %IAuth program must be spawned.
1254  * If a process is already running with the specified options, keep it.
1255  * Otherwise spawn a new child process to perform the %IAuth function.
1256  * @param[in] argc Number of parameters to use when starting process.
1257  * @param[in] argv Array of parameters to start process.
1258  * @return 0 on failure, 1 on new process, 2 on reuse of existing process.
1259  */
1260 int auth_spawn(int argc, char *argv[])
1261 {
1262   int ii;
1263
1264   if (iauth) {
1265     int same = 1;
1266
1267     /* Check that incoming arguments all match pre-existing arguments. */
1268     for (ii = 0; same && (ii < argc); ++ii) {
1269       if (NULL == iauth->i_argv[ii]
1270           || 0 != strcmp(iauth->i_argv[ii], argv[ii]))
1271         same = 0;
1272     }
1273     /* Check that we have no more pre-existing arguments. */
1274     if (iauth->i_argv[ii])
1275       same = 0;
1276     /* If they are the same and still connected, clear the "closing" flag and exit.*/
1277     if (same && i_GetConnected(iauth)) {
1278       IAuthClr(iauth, IAUTH_CLOSING);
1279       return 2;
1280     }
1281     /* Deallocate old argv elements. */
1282     for (ii = 0; iauth->i_argv[ii]; ++ii)
1283       MyFree(iauth->i_argv[ii]);
1284     MyFree(iauth->i_argv);
1285   }
1286
1287   /* Need to initialize a new connection. */
1288   iauth = MyCalloc(1, sizeof(*iauth));
1289   msgq_init(i_sendQ(iauth));
1290   /* Populate iauth's argv array. */
1291   iauth->i_argv = MyCalloc(argc + 1, sizeof(iauth->i_argv[0]));
1292   for (ii = 0; ii < argc; ++ii)
1293     DupString(iauth->i_argv[ii], argv[ii]);
1294   iauth->i_argv[ii] = NULL;
1295   /* Try to spawn it, and handle the results. */
1296   if (iauth_do_spawn(iauth, 0))
1297     return 0;
1298   IAuthClr(iauth, IAUTH_CLOSING);
1299   return 1;
1300 }
1301
1302 /** Mark all %IAuth connections as closing. */
1303 void auth_mark_closing(void)
1304 {
1305   if (iauth)
1306     IAuthSet(iauth, IAUTH_CLOSING);
1307 }
1308
1309 /** Complete disconnection of an %IAuth connection.
1310  * @param[in] iauth %Connection to fully close.
1311  */
1312 static void iauth_disconnect(struct IAuth *iauth)
1313 {
1314   if (!i_GetConnected(iauth))
1315     return;
1316
1317   /* Close main socket. */
1318   close(s_fd(i_socket(iauth)));
1319   socket_del(i_socket(iauth));
1320   s_fd(i_socket(iauth)) = -1;
1321
1322   /* Close error socket. */
1323   close(s_fd(i_stderr(iauth)));
1324   socket_del(i_stderr(iauth));
1325   s_fd(i_stderr(iauth)) = -1;
1326 }
1327
1328 /** Close all %IAuth connections marked as closing. */
1329 void auth_close_unused(void)
1330 {
1331   if (IAuthHas(iauth, IAUTH_CLOSING)) {
1332     int ii;
1333     iauth_disconnect(iauth);
1334     if (iauth->i_argv) {
1335       for (ii = 0; iauth->i_argv[ii]; ++ii)
1336         MyFree(iauth->i_argv[ii]);
1337       MyFree(iauth->i_argv);
1338     }
1339     MyFree(iauth);
1340   }
1341 }
1342
1343 /** Send queued output to \a iauth.
1344  * @param[in] iauth Writable connection with queued data.
1345  */
1346 static void iauth_write(struct IAuth *iauth)
1347 {
1348   unsigned int bytes_tried, bytes_sent;
1349   IOResult iores;
1350
1351   if (IAuthHas(iauth, IAUTH_BLOCKED))
1352     return;
1353   while (MsgQLength(i_sendQ(iauth)) > 0) {
1354     iores = os_sendv_nonb(s_fd(i_socket(iauth)), i_sendQ(iauth), &bytes_tried, &bytes_sent);
1355     switch (iores) {
1356     case IO_SUCCESS:
1357       msgq_delete(i_sendQ(iauth), bytes_sent);
1358       iauth->i_sendB += bytes_sent;
1359       if (bytes_tried == bytes_sent)
1360         break;
1361       /* If bytes_sent < bytes_tried, fall through to IO_BLOCKED. */
1362     case IO_BLOCKED:
1363       IAuthSet(iauth, IAUTH_BLOCKED);
1364       socket_events(i_socket(iauth), SOCK_ACTION_ADD | SOCK_EVENT_WRITABLE);
1365       return;
1366     case IO_FAILURE:
1367       iauth_disconnect(iauth);
1368       return;
1369     }
1370   }
1371   /* We were able to flush all events, so remove notification. */
1372   socket_events(i_socket(iauth), SOCK_ACTION_DEL | SOCK_EVENT_WRITABLE);
1373 }
1374
1375 /** Send a message to iauth.
1376  * @param[in] cptr Optional client context for message.
1377  * @param[in] format Format string for message.
1378  * @return Non-zero on successful send or buffering, zero on failure.
1379  */
1380 static int sendto_iauth(struct Client *cptr, const char *format, ...)
1381 {
1382   struct VarData vd;
1383   struct MsgBuf *mb;
1384
1385   /* Do not send requests when we have no iauth. */
1386   if (!i_GetConnected(iauth))
1387     return 0;
1388   /* Do not send for clients in the NORMAL state. */
1389   if (cptr
1390       && (format[0] != 'D')
1391       && (!cli_auth(cptr) || !FlagHas(&cli_auth(cptr)->flags, AR_IAUTH_PENDING)))
1392     return 0;
1393
1394   /* Build the message buffer. */
1395   vd.vd_format = format;
1396   va_start(vd.vd_args, format);
1397   if (0 == cptr)
1398     mb = msgq_make(NULL, "-1 %v", &vd);
1399   else
1400     mb = msgq_make(NULL, "%d %v", cli_fd(cptr), &vd);
1401   va_end(vd.vd_args);
1402
1403   /* Tack it onto the iauth sendq and try to write it. */
1404   ++iauth->i_sendM;
1405   msgq_add(i_sendQ(iauth), mb, 0);
1406   msgq_clean(mb);
1407   iauth_write(iauth);
1408   return 1;
1409 }
1410
1411 /** Send text to interested operators (SNO_AUTH server notice).
1412  * @param[in] iauth Active IAuth session.
1413  * @param[in] cli Client referenced by command.
1414  * @param[in] parc Number of parameters (1).
1415  * @param[in] params Text to send.
1416  * @return Zero.
1417  */
1418 static int iauth_cmd_snotice(struct IAuth *iauth, struct Client *cli,
1419                              int parc, char **params)
1420 {
1421   sendto_opmask_butone(NULL, SNO_AUTH, "%s", params[0]);
1422   return 0;
1423 }
1424
1425 /** Set the debug level for the session.
1426  * @param[in] iauth Active IAuth session.
1427  * @param[in] cli Client referenced by command.
1428  * @param[in] parc Number of parameters (1).
1429  * @param[in] params String starting with an integer.
1430  * @return Zero.
1431  */
1432 static int iauth_cmd_debuglevel(struct IAuth *iauth, struct Client *cli,
1433                                 int parc, char **params)
1434 {
1435   int new_level;
1436
1437   new_level = parc > 0 ? atoi(params[0]) : 0;
1438   if (i_debug(iauth) > 0 || new_level > 0) {
1439     /* The "ia_dbg" name is borrowed from (IRCnet) ircd. */
1440     sendto_opmask_butone(NULL, SNO_AUTH, "ia_dbg = %d", new_level);
1441   }
1442   i_debug(iauth) = new_level;
1443   return 0;
1444 }
1445
1446 /** Set policy options for the session.
1447  * Old policy is forgotten, and any of the following characters in \a
1448  * params enable the corresponding policy:
1449  * \li A IAUTH_ADDLINFO
1450  * \li R IAUTH_REQUIRED
1451  * \li T IAUTH_TIMEOUT
1452  * \li W IAUTH_EXTRAWAIT
1453  * \li U IAUTH_UNDERNET
1454  *
1455  * @param[in] iauth Active IAuth session.
1456  * @param[in] cli Client referenced by command.
1457  * @param[in] parc Number of parameters (1).
1458  * @param[in] params Zero or more policy options.
1459  * @return Zero.
1460  */
1461 static int iauth_cmd_policy(struct IAuth *iauth, struct Client *cli,
1462                             int parc, char **params)
1463 {
1464   enum IAuthFlag flag;
1465   char *p;
1466
1467   /* Erase old policy first. */
1468   for (flag = IAUTH_FIRST_OPTION; flag < IAUTH_LAST_FLAG; ++flag)
1469     IAuthClr(iauth, flag);
1470
1471   if (parc > 0) /* only try to parse if we were given a policy string */
1472     /* Parse new policy set. */
1473     for (p = params[0]; *p; p++) switch (*p) {
1474     case 'A': IAuthSet(iauth, IAUTH_ADDLINFO); break;
1475     case 'R': IAuthSet(iauth, IAUTH_REQUIRED); break;
1476     case 'T': IAuthSet(iauth, IAUTH_TIMEOUT); break;
1477     case 'W': IAuthSet(iauth, IAUTH_EXTRAWAIT); break;
1478     case 'U': IAuthSet(iauth, IAUTH_UNDERNET); break;
1479     }
1480
1481   /* Optionally notify operators. */
1482   if (i_debug(iauth) > 0)
1483     sendto_opmask_butone(NULL, SNO_AUTH, "iauth options: %s", params[0]);
1484   return 0;
1485 }
1486
1487 /** Set the iauth program version number.
1488  * @param[in] iauth Active IAuth session.
1489  * @param[in] cli Client referenced by command.
1490  * @param[in] parc Number of parameters (1).
1491  * @param[in] params Version number or name.
1492  * @return Zero.
1493  */
1494 static int iauth_cmd_version(struct IAuth *iauth, struct Client *cli,
1495                              int parc, char **params)
1496 {
1497   MyFree(iauth->i_version);
1498   DupString(iauth->i_version, parc > 0 ? params[0] : "<NONE>");
1499   sendto_opmask_butone(NULL, SNO_AUTH, "iauth version %s running.",
1500                        iauth->i_version);
1501   return 0;
1502 }
1503
1504 /** Paste a parameter list together into a single string.
1505  * @param[in] parc Number of parameters.
1506  * @param[in] params Parameter list to paste together.
1507  * @return Pasted parameter list.
1508  */
1509 static char *paste_params(int parc, char **params)
1510 {
1511   char *str, *tmp;
1512   int len = 0, lengths[MAXPARA], i;
1513
1514   /* Compute the length... */
1515   for (i = 0; i < parc; i++)
1516     len += lengths[i] = strlen(params[i]);
1517
1518   /* Allocate memory, accounting for string lengths, spaces (parc - 1), a
1519    * sentinel, and the trailing \0
1520    */
1521   str = MyMalloc(len + parc + 1);
1522
1523   /* Build the pasted string */
1524   for (tmp = str, i = 0; i < parc; i++) {
1525     if (i) /* add space separator... */
1526       *(tmp++) = ' ';
1527     if (i == parc - 1) /* add colon sentinel */
1528       *(tmp++) = ':';
1529
1530     /* Copy string component... */
1531     memcpy(tmp, params[i], lengths[i]);
1532     tmp += lengths[i]; /* move to end of string */
1533   }
1534
1535   /* terminate the string... */
1536   *tmp = '\0';
1537
1538   return str; /* return the pasted string */
1539 }
1540
1541 /** Clear cached iauth configuration information.
1542  * @param[in] iauth Active IAuth session.
1543  * @param[in] cli Client referenced by command.
1544  * @param[in] parc Number of parameters (0).
1545  * @param[in] params Parameter list (ignored).
1546  * @return Zero.
1547  */
1548 static int iauth_cmd_newconfig(struct IAuth *iauth, struct Client *cli,
1549                                int parc, char **params)
1550 {
1551   struct SLink *head;
1552   struct SLink *next;
1553
1554   head = iauth->i_config;
1555   iauth->i_config = NULL;
1556   for (; head; head = next) {
1557     next = head->next;
1558     MyFree(head->value.cp);
1559     free_link(head);
1560   }
1561   sendto_opmask_butone(NULL, SNO_AUTH, "New iauth configuration.");
1562   return 0;
1563 }
1564
1565 /** Append iauth configuration information.
1566  * @param[in] iauth Active IAuth session.
1567  * @param[in] cli Client referenced by command.
1568  * @param[in] parc Number of parameters.
1569  * @param[in] params Description of configuration element.
1570  * @return Zero.
1571  */
1572 static int iauth_cmd_config(struct IAuth *iauth, struct Client *cli,
1573                             int parc, char **params)
1574 {
1575   struct SLink *node;
1576
1577   if (iauth->i_config) {
1578     for (node = iauth->i_config; node->next; node = node->next) ;
1579     node = node->next = make_link();
1580   } else {
1581     node = iauth->i_config = make_link();
1582   }
1583   node->value.cp = paste_params(parc, params);
1584   node->next = 0; /* must be explicitly cleared */
1585   return 0;
1586 }
1587
1588 /** Clear cached iauth configuration information.
1589  * @param[in] iauth Active IAuth session.
1590  * @param[in] cli Client referenced by command.
1591  * @param[in] parc Number of parameters (0).
1592  * @param[in] params Parameter list (ignored).
1593  * @return Zero.
1594  */
1595 static int iauth_cmd_newstats(struct IAuth *iauth, struct Client *cli,
1596                               int parc, char **params)
1597 {
1598   struct SLink *head;
1599   struct SLink *next;
1600
1601   head = iauth->i_stats;
1602   iauth->i_stats = NULL;
1603   for (; head; head = next) {
1604     next = head->next;
1605     MyFree(head->value.cp);
1606     free_link(head);
1607   }
1608   sendto_opmask_butone(NULL, SNO_AUTH, "New iauth statistics.");
1609   return 0;
1610 }
1611
1612 /** Append iauth statistics information.
1613  * @param[in] iauth Active IAuth session.
1614  * @param[in] cli Client referenced by command.
1615  * @param[in] parc Number of parameters.
1616  * @param[in] params Statistics element.
1617  * @return Zero.
1618  */
1619 static int iauth_cmd_stats(struct IAuth *iauth, struct Client *cli,
1620                            int parc, char **params)
1621 {
1622   struct SLink *node;
1623   if (iauth->i_stats) {
1624     for (node = iauth->i_stats; node->next; node = node->next) ;
1625     node = node->next = make_link();
1626   } else {
1627     node = iauth->i_stats = make_link();
1628   }
1629   node->value.cp = paste_params(parc, params);
1630   node->next = 0; /* must be explicitly cleared */
1631   return 0;
1632 }
1633
1634 /** Set client's username to a trusted string even if it breaks the rules.
1635  * @param[in] iauth Active IAuth session.
1636  * @param[in] cli Client referenced by command.
1637  * @param[in] parc Number of parameters (1).
1638  * @param[in] params Forced username.
1639  * @return One.
1640  */
1641 static int iauth_cmd_username_forced(struct IAuth *iauth, struct Client *cli,
1642                                      int parc, char **params)
1643 {
1644   assert(cli_auth(cli) != NULL);
1645   FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
1646   if (!EmptyString(params[0])) {
1647     ircd_strncpy(cli_username(cli), params[0], USERLEN);
1648     SetGotId(cli);
1649     FlagSet(&cli_auth(cli)->flags, AR_IAUTH_USERNAME);
1650     FlagSet(&cli_auth(cli)->flags, AR_IAUTH_FUSERNAME);
1651   }
1652   return 1;
1653 }
1654
1655 /** Set client's username to a trusted string.
1656  * @param[in] iauth Active IAuth session.
1657  * @param[in] cli Client referenced by command.
1658  * @param[in] parc Number of parameters (1).
1659  * @param[in] params Trusted username.
1660  * @return One.
1661  */
1662 static int iauth_cmd_username_good(struct IAuth *iauth, struct Client *cli,
1663                                    int parc, char **params)
1664 {
1665   assert(cli_auth(cli) != NULL);
1666   FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
1667   if (!EmptyString(params[0])) {
1668     ircd_strncpy(cli_username(cli), params[0], USERLEN);
1669     SetGotId(cli);
1670     FlagSet(&cli_auth(cli)->flags, AR_IAUTH_USERNAME);
1671   }
1672   return 1;
1673 }
1674
1675 /** Set client's username to an untrusted string.
1676  * @param[in] iauth Active IAuth session.
1677  * @param[in] cli Client referenced by command.
1678  * @param[in] parc Number of parameters (1).
1679  * @param[in] params Untrusted username.
1680  * @return One.
1681  */
1682 static int iauth_cmd_username_bad(struct IAuth *iauth, struct Client *cli,
1683                                   int parc, char **params)
1684 {
1685   assert(cli_auth(cli) != NULL);
1686   FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
1687   if (!EmptyString(params[0]))
1688     ircd_strncpy(cli_user(cli)->username, params[0], USERLEN);
1689   return 1;
1690 }
1691
1692 /** Set client's hostname.
1693  * @param[in] iauth Active IAuth session.
1694  * @param[in] cli Client referenced by command.
1695  * @param[in] parc Number of parameters (1).
1696  * @param[in] params New hostname for client.
1697  * @return Non-zero if \a cli authorization should be checked for completion.
1698  */
1699 static int iauth_cmd_hostname(struct IAuth *iauth, struct Client *cli,
1700                               int parc, char **params)
1701 {
1702   struct AuthRequest *auth;
1703
1704   if (EmptyString(params[0])) {
1705     sendto_iauth(cli, "E Missing :Missing hostname parameter");
1706     return 0;
1707   }
1708
1709   auth = cli_auth(cli);
1710   assert(auth != NULL);
1711
1712   /* If a DNS request is pending, abort it. */
1713   if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
1714     FlagClr(&auth->flags, AR_DNS_PENDING);
1715     delete_resolver_queries(auth);
1716     if (IsUserPort(cli))
1717       sendheader(cli, REPORT_FIN_DNS);
1718   }
1719   /* Set hostname from params. */
1720   ircd_strncpy(cli_sockhost(cli), params[0], HOSTLEN);
1721   return 1;
1722 }
1723
1724 /** Set client's IP address.
1725  * @param[in] iauth Active IAuth session.
1726  * @param[in] cli Client referenced by command.
1727  * @param[in] parc Number of parameters (1).
1728  * @param[in] params New IP address for client in dotted quad or
1729  *   standard IPv6 format.
1730  * @return Zero.
1731  */
1732 static int iauth_cmd_ip_address(struct IAuth *iauth, struct Client *cli,
1733                                 int parc, char **params)
1734 {
1735   struct irc_in_addr addr;
1736   struct AuthRequest *auth;
1737
1738   if (EmptyString(params[0])) {
1739     sendto_iauth(cli, "E Missing :Missing IP address parameter");
1740     return 0;
1741   }
1742
1743   /* Get AuthRequest for client. */
1744   auth = cli_auth(cli);
1745   assert(auth != NULL);
1746
1747   /* Parse the client's new IP address. */
1748   if (!ircd_aton(&addr, params[0])) {
1749     sendto_iauth(cli, "E Invalid :Unable to parse IP address [%s]", params[0]);
1750     return 0;
1751   }
1752
1753   /* If this is the first IP override, save the client's original
1754    * address in case we get a DNS response later.
1755    */
1756   if (!irc_in_addr_valid(&auth->original))
1757     memcpy(&auth->original, &cli_ip(cli), sizeof(auth->original));
1758
1759   /* Undo original IP connection in IPcheck. */
1760   IPcheck_connect_fail(cli);
1761   ClearIPChecked(cli);
1762
1763   /* Update the IP and charge them as a remote connect. */
1764   memcpy(&cli_ip(cli), &addr, sizeof(cli_ip(cli)));
1765   IPcheck_remote_connect(cli, 0);
1766
1767   return 0;
1768 }
1769
1770 /** Find a ConfItem structure for a named connection class.
1771  * @param[in] class_name Name of configuration class to find.
1772  * @return A ConfItem of type CONF_CLIENT for the class, or NULL on failure.
1773  */
1774 static struct ConfItem *auth_find_class_conf(const char *class_name)
1775 {
1776   static struct ConfItem *aconf_list;
1777   struct ConnectionClass *class;
1778   struct ConfItem *aconf;
1779
1780   /* Make sure the configuration class is valid. */
1781   class = find_class(class_name);
1782   if (!class)
1783     return NULL;
1784
1785   /* Look for an existing ConfItem for the class. */
1786   for (aconf = aconf_list; aconf; aconf = aconf->next)
1787     if (aconf->conn_class == class)
1788       break;
1789
1790   /* If no ConfItem, create one. */
1791   if (!aconf) {
1792     aconf = make_conf(CONF_CLIENT);
1793     if (!aconf) {
1794       sendto_opmask_butone(NULL, SNO_AUTH,
1795                            "Unable to allocate ConfItem for class %s!",
1796                            ConClass(class));
1797       return NULL;
1798     }
1799     aconf->conn_class = class;
1800     aconf->next = aconf_list;
1801     aconf_list = aconf;
1802   }
1803
1804   return aconf;
1805 }
1806
1807 /** Accept a client in IAuth.
1808  * @param[in] iauth Active IAuth session.
1809  * @param[in] cli Client referenced by command.
1810  * @param[in] parc Number of parameters.
1811  * @param[in] params Optional class name for client.
1812  * @return One.
1813  */
1814 static int iauth_cmd_done_client(struct IAuth *iauth, struct Client *cli,
1815                                  int parc, char **params)
1816 {
1817   static time_t warn_time;
1818
1819   /* Clear iauth pending flag. */
1820   assert(cli_auth(cli) != NULL);
1821   FlagClr(&cli_auth(cli)->flags, AR_IAUTH_PENDING);
1822
1823   /* If a connection class was specified (and usable), assign the client to it. */
1824   if (!EmptyString(params[0])) {
1825     struct ConfItem *aconf;
1826
1827     aconf = auth_find_class_conf(params[0]);
1828     if (aconf)
1829       attach_conf(cli, aconf);
1830     else
1831       sendto_opmask_butone_ratelimited(NULL, SNO_AUTH, &warn_time,
1832                                        "iauth tried to use undefined class [%s]",
1833                                        params[0]);
1834   }
1835
1836   return 1;
1837 }
1838
1839 /** Accept a client in IAuth and assign them to an account.
1840  * @param[in] iauth Active IAuth session.
1841  * @param[in] cli Client referenced by command.
1842  * @param[in] parc Number of parameters.
1843  * @param[in] params Account name and optional class name for client.
1844  * @return Non-zero if \a cli authorization should be checked for completion.
1845  */
1846 static int iauth_cmd_done_account(struct IAuth *iauth, struct Client *cli,
1847                                   int parc, char **params)
1848 {
1849   size_t len;
1850
1851   /* Sanity check. */
1852   if (EmptyString(params[0])) {
1853     sendto_iauth(cli, "E Missing :Missing account parameter");
1854     return 0;
1855   }
1856   /* Check length of account name. */
1857   len = strcspn(params[0], ": ");
1858   if (len > ACCOUNTLEN) {
1859     sendto_iauth(cli, "E Invalid :Account parameter too long");
1860     return 0;
1861   }
1862   /* If account has a creation timestamp, use it. */
1863   assert(cli_user(cli) != NULL);
1864   if (params[0][len] == ':')
1865     cli_user(cli)->acc_create = strtoul(params[0] + len + 1, NULL, 10);
1866
1867   /* Copy account name to User structure. */
1868   ircd_strncpy(cli_user(cli)->account, params[0], ACCOUNTLEN);
1869   SetAccount(cli);
1870
1871   /* Fall through to the normal "done" handler. */
1872   return iauth_cmd_done_client(iauth, cli, parc - 1, params + 1);
1873 }
1874
1875 /** Reject a client's connection.
1876  * @param[in] iauth Active IAuth session.
1877  * @param[in] cli Client referenced by command.
1878  * @param[in] parc Number of parameters (1).
1879  * @param[in] params Optional kill message.
1880  * @return Zero.
1881  */
1882 static int iauth_cmd_kill(struct IAuth *iauth, struct Client *cli,
1883                           int parc, char **params)
1884 {
1885   if (cli_auth(cli))
1886     FlagClr(&cli_auth(cli)->flags, AR_IAUTH_PENDING);
1887   if (EmptyString(params[0]))
1888     params[0] = "Access denied";
1889   exit_client(cli, cli, &me, params[0]);
1890   return 0;
1891 }
1892
1893 /** Send a challenge string to the client.
1894  * @param[in] iauth Active IAuth session.
1895  * @param[in] cli Client referenced by command.
1896  * @param[in] parc Number of parameters (1).
1897  * @param[in] params Challenge message for client.
1898  * @return Zero.
1899  */
1900 static int iauth_cmd_challenge(struct IAuth *iauth, struct Client *cli,
1901                                int parc, char **params)
1902 {
1903   if (!EmptyString(params[0]))
1904     sendrawto_one(cli, "NOTICE AUTH :*** %s", params[0]);
1905   return 0;
1906 }
1907
1908 /** Parse a \a message from \a iauth.
1909  * @param[in] iauth Active IAuth session.
1910  * @param[in] message Message to be parsed.
1911  */
1912 static void iauth_parse(struct IAuth *iauth, char *message)
1913 {
1914   char *params[MAXPARA + 1]; /* leave space for NULL */
1915   int parc = 0;
1916   iauth_cmd_handler handler;
1917   struct AuthRequest *auth;
1918   struct Client *cli;
1919   int has_cli;
1920   int id;
1921
1922   /* Find command handler... */
1923   switch (*(message++)) {
1924   case '>': handler = iauth_cmd_snotice; has_cli = 0; break;
1925   case 'G': handler = iauth_cmd_debuglevel; has_cli = 0; break;
1926   case 'O': handler = iauth_cmd_policy; has_cli = 0; break;
1927   case 'V': handler = iauth_cmd_version; has_cli = 0; break;
1928   case 'a': handler = iauth_cmd_newconfig; has_cli = 0; break;
1929   case 'A': handler = iauth_cmd_config; has_cli = 0; break;
1930   case 's': handler = iauth_cmd_newstats; has_cli = 0; break;
1931   case 'S': handler = iauth_cmd_stats; has_cli = 0; break;
1932   case 'o': handler = iauth_cmd_username_forced; has_cli = 1; break;
1933   case 'U': handler = iauth_cmd_username_good; has_cli = 1; break;
1934   case 'u': handler = iauth_cmd_username_bad; has_cli = 1; break;
1935   case 'N': handler = iauth_cmd_hostname; has_cli = 1; break;
1936   case 'I': handler = iauth_cmd_ip_address; has_cli = 1; break;
1937   case 'C': handler = iauth_cmd_challenge; has_cli = 1; break;
1938   case 'D': handler = iauth_cmd_done_client; has_cli = 1; break;
1939   case 'R': handler = iauth_cmd_done_account; has_cli = 1; break;
1940   case 'k': /* The 'k' command indicates the user should be booted
1941              * off without telling opers.  There is no way to
1942              * signal that to exit_client(), so we fall through to
1943              * the case that we do implement.
1944              */
1945   case 'K': handler = iauth_cmd_kill; has_cli = 2; break;
1946   case 'r': /* we handle termination directly */ return;
1947   default:  sendto_iauth(NULL, "E Garbage :[%s]", message); return;
1948   }
1949
1950   while (parc < MAXPARA) {
1951     while (IsSpace(*message)) /* skip leading whitespace */
1952       message++;
1953
1954     if (!*message) /* hit the end of the string, break out */
1955       break;
1956
1957     if (*message == ':') { /* found sentinel... */
1958       params[parc++] = message + 1;
1959       break; /* it's the last parameter anyway */
1960     }
1961
1962     params[parc++] = message; /* save the parameter */
1963     while (*message && !IsSpace(*message))
1964       message++; /* find the end of the parameter */
1965
1966     if (*message) /* terminate the parameter */
1967       *(message++) = '\0';
1968   }
1969
1970   params[parc] = NULL; /* terminate the parameter list */
1971
1972   /* Check to see if the command specifies a client... */
1973   if (!has_cli) {
1974     /* Handler does not need a client. */
1975     handler(iauth, NULL, parc, params);
1976   } else {
1977     /* Try to find the client associated with the request. */
1978     id = strtol(params[0], NULL, 10);
1979     if (id < 0 || id > HighestFd || !(cli = LocalClientArray[id]))
1980       /* Client no longer exists (or never existed). */
1981       sendto_iauth(NULL, "E Gone :[%s %s %s]", params[0], params[1],
1982                    params[2]);
1983     else if ((!(auth = cli_auth(cli)) ||
1984               !FlagHas(&auth->flags, AR_IAUTH_PENDING)) &&
1985              has_cli == 1)
1986       /* Client is done with IAuth checks. */
1987       sendto_iauth(cli, "E Done :[%s %s %s]", params[0], params[1], params[2]);
1988     else {
1989       struct irc_sockaddr addr;
1990       int res;
1991
1992       /* Parse IP address and port number from parameters */
1993       res = ipmask_parse(params[1], &addr.addr, NULL);
1994       addr.port = strtol(params[2], NULL, 10);
1995
1996       /* Check IP address and port number against expected. */
1997       if (0 == res ||
1998           irc_in_addr_cmp(&addr.addr, &cli_ip(cli)) ||
1999           (auth && addr.port != auth->port))
2000         /* Report mismatch to iauth. */
2001         sendto_iauth(cli, "E Mismatch :[%s] != [%s]", params[1],
2002                      ircd_ntoa(&cli_ip(cli)));
2003       else if (handler(iauth, cli, parc - 3, params + 3))
2004         /* Handler indicated a possible state change. */
2005         check_auth_finished(auth);
2006     }
2007   }
2008 }
2009
2010 /** Read input from \a iauth.
2011  * Reads up to SERVER_TCP_WINDOW bytes per pass.
2012  * @param[in] iauth Readable connection.
2013  */
2014 static void iauth_read(struct IAuth *iauth)
2015 {
2016   static char readbuf[SERVER_TCP_WINDOW];
2017   unsigned int length, count;
2018   char *sol;
2019   char *eol;
2020
2021   /* Copy partial data to readbuf, append new data. */
2022   length = iauth->i_count;
2023   memcpy(readbuf, iauth->i_buffer, length);
2024   if (IO_SUCCESS != os_recv_nonb(s_fd(i_socket(iauth)),
2025                                  readbuf + length,
2026                                  sizeof(readbuf) - length - 1,
2027                                  &count))
2028     return;
2029   readbuf[length += count] = '\0';
2030
2031   /* Parse each complete line. */
2032   for (sol = readbuf; (eol = strchr(sol, '\n')) != NULL; sol = eol + 1) {
2033     *eol = '\0';
2034     if (*(eol - 1) == '\r') /* take out carriage returns, too... */
2035       *(eol - 1) = '\0';
2036
2037     /* If spammy debug, send the message to opers. */
2038     if (i_debug(iauth) > 1)
2039       sendto_opmask_butone(NULL, SNO_AUTH, "Parsing: \"%s\"", sol);
2040
2041     /* Parse the line... */
2042     iauth_parse(iauth, sol);
2043   }
2044
2045   /* Put unused data back into connection's buffer. */
2046   iauth->i_count = strlen(sol);
2047   if (iauth->i_count > BUFSIZE)
2048     iauth->i_count = BUFSIZE;
2049   memcpy(iauth->i_buffer, sol, iauth->i_count);
2050 }
2051
2052 /** Handle socket activity for an %IAuth connection.
2053  * @param[in] ev &Socket event; the IAuth connection is the user data
2054  *   pointer for the socket.
2055  */
2056 static void iauth_sock_callback(struct Event *ev)
2057 {
2058   struct IAuth *iauth;
2059
2060   assert(0 != ev_socket(ev));
2061   iauth = (struct IAuth*) s_data(ev_socket(ev));
2062   assert(0 != iauth);
2063
2064   switch (ev_type(ev)) {
2065   case ET_DESTROY:
2066     /* Hm, what happened here? */
2067     if (!IAuthHas(iauth, IAUTH_CLOSING))
2068       iauth_do_spawn(iauth, 1);
2069     break;
2070   case ET_READ:
2071     iauth_read(iauth);
2072     break;
2073   case ET_WRITE:
2074     IAuthClr(iauth, IAUTH_BLOCKED);
2075     iauth_write(iauth);
2076     break;
2077   case ET_ERROR:
2078     log_write(LS_IAUTH, L_ERROR, 0, "IAuth socket error: %s", strerror(ev_data(ev)));
2079     /* and fall through to the ET_EOF case */
2080   case ET_EOF:
2081     iauth_disconnect(iauth);
2082     break;
2083   default:
2084     assert(0 && "Unrecognized event type");
2085     break;
2086   }
2087 }
2088
2089 /** Read error input from \a iauth.
2090  * @param[in] iauth Readable connection.
2091  */
2092 static void iauth_read_stderr(struct IAuth *iauth)
2093 {
2094   static char readbuf[SERVER_TCP_WINDOW];
2095   unsigned int length, count;
2096   char *sol;
2097   char *eol;
2098
2099   /* Copy partial data to readbuf, append new data. */
2100   length = iauth->i_errcount;
2101   memcpy(readbuf, iauth->i_errbuf, length);
2102   if (IO_SUCCESS != os_recv_nonb(s_fd(i_stderr(iauth)),
2103                                  readbuf + length,
2104                                  sizeof(readbuf) - length - 1,
2105                                  &count))
2106     return;
2107   readbuf[length += count] = '\0';
2108
2109   /* Send each complete line to SNO_AUTH. */
2110   for (sol = readbuf; (eol = strchr(sol, '\n')) != NULL; sol = eol + 1) {
2111     *eol = '\0';
2112     if (*(eol - 1) == '\r') /* take out carriage returns, too... */
2113       *(eol - 1) = '\0';
2114     Debug((DEBUG_ERROR, "IAuth error: %s", sol));
2115     log_write(LS_IAUTH, L_ERROR, 0, "IAuth error: %s", sol);
2116     sendto_opmask_butone(NULL, SNO_AUTH, "%s", sol);
2117   }
2118
2119   /* Put unused data back into connection's buffer. */
2120   iauth->i_errcount = strlen(sol);
2121   if (iauth->i_errcount > BUFSIZE)
2122     iauth->i_errcount = BUFSIZE;
2123   memcpy(iauth->i_errbuf, sol, iauth->i_errcount);
2124 }
2125
2126 /** Handle error socket activity for an %IAuth connection.
2127  * @param[in] ev &Socket event; the IAuth connection is the user data
2128  *   pointer for the socket.
2129  */
2130 static void iauth_stderr_callback(struct Event *ev)
2131 {
2132   struct IAuth *iauth;
2133
2134   assert(0 != ev_socket(ev));
2135   iauth = (struct IAuth*) s_data(ev_socket(ev));
2136   assert(0 != iauth);
2137
2138   switch (ev_type(ev)) {
2139   case ET_READ:
2140     iauth_read_stderr(iauth);
2141     break;
2142   case ET_ERROR:
2143     log_write(LS_IAUTH, L_ERROR, 0, "IAuth stderr error: %s", strerror(ev_data(ev)));
2144     /* and fall through to the ET_EOF/ET_DESTROY case */
2145   case ET_DESTROY:
2146   case ET_EOF:
2147     break;
2148   default:
2149     assert(0 && "Unrecognized event type");
2150     break;
2151   }
2152 }
2153
2154 /** Report active iauth's configuration to \a cptr.
2155  * @param[in] cptr Client requesting statistics.
2156  * @param[in] sd Stats descriptor for request.
2157  * @param[in] param Extra parameter from user (may be NULL).
2158  */
2159 void report_iauth_conf(struct Client *cptr, const struct StatDesc *sd, char *param)
2160 {
2161     struct SLink *link;
2162
2163     if (iauth) for (link = iauth->i_config; link; link = link->next)
2164     {
2165         send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":%s",
2166                    link->value.cp);
2167     }
2168     send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":End of IAuth configuration.");
2169 }
2170
2171 /** Report active iauth's statistics to \a cptr.
2172  * @param[in] cptr Client requesting statistics.
2173  * @param[in] sd Stats descriptor for request.
2174  * @param[in] param Extra parameter from user (may be NULL).
2175  */
2176  void report_iauth_stats(struct Client *cptr, const struct StatDesc *sd, char *param)
2177 {
2178     struct SLink *link;
2179
2180     if (iauth) for (link = iauth->i_stats; link; link = link->next)
2181     {
2182         send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":%s",
2183                    link->value.cp);
2184     }
2185     send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":End of IAuth statistics.");
2186 }