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