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