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