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