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