1 /************************************************************************
2 * IRC - Internet Relay Chat, src/s_auth.c
3 * Copyright (C) 1992 Darren Reed
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)
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.
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.
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>
28 * December 26, 2005 - Rewrite the flag handling and integrate that with
29 * an IRCnet-style IAuth protocol.
33 * @brief Implementation of DNS and ident lookups.
43 #include "ircd_alloc.h"
44 #include "ircd_chattr.h"
45 #include "ircd_events.h"
46 #include "ircd_features.h"
48 #include "ircd_osdep.h"
49 #include "ircd_reply.h"
50 #include "ircd_snprintf.h"
51 #include "ircd_string.h"
53 #include "msg.h" /* for MAXPARA */
56 #include "querycmds.h"
71 #include <sys/socket.h>
72 #include <sys/ioctl.h>
74 /** Pending operations during registration. */
75 enum AuthRequestFlag {
76 AR_AUTH_PENDING, /**< ident connecting or waiting for response */
77 AR_DNS_PENDING, /**< dns request sent, waiting for response */
78 AR_CAP_PENDING, /**< in middle of CAP negotiations */
79 AR_NEEDS_PONG, /**< user has not PONGed */
80 AR_NEEDS_USER, /**< user must send USER command */
81 AR_NEEDS_NICK, /**< user must send NICK command */
82 AR_LAST_SCAN = AR_NEEDS_NICK, /**< maximum flag to scan through */
83 AR_IAUTH_PENDING, /**< iauth request sent, waiting for response */
84 AR_IAUTH_HURRY, /**< we told iauth to hurry up */
85 AR_IAUTH_USERNAME, /**< iauth sent a username (preferred or forced) */
86 AR_IAUTH_FUSERNAME, /**< iauth sent a forced username */
87 AR_IAUTH_SOFT_DONE, /**< iauth has no objection to client */
88 AR_PASSWORD_CHECKED, /**< client password already checked */
92 DECLARE_FLAGSET(AuthRequestFlags, AR_NUM_FLAGS);
94 /** Stores registration state of a client. */
96 struct AuthRequest* next; /**< linked list node ptr */
97 struct AuthRequest* prev; /**< linked list node ptr */
98 struct Client* client; /**< pointer to client struct for request */
99 struct irc_sockaddr local; /**< local endpoint address */
100 struct irc_in_addr original; /**< original client IP address */
101 struct Socket socket; /**< socket descriptor for auth queries */
102 struct Timer timeout; /**< timeout timer for ident and dns queries */
103 struct AuthRequestFlags flags; /**< current state of request */
104 unsigned int cookie; /**< cookie the user must PONG */
105 unsigned short port; /**< client's remote port number */
108 /** Array of message text (with length) pairs for AUTH status
109 * messages. Indexed using #ReportType.
114 } HeaderMessages [] = {
115 #define MSG(STR) { STR, sizeof(STR) - 1 }
116 MSG("NOTICE AUTH :*** Looking up your hostname\r\n"),
117 MSG("NOTICE AUTH :*** Found your hostname\r\n"),
118 MSG("NOTICE AUTH :*** Couldn't look up your hostname\r\n"),
119 MSG("NOTICE AUTH :*** Checking Ident\r\n"),
120 MSG("NOTICE AUTH :*** Got ident response\r\n"),
121 MSG("NOTICE AUTH :*** No ident response\r\n"),
122 MSG("NOTICE AUTH :*** \r\n"),
123 MSG("NOTICE AUTH :*** Your forward and reverse DNS do not match, "
124 "ignoring hostname.\r\n"),
125 MSG("NOTICE AUTH :*** Invalid hostname\r\n")
129 /** Enum used to index messages in the HeaderMessages[] array. */
142 /** Sends response \a r (from #ReportType) to client \a c. */
143 #define sendheader(c, r) \
144 send(cli_fd(c), HeaderMessages[(r)].message, HeaderMessages[(r)].length, 0)
146 /** Enumeration of IAuth connection flags. */
149 IAUTH_BLOCKED, /**< socket buffer full */
150 IAUTH_CLOSING, /**< candidate to be disposed */
151 /* The following flags are controlled by iauth's "O" options command. */
152 IAUTH_ADDLINFO, /**< Send additional info
153 * (password and username). */
154 IAUTH_FIRST_OPTION = IAUTH_ADDLINFO, /**< First flag that is a policy option. */
155 IAUTH_REQUIRED, /**< IAuth completion required for registration. */
156 IAUTH_TIMEOUT, /**< Refuse new connections if IAuth is behind. */
157 IAUTH_EXTRAWAIT, /**< Give IAuth extra time to answer. */
158 IAUTH_UNDERNET, /**< Enable Undernet extensions. */
159 IAUTH_LAST_FLAG /**< total number of flags */
161 /** Declare a bitset structure indexed by IAuthFlag. */
162 DECLARE_FLAGSET(IAuthFlags, IAUTH_LAST_FLAG);
164 /** Describes state of an IAuth connection. */
166 struct MsgQ i_sendQ; /**< messages queued to send */
167 struct Socket i_socket; /**< main socket to iauth */
168 struct Socket i_stderr; /**< error socket for iauth */
169 struct IAuthFlags i_flags; /**< connection state/status/flags */
170 uint64_t i_recvB; /**< bytes received */
171 uint64_t i_sendB; /**< bytes sent */
172 time_t started; /**< time that this instance was started */
173 unsigned int i_recvM; /**< messages received */
174 unsigned int i_sendM; /**< messages sent */
175 unsigned int i_count; /**< characters used in i_buffer */
176 unsigned int i_errcount; /**< characters used in i_errbuf */
177 int i_debug; /**< debug level */
178 char i_buffer[BUFSIZE+1]; /**< partial unprocessed line from server */
179 char i_errbuf[BUFSIZE+1]; /**< partial unprocessed error line */
180 char *i_version; /**< iauth version string */
181 struct SLink *i_config; /**< configuration string list */
182 struct SLink *i_stats; /**< statistics string list */
183 char **i_argv; /**< argument list */
186 /** Return whether flag \a flag is set on \a iauth. */
187 #define IAuthHas(iauth, flag) ((iauth) && FlagHas(&(iauth)->i_flags, flag))
188 /** Set flag \a flag on \a iauth. */
189 #define IAuthSet(iauth, flag) FlagSet(&(iauth)->i_flags, flag)
190 /** Clear flag \a flag from \a iauth. */
191 #define IAuthClr(iauth, flag) FlagClr(&(iauth)->i_flags, flag)
192 /** Get connected flag for \a iauth. */
193 #define i_GetConnected(iauth) ((iauth) && s_fd(i_socket(iauth)) > -1)
195 /** Return socket event generator for \a iauth. */
196 #define i_socket(iauth) (&(iauth)->i_socket)
197 /** Return stderr socket for \a iauth. */
198 #define i_stderr(iauth) (&(iauth)->i_stderr)
199 /** Return outbound message queue for \a iauth. */
200 #define i_sendQ(iauth) (&(iauth)->i_sendQ)
201 /** Return debug level for \a iauth. */
202 #define i_debug(iauth) ((iauth)->i_debug)
204 /** Active instance of IAuth. */
205 static struct IAuth *iauth;
206 /** Freelist of AuthRequest structures. */
207 static struct AuthRequest *auth_freelist;
209 static void iauth_sock_callback(struct Event *ev);
210 static void iauth_stderr_callback(struct Event *ev);
211 static int sendto_iauth(struct Client *cptr, const char *format, ...);
212 static int preregister_user(struct Client *cptr);
213 typedef int (*iauth_cmd_handler)(struct IAuth *iauth, struct Client *cli,
214 int parc, char **params);
216 /** Set username for user associated with \a auth.
217 * @param[in] auth Client authorization request to work on.
218 * @return Zero if client is kept, CPTR_KILLED if client rejected.
220 static int auth_set_username(struct AuthRequest *auth)
222 struct Client *sptr = auth->client;
223 struct User *user = cli_user(sptr);
234 short digitgroups = 0;
238 if (FlagHas(&auth->flags, AR_IAUTH_USERNAME))
240 ircd_strncpy(cli_user(sptr)->username, cli_username(sptr), USERLEN);
244 /* Copy username from source to destination. Since they may be the
245 * same, and we may prefix with a '~', use a buffer character (ch)
246 * to hold the next character to copy.
248 s = IsIdented(sptr) ? cli_username(sptr) : user->username;
251 if (HasFlag(sptr, FLAG_DOID) && !IsIdented(sptr))
256 while (last && !IsCntrl(last) && rlen--)
259 *d++ = IsUserChar(last) ? last : '_';
260 last = (ch != '~') ? ch : '_';
265 /* If username is empty or just ~, reject. */
266 if ((user->username[0] == '\0')
267 || ((user->username[0] == '~') && (user->username[1] == '\0')))
268 return exit_client(sptr, sptr, &me, "USER: Bogus userid.");
270 /* Check for K- or G-line. */
271 killreason = find_kill(sptr);
273 ServerStats->is_ref++;
274 return exit_client(sptr, sptr, &me,
275 (killreason == -1 ? "K-lined" : "G-lined"));
278 if (!FlagHas(&auth->flags, AR_IAUTH_FUSERNAME))
280 /* Check for mixed case usernames, meaning probably hacked. Jon2 3-94
281 * Explanations of rules moved to where it is checked Entrope 2-06
283 s = d = user->username + (user->username[0] == '~');
292 else if (IsUpper(ch))
295 /* Accept caps as leading if we haven't seen lower case or digits yet. */
296 if ((leadcaps || pos == 0) && !lower && !digits)
299 else if (IsDigit(ch))
302 if (pos == 0 || !IsDigit(last))
305 /* If more than two groups of digits, reject. */
310 else if (ch == '-' || ch == '_' || ch == '.')
313 /* If -_. exist at start, consecutively, or more than twice, reject. */
314 if (pos == 0 || last == '-' || last == '_' || last == '.' || other > 2)
317 else /* All other punctuation is rejected. */
321 /* If mixed case, first must be capital, but no more than three;
322 * but if three capitals, they must all be leading. */
323 if (lower && upper && (!leadcaps || leadcaps > 3 ||
324 (upper > 2 && upper > leadcaps)))
326 /* If two different groups of digits, one must be either at the
328 if (digitgroups == 2 && !(IsDigit(s[0]) || IsDigit(ch)))
330 /* Must have at least one letter. */
331 if (!lower && !upper)
333 /* Final character must not be punctuation. */
341 /* If we confirmed their username, and it is what they claimed,
343 if (IsIdented(sptr) && !strcmp(cli_username(sptr), user->username))
346 ServerStats->is_ref++;
347 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
348 ":Your username is invalid.");
349 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
350 ":Connect with your real username, in lowercase.");
351 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
352 ":If your mail address were foo@bar.com, your username "
354 return exit_client(sptr, sptr, &me, "USER: Bad username");
357 /** Check whether an authorization request is complete.
358 * This means that no flags from 0 to #AR_LAST_SCAN are set on \a auth.
359 * If #AR_IAUTH_PENDING is set, optionally go into "hurry" state. If
360 * 0 through #AR_LAST_SCAN and #AR_IAUTH_PENDING are all clear,
361 * destroy \a auth, clear the password, set the username, and register
363 * @param[in] auth Authorization request to check.
364 * @return Zero if client is kept, CPTR_KILLED if client rejected.
366 static int check_auth_finished(struct AuthRequest *auth)
368 enum AuthRequestFlag flag;
371 /* Check non-iauth registration blocking flags. */
372 for (flag = 0; flag <= AR_LAST_SCAN; ++flag)
373 if (FlagHas(&auth->flags, flag))
375 Debug((DEBUG_INFO, "Auth %p [%d] still has flag %d", auth,
376 cli_fd(auth->client), flag));
380 /* If appropriate, do preliminary assignment to connection class. */
381 if (IsUserPort(auth->client)
382 && !FlagHas(&auth->flags, AR_IAUTH_HURRY)
383 && preregister_user(auth->client))
386 /* If we have not done so, check client password. Do this as soon
387 * as possible so that iauth's challenge/response (which uses PASS
388 * for responses) is not confused with the client's password.
390 if (IsUserPort(auth->client)
391 && !FlagHas(&auth->flags, AR_PASSWORD_CHECKED))
393 struct ConfItem *aconf;
395 aconf = cli_confs(auth->client)->value.aconf;
397 && !EmptyString(aconf->passwd)
398 && strcmp(cli_passwd(auth->client), aconf->passwd))
400 ServerStats->is_ref++;
401 send_reply(auth->client, ERR_PASSWDMISMATCH);
402 return exit_client(auth->client, auth->client, &me, "Bad Password");
404 FlagSet(&auth->flags, AR_PASSWORD_CHECKED);
407 /* Check if iauth is done. */
408 if (FlagHas(&auth->flags, AR_IAUTH_PENDING))
410 /* Switch auth request to hurry-up state. */
411 if (!FlagHas(&auth->flags, AR_IAUTH_HURRY))
413 /* Set "hurry" flag in auth request. */
414 FlagSet(&auth->flags, AR_IAUTH_HURRY);
416 /* If iauth wants it, send notification. */
417 if (IAuthHas(iauth, IAUTH_UNDERNET))
418 sendto_iauth(auth->client, "H %s", get_client_class(auth->client));
420 /* If iauth wants it, give client more time. */
421 if (IAuthHas(iauth, IAUTH_EXTRAWAIT))
422 cli_firsttime(auth->client) = CurrentTime;
425 Debug((DEBUG_INFO, "Auth %p [%d] still has flag %d", auth,
426 cli_fd(auth->client), AR_IAUTH_PENDING));
430 FlagSet(&auth->flags, AR_IAUTH_HURRY);
432 if (IsUserPort(auth->client))
434 memset(cli_passwd(auth->client), 0, sizeof(cli_passwd(auth->client)));
435 res = auth_set_username(auth);
437 res = register_user(auth->client, auth->client);
442 destroy_auth_request(auth);
446 /** Verify that a hostname is valid, i.e., only contains characters
447 * valid for a hostname and that a hostname is not too long.
448 * @param host Hostname to check.
449 * @param maxlen Maximum length of hostname, not including NUL terminator.
450 * @return Non-zero if the hostname is valid.
453 auth_verify_hostname(const char *host, int maxlen)
457 /* Walk through the host name */
458 for (i = 0; host[i]; i++)
459 /* If it's not a hostname character or if it's too long, return false */
460 if (!IsHostChar(host[i]) || i >= maxlen)
463 return 1; /* it's a valid hostname */
466 /** Check whether a client already has a CONF_CLIENT configuration
469 * @return A pointer to the client's first CONF_CLIENT, or NULL if
472 static struct ConfItem *find_conf_client(struct Client *cptr)
476 for (list = cli_confs(cptr); list != NULL; list = list->next) {
477 struct ConfItem *aconf;
478 aconf = list->value.aconf;
479 if (aconf->status & CONF_CLIENT)
486 /** Assign a client to a connection class.
487 * @param[in] cptr Client to assign to a class.
488 * @return Zero if client is kept, CPTR_KILLED if rejected.
490 static int preregister_user(struct Client *cptr)
492 static time_t last_too_many1;
493 static time_t last_too_many2;
495 ircd_strncpy(cli_user(cptr)->host, cli_sockhost(cptr), HOSTLEN);
496 ircd_strncpy(cli_user(cptr)->realhost, cli_sockhost(cptr), HOSTLEN);
498 if (find_conf_client(cptr)) {
502 switch (conf_check_client(cptr))
506 case ACR_NO_AUTHORIZATION:
507 sendto_opmask_butone(0, SNO_UNAUTH, "Unauthorized connection from %s.",
508 get_client_name(cptr, HIDE_IP));
509 ++ServerStats->is_ref;
510 return exit_client(cptr, cptr, &me,
511 "No Authorization - use another server");
512 case ACR_TOO_MANY_IN_CLASS:
513 sendto_opmask_butone_ratelimited(0, SNO_TOOMANY, &last_too_many1,
514 "Too many connections in class %s for %s.",
515 get_client_class(cptr),
516 get_client_name(cptr, SHOW_IP));
517 ++ServerStats->is_ref;
518 return exit_client(cptr, cptr, &me,
519 "Sorry, your connection class is full - try "
520 "again later or try another server");
521 case ACR_TOO_MANY_FROM_IP:
522 sendto_opmask_butone_ratelimited(0, SNO_TOOMANY, &last_too_many2,
523 "Too many connections from same IP for %s.",
524 get_client_name(cptr, SHOW_IP));
525 ++ServerStats->is_ref;
526 return exit_client(cptr, cptr, &me,
527 "Too many connections from your host");
528 case ACR_ALREADY_AUTHORIZED:
529 /* Can this ever happen? */
531 ++ServerStats->is_ref;
532 IPcheck_connect_fail(cptr);
533 return exit_client(cptr, cptr, &me, "Unknown error -- Try again");
538 /** Send the ident server a query giving "theirport , ourport". The
539 * write is only attempted *once* so it is deemed to be a fail if the
540 * entire write doesn't write all the data given. This shouldn't be a
541 * problem since the socket should have a write buffer far greater
542 * than this message to store it in should problems arise. -avalon
543 * @param[in] auth The request to send.
545 static void send_auth_query(struct AuthRequest* auth)
552 ircd_snprintf(0, authbuf, sizeof(authbuf), "%hu , %hu\r\n",
553 auth->port, auth->local.port);
555 if (IO_SUCCESS != os_send_nonb(s_fd(&auth->socket), authbuf, strlen(authbuf), &count)) {
556 close(s_fd(&auth->socket));
557 socket_del(&auth->socket);
558 s_fd(&auth->socket) = -1;
559 ++ServerStats->is_abad;
560 if (IsUserPort(auth->client))
561 sendheader(auth->client, REPORT_FAIL_ID);
562 FlagClr(&auth->flags, AR_AUTH_PENDING);
563 check_auth_finished(auth);
567 /** Enum used to index ident reply fields in a human-readable way. */
568 enum IdentReplyFields {
576 /** Parse an ident reply line and extract the userid from it.
577 * @param[in] reply The ident reply line.
578 * @return The userid, or NULL on parse failure.
580 static char* check_ident_reply(char* reply)
584 char* vector[USERID_TOKEN_COUNT];
585 int count = token_vector(reply, ':', vector, USERID_TOKEN_COUNT);
587 if (USERID_TOKEN_COUNT != count)
590 * second token is the reply type
592 token = vector[IDENT_REPLY_TYPE];
593 if (EmptyString(token))
596 while (IsSpace(*token))
599 if (0 != strncmp(token, "USERID", 6))
603 * third token is the os type
605 token = vector[IDENT_OS_TYPE];
606 if (EmptyString(token))
608 while (IsSpace(*token))
612 * Unless "OTHER" is specified as the operating system
613 * type, the server is expected to return the "normal"
614 * user identification of the owner of this connection.
615 * "Normal" in this context may be taken to mean a string
616 * of characters which uniquely identifies the connection
617 * owner such as a user identifier assigned by the system
618 * administrator and used by such user as a mail
619 * identifier, or as the "user" part of a user/password
620 * pair used to gain access to system resources. When an
621 * operating system is specified (e.g., anything but
622 * "OTHER"), the user identifier is expected to be in a
623 * more or less immediately useful form - e.g., something
624 * that could be used as an argument to "finger" or as a
627 if (0 == strncmp(token, "OTHER", 5))
630 * fourth token is the username
632 token = vector[IDENT_INFO];
633 if (EmptyString(token))
635 while (IsSpace(*token))
638 * look for the end of the username, terminators are '\0, @, <SPACE>, :'
640 for (end = token; *end; ++end) {
641 if (IsSpace(*end) || '@' == *end || ':' == *end)
648 /** Read the reply (if any) from the ident server we connected to. We
649 * only give it one shot, if the reply isn't good the first time fail
650 * the authentication entirely. --Bleep
651 * @param[in] auth The request to read.
653 static void read_auth_reply(struct AuthRequest* auth)
658 * rfc1453 sez we MUST accept 512 bytes
660 char buf[BUFSIZE + 1];
663 assert(0 != auth->client);
664 assert(auth == cli_auth(auth->client));
666 if (IO_SUCCESS == os_recv_nonb(s_fd(&auth->socket), buf, BUFSIZE, &len)) {
668 Debug((DEBUG_INFO, "Auth %p [%d] reply: %s", auth, cli_fd(auth->client), buf));
669 username = check_ident_reply(buf);
670 Debug((DEBUG_INFO, "Username: %s", username));
673 Debug((DEBUG_INFO, "Deleting auth [%d] socket %p", auth, cli_fd(auth->client)));
674 close(s_fd(&auth->socket));
675 socket_del(&auth->socket);
676 s_fd(&auth->socket) = -1;
678 if (EmptyString(username)) {
679 if (IsUserPort(auth->client))
680 sendheader(auth->client, REPORT_FAIL_ID);
681 ++ServerStats->is_abad;
683 if (IsUserPort(auth->client))
684 sendheader(auth->client, REPORT_FIN_ID);
685 ++ServerStats->is_asuc;
686 if (!FlagHas(&auth->flags, AR_IAUTH_USERNAME)) {
687 ircd_strncpy(cli_username(auth->client), username, USERLEN);
688 SetGotId(auth->client);
690 if (IAuthHas(iauth, IAUTH_UNDERNET))
691 sendto_iauth(auth->client, "u %s", username);
694 FlagClr(&auth->flags, AR_AUTH_PENDING);
695 check_auth_finished(auth);
698 /** Handle socket I/O activity.
699 * @param[in] ev A socket event whos associated data is the active
700 * struct AuthRequest.
702 static void auth_sock_callback(struct Event* ev)
704 struct AuthRequest* auth;
706 assert(0 != ev_socket(ev));
707 assert(0 != s_data(ev_socket(ev)));
709 auth = (struct AuthRequest*) s_data(ev_socket(ev));
711 switch (ev_type(ev)) {
712 case ET_DESTROY: /* being destroyed */
715 case ET_CONNECT: /* socket connection completed */
716 Debug((DEBUG_INFO, "Connection completed for auth %p [%d]; sending query",
717 auth, cli_fd(auth->client)));
718 socket_state(&auth->socket, SS_CONNECTED);
719 send_auth_query(auth);
722 case ET_READ: /* socket is readable */
723 case ET_EOF: /* end of file on socket */
724 case ET_ERROR: /* error on socket */
725 Debug((DEBUG_INFO, "Auth socket %p [%p] readable", auth, ev_socket(ev)));
726 read_auth_reply(auth);
730 assert(0 && "Unrecognized event in auth_socket_callback().");
735 /** Stop an auth request completely.
736 * @param[in] auth The struct AuthRequest to cancel.
738 void destroy_auth_request(struct AuthRequest* auth)
740 Debug((DEBUG_INFO, "Deleting auth request for %p", auth->client));
742 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
743 delete_resolver_queries(auth);
746 if (-1 < s_fd(&auth->socket)) {
747 close(s_fd(&auth->socket));
748 socket_del(&auth->socket);
749 s_fd(&auth->socket) = -1;
752 if (t_active(&auth->timeout))
753 timer_del(&auth->timeout);
755 cli_auth(auth->client) = NULL;
756 auth->next = auth_freelist;
757 auth_freelist = auth;
760 /** Handle a 'ping' (authorization) timeout for a client.
761 * @param[in] cptr The client whose session authorization has timed out.
762 * @return Zero if client is kept, CPTR_KILLED if client rejected.
764 int auth_ping_timeout(struct Client *cptr)
766 struct AuthRequest *auth;
767 enum AuthRequestFlag flag;
769 auth = cli_auth(cptr);
771 /* Check whether the auth request is gone (more likely, it never
772 * existed, as in an outbound server connection). */
774 return exit_client_msg(cptr, cptr, &me, "Registration Timeout");
776 /* Check for a user-controlled timeout. */
777 for (flag = 0; flag <= AR_LAST_SCAN; ++flag) {
778 if (FlagHas(&auth->flags, flag)) {
779 /* Display message if they have sent a NICK and a USER but no
782 if (*(cli_name(cptr)) && cli_user(cptr) && *(cli_user(cptr))->username) {
783 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
784 ":Your client may not be compatible with this server.");
785 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
786 ":Compatible clients are available at %s",
787 feature_str(FEAT_URL_CLIENTS));
789 return exit_client_msg(cptr, cptr, &me, "Registration Timeout");
793 /* Check for iauth timeout. */
794 if (FlagHas(&auth->flags, AR_IAUTH_PENDING)) {
795 if (IAuthHas(iauth, IAUTH_REQUIRED)
796 && !FlagHas(&auth->flags, AR_IAUTH_SOFT_DONE)) {
797 sendheader(cptr, REPORT_FAIL_IAUTH);
798 return exit_client_msg(cptr, cptr, &me, "Authorization Timeout");
800 sendto_iauth(cptr, "T");
801 FlagClr(&auth->flags, AR_IAUTH_PENDING);
802 return check_auth_finished(auth);
805 assert(0 && "Unexpectedly reached end of auth_ping_timeout()");
809 /** Timeout a given auth request.
810 * @param[in] ev A timer event whose associated data is the expired
811 * struct AuthRequest.
813 static void auth_timeout_callback(struct Event* ev)
815 struct AuthRequest* auth;
817 assert(0 != ev_timer(ev));
818 assert(0 != t_data(ev_timer(ev)));
820 auth = (struct AuthRequest*) t_data(ev_timer(ev));
822 if (ev_type(ev) == ET_EXPIRE) {
823 /* Report the timeout in the log. */
824 log_write(LS_RESOLVER, L_INFO, 0, "Registration timeout %s",
825 get_client_name(auth->client, HIDE_IP));
827 /* Notify client if ident lookup failed. */
828 if (FlagHas(&auth->flags, AR_AUTH_PENDING)) {
829 FlagClr(&auth->flags, AR_AUTH_PENDING);
830 if (IsUserPort(auth->client))
831 sendheader(auth->client, REPORT_FAIL_ID);
834 /* Likewise if dns lookup failed. */
835 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
836 FlagClr(&auth->flags, AR_DNS_PENDING);
837 delete_resolver_queries(auth);
838 if (IsUserPort(auth->client))
839 sendheader(auth->client, REPORT_FAIL_DNS);
842 /* Try to register the client. */
843 check_auth_finished(auth);
847 /** Handle a complete DNS lookup. Send the client on it's way to a
848 * connection completion, regardless of success or failure -- unless
849 * there was a mismatch and KILL_IPMISMATCH is set.
850 * @param[in] vptr The pending struct AuthRequest.
851 * @param[in] addr IP address being resolved.
852 * @param[in] h_name Resolved name, or NULL if lookup failed.
854 static void auth_dns_callback(void* vptr, const struct irc_in_addr *addr, const char *h_name)
856 struct AuthRequest* auth = (struct AuthRequest*) vptr;
859 FlagClr(&auth->flags, AR_DNS_PENDING);
861 /* DNS entry was missing for the IP. */
862 if (IsUserPort(auth->client))
863 sendheader(auth->client, REPORT_FAIL_DNS);
864 sendto_iauth(auth->client, "d");
865 } else if (!irc_in_addr_valid(addr)
866 || (irc_in_addr_cmp(&cli_ip(auth->client), addr)
867 && irc_in_addr_cmp(&auth->original, addr))) {
868 /* IP for hostname did not match client's IP. */
869 sendto_opmask_butone(0, SNO_IPMISMATCH, "IP# Mismatch: %s != %s[%s]",
870 cli_sock_ip(auth->client), h_name,
872 if (IsUserPort(auth->client))
873 sendheader(auth->client, REPORT_IP_MISMATCH);
874 if (feature_bool(FEAT_KILL_IPMISMATCH)) {
875 exit_client(auth->client, auth->client, &me, "IP mismatch");
878 } else if (!auth_verify_hostname(h_name, HOSTLEN)) {
879 /* Hostname did not look valid. */
880 if (IsUserPort(auth->client))
881 sendheader(auth->client, REPORT_INVAL_DNS);
882 sendto_iauth(auth->client, "d");
884 /* Hostname and mappings checked out. */
885 if (IsUserPort(auth->client))
886 sendheader(auth->client, REPORT_FIN_DNS);
887 ircd_strncpy(cli_sockhost(auth->client), h_name, HOSTLEN);
888 sendto_iauth(auth->client, "N %s", h_name);
890 check_auth_finished(auth);
893 /** Flag the client to show an attempt to contact the ident server on
894 * the client's host. Should the connect or any later phase of the
895 * identifying process fail, it is aborted and the user is given a
896 * username of "unknown".
897 * @param[in] auth The request for which to start the ident lookup.
899 static void start_auth_query(struct AuthRequest* auth)
901 struct irc_sockaddr remote_addr;
902 struct irc_sockaddr local_addr;
907 assert(0 != auth->client);
910 * get the local address of the client and bind to that to
911 * make the auth request. This used to be done only for
912 * ifdef VIRTUAL_HOST, but needs to be done for all clients
913 * since the ident request must originate from that same address--
914 * and machines with multiple IP addresses are common now
916 memcpy(&local_addr, &auth->local, sizeof(local_addr));
918 memcpy(&remote_addr.addr, &cli_ip(auth->client), sizeof(remote_addr.addr));
919 remote_addr.port = 113;
920 fd = os_socket(&local_addr, SOCK_STREAM, "auth query", 0);
922 ++ServerStats->is_abad;
923 if (IsUserPort(auth->client))
924 sendheader(auth->client, REPORT_FAIL_ID);
927 if (IsUserPort(auth->client))
928 sendheader(auth->client, REPORT_DO_ID);
930 if ((result = os_connect_nonb(fd, &remote_addr)) == IO_FAILURE ||
931 !socket_add(&auth->socket, auth_sock_callback, (void*) auth,
932 result == IO_SUCCESS ? SS_CONNECTED : SS_CONNECTING,
933 SOCK_EVENT_READABLE, fd)) {
934 ++ServerStats->is_abad;
935 if (IsUserPort(auth->client))
936 sendheader(auth->client, REPORT_FAIL_ID);
941 FlagSet(&auth->flags, AR_AUTH_PENDING);
942 if (result == IO_SUCCESS)
943 send_auth_query(auth);
946 /** Initiate DNS lookup for a client.
947 * @param[in] auth The auth request for which to start the DNS lookup.
949 static void start_dns_query(struct AuthRequest *auth)
951 if (feature_bool(FEAT_NODNS)) {
952 sendto_iauth(auth->client, "d");
956 if (irc_in_addr_is_loopback(&cli_ip(auth->client))) {
957 strcpy(cli_sockhost(auth->client), cli_name(&me));
958 sendto_iauth(auth->client, "N %s", cli_sockhost(auth->client));
962 if (IsUserPort(auth->client))
963 sendheader(auth->client, REPORT_DO_DNS);
965 FlagSet(&auth->flags, AR_DNS_PENDING);
966 gethost_byaddr(&cli_ip(auth->client), auth_dns_callback, auth);
969 /** Initiate IAuth check for a client.
970 * @param[in] auth The auth request for which to star the IAuth check.
972 static void start_iauth_query(struct AuthRequest *auth)
974 FlagSet(&auth->flags, AR_IAUTH_PENDING);
975 if (!sendto_iauth(auth->client, "C %s %hu %s %hu",
976 cli_sock_ip(auth->client), auth->port,
977 ircd_ntoa(&auth->local.addr), auth->local.port))
978 FlagClr(&auth->flags, AR_IAUTH_PENDING);
981 /** Starts auth (identd) and dns queries for a client.
982 * @param[in] client The client for which to start queries.
984 void start_auth(struct Client* client)
986 struct irc_sockaddr remote;
987 struct AuthRequest* auth;
990 Debug((DEBUG_INFO, "Beginning auth request on client %p", client));
992 /* Register with event handlers. */
993 cli_lasttime(client) = CurrentTime;
994 cli_since(client) = CurrentTime;
995 if (cli_fd(client) > HighestFd)
996 HighestFd = cli_fd(client);
997 LocalClientArray[cli_fd(client)] = client;
998 socket_events(&(cli_socket(client)), SOCK_ACTION_SET | SOCK_EVENT_READABLE);
1000 /* Allocate the AuthRequest. */
1001 auth = auth_freelist;
1003 auth_freelist = auth->next;
1005 auth = MyMalloc(sizeof(*auth));
1007 memset(auth, 0, sizeof(*auth));
1008 auth->client = client;
1009 cli_auth(client) = auth;
1010 s_fd(&auth->socket) = -1;
1011 timer_add(timer_init(&auth->timeout), auth_timeout_callback, (void*) auth,
1012 TT_RELATIVE, feature_int(FEAT_AUTH_TIMEOUT));
1014 /* Try to get socket endpoint addresses. */
1015 if (!os_get_sockname(cli_fd(client), &auth->local)
1016 || !os_get_peername(cli_fd(client), &remote)) {
1017 ++ServerStats->is_abad;
1018 if (IsUserPort(auth->client))
1019 sendheader(auth->client, REPORT_FAIL_ID);
1020 exit_client(auth->client, auth->client, &me, "Socket local/peer lookup failed");
1023 auth->port = remote.port;
1025 /* Set required client inputs for users. */
1026 if (IsUserPort(client)) {
1027 cli_user(client) = make_user(client);
1028 cli_user(client)->server = &me;
1029 FlagSet(&auth->flags, AR_NEEDS_USER);
1030 FlagSet(&auth->flags, AR_NEEDS_NICK);
1032 /* Try to start iauth lookup. */
1033 start_iauth_query(auth);
1036 /* Try to start DNS lookup. */
1037 start_dns_query(auth);
1039 /* Try to start ident lookup. */
1040 start_auth_query(auth);
1042 /* Add client to GlobalClientList. */
1043 add_client_to_list(client);
1045 /* Check which auth events remain pending. */
1046 check_auth_finished(auth);
1049 /** Mark that a user has PONGed while unregistered.
1050 * @param[in] auth Authorization request for client.
1051 * @param[in] cookie PONG cookie value sent by client.
1052 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1054 int auth_set_pong(struct AuthRequest *auth, unsigned int cookie)
1056 assert(auth != NULL);
1057 if (!FlagHas(&auth->flags, AR_NEEDS_PONG))
1059 if (cookie != auth->cookie)
1061 send_reply(auth->client, SND_EXPLICIT | ERR_BADPING,
1062 ":To connect, type /QUOTE PONG %u", auth->cookie);
1065 cli_lasttime(auth->client) = CurrentTime;
1066 FlagClr(&auth->flags, AR_NEEDS_PONG);
1067 return check_auth_finished(auth);
1070 /** Record a user's claimed username and userinfo.
1071 * @param[in] auth Authorization request for client.
1072 * @param[in] username Client's asserted username.
1073 * @param[in] hostname Third argument of USER command (client's
1074 * hostname, per RFC 1459).
1075 * @param[in] servername Fourth argument of USER command (server's
1076 * name, per RFC 1459).
1077 * @param[in] userinfo Client's asserted self-description.
1078 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1080 int auth_set_user(struct AuthRequest *auth, const char *username, const char *hostname, const char *servername, const char *userinfo)
1082 struct Client *cptr;
1084 assert(auth != NULL);
1085 if (FlagHas(&auth->flags, AR_IAUTH_HURRY))
1087 FlagClr(&auth->flags, AR_NEEDS_USER);
1088 cptr = auth->client;
1089 ircd_strncpy(cli_info(cptr), userinfo, REALLEN);
1090 ircd_strncpy(cli_user(cptr)->username, username, USERLEN);
1091 ircd_strncpy(cli_user(cptr)->host, cli_sockhost(cptr), HOSTLEN);
1092 if (IAuthHas(iauth, IAUTH_UNDERNET))
1093 sendto_iauth(cptr, "U %s %s %s :%s", username, hostname, servername, userinfo);
1094 else if (IAuthHas(iauth, IAUTH_ADDLINFO))
1095 sendto_iauth(cptr, "U %s", username);
1096 return check_auth_finished(auth);
1099 /** Handle authorization-related aspects of initial nickname selection.
1100 * This is called after verifying that the nickname is available.
1101 * @param[in] auth Authorization request for client.
1102 * @param[in] nickname Client's requested nickname.
1103 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1105 int auth_set_nick(struct AuthRequest *auth, const char *nickname)
1107 assert(auth != NULL);
1108 FlagClr(&auth->flags, AR_NEEDS_NICK);
1110 * If the client hasn't gotten a cookie-ping yet,
1111 * choose a cookie and send it. -record!jegelhof@cloud9.net
1113 if (!auth->cookie) {
1115 auth->cookie = ircrandom();
1116 } while (!auth->cookie);
1117 sendrawto_one(auth->client, "PING :%u", auth->cookie);
1118 FlagSet(&auth->flags, AR_NEEDS_PONG);
1120 if (IAuthHas(iauth, IAUTH_UNDERNET))
1121 sendto_iauth(auth->client, "n %s", nickname);
1122 return check_auth_finished(auth);
1125 /** Record a user's password.
1126 * @param[in] auth Authorization request for client.
1127 * @param[in] password Client's password.
1128 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1130 int auth_set_password(struct AuthRequest *auth, const char *password)
1132 assert(auth != NULL);
1133 if (IAuthHas(iauth, IAUTH_ADDLINFO))
1134 sendto_iauth(auth->client, "P :%s", password);
1138 /** Send exit notification for \a cptr to iauth.
1139 * @param[in] cptr Client who is exiting.
1141 void auth_send_exit(struct Client *cptr)
1143 sendto_iauth(cptr, "D");
1146 /** Forward an XREPLY on to iauth.
1147 * @param[in] sptr Source of the XREPLY.
1148 * @param[in] routing Routing information for the original XQUERY.
1149 * @param[in] reply Contents of the reply.
1151 void auth_send_xreply(struct Client *sptr, const char *routing,
1154 sendto_iauth(NULL, "X %#C %s :%s", sptr, routing, reply);
1157 /** Mark that a user has started capabilities negotiation.
1158 * This blocks authorization until auth_cap_done() is called.
1159 * @param[in] auth Authorization request for client.
1160 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1162 int auth_cap_start(struct AuthRequest *auth)
1164 assert(auth != NULL);
1165 FlagSet(&auth->flags, AR_CAP_PENDING);
1169 /** Mark that a user has completed capabilities negotiation.
1170 * This unblocks authorization if auth_cap_start() was called.
1171 * @param[in] auth Authorization request for client.
1172 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1174 int auth_cap_done(struct AuthRequest *auth)
1176 assert(auth != NULL);
1177 FlagClr(&auth->flags, AR_CAP_PENDING);
1178 return check_auth_finished(auth);
1181 /** Attempt to spawn the process for an IAuth instance.
1182 * @param[in] iauth IAuth descriptor.
1183 * @param[in] automatic If non-zero, apply sanity checks against
1184 * excessive automatic restarts.
1185 * @return 0 on success, non-zero on failure.
1187 int iauth_do_spawn(struct IAuth *iauth, int automatic)
1194 if (automatic && CurrentTime - iauth->started < 5)
1196 sendto_opmask_butone(NULL, SNO_AUTH, "IAuth crashed fast, leaving it dead.");
1200 /* Record time we tried to spawn the iauth process. */
1201 iauth->started = CurrentTime;
1203 /* Attempt to allocate a pair of sockets. */
1204 res = os_socketpair(s_io);
1207 Debug((DEBUG_INFO, "Unable to create IAuth socketpair: %s", strerror(res)));
1211 /* Mark the parent's side of the pair (element 0) as non-blocking. */
1212 res = os_set_nonblocking(s_io[0]);
1215 Debug((DEBUG_INFO, "Unable to make IAuth socket non-blocking: %s", strerror(res)));
1221 /* Initialize the socket structure to talk to the child. */
1222 res = socket_add(i_socket(iauth), iauth_sock_callback, iauth,
1223 SS_CONNECTED, SOCK_EVENT_READABLE, s_io[0]);
1226 Debug((DEBUG_INFO, "Unable to register IAuth socket: %s", strerror(res)));
1232 /* Allocate another pair for stderr. */
1233 res = os_socketpair(s_err);
1236 Debug((DEBUG_INFO, "Unable to create IAuth stderr: %s", strerror(res)));
1237 socket_del(i_socket(iauth));
1243 /* Mark parent side of this pair non-blocking, too. */
1244 res = os_set_nonblocking(s_err[0]);
1247 Debug((DEBUG_INFO, "Unable to make IAuth stderr non-blocking: %s", strerror(res)));
1250 socket_del(i_socket(iauth));
1256 /* And set up i_stderr(iauth). */
1257 res = socket_add(i_stderr(iauth), iauth_stderr_callback, iauth,
1258 SS_CONNECTED, SOCK_EVENT_READABLE, s_err[0]);
1261 Debug((DEBUG_INFO, "Unable to register IAuth stderr: %s", strerror(res)));
1264 socket_del(i_socket(iauth));
1270 /* Attempt to fork a child process. */
1273 /* Error forking the child, still in parent. */
1275 Debug((DEBUG_INFO, "Unable to fork IAuth child: %s", strerror(res)));
1276 socket_del(i_stderr(iauth));
1279 socket_del(i_socket(iauth));
1286 /* We are the parent process. Close the child's sockets. */
1289 /* Send our server name (supposedly for proxy checking purposes)
1290 * and maximum number of connections (for allocation hints).
1291 * Need to use conf_get_local() since &me may not be fully
1292 * initialized the first time we run.
1294 sendto_iauth(NULL, "M %s %d", conf_get_local()->name, MAXCONNECTIONS);
1295 /* Indicate success (until the child dies). */
1299 /* We are the child process.
1300 * Duplicate our end of the socket to stdin, stdout and stderr.
1301 * Then close all the higher-numbered FDs and exec the process.
1303 if (dup2(s_io[1], 0) == 0
1304 && dup2(s_io[1], 1) == 1
1305 && dup2(s_err[1], 2) == 2) {
1306 close_connections(0);
1307 execvp(iauth->i_argv[0], iauth->i_argv);
1310 /* If we got here, something was seriously wrong. */
1314 /** See if an %IAuth program must be spawned.
1315 * If a process is already running with the specified options, keep it.
1316 * Otherwise spawn a new child process to perform the %IAuth function.
1317 * @param[in] argc Number of parameters to use when starting process.
1318 * @param[in] argv Array of parameters to start process.
1319 * @return 0 on failure, 1 on new process, 2 on reuse of existing process.
1321 int auth_spawn(int argc, char *argv[])
1328 /* Check that incoming arguments all match pre-existing arguments. */
1329 for (ii = 0; same && (ii < argc); ++ii) {
1330 if (NULL == iauth->i_argv[ii]
1331 || 0 != strcmp(iauth->i_argv[ii], argv[ii]))
1334 /* Check that we have no more pre-existing arguments. */
1335 if (same && iauth->i_argv[ii])
1337 /* If they are the same and still connected, clear the "closing" flag and exit. */
1338 if (same && i_GetConnected(iauth)) {
1339 Debug((DEBUG_INFO, "Reusing existing IAuth process"));
1340 IAuthClr(iauth, IAUTH_CLOSING);
1343 auth_close_unused();
1346 /* Need to initialize a new connection. */
1347 iauth = MyCalloc(1, sizeof(*iauth));
1348 msgq_init(i_sendQ(iauth));
1349 /* Populate iauth's argv array. */
1350 iauth->i_argv = MyCalloc(argc + 1, sizeof(iauth->i_argv[0]));
1351 for (ii = 0; ii < argc; ++ii)
1352 DupString(iauth->i_argv[ii], argv[ii]);
1353 iauth->i_argv[ii] = NULL;
1354 /* Try to spawn it, and handle the results. */
1355 if (iauth_do_spawn(iauth, 0))
1357 IAuthClr(iauth, IAUTH_CLOSING);
1361 /** Mark all %IAuth connections as closing. */
1362 void auth_mark_closing(void)
1365 IAuthSet(iauth, IAUTH_CLOSING);
1368 /** Complete disconnection of an %IAuth connection.
1369 * @param[in] iauth %Connection to fully close.
1371 static void iauth_disconnect(struct IAuth *iauth)
1376 /* Close main socket. */
1377 if (s_fd(i_socket(iauth)) != -1) {
1378 close(s_fd(i_socket(iauth)));
1379 socket_del(i_socket(iauth));
1380 s_fd(i_socket(iauth)) = -1;
1383 /* Close error socket. */
1384 if (s_fd(i_stderr(iauth)) != -1) {
1385 close(s_fd(i_stderr(iauth)));
1386 socket_del(i_stderr(iauth));
1387 s_fd(i_stderr(iauth)) = -1;
1391 /** Close all %IAuth connections marked as closing. */
1392 void auth_close_unused(void)
1394 if (IAuthHas(iauth, IAUTH_CLOSING)) {
1396 iauth_disconnect(iauth);
1397 if (iauth->i_argv) {
1398 for (ii = 0; iauth->i_argv[ii]; ++ii)
1399 MyFree(iauth->i_argv[ii]);
1400 MyFree(iauth->i_argv);
1406 /** Send queued output to \a iauth.
1407 * @param[in] iauth Writable connection with queued data.
1409 static void iauth_write(struct IAuth *iauth)
1411 unsigned int bytes_tried, bytes_sent;
1414 if (IAuthHas(iauth, IAUTH_BLOCKED))
1416 while (MsgQLength(i_sendQ(iauth)) > 0) {
1417 iores = os_sendv_nonb(s_fd(i_socket(iauth)), i_sendQ(iauth), &bytes_tried, &bytes_sent);
1420 msgq_delete(i_sendQ(iauth), bytes_sent);
1421 iauth->i_sendB += bytes_sent;
1422 if (bytes_tried == bytes_sent)
1424 /* If bytes_sent < bytes_tried, fall through to IO_BLOCKED. */
1426 IAuthSet(iauth, IAUTH_BLOCKED);
1427 socket_events(i_socket(iauth), SOCK_ACTION_ADD | SOCK_EVENT_WRITABLE);
1430 iauth_disconnect(iauth);
1434 /* We were able to flush all events, so remove notification. */
1435 socket_events(i_socket(iauth), SOCK_ACTION_DEL | SOCK_EVENT_WRITABLE);
1438 /** Send a message to iauth.
1439 * @param[in] cptr Optional client context for message.
1440 * @param[in] format Format string for message.
1441 * @return Non-zero on successful send or buffering, zero on failure.
1443 static int sendto_iauth(struct Client *cptr, const char *format, ...)
1448 /* Do not send requests when we have no iauth. */
1449 if (!i_GetConnected(iauth))
1451 /* Do not send for clients in the NORMAL state. */
1453 && (format[0] != 'D')
1454 && (!cli_auth(cptr) || !FlagHas(&cli_auth(cptr)->flags, AR_IAUTH_PENDING)))
1457 /* Build the message buffer. */
1458 vd.vd_format = format;
1459 va_start(vd.vd_args, format);
1461 mb = msgq_make(NULL, "-1 %v", &vd);
1463 mb = msgq_make(NULL, "%d %v", cli_fd(cptr), &vd);
1466 /* Tack it onto the iauth sendq and try to write it. */
1468 msgq_add(i_sendQ(iauth), mb, 0);
1474 /** Send text to interested operators (SNO_AUTH server notice).
1475 * @param[in] iauth Active IAuth session.
1476 * @param[in] cli Client referenced by command.
1477 * @param[in] parc Number of parameters (1).
1478 * @param[in] params Text to send.
1481 static int iauth_cmd_snotice(struct IAuth *iauth, struct Client *cli,
1482 int parc, char **params)
1484 sendto_opmask_butone(NULL, SNO_AUTH, "%s", params[0]);
1488 /** Set the debug level for the session.
1489 * @param[in] iauth Active IAuth session.
1490 * @param[in] cli Client referenced by command.
1491 * @param[in] parc Number of parameters (1).
1492 * @param[in] params String starting with an integer.
1495 static int iauth_cmd_debuglevel(struct IAuth *iauth, struct Client *cli,
1496 int parc, char **params)
1500 new_level = parc > 0 ? atoi(params[0]) : 0;
1501 if (i_debug(iauth) > 0 || new_level > 0) {
1502 /* The "ia_dbg" name is borrowed from (IRCnet) ircd. */
1503 sendto_opmask_butone(NULL, SNO_AUTH, "ia_dbg = %d", new_level);
1505 i_debug(iauth) = new_level;
1509 /** Set policy options for the session.
1510 * Old policy is forgotten, and any of the following characters in \a
1511 * params enable the corresponding policy:
1512 * \li A IAUTH_ADDLINFO
1513 * \li R IAUTH_REQUIRED
1514 * \li T IAUTH_TIMEOUT
1515 * \li W IAUTH_EXTRAWAIT
1516 * \li U IAUTH_UNDERNET
1518 * @param[in] iauth Active IAuth session.
1519 * @param[in] cli Client referenced by command.
1520 * @param[in] parc Number of parameters (1).
1521 * @param[in] params Zero or more policy options.
1524 static int iauth_cmd_policy(struct IAuth *iauth, struct Client *cli,
1525 int parc, char **params)
1527 enum IAuthFlag flag;
1530 /* Erase old policy first. */
1531 for (flag = IAUTH_FIRST_OPTION; flag < IAUTH_LAST_FLAG; ++flag)
1532 IAuthClr(iauth, flag);
1534 if (parc > 0) /* only try to parse if we were given a policy string */
1535 /* Parse new policy set. */
1536 for (p = params[0]; *p; p++) switch (*p) {
1537 case 'A': IAuthSet(iauth, IAUTH_ADDLINFO); break;
1538 case 'R': IAuthSet(iauth, IAUTH_REQUIRED); break;
1539 case 'T': IAuthSet(iauth, IAUTH_TIMEOUT); break;
1540 case 'W': IAuthSet(iauth, IAUTH_EXTRAWAIT); break;
1541 case 'U': IAuthSet(iauth, IAUTH_UNDERNET); break;
1544 /* Optionally notify operators. */
1545 if (i_debug(iauth) > 0)
1546 sendto_opmask_butone(NULL, SNO_AUTH, "iauth options: %s", params[0]);
1550 /** Set the iauth program version number.
1551 * @param[in] iauth Active IAuth session.
1552 * @param[in] cli Client referenced by command.
1553 * @param[in] parc Number of parameters (1).
1554 * @param[in] params Version number or name.
1557 static int iauth_cmd_version(struct IAuth *iauth, struct Client *cli,
1558 int parc, char **params)
1560 MyFree(iauth->i_version);
1561 DupString(iauth->i_version, parc > 0 ? params[0] : "<NONE>");
1562 sendto_opmask_butone(NULL, SNO_AUTH, "iauth version %s running.",
1567 /** Paste a parameter list together into a single string.
1568 * @param[in] parc Number of parameters.
1569 * @param[in] params Parameter list to paste together.
1570 * @return Pasted parameter list.
1572 static char *paste_params(int parc, char **params)
1575 int len = 0, lengths[MAXPARA], i;
1577 /* Compute the length... */
1578 for (i = 0; i < parc; i++)
1579 len += lengths[i] = strlen(params[i]);
1581 /* Allocate memory, accounting for string lengths, spaces (parc - 1), a
1582 * sentinel, and the trailing \0
1584 str = MyMalloc(len + parc + 1);
1586 /* Build the pasted string */
1587 for (tmp = str, i = 0; i < parc; i++) {
1588 if (i) /* add space separator... */
1590 if (i == parc - 1) /* add colon sentinel */
1593 /* Copy string component... */
1594 memcpy(tmp, params[i], lengths[i]);
1595 tmp += lengths[i]; /* move to end of string */
1598 /* terminate the string... */
1601 return str; /* return the pasted string */
1604 /** Clear cached iauth configuration information.
1605 * @param[in] iauth Active IAuth session.
1606 * @param[in] cli Client referenced by command.
1607 * @param[in] parc Number of parameters (0).
1608 * @param[in] params Parameter list (ignored).
1611 static int iauth_cmd_newconfig(struct IAuth *iauth, struct Client *cli,
1612 int parc, char **params)
1617 head = iauth->i_config;
1618 iauth->i_config = NULL;
1619 for (; head; head = next) {
1621 MyFree(head->value.cp);
1624 sendto_opmask_butone(NULL, SNO_AUTH, "New iauth configuration.");
1628 /** Append iauth configuration information.
1629 * @param[in] iauth Active IAuth session.
1630 * @param[in] cli Client referenced by command.
1631 * @param[in] parc Number of parameters.
1632 * @param[in] params Description of configuration element.
1635 static int iauth_cmd_config(struct IAuth *iauth, struct Client *cli,
1636 int parc, char **params)
1640 if (iauth->i_config) {
1641 for (node = iauth->i_config; node->next; node = node->next) ;
1642 node = node->next = make_link();
1644 node = iauth->i_config = make_link();
1646 node->value.cp = paste_params(parc, params);
1647 node->next = 0; /* must be explicitly cleared */
1651 /** Clear cached iauth configuration information.
1652 * @param[in] iauth Active IAuth session.
1653 * @param[in] cli Client referenced by command.
1654 * @param[in] parc Number of parameters (0).
1655 * @param[in] params Parameter list (ignored).
1658 static int iauth_cmd_newstats(struct IAuth *iauth, struct Client *cli,
1659 int parc, char **params)
1664 head = iauth->i_stats;
1665 iauth->i_stats = NULL;
1666 for (; head; head = next) {
1668 MyFree(head->value.cp);
1671 sendto_opmask_butone(NULL, SNO_AUTH, "New iauth statistics.");
1675 /** Append iauth statistics information.
1676 * @param[in] iauth Active IAuth session.
1677 * @param[in] cli Client referenced by command.
1678 * @param[in] parc Number of parameters.
1679 * @param[in] params Statistics element.
1682 static int iauth_cmd_stats(struct IAuth *iauth, struct Client *cli,
1683 int parc, char **params)
1686 if (iauth->i_stats) {
1687 for (node = iauth->i_stats; node->next; node = node->next) ;
1688 node = node->next = make_link();
1690 node = iauth->i_stats = make_link();
1692 node->value.cp = paste_params(parc, params);
1693 node->next = 0; /* must be explicitly cleared */
1697 /** Set client's username to a trusted string even if it breaks the rules.
1698 * @param[in] iauth Active IAuth session.
1699 * @param[in] cli Client referenced by command.
1700 * @param[in] parc Number of parameters (1).
1701 * @param[in] params Forced username.
1704 static int iauth_cmd_username_forced(struct IAuth *iauth, struct Client *cli,
1705 int parc, char **params)
1707 assert(cli_auth(cli) != NULL);
1708 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
1709 if (!EmptyString(params[0])) {
1710 ircd_strncpy(cli_username(cli), params[0], USERLEN);
1712 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_USERNAME);
1713 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_FUSERNAME);
1718 /** Set client's username to a trusted string.
1719 * @param[in] iauth Active IAuth session.
1720 * @param[in] cli Client referenced by command.
1721 * @param[in] parc Number of parameters (1).
1722 * @param[in] params Trusted username.
1725 static int iauth_cmd_username_good(struct IAuth *iauth, struct Client *cli,
1726 int parc, char **params)
1728 assert(cli_auth(cli) != NULL);
1729 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
1730 if (!EmptyString(params[0])) {
1731 ircd_strncpy(cli_username(cli), params[0], USERLEN);
1733 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_USERNAME);
1738 /** Set client's username to an untrusted string.
1739 * @param[in] iauth Active IAuth session.
1740 * @param[in] cli Client referenced by command.
1741 * @param[in] parc Number of parameters (1).
1742 * @param[in] params Untrusted username.
1745 static int iauth_cmd_username_bad(struct IAuth *iauth, struct Client *cli,
1746 int parc, char **params)
1748 assert(cli_auth(cli) != NULL);
1749 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
1750 if (!EmptyString(params[0]))
1751 ircd_strncpy(cli_user(cli)->username, params[0], USERLEN);
1755 /** Set client's hostname.
1756 * @param[in] iauth Active IAuth session.
1757 * @param[in] cli Client referenced by command.
1758 * @param[in] parc Number of parameters (1).
1759 * @param[in] params New hostname for client.
1760 * @return Non-zero if \a cli authorization should be checked for completion.
1762 static int iauth_cmd_hostname(struct IAuth *iauth, struct Client *cli,
1763 int parc, char **params)
1765 struct AuthRequest *auth;
1767 if (EmptyString(params[0])) {
1768 sendto_iauth(cli, "E Missing :Missing hostname parameter");
1772 auth = cli_auth(cli);
1773 assert(auth != NULL);
1775 /* If a DNS request is pending, abort it. */
1776 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
1777 FlagClr(&auth->flags, AR_DNS_PENDING);
1778 delete_resolver_queries(auth);
1779 if (IsUserPort(cli))
1780 sendheader(cli, REPORT_FIN_DNS);
1782 /* Set hostname from params. */
1783 ircd_strncpy(cli_sockhost(cli), params[0], HOSTLEN);
1784 /* If we have gotten here, the user is in a "hurry" state and has
1785 * been pre-registered. Their hostname was set during that, and
1786 * needs to be overwritten now.
1788 if (FlagHas(&auth->flags, AR_IAUTH_HURRY)) {
1789 ircd_strncpy(cli_user(cli)->host, cli_sockhost(cli), HOSTLEN);
1790 ircd_strncpy(cli_user(cli)->realhost, cli_sockhost(cli), HOSTLEN);
1795 /** Set client's IP address.
1796 * @param[in] iauth Active IAuth session.
1797 * @param[in] cli Client referenced by command.
1798 * @param[in] parc Number of parameters (1).
1799 * @param[in] params New IP address for client in dotted quad or
1800 * standard IPv6 format.
1803 static int iauth_cmd_ip_address(struct IAuth *iauth, struct Client *cli,
1804 int parc, char **params)
1806 struct irc_in_addr addr;
1807 struct AuthRequest *auth;
1809 if (EmptyString(params[0])) {
1810 sendto_iauth(cli, "E Missing :Missing IP address parameter");
1814 /* Get AuthRequest for client. */
1815 auth = cli_auth(cli);
1816 assert(auth != NULL);
1818 /* Parse the client's new IP address. */
1819 if (!ircd_aton(&addr, params[0])) {
1820 sendto_iauth(cli, "E Invalid :Unable to parse IP address [%s]", params[0]);
1824 /* If this is the first IP override, save the client's original
1825 * address in case we get a DNS response later.
1827 if (!irc_in_addr_valid(&auth->original))
1828 memcpy(&auth->original, &cli_ip(cli), sizeof(auth->original));
1830 /* Undo original IP connection in IPcheck. */
1831 IPcheck_connect_fail(cli);
1832 ClearIPChecked(cli);
1834 /* Update the IP and charge them as a remote connect. */
1835 memcpy(&cli_ip(cli), &addr, sizeof(cli_ip(cli)));
1836 IPcheck_remote_connect(cli, 0);
1841 /** Find a ConfItem structure for a named connection class.
1842 * @param[in] class_name Name of configuration class to find.
1843 * @return A ConfItem of type CONF_CLIENT for the class, or NULL on failure.
1845 static struct ConfItem *auth_find_class_conf(const char *class_name)
1847 static struct ConfItem *aconf_list;
1848 struct ConnectionClass *class;
1849 struct ConfItem *aconf;
1851 /* Make sure the configuration class is valid. */
1852 class = find_class(class_name);
1853 if (!class || !class->valid)
1856 /* Look for an existing ConfItem for the class. */
1857 for (aconf = aconf_list; aconf; aconf = aconf->next)
1858 if (aconf->conn_class == class)
1861 /* If no ConfItem, create one. */
1863 aconf = make_conf(CONF_CLIENT);
1865 sendto_opmask_butone(NULL, SNO_AUTH,
1866 "Unable to allocate ConfItem for class %s!",
1870 /* make_conf() "helpfully" links the conf into GlobalConfList,
1871 * which we do not want, so undo that. (Ugh.)
1873 if (aconf == GlobalConfList) {
1874 GlobalConfList = aconf->next;
1876 /* Back to business as usual. */
1877 aconf->conn_class = class;
1878 aconf->next = aconf_list;
1885 /** Tentatively accept a client in IAuth.
1886 * @param[in] iauth Active IAuth session.
1887 * @param[in] cli Client referenced by command.
1888 * @param[in] parc Number of parameters.
1889 * @param[in] params Optional class name for client.
1890 * @return Negative (CPTR_KILLED) if the connection is refused, one otherwise.
1892 static int iauth_cmd_soft_done(struct IAuth *iauth, struct Client *cli,
1893 int parc, char **params)
1895 /* Clear iauth pending flag. */
1896 assert(cli_auth(cli) != NULL);
1897 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_SOFT_DONE);
1901 /** Accept a client in IAuth.
1902 * @param[in] iauth Active IAuth session.
1903 * @param[in] cli Client referenced by command.
1904 * @param[in] parc Number of parameters.
1905 * @param[in] params Optional class name for client.
1906 * @return Negative (CPTR_KILLED) if the connection is refused, one otherwise.
1908 static int iauth_cmd_done_client(struct IAuth *iauth, struct Client *cli,
1909 int parc, char **params)
1911 static time_t warn_time;
1913 /* Clear iauth pending flag. */
1914 assert(cli_auth(cli) != NULL);
1915 FlagClr(&cli_auth(cli)->flags, AR_IAUTH_PENDING);
1917 /* If a connection class was specified (and usable), assign the client to it. */
1918 if (!EmptyString(params[0])) {
1919 struct ConfItem *aconf;
1921 aconf = auth_find_class_conf(params[0]);
1923 enum AuthorizationCheckResult acr;
1925 acr = attach_conf(cli, aconf);
1928 /* There should maybe be some way to set FLAG_DOID here.. */
1930 case ACR_TOO_MANY_IN_CLASS:
1931 ++ServerStats->is_ref;
1932 return exit_client(cli, cli, &me,
1933 "Sorry, your connection class is full - try "
1934 "again later or try another server");
1936 log_write(LS_IAUTH, L_ERROR, 0, "IAuth: Unexpected AuthorizationCheckResult %d from attach_conf()", acr);
1940 sendto_opmask_butone_ratelimited(NULL, SNO_AUTH, &warn_time,
1941 "iauth tried to use undefined class [%s]",
1948 /** Accept a client in IAuth and assign them to an account.
1949 * @param[in] iauth Active IAuth session.
1950 * @param[in] cli Client referenced by command.
1951 * @param[in] parc Number of parameters.
1952 * @param[in] params Account name and optional class name for client.
1953 * @return Negative if the connection is refused, otherwise non-zero
1954 * if \a cli authorization should be checked for completion.
1956 static int iauth_cmd_done_account(struct IAuth *iauth, struct Client *cli,
1957 int parc, char **params)
1962 if (EmptyString(params[0])) {
1963 sendto_iauth(cli, "E Missing :Missing account parameter");
1966 /* Check length of account name. */
1967 len = strcspn(params[0], ": ");
1968 if (len > ACCOUNTLEN) {
1969 sendto_iauth(cli, "E Invalid :Account parameter too long");
1972 /* If account has a creation timestamp, use it. */
1973 assert(cli_user(cli) != NULL);
1974 if (params[0][len] == ':') {
1975 cli_user(cli)->acc_create = strtoul(params[0] + len + 1, NULL, 10);
1976 params[0][len] = '\0';
1979 /* Copy account name to User structure. */
1980 ircd_strncpy(cli_user(cli)->account, params[0], ACCOUNTLEN);
1983 /* Fall through to the normal "done" handler. */
1984 return iauth_cmd_done_client(iauth, cli, parc - 1, params + 1);
1987 /** Reject a client's connection.
1988 * @param[in] iauth Active IAuth session.
1989 * @param[in] cli Client referenced by command.
1990 * @param[in] parc Number of parameters (1).
1991 * @param[in] params Optional kill message.
1994 static int iauth_cmd_kill(struct IAuth *iauth, struct Client *cli,
1995 int parc, char **params)
1998 FlagClr(&cli_auth(cli)->flags, AR_IAUTH_PENDING);
1999 if (EmptyString(params[0]))
2000 params[0] = "Access denied";
2001 exit_client(cli, cli, &me, params[0]);
2005 /** Change a client's usermode.
2006 * @param[in] iauth Active IAuth session.
2007 * @param[in] cli Client referenced by command.
2008 * @param[in] parc Number of parameters (at least one).
2009 * @param[in] params Usermode arguments for client (with the first
2010 * starting with '+').
2013 static int iauth_cmd_usermode(struct IAuth *iauth, struct Client *cli,
2014 int parc, char **params)
2016 if (params[0][0] == '+')
2018 set_user_mode(cli, cli, parc + 2, params - 2, ALLOWMODES_ANY);
2024 /** Send a challenge string to the client.
2025 * @param[in] iauth Active IAuth session.
2026 * @param[in] cli Client referenced by command.
2027 * @param[in] parc Number of parameters (1).
2028 * @param[in] params Challenge message for client.
2031 static int iauth_cmd_challenge(struct IAuth *iauth, struct Client *cli,
2032 int parc, char **params)
2034 if (!EmptyString(params[0]))
2035 sendrawto_one(cli, "NOTICE AUTH :*** %s", params[0]);
2039 /** Send an extension query to a specified remote server.
2040 * @param[in] iauth Active IAuth session.
2041 * @param[in] cli Client referenced by command.
2042 * @param[in] parc Number of parameters (3).
2043 * @param[in] params Remote server, routing information, and query.
2046 static int iauth_cmd_xquery(struct IAuth *iauth, struct Client *cli,
2047 int parc, char **params)
2050 const char *routing;
2052 struct Client *acptr;
2054 /* Process parameters */
2055 if (EmptyString(params[0])) {
2056 sendto_iauth(cli, "E Missing :Missing server parameter");
2061 if (EmptyString(params[1])) {
2062 sendto_iauth(cli, "E Missing :Missing routing parameter");
2065 routing = params[1];
2067 if (EmptyString(params[2])) {
2068 sendto_iauth(cli, "E Missing :Missing query parameter");
2073 /* Try to find the specified server */
2074 if (!(acptr = find_match_server(serv))) {
2075 sendto_iauth(cli, "x %s %s :Server not online", serv, routing);
2079 /* If it's to us, do nothing; otherwise, forward the query */
2081 /* The "iauth:" prefix helps ircu route the reply to iauth */
2082 sendcmdto_one(&me, CMD_XQUERY, acptr, "%C iauth:%s :%s", acptr, routing,
2088 /** Parse a \a message from \a iauth.
2089 * @param[in] iauth Active IAuth session.
2090 * @param[in] message Message to be parsed.
2092 static void iauth_parse(struct IAuth *iauth, char *message)
2094 char *params[MAXPARA + 1]; /* leave space for NULL */
2096 iauth_cmd_handler handler;
2097 struct AuthRequest *auth;
2102 /* Find command handler... */
2103 switch (*(message++)) {
2104 case '>': handler = iauth_cmd_snotice; has_cli = 0; break;
2105 case 'G': handler = iauth_cmd_debuglevel; has_cli = 0; break;
2106 case 'O': handler = iauth_cmd_policy; has_cli = 0; break;
2107 case 'V': handler = iauth_cmd_version; has_cli = 0; break;
2108 case 'a': handler = iauth_cmd_newconfig; has_cli = 0; break;
2109 case 'A': handler = iauth_cmd_config; has_cli = 0; break;
2110 case 's': handler = iauth_cmd_newstats; has_cli = 0; break;
2111 case 'S': handler = iauth_cmd_stats; has_cli = 0; break;
2112 case 'X': handler = iauth_cmd_xquery; has_cli = 0; break;
2113 case 'o': handler = iauth_cmd_username_forced; has_cli = 1; break;
2114 case 'U': handler = iauth_cmd_username_good; has_cli = 1; break;
2115 case 'u': handler = iauth_cmd_username_bad; has_cli = 1; break;
2116 case 'N': handler = iauth_cmd_hostname; has_cli = 1; break;
2117 case 'I': handler = iauth_cmd_ip_address; has_cli = 1; break;
2118 case 'M': handler = iauth_cmd_usermode; has_cli = 1; break;
2119 case 'C': handler = iauth_cmd_challenge; has_cli = 1; break;
2120 case 'd': handler = iauth_cmd_soft_done; has_cli = 1; break;
2121 case 'D': handler = iauth_cmd_done_client; has_cli = 1; break;
2122 case 'R': handler = iauth_cmd_done_account; has_cli = 1; break;
2123 case 'k': /* The 'k' command indicates the user should be booted
2124 * off without telling opers. There is no way to
2125 * signal that to exit_client(), so we fall through to
2126 * the case that we do implement.
2128 case 'K': handler = iauth_cmd_kill; has_cli = 2; break;
2129 case 'r': /* we handle termination directly */ return;
2130 default: sendto_iauth(NULL, "E Garbage :[%s]", message); return;
2133 while (parc < MAXPARA) {
2134 while (IsSpace(*message)) /* skip leading whitespace */
2137 if (!*message) /* hit the end of the string, break out */
2140 if (*message == ':') { /* found sentinel... */
2141 params[parc++] = message + 1;
2142 break; /* it's the last parameter anyway */
2145 params[parc++] = message; /* save the parameter */
2146 while (*message && !IsSpace(*message))
2147 message++; /* find the end of the parameter */
2149 if (*message) /* terminate the parameter */
2150 *(message++) = '\0';
2153 params[parc] = NULL; /* terminate the parameter list */
2155 /* Check to see if the command specifies a client... */
2157 /* Handler does not need a client. */
2158 handler(iauth, NULL, parc, params);
2160 /* Try to find the client associated with the request. */
2161 id = strtol(params[0], NULL, 10);
2163 sendto_iauth(NULL, "E Missing :Need <id> <ip> <port>");
2164 else if (id < 0 || id > HighestFd || !(cli = LocalClientArray[id]))
2165 /* Client no longer exists (or never existed). */
2166 sendto_iauth(NULL, "E Gone :[%s %s %s]", params[0], params[1],
2168 else if ((!(auth = cli_auth(cli)) ||
2169 !FlagHas(&auth->flags, AR_IAUTH_PENDING)) &&
2171 /* Client is done with IAuth checks. */
2172 sendto_iauth(cli, "E Done :[%s %s %s]", params[0], params[1], params[2]);
2174 struct irc_sockaddr addr;
2177 /* Parse IP address and port number from parameters */
2178 res = ipmask_parse(params[1], &addr.addr, NULL);
2179 addr.port = strtol(params[2], NULL, 10);
2181 /* Check IP address and port number against expected. */
2183 irc_in_addr_cmp(&addr.addr, &cli_ip(cli)) ||
2184 (auth && addr.port != auth->port))
2185 /* Report mismatch to iauth. */
2186 sendto_iauth(cli, "E Mismatch :[%s] != [%s]", params[1],
2187 ircd_ntoa(&cli_ip(cli)));
2188 else if (handler(iauth, cli, parc - 3, params + 3) > 0)
2189 /* Handler indicated a possible state change. */
2190 check_auth_finished(auth);
2195 /** Read input from \a iauth.
2196 * Reads up to SERVER_TCP_WINDOW bytes per pass.
2197 * @param[in] iauth Readable connection.
2199 static void iauth_read(struct IAuth *iauth)
2201 static char readbuf[SERVER_TCP_WINDOW];
2202 unsigned int length, count;
2206 /* Copy partial data to readbuf, append new data. */
2207 length = iauth->i_count;
2208 memcpy(readbuf, iauth->i_buffer, length);
2209 if (IO_SUCCESS != os_recv_nonb(s_fd(i_socket(iauth)),
2211 sizeof(readbuf) - length - 1,
2214 readbuf[length += count] = '\0';
2216 /* Parse each complete line. */
2217 for (sol = readbuf; (eol = strchr(sol, '\n')) != NULL; sol = eol + 1) {
2219 if (*(eol - 1) == '\r') /* take out carriage returns, too... */
2222 /* If spammy debug, send the message to opers. */
2223 if (i_debug(iauth) > 1)
2224 sendto_opmask_butone(NULL, SNO_AUTH, "Parsing: \"%s\"", sol);
2226 /* Parse the line... */
2227 iauth_parse(iauth, sol);
2230 /* Put unused data back into connection's buffer. */
2231 iauth->i_count = strlen(sol);
2232 if (iauth->i_count > BUFSIZE)
2233 iauth->i_count = BUFSIZE;
2234 memcpy(iauth->i_buffer, sol, iauth->i_count);
2237 /** Handle socket activity for an %IAuth connection.
2238 * @param[in] ev &Socket event; the IAuth connection is the user data
2239 * pointer for the socket.
2241 static void iauth_sock_callback(struct Event *ev)
2243 struct IAuth *iauth;
2245 assert(0 != ev_socket(ev));
2246 iauth = (struct IAuth*) s_data(ev_socket(ev));
2249 switch (ev_type(ev)) {
2251 /* Hm, what happened here? */
2252 if (!IAuthHas(iauth, IAUTH_CLOSING))
2253 iauth_do_spawn(iauth, 1);
2259 IAuthClr(iauth, IAUTH_BLOCKED);
2263 log_write(LS_IAUTH, L_ERROR, 0, "IAuth socket error: %s", strerror(ev_data(ev)));
2264 /* and fall through to the ET_EOF case */
2266 iauth_disconnect(iauth);
2269 assert(0 && "Unrecognized event type");
2274 /** Read error input from \a iauth.
2275 * @param[in] iauth Readable connection.
2277 static void iauth_read_stderr(struct IAuth *iauth)
2279 static char readbuf[SERVER_TCP_WINDOW];
2280 unsigned int length, count;
2284 /* Copy partial data to readbuf, append new data. */
2285 length = iauth->i_errcount;
2286 memcpy(readbuf, iauth->i_errbuf, length);
2287 if (IO_SUCCESS != os_recv_nonb(s_fd(i_stderr(iauth)),
2289 sizeof(readbuf) - length - 1,
2292 readbuf[length += count] = '\0';
2294 /* Send each complete line to SNO_AUTH. */
2295 for (sol = readbuf; (eol = strchr(sol, '\n')) != NULL; sol = eol + 1) {
2297 if (*(eol - 1) == '\r') /* take out carriage returns, too... */
2299 Debug((DEBUG_ERROR, "IAuth error: %s", sol));
2300 log_write(LS_IAUTH, L_ERROR, 0, "IAuth error: %s", sol);
2301 sendto_opmask_butone(NULL, SNO_AUTH, "%s", sol);
2304 /* Put unused data back into connection's buffer. */
2305 iauth->i_errcount = strlen(sol);
2306 if (iauth->i_errcount > BUFSIZE)
2307 iauth->i_errcount = BUFSIZE;
2308 memcpy(iauth->i_errbuf, sol, iauth->i_errcount);
2311 /** Handle error socket activity for an %IAuth connection.
2312 * @param[in] ev &Socket event; the IAuth connection is the user data
2313 * pointer for the socket.
2315 static void iauth_stderr_callback(struct Event *ev)
2317 struct IAuth *iauth;
2319 assert(0 != ev_socket(ev));
2320 iauth = (struct IAuth*) s_data(ev_socket(ev));
2323 switch (ev_type(ev)) {
2325 /* We do not restart iauth here: the stdout handler does that for us. */
2328 iauth_read_stderr(iauth);
2331 log_write(LS_IAUTH, L_ERROR, 0, "IAuth stderr error: %s", strerror(ev_data(ev)));
2332 /* and fall through to the ET_EOF case */
2334 iauth_disconnect(iauth);
2337 assert(0 && "Unrecognized event type");
2342 /** Report active iauth's configuration to \a cptr.
2343 * @param[in] cptr Client requesting statistics.
2344 * @param[in] sd Stats descriptor for request.
2345 * @param[in] param Extra parameter from user (may be NULL).
2347 void report_iauth_conf(struct Client *cptr, const struct StatDesc *sd, char *param)
2351 if (iauth) for (link = iauth->i_config; link; link = link->next)
2353 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":%s",
2358 /** Report active iauth's statistics to \a cptr.
2359 * @param[in] cptr Client requesting statistics.
2360 * @param[in] sd Stats descriptor for request.
2361 * @param[in] param Extra parameter from user (may be NULL).
2363 void report_iauth_stats(struct Client *cptr, const struct StatDesc *sd, char *param)
2367 if (iauth) for (link = iauth->i_stats; link; link = link->next)
2369 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":%s",