Fix SF bug #2694761 (iauth class assignment did not work correctly).
[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     return errno;
1193
1194   /* Mark the parent's side of the pair (element 0) as non-blocking. */
1195   res = os_set_nonblocking(s_io[0]);
1196   if (!res) {
1197     res = errno;
1198     close(s_io[1]);
1199     close(s_io[0]);
1200     return res;
1201   }
1202
1203   /* Initialize the socket structure to talk to the child. */
1204   res = socket_add(i_socket(iauth), iauth_sock_callback, iauth,
1205                    SS_CONNECTED, SOCK_EVENT_READABLE, s_io[0]);
1206   if (!res) {
1207     res = errno;
1208     close(s_io[1]);
1209     close(s_io[0]);
1210     return res;
1211   }
1212
1213   /* Allocate another pair for stderr. */
1214   res = os_socketpair(s_err);
1215   if (res) {
1216     res = errno;
1217     socket_del(i_socket(iauth));
1218     close(s_io[1]);
1219     close(s_io[0]);
1220     return res;
1221   }
1222
1223   /* Mark parent side of this pair non-blocking, too. */
1224   res = os_set_nonblocking(s_err[0]);
1225   if (!res) {
1226     res = errno;
1227     close(s_err[1]);
1228     close(s_err[0]);
1229     socket_del(i_socket(iauth));
1230     close(s_io[1]);
1231     close(s_io[0]);
1232     return res;
1233   }
1234
1235   /* And set up i_stderr(iauth). */
1236   res = socket_add(i_stderr(iauth), iauth_stderr_callback, iauth,
1237                    SS_CONNECTED, SOCK_EVENT_READABLE, s_err[0]);
1238   if (!res) {
1239     res = errno;
1240     close(s_err[1]);
1241     close(s_err[0]);
1242     socket_del(i_socket(iauth));
1243     close(s_io[1]);
1244     close(s_io[0]);
1245     return res;
1246   }
1247
1248   /* Attempt to fork a child process. */
1249   cpid = fork();
1250   if (cpid < 0) {
1251     /* Error forking the child, still in parent. */
1252     res = errno;
1253     socket_del(i_stderr(iauth));
1254     close(s_err[1]);
1255     close(s_err[0]);
1256     socket_del(i_socket(iauth));
1257     close(s_io[1]);
1258     close(s_io[0]);
1259     return res;
1260   }
1261
1262   if (cpid > 0) {
1263     /* We are the parent process.  Close the child's sockets. */
1264     close(s_io[1]);
1265     close(s_err[1]);
1266     /* Send our server name (supposedly for proxy checking purposes)
1267      * and maximum number of connections (for allocation hints).
1268      * Need to use conf_get_local() since &me may not be fully
1269      * initialized the first time we run.
1270      */
1271     sendto_iauth(NULL, "M %s %d", conf_get_local()->name, MAXCONNECTIONS);
1272     /* Indicate success (until the child dies). */
1273     return 0;
1274   }
1275
1276   /* We are the child process.
1277    * Duplicate our end of the socket to stdin, stdout and stderr.
1278    * Then close all the higher-numbered FDs and exec the process.
1279    */
1280   if (dup2(s_io[1], 0) == 0
1281       && dup2(s_io[1], 1) == 1
1282       && dup2(s_err[1], 2) == 2) {
1283     close_connections(0);
1284     execvp(iauth->i_argv[0], iauth->i_argv);
1285   }
1286
1287   /* If we got here, something was seriously wrong. */
1288   exit(EXIT_FAILURE);
1289 }
1290
1291 /** See if an %IAuth program must be spawned.
1292  * If a process is already running with the specified options, keep it.
1293  * Otherwise spawn a new child process to perform the %IAuth function.
1294  * @param[in] argc Number of parameters to use when starting process.
1295  * @param[in] argv Array of parameters to start process.
1296  * @return 0 on failure, 1 on new process, 2 on reuse of existing process.
1297  */
1298 int auth_spawn(int argc, char *argv[])
1299 {
1300   int ii;
1301
1302   if (iauth) {
1303     int same = 1;
1304
1305     /* Check that incoming arguments all match pre-existing arguments. */
1306     for (ii = 0; same && (ii < argc); ++ii) {
1307       if (NULL == iauth->i_argv[ii]
1308           || 0 != strcmp(iauth->i_argv[ii], argv[ii]))
1309         same = 0;
1310     }
1311     /* Check that we have no more pre-existing arguments. */
1312     if (iauth->i_argv[ii])
1313       same = 0;
1314     /* If they are the same and still connected, clear the "closing" flag and exit.*/
1315     if (same && i_GetConnected(iauth)) {
1316       IAuthClr(iauth, IAUTH_CLOSING);
1317       return 2;
1318     }
1319     /* Deallocate old argv elements. */
1320     for (ii = 0; iauth->i_argv[ii]; ++ii)
1321       MyFree(iauth->i_argv[ii]);
1322     MyFree(iauth->i_argv);
1323   }
1324
1325   /* Need to initialize a new connection. */
1326   iauth = MyCalloc(1, sizeof(*iauth));
1327   msgq_init(i_sendQ(iauth));
1328   /* Populate iauth's argv array. */
1329   iauth->i_argv = MyCalloc(argc + 1, sizeof(iauth->i_argv[0]));
1330   for (ii = 0; ii < argc; ++ii)
1331     DupString(iauth->i_argv[ii], argv[ii]);
1332   iauth->i_argv[ii] = NULL;
1333   /* Try to spawn it, and handle the results. */
1334   if (iauth_do_spawn(iauth, 0))
1335     return 0;
1336   IAuthClr(iauth, IAUTH_CLOSING);
1337   return 1;
1338 }
1339
1340 /** Mark all %IAuth connections as closing. */
1341 void auth_mark_closing(void)
1342 {
1343   if (iauth)
1344     IAuthSet(iauth, IAUTH_CLOSING);
1345 }
1346
1347 /** Complete disconnection of an %IAuth connection.
1348  * @param[in] iauth %Connection to fully close.
1349  */
1350 static void iauth_disconnect(struct IAuth *iauth)
1351 {
1352   if (iauth == NULL)
1353     return;
1354
1355   /* Close main socket. */
1356   if (s_fd(i_socket(iauth)) != -1) {
1357     close(s_fd(i_socket(iauth)));
1358     socket_del(i_socket(iauth));
1359     s_fd(i_socket(iauth)) = -1;
1360   }
1361
1362   /* Close error socket. */
1363   if (s_fd(i_stderr(iauth)) != -1) {
1364     close(s_fd(i_stderr(iauth)));
1365     socket_del(i_stderr(iauth));
1366     s_fd(i_stderr(iauth)) = -1;
1367   }
1368 }
1369
1370 /** Close all %IAuth connections marked as closing. */
1371 void auth_close_unused(void)
1372 {
1373   if (IAuthHas(iauth, IAUTH_CLOSING)) {
1374     int ii;
1375     iauth_disconnect(iauth);
1376     if (iauth->i_argv) {
1377       for (ii = 0; iauth->i_argv[ii]; ++ii)
1378         MyFree(iauth->i_argv[ii]);
1379       MyFree(iauth->i_argv);
1380     }
1381     MyFree(iauth);
1382   }
1383 }
1384
1385 /** Send queued output to \a iauth.
1386  * @param[in] iauth Writable connection with queued data.
1387  */
1388 static void iauth_write(struct IAuth *iauth)
1389 {
1390   unsigned int bytes_tried, bytes_sent;
1391   IOResult iores;
1392
1393   if (IAuthHas(iauth, IAUTH_BLOCKED))
1394     return;
1395   while (MsgQLength(i_sendQ(iauth)) > 0) {
1396     iores = os_sendv_nonb(s_fd(i_socket(iauth)), i_sendQ(iauth), &bytes_tried, &bytes_sent);
1397     switch (iores) {
1398     case IO_SUCCESS:
1399       msgq_delete(i_sendQ(iauth), bytes_sent);
1400       iauth->i_sendB += bytes_sent;
1401       if (bytes_tried == bytes_sent)
1402         break;
1403       /* If bytes_sent < bytes_tried, fall through to IO_BLOCKED. */
1404     case IO_BLOCKED:
1405       IAuthSet(iauth, IAUTH_BLOCKED);
1406       socket_events(i_socket(iauth), SOCK_ACTION_ADD | SOCK_EVENT_WRITABLE);
1407       return;
1408     case IO_FAILURE:
1409       iauth_disconnect(iauth);
1410       return;
1411     }
1412   }
1413   /* We were able to flush all events, so remove notification. */
1414   socket_events(i_socket(iauth), SOCK_ACTION_DEL | SOCK_EVENT_WRITABLE);
1415 }
1416
1417 /** Send a message to iauth.
1418  * @param[in] cptr Optional client context for message.
1419  * @param[in] format Format string for message.
1420  * @return Non-zero on successful send or buffering, zero on failure.
1421  */
1422 static int sendto_iauth(struct Client *cptr, const char *format, ...)
1423 {
1424   struct VarData vd;
1425   struct MsgBuf *mb;
1426
1427   /* Do not send requests when we have no iauth. */
1428   if (!i_GetConnected(iauth))
1429     return 0;
1430   /* Do not send for clients in the NORMAL state. */
1431   if (cptr
1432       && (format[0] != 'D')
1433       && (!cli_auth(cptr) || !FlagHas(&cli_auth(cptr)->flags, AR_IAUTH_PENDING)))
1434     return 0;
1435
1436   /* Build the message buffer. */
1437   vd.vd_format = format;
1438   va_start(vd.vd_args, format);
1439   if (0 == cptr)
1440     mb = msgq_make(NULL, "-1 %v", &vd);
1441   else
1442     mb = msgq_make(NULL, "%d %v", cli_fd(cptr), &vd);
1443   va_end(vd.vd_args);
1444
1445   /* Tack it onto the iauth sendq and try to write it. */
1446   ++iauth->i_sendM;
1447   msgq_add(i_sendQ(iauth), mb, 0);
1448   msgq_clean(mb);
1449   iauth_write(iauth);
1450   return 1;
1451 }
1452
1453 /** Send text to interested operators (SNO_AUTH server notice).
1454  * @param[in] iauth Active IAuth session.
1455  * @param[in] cli Client referenced by command.
1456  * @param[in] parc Number of parameters (1).
1457  * @param[in] params Text to send.
1458  * @return Zero.
1459  */
1460 static int iauth_cmd_snotice(struct IAuth *iauth, struct Client *cli,
1461                              int parc, char **params)
1462 {
1463   sendto_opmask_butone(NULL, SNO_AUTH, "%s", params[0]);
1464   return 0;
1465 }
1466
1467 /** Set the debug level for the session.
1468  * @param[in] iauth Active IAuth session.
1469  * @param[in] cli Client referenced by command.
1470  * @param[in] parc Number of parameters (1).
1471  * @param[in] params String starting with an integer.
1472  * @return Zero.
1473  */
1474 static int iauth_cmd_debuglevel(struct IAuth *iauth, struct Client *cli,
1475                                 int parc, char **params)
1476 {
1477   int new_level;
1478
1479   new_level = parc > 0 ? atoi(params[0]) : 0;
1480   if (i_debug(iauth) > 0 || new_level > 0) {
1481     /* The "ia_dbg" name is borrowed from (IRCnet) ircd. */
1482     sendto_opmask_butone(NULL, SNO_AUTH, "ia_dbg = %d", new_level);
1483   }
1484   i_debug(iauth) = new_level;
1485   return 0;
1486 }
1487
1488 /** Set policy options for the session.
1489  * Old policy is forgotten, and any of the following characters in \a
1490  * params enable the corresponding policy:
1491  * \li A IAUTH_ADDLINFO
1492  * \li R IAUTH_REQUIRED
1493  * \li T IAUTH_TIMEOUT
1494  * \li W IAUTH_EXTRAWAIT
1495  * \li U IAUTH_UNDERNET
1496  *
1497  * @param[in] iauth Active IAuth session.
1498  * @param[in] cli Client referenced by command.
1499  * @param[in] parc Number of parameters (1).
1500  * @param[in] params Zero or more policy options.
1501  * @return Zero.
1502  */
1503 static int iauth_cmd_policy(struct IAuth *iauth, struct Client *cli,
1504                             int parc, char **params)
1505 {
1506   enum IAuthFlag flag;
1507   char *p;
1508
1509   /* Erase old policy first. */
1510   for (flag = IAUTH_FIRST_OPTION; flag < IAUTH_LAST_FLAG; ++flag)
1511     IAuthClr(iauth, flag);
1512
1513   if (parc > 0) /* only try to parse if we were given a policy string */
1514     /* Parse new policy set. */
1515     for (p = params[0]; *p; p++) switch (*p) {
1516     case 'A': IAuthSet(iauth, IAUTH_ADDLINFO); break;
1517     case 'R': IAuthSet(iauth, IAUTH_REQUIRED); break;
1518     case 'T': IAuthSet(iauth, IAUTH_TIMEOUT); break;
1519     case 'W': IAuthSet(iauth, IAUTH_EXTRAWAIT); break;
1520     case 'U': IAuthSet(iauth, IAUTH_UNDERNET); break;
1521     }
1522
1523   /* Optionally notify operators. */
1524   if (i_debug(iauth) > 0)
1525     sendto_opmask_butone(NULL, SNO_AUTH, "iauth options: %s", params[0]);
1526   return 0;
1527 }
1528
1529 /** Set the iauth program version number.
1530  * @param[in] iauth Active IAuth session.
1531  * @param[in] cli Client referenced by command.
1532  * @param[in] parc Number of parameters (1).
1533  * @param[in] params Version number or name.
1534  * @return Zero.
1535  */
1536 static int iauth_cmd_version(struct IAuth *iauth, struct Client *cli,
1537                              int parc, char **params)
1538 {
1539   MyFree(iauth->i_version);
1540   DupString(iauth->i_version, parc > 0 ? params[0] : "<NONE>");
1541   sendto_opmask_butone(NULL, SNO_AUTH, "iauth version %s running.",
1542                        iauth->i_version);
1543   return 0;
1544 }
1545
1546 /** Paste a parameter list together into a single string.
1547  * @param[in] parc Number of parameters.
1548  * @param[in] params Parameter list to paste together.
1549  * @return Pasted parameter list.
1550  */
1551 static char *paste_params(int parc, char **params)
1552 {
1553   char *str, *tmp;
1554   int len = 0, lengths[MAXPARA], i;
1555
1556   /* Compute the length... */
1557   for (i = 0; i < parc; i++)
1558     len += lengths[i] = strlen(params[i]);
1559
1560   /* Allocate memory, accounting for string lengths, spaces (parc - 1), a
1561    * sentinel, and the trailing \0
1562    */
1563   str = MyMalloc(len + parc + 1);
1564
1565   /* Build the pasted string */
1566   for (tmp = str, i = 0; i < parc; i++) {
1567     if (i) /* add space separator... */
1568       *(tmp++) = ' ';
1569     if (i == parc - 1) /* add colon sentinel */
1570       *(tmp++) = ':';
1571
1572     /* Copy string component... */
1573     memcpy(tmp, params[i], lengths[i]);
1574     tmp += lengths[i]; /* move to end of string */
1575   }
1576
1577   /* terminate the string... */
1578   *tmp = '\0';
1579
1580   return str; /* return the pasted string */
1581 }
1582
1583 /** Clear cached iauth configuration information.
1584  * @param[in] iauth Active IAuth session.
1585  * @param[in] cli Client referenced by command.
1586  * @param[in] parc Number of parameters (0).
1587  * @param[in] params Parameter list (ignored).
1588  * @return Zero.
1589  */
1590 static int iauth_cmd_newconfig(struct IAuth *iauth, struct Client *cli,
1591                                int parc, char **params)
1592 {
1593   struct SLink *head;
1594   struct SLink *next;
1595
1596   head = iauth->i_config;
1597   iauth->i_config = NULL;
1598   for (; head; head = next) {
1599     next = head->next;
1600     MyFree(head->value.cp);
1601     free_link(head);
1602   }
1603   sendto_opmask_butone(NULL, SNO_AUTH, "New iauth configuration.");
1604   return 0;
1605 }
1606
1607 /** Append iauth configuration information.
1608  * @param[in] iauth Active IAuth session.
1609  * @param[in] cli Client referenced by command.
1610  * @param[in] parc Number of parameters.
1611  * @param[in] params Description of configuration element.
1612  * @return Zero.
1613  */
1614 static int iauth_cmd_config(struct IAuth *iauth, struct Client *cli,
1615                             int parc, char **params)
1616 {
1617   struct SLink *node;
1618
1619   if (iauth->i_config) {
1620     for (node = iauth->i_config; node->next; node = node->next) ;
1621     node = node->next = make_link();
1622   } else {
1623     node = iauth->i_config = make_link();
1624   }
1625   node->value.cp = paste_params(parc, params);
1626   node->next = 0; /* must be explicitly cleared */
1627   return 0;
1628 }
1629
1630 /** Clear cached 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 (0).
1634  * @param[in] params Parameter list (ignored).
1635  * @return Zero.
1636  */
1637 static int iauth_cmd_newstats(struct IAuth *iauth, struct Client *cli,
1638                               int parc, char **params)
1639 {
1640   struct SLink *head;
1641   struct SLink *next;
1642
1643   head = iauth->i_stats;
1644   iauth->i_stats = NULL;
1645   for (; head; head = next) {
1646     next = head->next;
1647     MyFree(head->value.cp);
1648     free_link(head);
1649   }
1650   sendto_opmask_butone(NULL, SNO_AUTH, "New iauth statistics.");
1651   return 0;
1652 }
1653
1654 /** Append iauth statistics information.
1655  * @param[in] iauth Active IAuth session.
1656  * @param[in] cli Client referenced by command.
1657  * @param[in] parc Number of parameters.
1658  * @param[in] params Statistics element.
1659  * @return Zero.
1660  */
1661 static int iauth_cmd_stats(struct IAuth *iauth, struct Client *cli,
1662                            int parc, char **params)
1663 {
1664   struct SLink *node;
1665   if (iauth->i_stats) {
1666     for (node = iauth->i_stats; node->next; node = node->next) ;
1667     node = node->next = make_link();
1668   } else {
1669     node = iauth->i_stats = make_link();
1670   }
1671   node->value.cp = paste_params(parc, params);
1672   node->next = 0; /* must be explicitly cleared */
1673   return 0;
1674 }
1675
1676 /** Set client's username to a trusted string even if it breaks the rules.
1677  * @param[in] iauth Active IAuth session.
1678  * @param[in] cli Client referenced by command.
1679  * @param[in] parc Number of parameters (1).
1680  * @param[in] params Forced username.
1681  * @return One.
1682  */
1683 static int iauth_cmd_username_forced(struct IAuth *iauth, struct Client *cli,
1684                                      int parc, char **params)
1685 {
1686   assert(cli_auth(cli) != NULL);
1687   FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
1688   if (!EmptyString(params[0])) {
1689     ircd_strncpy(cli_username(cli), params[0], USERLEN);
1690     SetGotId(cli);
1691     FlagSet(&cli_auth(cli)->flags, AR_IAUTH_USERNAME);
1692     FlagSet(&cli_auth(cli)->flags, AR_IAUTH_FUSERNAME);
1693   }
1694   return 1;
1695 }
1696
1697 /** Set client's username to a trusted string.
1698  * @param[in] iauth Active IAuth session.
1699  * @param[in] cli Client referenced by command.
1700  * @param[in] parc Number of parameters (1).
1701  * @param[in] params Trusted username.
1702  * @return One.
1703  */
1704 static int iauth_cmd_username_good(struct IAuth *iauth, struct Client *cli,
1705                                    int parc, char **params)
1706 {
1707   assert(cli_auth(cli) != NULL);
1708   FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
1709   if (!EmptyString(params[0])) {
1710     ircd_strncpy(cli_username(cli), params[0], USERLEN);
1711     SetGotId(cli);
1712     FlagSet(&cli_auth(cli)->flags, AR_IAUTH_USERNAME);
1713   }
1714   return 1;
1715 }
1716
1717 /** Set client's username to an untrusted string.
1718  * @param[in] iauth Active IAuth session.
1719  * @param[in] cli Client referenced by command.
1720  * @param[in] parc Number of parameters (1).
1721  * @param[in] params Untrusted username.
1722  * @return One.
1723  */
1724 static int iauth_cmd_username_bad(struct IAuth *iauth, struct Client *cli,
1725                                   int parc, char **params)
1726 {
1727   assert(cli_auth(cli) != NULL);
1728   FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
1729   if (!EmptyString(params[0]))
1730     ircd_strncpy(cli_user(cli)->username, params[0], USERLEN);
1731   return 1;
1732 }
1733
1734 /** Set client's hostname.
1735  * @param[in] iauth Active IAuth session.
1736  * @param[in] cli Client referenced by command.
1737  * @param[in] parc Number of parameters (1).
1738  * @param[in] params New hostname for client.
1739  * @return Non-zero if \a cli authorization should be checked for completion.
1740  */
1741 static int iauth_cmd_hostname(struct IAuth *iauth, struct Client *cli,
1742                               int parc, char **params)
1743 {
1744   struct AuthRequest *auth;
1745
1746   if (EmptyString(params[0])) {
1747     sendto_iauth(cli, "E Missing :Missing hostname parameter");
1748     return 0;
1749   }
1750
1751   auth = cli_auth(cli);
1752   assert(auth != NULL);
1753
1754   /* If a DNS request is pending, abort it. */
1755   if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
1756     FlagClr(&auth->flags, AR_DNS_PENDING);
1757     delete_resolver_queries(auth);
1758     if (IsUserPort(cli))
1759       sendheader(cli, REPORT_FIN_DNS);
1760   }
1761   /* Set hostname from params. */
1762   ircd_strncpy(cli_sockhost(cli), params[0], HOSTLEN);
1763   /* If we have gotten here, the user is in a "hurry" state and has
1764    * been pre-registered.  Their hostname was set during that, and
1765    * needs to be overwritten now.
1766    */
1767   if (FlagHas(&auth->flags, AR_IAUTH_HURRY)) {
1768     ircd_strncpy(cli_user(cli)->host, cli_sockhost(cli), HOSTLEN);
1769     ircd_strncpy(cli_user(cli)->realhost, cli_sockhost(cli), HOSTLEN);
1770   }
1771   return 1;
1772 }
1773
1774 /** Set client's IP address.
1775  * @param[in] iauth Active IAuth session.
1776  * @param[in] cli Client referenced by command.
1777  * @param[in] parc Number of parameters (1).
1778  * @param[in] params New IP address for client in dotted quad or
1779  *   standard IPv6 format.
1780  * @return Zero.
1781  */
1782 static int iauth_cmd_ip_address(struct IAuth *iauth, struct Client *cli,
1783                                 int parc, char **params)
1784 {
1785   struct irc_in_addr addr;
1786   struct AuthRequest *auth;
1787
1788   if (EmptyString(params[0])) {
1789     sendto_iauth(cli, "E Missing :Missing IP address parameter");
1790     return 0;
1791   }
1792
1793   /* Get AuthRequest for client. */
1794   auth = cli_auth(cli);
1795   assert(auth != NULL);
1796
1797   /* Parse the client's new IP address. */
1798   if (!ircd_aton(&addr, params[0])) {
1799     sendto_iauth(cli, "E Invalid :Unable to parse IP address [%s]", params[0]);
1800     return 0;
1801   }
1802
1803   /* If this is the first IP override, save the client's original
1804    * address in case we get a DNS response later.
1805    */
1806   if (!irc_in_addr_valid(&auth->original))
1807     memcpy(&auth->original, &cli_ip(cli), sizeof(auth->original));
1808
1809   /* Undo original IP connection in IPcheck. */
1810   IPcheck_connect_fail(cli);
1811   ClearIPChecked(cli);
1812
1813   /* Update the IP and charge them as a remote connect. */
1814   memcpy(&cli_ip(cli), &addr, sizeof(cli_ip(cli)));
1815   IPcheck_remote_connect(cli, 0);
1816
1817   return 0;
1818 }
1819
1820 /** Find a ConfItem structure for a named connection class.
1821  * @param[in] class_name Name of configuration class to find.
1822  * @return A ConfItem of type CONF_CLIENT for the class, or NULL on failure.
1823  */
1824 static struct ConfItem *auth_find_class_conf(const char *class_name)
1825 {
1826   static struct ConfItem *aconf_list;
1827   struct ConnectionClass *class;
1828   struct ConfItem *aconf;
1829
1830   /* Make sure the configuration class is valid. */
1831   class = find_class(class_name);
1832   if (!class || !class->valid)
1833     return NULL;
1834
1835   /* Look for an existing ConfItem for the class. */
1836   for (aconf = aconf_list; aconf; aconf = aconf->next)
1837     if (aconf->conn_class == class)
1838       break;
1839
1840   /* If no ConfItem, create one. */
1841   if (!aconf) {
1842     aconf = make_conf(CONF_CLIENT);
1843     if (!aconf) {
1844       sendto_opmask_butone(NULL, SNO_AUTH,
1845                            "Unable to allocate ConfItem for class %s!",
1846                            ConClass(class));
1847       return NULL;
1848     }
1849     /* make_conf() "helpfully" links the conf into GlobalConfList,
1850      * which we do not want, so undo that.  (Ugh.)
1851      */
1852     if (aconf == GlobalConfList) {
1853       GlobalConfList = aconf->next;
1854     }
1855     /* Back to business as usual. */
1856     aconf->conn_class = class;
1857     aconf->next = aconf_list;
1858     aconf_list = aconf;
1859   }
1860
1861   return aconf;
1862 }
1863
1864 /** Accept a client in IAuth.
1865  * @param[in] iauth Active IAuth session.
1866  * @param[in] cli Client referenced by command.
1867  * @param[in] parc Number of parameters.
1868  * @param[in] params Optional class name for client.
1869  * @return Negative (CPTR_KILLED) if the connection is refused, one otherwise.
1870  */
1871 static int iauth_cmd_done_client(struct IAuth *iauth, struct Client *cli,
1872                                  int parc, char **params)
1873 {
1874   static time_t warn_time;
1875
1876   /* Clear iauth pending flag. */
1877   assert(cli_auth(cli) != NULL);
1878   FlagClr(&cli_auth(cli)->flags, AR_IAUTH_PENDING);
1879
1880   /* If a connection class was specified (and usable), assign the client to it. */
1881   if (!EmptyString(params[0])) {
1882     struct ConfItem *aconf;
1883
1884     aconf = auth_find_class_conf(params[0]);
1885     if (aconf) {
1886       enum AuthorizationCheckResult acr;
1887
1888       acr = attach_conf(cli, aconf);
1889       switch (acr) {
1890       case ACR_OK:
1891         /* There should maybe be some way to set FLAG_DOID here.. */
1892         break;
1893       case ACR_TOO_MANY_IN_CLASS:
1894         ++ServerStats->is_ref;
1895         return exit_client(cli, cli, &me,
1896                            "Sorry, your connection class is full - try "
1897                            "again later or try another server");
1898       default:
1899         log_write(LS_IAUTH, L_ERROR, 0, "IAuth: Unexpected AuthorizationCheckResult %d from attach_conf()", acr);
1900         break;
1901       }
1902     } else
1903       sendto_opmask_butone_ratelimited(NULL, SNO_AUTH, &warn_time,
1904                                        "iauth tried to use undefined class [%s]",
1905                                        params[0]);
1906   }
1907
1908   return 1;
1909 }
1910
1911 /** Accept a client in IAuth and assign them to an account.
1912  * @param[in] iauth Active IAuth session.
1913  * @param[in] cli Client referenced by command.
1914  * @param[in] parc Number of parameters.
1915  * @param[in] params Account name and optional class name for client.
1916  * @return Negative if the connection is refused, otherwise non-zero
1917  *   if \a cli authorization should be checked for completion.
1918  */
1919 static int iauth_cmd_done_account(struct IAuth *iauth, struct Client *cli,
1920                                   int parc, char **params)
1921 {
1922   size_t len;
1923
1924   /* Sanity check. */
1925   if (EmptyString(params[0])) {
1926     sendto_iauth(cli, "E Missing :Missing account parameter");
1927     return 0;
1928   }
1929   /* Check length of account name. */
1930   len = strcspn(params[0], ": ");
1931   if (len > ACCOUNTLEN) {
1932     sendto_iauth(cli, "E Invalid :Account parameter too long");
1933     return 0;
1934   }
1935   /* If account has a creation timestamp, use it. */
1936   assert(cli_user(cli) != NULL);
1937   if (params[0][len] == ':')
1938     cli_user(cli)->acc_create = strtoul(params[0] + len + 1, NULL, 10);
1939
1940   /* Copy account name to User structure. */
1941   ircd_strncpy(cli_user(cli)->account, params[0], ACCOUNTLEN);
1942   SetAccount(cli);
1943
1944   /* Fall through to the normal "done" handler. */
1945   return iauth_cmd_done_client(iauth, cli, parc - 1, params + 1);
1946 }
1947
1948 /** Reject a client's connection.
1949  * @param[in] iauth Active IAuth session.
1950  * @param[in] cli Client referenced by command.
1951  * @param[in] parc Number of parameters (1).
1952  * @param[in] params Optional kill message.
1953  * @return Zero.
1954  */
1955 static int iauth_cmd_kill(struct IAuth *iauth, struct Client *cli,
1956                           int parc, char **params)
1957 {
1958   if (cli_auth(cli))
1959     FlagClr(&cli_auth(cli)->flags, AR_IAUTH_PENDING);
1960   if (EmptyString(params[0]))
1961     params[0] = "Access denied";
1962   exit_client(cli, cli, &me, params[0]);
1963   return 0;
1964 }
1965
1966 /** Change a client's usermode.
1967  * @param[in] iauth Active IAuth session.
1968  * @param[in] cli Client referenced by command.
1969  * @param[in] parc Number of parameters (at least one).
1970  * @param[in] params Usermode arguments for client (with the first
1971  *   starting with '+').
1972  * @return Zero.
1973  */
1974 static int iauth_cmd_usermode(struct IAuth *iauth, struct Client *cli,
1975                               int parc, char **params)
1976 {
1977   if (params[0][0] == '+')
1978   {
1979     set_user_mode(cli, cli, parc + 2, params - 2, ALLOWMODES_ANY);
1980   }
1981   return 0;
1982 }
1983
1984
1985 /** Send a challenge string to the client.
1986  * @param[in] iauth Active IAuth session.
1987  * @param[in] cli Client referenced by command.
1988  * @param[in] parc Number of parameters (1).
1989  * @param[in] params Challenge message for client.
1990  * @return Zero.
1991  */
1992 static int iauth_cmd_challenge(struct IAuth *iauth, struct Client *cli,
1993                                int parc, char **params)
1994 {
1995   if (!EmptyString(params[0]))
1996     sendrawto_one(cli, "NOTICE AUTH :*** %s", params[0]);
1997   return 0;
1998 }
1999
2000 /** Parse a \a message from \a iauth.
2001  * @param[in] iauth Active IAuth session.
2002  * @param[in] message Message to be parsed.
2003  */
2004 static void iauth_parse(struct IAuth *iauth, char *message)
2005 {
2006   char *params[MAXPARA + 1]; /* leave space for NULL */
2007   int parc = 0;
2008   iauth_cmd_handler handler;
2009   struct AuthRequest *auth;
2010   struct Client *cli;
2011   int has_cli;
2012   int id;
2013
2014   /* Find command handler... */
2015   switch (*(message++)) {
2016   case '>': handler = iauth_cmd_snotice; has_cli = 0; break;
2017   case 'G': handler = iauth_cmd_debuglevel; has_cli = 0; break;
2018   case 'O': handler = iauth_cmd_policy; has_cli = 0; break;
2019   case 'V': handler = iauth_cmd_version; has_cli = 0; break;
2020   case 'a': handler = iauth_cmd_newconfig; has_cli = 0; break;
2021   case 'A': handler = iauth_cmd_config; has_cli = 0; break;
2022   case 's': handler = iauth_cmd_newstats; has_cli = 0; break;
2023   case 'S': handler = iauth_cmd_stats; has_cli = 0; break;
2024   case 'o': handler = iauth_cmd_username_forced; has_cli = 1; break;
2025   case 'U': handler = iauth_cmd_username_good; has_cli = 1; break;
2026   case 'u': handler = iauth_cmd_username_bad; has_cli = 1; break;
2027   case 'N': handler = iauth_cmd_hostname; has_cli = 1; break;
2028   case 'I': handler = iauth_cmd_ip_address; has_cli = 1; break;
2029   case 'M': handler = iauth_cmd_usermode; has_cli = 1; break;
2030   case 'C': handler = iauth_cmd_challenge; has_cli = 1; break;
2031   case 'D': handler = iauth_cmd_done_client; has_cli = 1; break;
2032   case 'R': handler = iauth_cmd_done_account; has_cli = 1; break;
2033   case 'k': /* The 'k' command indicates the user should be booted
2034              * off without telling opers.  There is no way to
2035              * signal that to exit_client(), so we fall through to
2036              * the case that we do implement.
2037              */
2038   case 'K': handler = iauth_cmd_kill; has_cli = 2; break;
2039   case 'r': /* we handle termination directly */ return;
2040   default:  sendto_iauth(NULL, "E Garbage :[%s]", message); return;
2041   }
2042
2043   while (parc < MAXPARA) {
2044     while (IsSpace(*message)) /* skip leading whitespace */
2045       message++;
2046
2047     if (!*message) /* hit the end of the string, break out */
2048       break;
2049
2050     if (*message == ':') { /* found sentinel... */
2051       params[parc++] = message + 1;
2052       break; /* it's the last parameter anyway */
2053     }
2054
2055     params[parc++] = message; /* save the parameter */
2056     while (*message && !IsSpace(*message))
2057       message++; /* find the end of the parameter */
2058
2059     if (*message) /* terminate the parameter */
2060       *(message++) = '\0';
2061   }
2062
2063   params[parc] = NULL; /* terminate the parameter list */
2064
2065   /* Check to see if the command specifies a client... */
2066   if (!has_cli) {
2067     /* Handler does not need a client. */
2068     handler(iauth, NULL, parc, params);
2069   } else {
2070     /* Try to find the client associated with the request. */
2071     id = strtol(params[0], NULL, 10);
2072     if (parc < 3)
2073       sendto_iauth(NULL, "E Missing :Need <id> <ip> <port>");
2074     else if (id < 0 || id > HighestFd || !(cli = LocalClientArray[id]))
2075       /* Client no longer exists (or never existed). */
2076       sendto_iauth(NULL, "E Gone :[%s %s %s]", params[0], params[1],
2077                    params[2]);
2078     else if ((!(auth = cli_auth(cli)) ||
2079               !FlagHas(&auth->flags, AR_IAUTH_PENDING)) &&
2080              has_cli == 1)
2081       /* Client is done with IAuth checks. */
2082       sendto_iauth(cli, "E Done :[%s %s %s]", params[0], params[1], params[2]);
2083     else {
2084       struct irc_sockaddr addr;
2085       int res;
2086
2087       /* Parse IP address and port number from parameters */
2088       res = ipmask_parse(params[1], &addr.addr, NULL);
2089       addr.port = strtol(params[2], NULL, 10);
2090
2091       /* Check IP address and port number against expected. */
2092       if (0 == res ||
2093           irc_in_addr_cmp(&addr.addr, &cli_ip(cli)) ||
2094           (auth && addr.port != auth->port))
2095         /* Report mismatch to iauth. */
2096         sendto_iauth(cli, "E Mismatch :[%s] != [%s]", params[1],
2097                      ircd_ntoa(&cli_ip(cli)));
2098       else if (handler(iauth, cli, parc - 3, params + 3) > 0)
2099         /* Handler indicated a possible state change. */
2100         check_auth_finished(auth);
2101     }
2102   }
2103 }
2104
2105 /** Read input from \a iauth.
2106  * Reads up to SERVER_TCP_WINDOW bytes per pass.
2107  * @param[in] iauth Readable connection.
2108  */
2109 static void iauth_read(struct IAuth *iauth)
2110 {
2111   static char readbuf[SERVER_TCP_WINDOW];
2112   unsigned int length, count;
2113   char *sol;
2114   char *eol;
2115
2116   /* Copy partial data to readbuf, append new data. */
2117   length = iauth->i_count;
2118   memcpy(readbuf, iauth->i_buffer, length);
2119   if (IO_SUCCESS != os_recv_nonb(s_fd(i_socket(iauth)),
2120                                  readbuf + length,
2121                                  sizeof(readbuf) - length - 1,
2122                                  &count))
2123     return;
2124   readbuf[length += count] = '\0';
2125
2126   /* Parse each complete line. */
2127   for (sol = readbuf; (eol = strchr(sol, '\n')) != NULL; sol = eol + 1) {
2128     *eol = '\0';
2129     if (*(eol - 1) == '\r') /* take out carriage returns, too... */
2130       *(eol - 1) = '\0';
2131
2132     /* If spammy debug, send the message to opers. */
2133     if (i_debug(iauth) > 1)
2134       sendto_opmask_butone(NULL, SNO_AUTH, "Parsing: \"%s\"", sol);
2135
2136     /* Parse the line... */
2137     iauth_parse(iauth, sol);
2138   }
2139
2140   /* Put unused data back into connection's buffer. */
2141   iauth->i_count = strlen(sol);
2142   if (iauth->i_count > BUFSIZE)
2143     iauth->i_count = BUFSIZE;
2144   memcpy(iauth->i_buffer, sol, iauth->i_count);
2145 }
2146
2147 /** Handle socket activity for an %IAuth connection.
2148  * @param[in] ev &Socket event; the IAuth connection is the user data
2149  *   pointer for the socket.
2150  */
2151 static void iauth_sock_callback(struct Event *ev)
2152 {
2153   struct IAuth *iauth;
2154
2155   assert(0 != ev_socket(ev));
2156   iauth = (struct IAuth*) s_data(ev_socket(ev));
2157   assert(0 != iauth);
2158
2159   switch (ev_type(ev)) {
2160   case ET_DESTROY:
2161     /* Hm, what happened here? */
2162     if (!IAuthHas(iauth, IAUTH_CLOSING))
2163       iauth_do_spawn(iauth, 1);
2164     break;
2165   case ET_READ:
2166     iauth_read(iauth);
2167     break;
2168   case ET_WRITE:
2169     IAuthClr(iauth, IAUTH_BLOCKED);
2170     iauth_write(iauth);
2171     break;
2172   case ET_ERROR:
2173     log_write(LS_IAUTH, L_ERROR, 0, "IAuth socket error: %s", strerror(ev_data(ev)));
2174     /* and fall through to the ET_EOF case */
2175   case ET_EOF:
2176     iauth_disconnect(iauth);
2177     break;
2178   default:
2179     assert(0 && "Unrecognized event type");
2180     break;
2181   }
2182 }
2183
2184 /** Read error input from \a iauth.
2185  * @param[in] iauth Readable connection.
2186  */
2187 static void iauth_read_stderr(struct IAuth *iauth)
2188 {
2189   static char readbuf[SERVER_TCP_WINDOW];
2190   unsigned int length, count;
2191   char *sol;
2192   char *eol;
2193
2194   /* Copy partial data to readbuf, append new data. */
2195   length = iauth->i_errcount;
2196   memcpy(readbuf, iauth->i_errbuf, length);
2197   if (IO_SUCCESS != os_recv_nonb(s_fd(i_stderr(iauth)),
2198                                  readbuf + length,
2199                                  sizeof(readbuf) - length - 1,
2200                                  &count))
2201     return;
2202   readbuf[length += count] = '\0';
2203
2204   /* Send each complete line to SNO_AUTH. */
2205   for (sol = readbuf; (eol = strchr(sol, '\n')) != NULL; sol = eol + 1) {
2206     *eol = '\0';
2207     if (*(eol - 1) == '\r') /* take out carriage returns, too... */
2208       *(eol - 1) = '\0';
2209     Debug((DEBUG_ERROR, "IAuth error: %s", sol));
2210     log_write(LS_IAUTH, L_ERROR, 0, "IAuth error: %s", sol);
2211     sendto_opmask_butone(NULL, SNO_AUTH, "%s", sol);
2212   }
2213
2214   /* Put unused data back into connection's buffer. */
2215   iauth->i_errcount = strlen(sol);
2216   if (iauth->i_errcount > BUFSIZE)
2217     iauth->i_errcount = BUFSIZE;
2218   memcpy(iauth->i_errbuf, sol, iauth->i_errcount);
2219 }
2220
2221 /** Handle error socket activity for an %IAuth connection.
2222  * @param[in] ev &Socket event; the IAuth connection is the user data
2223  *   pointer for the socket.
2224  */
2225 static void iauth_stderr_callback(struct Event *ev)
2226 {
2227   struct IAuth *iauth;
2228
2229   assert(0 != ev_socket(ev));
2230   iauth = (struct IAuth*) s_data(ev_socket(ev));
2231   assert(0 != iauth);
2232
2233   switch (ev_type(ev)) {
2234   case ET_DESTROY:
2235     /* We do not restart iauth here: the stdout handler does that for us. */
2236     break;
2237   case ET_READ:
2238     iauth_read_stderr(iauth);
2239     break;
2240   case ET_ERROR:
2241     log_write(LS_IAUTH, L_ERROR, 0, "IAuth stderr error: %s", strerror(ev_data(ev)));
2242     /* and fall through to the ET_EOF case */
2243   case ET_EOF:
2244     iauth_disconnect(iauth);
2245     break;
2246   default:
2247     assert(0 && "Unrecognized event type");
2248     break;
2249   }
2250 }
2251
2252 /** Report active iauth's configuration to \a cptr.
2253  * @param[in] cptr Client requesting statistics.
2254  * @param[in] sd Stats descriptor for request.
2255  * @param[in] param Extra parameter from user (may be NULL).
2256  */
2257 void report_iauth_conf(struct Client *cptr, const struct StatDesc *sd, char *param)
2258 {
2259     struct SLink *link;
2260
2261     if (iauth) for (link = iauth->i_config; link; link = link->next)
2262     {
2263         send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":%s",
2264                    link->value.cp);
2265     }
2266 }
2267
2268 /** Report active iauth's statistics to \a cptr.
2269  * @param[in] cptr Client requesting statistics.
2270  * @param[in] sd Stats descriptor for request.
2271  * @param[in] param Extra parameter from user (may be NULL).
2272  */
2273  void report_iauth_stats(struct Client *cptr, const struct StatDesc *sd, char *param)
2274 {
2275     struct SLink *link;
2276
2277     if (iauth) for (link = iauth->i_stats; link; link = link->next)
2278     {
2279         send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":%s",
2280                    link->value.cp);
2281     }
2282 }