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