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