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