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