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