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