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 /** Copies a username, cleaning it in the process.
218 * @param[out] dest Destination buffer for user name.
219 * @param[in] src Source buffer for user name. Must be distinct from
222 void clean_username(char *dest, const char *src)
227 /* First character can be ~, later characters cannot. */
231 *dest++ = IsUserChar(ch) ? ch : '_';
234 while (rlen-- && !IsCntrl(ch = *src++))
236 *dest++ = (IsUserChar(ch) && (ch != '~')) ? ch : '_';
241 /** Set username for user associated with \a auth.
242 * @param[in] auth Client authorization request to work on.
243 * @return Zero if client is kept, CPTR_KILLED if client rejected.
245 static int auth_set_username(struct AuthRequest *auth)
247 struct Client *sptr = auth->client;
248 struct User *user = cli_user(sptr);
257 short digitgroups = 0;
261 if (FlagHas(&auth->flags, AR_IAUTH_FUSERNAME))
263 ircd_strncpy(user->username, cli_username(sptr), USERLEN);
265 else if (IsIdented(sptr))
267 clean_username(user->username, cli_username(sptr));
269 else if (HasFlag(sptr, FLAG_DOID))
271 /* Prepend ~ to user->username. */
274 for (last = '~'; (ch = *s) != '\0'; )
281 } /* else cleaned version of client-provided name is in place */
283 /* If username is empty or just ~, reject. */
284 if ((user->username[0] == '\0')
285 || ((user->username[0] == '~') && (user->username[1] == '\0')))
286 return exit_client(sptr, sptr, &me, "USER: Bogus userid.");
288 /* Check for K- or G-line. */
289 killreason = find_kill(sptr);
291 ServerStats->is_ref++;
292 return exit_client(sptr, sptr, &me,
293 (killreason == -1 ? "K-lined" : "G-lined"));
296 if (!FlagHas(&auth->flags, AR_IAUTH_FUSERNAME))
298 /* Check for mixed case usernames, meaning probably hacked. Jon2 3-94
299 * Explanations of rules moved to where it is checked Entrope 2-06
301 s = d = user->username + (user->username[0] == '~');
310 else if (IsUpper(ch))
313 /* Accept caps as leading if we haven't seen lower case or digits yet. */
314 if ((leadcaps || last == '\0') && !lower && !digits)
317 else if (IsDigit(ch))
323 /* If more than two groups of digits, reject. */
328 else if (ch == '-' || ch == '_' || ch == '.')
331 /* If -_. exist at start, consecutively, or more than twice, reject. */
332 if (last == '\0' || last == '-' || last == '_' || last == '.' || other > 2)
335 else /* All other punctuation is rejected. */
339 /* If mixed case, first must be capital, but no more than three;
340 * but if three capitals, they must all be leading. */
341 if (lower && upper && (!leadcaps || leadcaps > 3 ||
342 (upper > 2 && upper > leadcaps)))
344 /* If two different groups of digits, one must be either at the
346 if (digitgroups == 2 && !(IsDigit(s[0]) || IsDigit(ch)))
348 /* Must have at least one letter. */
349 if (!lower && !upper)
351 /* Final character must not be punctuation. */
359 /* If we confirmed their username, and it is what they claimed,
361 if (IsIdented(sptr) && !strcmp(cli_username(sptr), user->username))
364 ServerStats->is_ref++;
365 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
366 ":Your username is invalid.");
367 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
368 ":Connect with your real username, in lowercase.");
369 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
370 ":If your mail address were foo@bar.com, your username "
372 return exit_client(sptr, sptr, &me, "USER: Bad username");
375 /** Check whether an authorization request is complete.
376 * This means that no flags from 0 to #AR_LAST_SCAN are set on \a auth.
377 * If #AR_IAUTH_PENDING is set, optionally go into "hurry" state. If
378 * 0 through #AR_LAST_SCAN and #AR_IAUTH_PENDING are all clear,
379 * destroy \a auth, clear the password, set the username, and register
381 * @param[in] auth Authorization request to check.
382 * @return Zero if client is kept, CPTR_KILLED if client rejected.
384 static int check_auth_finished(struct AuthRequest *auth)
386 enum AuthRequestFlag flag;
389 /* Check non-iauth registration blocking flags. */
390 for (flag = 0; flag <= AR_LAST_SCAN; ++flag)
391 if (FlagHas(&auth->flags, flag))
393 Debug((DEBUG_INFO, "Auth %p [%d] still has flag %d", auth,
394 cli_fd(auth->client), flag));
398 /* If appropriate, do preliminary assignment to connection class. */
399 if (IsUserPort(auth->client)
400 && !FlagHas(&auth->flags, AR_IAUTH_HURRY)
401 && preregister_user(auth->client))
404 /* If we have not done so, check client password. Do this as soon
405 * as possible so that iauth's challenge/response (which uses PASS
406 * for responses) is not confused with the client's password.
408 if (IsUserPort(auth->client)
409 && !FlagHas(&auth->flags, AR_PASSWORD_CHECKED))
411 struct ConfItem *aconf;
413 aconf = cli_confs(auth->client)->value.aconf;
415 && !EmptyString(aconf->passwd)
416 && strcmp(cli_passwd(auth->client), aconf->passwd))
418 ServerStats->is_ref++;
419 send_reply(auth->client, ERR_PASSWDMISMATCH);
420 return exit_client(auth->client, auth->client, &me, "Bad Password");
422 FlagSet(&auth->flags, AR_PASSWORD_CHECKED);
425 /* Check if iauth is done. */
426 if (FlagHas(&auth->flags, AR_IAUTH_PENDING))
428 /* Switch auth request to hurry-up state. */
429 if (!FlagHas(&auth->flags, AR_IAUTH_HURRY))
431 /* Set "hurry" flag in auth request. */
432 FlagSet(&auth->flags, AR_IAUTH_HURRY);
434 /* If iauth wants it, send notification. */
435 if (IAuthHas(iauth, IAUTH_UNDERNET))
436 sendto_iauth(auth->client, "H %s", get_client_class(auth->client));
438 /* If iauth wants it, give client more time. */
439 if (IAuthHas(iauth, IAUTH_EXTRAWAIT))
440 cli_firsttime(auth->client) = CurrentTime;
443 Debug((DEBUG_INFO, "Auth %p [%d] still has flag %d", auth,
444 cli_fd(auth->client), AR_IAUTH_PENDING));
448 FlagSet(&auth->flags, AR_IAUTH_HURRY);
450 if (IsUserPort(auth->client))
452 memset(cli_passwd(auth->client), 0, sizeof(cli_passwd(auth->client)));
453 res = auth_set_username(auth);
455 res = register_user(auth->client, auth->client);
460 destroy_auth_request(auth);
464 /** Verify that a hostname is valid, i.e., only contains characters
465 * valid for a hostname and that a hostname is not too long.
466 * @param host Hostname to check.
467 * @param maxlen Maximum length of hostname, not including NUL terminator.
468 * @return Non-zero if the hostname is valid.
471 auth_verify_hostname(const char *host, int maxlen)
475 /* Walk through the host name */
476 for (i = 0; host[i]; i++)
477 /* If it's not a hostname character or if it's too long, return false */
478 if (!IsHostChar(host[i]) || i >= maxlen)
481 return 1; /* it's a valid hostname */
484 /** Check whether a client already has a CONF_CLIENT configuration
487 * @return A pointer to the client's first CONF_CLIENT, or NULL if
490 static struct ConfItem *find_conf_client(struct Client *cptr)
494 for (list = cli_confs(cptr); list != NULL; list = list->next) {
495 struct ConfItem *aconf;
496 aconf = list->value.aconf;
497 if (aconf->status & CONF_CLIENT)
504 /** Assign a client to a connection class.
505 * @param[in] cptr Client to assign to a class.
506 * @return Zero if client is kept, CPTR_KILLED if rejected.
508 static int preregister_user(struct Client *cptr)
510 static time_t last_too_many1;
511 static time_t last_too_many2;
513 ircd_strncpy(cli_user(cptr)->host, cli_sockhost(cptr), HOSTLEN);
514 ircd_strncpy(cli_user(cptr)->realhost, cli_sockhost(cptr), HOSTLEN);
516 if (find_conf_client(cptr)) {
520 switch (conf_check_client(cptr))
524 case ACR_NO_AUTHORIZATION:
525 sendto_opmask_butone(0, SNO_UNAUTH, "Unauthorized connection from %s.",
526 get_client_name(cptr, HIDE_IP));
527 ++ServerStats->is_ref;
528 return exit_client(cptr, cptr, &me,
529 "No Authorization - use another server");
530 case ACR_TOO_MANY_IN_CLASS:
531 sendto_opmask_butone_ratelimited(0, SNO_TOOMANY, &last_too_many1,
532 "Too many connections in class %s for %s.",
533 get_client_class(cptr),
534 get_client_name(cptr, SHOW_IP));
535 ++ServerStats->is_ref;
536 return exit_client(cptr, cptr, &me,
537 "Sorry, your connection class is full - try "
538 "again later or try another server");
539 case ACR_TOO_MANY_FROM_IP:
540 sendto_opmask_butone_ratelimited(0, SNO_TOOMANY, &last_too_many2,
541 "Too many connections from same IP for %s.",
542 get_client_name(cptr, SHOW_IP));
543 ++ServerStats->is_ref;
544 return exit_client(cptr, cptr, &me,
545 "Too many connections from your host");
546 case ACR_ALREADY_AUTHORIZED:
547 /* Can this ever happen? */
549 ++ServerStats->is_ref;
550 IPcheck_connect_fail(cptr, 0);
551 return exit_client(cptr, cptr, &me, "Unknown error -- Try again");
556 /** Send the ident server a query giving "theirport , ourport". The
557 * write is only attempted *once* so it is deemed to be a fail if the
558 * entire write doesn't write all the data given. This shouldn't be a
559 * problem since the socket should have a write buffer far greater
560 * than this message to store it in should problems arise. -avalon
561 * @param[in] auth The request to send.
563 static void send_auth_query(struct AuthRequest* auth)
570 ircd_snprintf(0, authbuf, sizeof(authbuf), "%hu , %hu\r\n",
571 auth->port, auth->local.port);
573 if (IO_SUCCESS != os_send_nonb(s_fd(&auth->socket), authbuf, strlen(authbuf), &count)) {
574 close(s_fd(&auth->socket));
575 socket_del(&auth->socket);
576 s_fd(&auth->socket) = -1;
577 ++ServerStats->is_abad;
578 if (IsUserPort(auth->client))
579 sendheader(auth->client, REPORT_FAIL_ID);
580 FlagClr(&auth->flags, AR_AUTH_PENDING);
581 check_auth_finished(auth);
585 /** Enum used to index ident reply fields in a human-readable way. */
586 enum IdentReplyFields {
594 /** Parse an ident reply line and extract the userid from it.
595 * @param[in] reply The ident reply line.
596 * @return The userid, or NULL on parse failure.
598 static char* check_ident_reply(char* reply)
602 char* vector[USERID_TOKEN_COUNT];
603 int count = token_vector(reply, ':', vector, USERID_TOKEN_COUNT);
605 if (USERID_TOKEN_COUNT != count)
608 * second token is the reply type
610 token = vector[IDENT_REPLY_TYPE];
611 if (EmptyString(token))
614 while (IsSpace(*token))
617 if (0 != strncmp(token, "USERID", 6))
621 * third token is the os type
623 token = vector[IDENT_OS_TYPE];
624 if (EmptyString(token))
626 while (IsSpace(*token))
630 * Unless "OTHER" is specified as the operating system
631 * type, the server is expected to return the "normal"
632 * user identification of the owner of this connection.
633 * "Normal" in this context may be taken to mean a string
634 * of characters which uniquely identifies the connection
635 * owner such as a user identifier assigned by the system
636 * administrator and used by such user as a mail
637 * identifier, or as the "user" part of a user/password
638 * pair used to gain access to system resources. When an
639 * operating system is specified (e.g., anything but
640 * "OTHER"), the user identifier is expected to be in a
641 * more or less immediately useful form - e.g., something
642 * that could be used as an argument to "finger" or as a
645 if (0 == strncmp(token, "OTHER", 5))
648 * fourth token is the username
650 token = vector[IDENT_INFO];
651 if (EmptyString(token))
653 while (IsSpace(*token))
656 * look for the end of the username, terminators are '\0, @, <SPACE>, :'
658 for (end = token; *end; ++end) {
659 if (IsSpace(*end) || '@' == *end || ':' == *end)
666 /** Read the reply (if any) from the ident server we connected to. We
667 * only give it one shot, if the reply isn't good the first time fail
668 * the authentication entirely. --Bleep
669 * @param[in] auth The request to read.
671 static void read_auth_reply(struct AuthRequest* auth)
676 * rfc1453 sez we MUST accept 512 bytes
678 char buf[BUFSIZE + 1];
681 assert(0 != auth->client);
682 assert(auth == cli_auth(auth->client));
684 if (IO_SUCCESS == os_recv_nonb(s_fd(&auth->socket), buf, BUFSIZE, &len)) {
686 Debug((DEBUG_INFO, "Auth %p [%d] reply: %s", auth, cli_fd(auth->client), buf));
687 username = check_ident_reply(buf);
688 Debug((DEBUG_INFO, "Username: %s", username));
691 Debug((DEBUG_INFO, "Deleting auth [%d] socket %p", auth, cli_fd(auth->client)));
692 close(s_fd(&auth->socket));
693 socket_del(&auth->socket);
694 s_fd(&auth->socket) = -1;
696 if (EmptyString(username)) {
697 if (IsUserPort(auth->client))
698 sendheader(auth->client, REPORT_FAIL_ID);
699 ++ServerStats->is_abad;
700 if (IAuthHas(iauth, IAUTH_UNDERNET))
701 sendto_iauth(auth->client, "u");
703 if (IsUserPort(auth->client))
704 sendheader(auth->client, REPORT_FIN_ID);
705 ++ServerStats->is_asuc;
706 if (!FlagHas(&auth->flags, AR_IAUTH_USERNAME)) {
707 ircd_strncpy(cli_username(auth->client), username, USERLEN);
708 SetGotId(auth->client);
710 if (IAuthHas(iauth, IAUTH_UNDERNET))
711 sendto_iauth(auth->client, "u %s", username);
714 FlagClr(&auth->flags, AR_AUTH_PENDING);
715 check_auth_finished(auth);
718 /** Handle socket I/O activity.
719 * @param[in] ev A socket event whos associated data is the active
720 * struct AuthRequest.
722 static void auth_sock_callback(struct Event* ev)
724 struct AuthRequest* auth;
726 assert(0 != ev_socket(ev));
727 assert(0 != s_data(ev_socket(ev)));
729 auth = (struct AuthRequest*) s_data(ev_socket(ev));
731 switch (ev_type(ev)) {
732 case ET_DESTROY: /* being destroyed */
735 case ET_CONNECT: /* socket connection completed */
736 Debug((DEBUG_INFO, "Connection completed for auth %p [%d]; sending query",
737 auth, cli_fd(auth->client)));
738 socket_state(&auth->socket, SS_CONNECTED);
739 send_auth_query(auth);
742 case ET_READ: /* socket is readable */
743 case ET_EOF: /* end of file on socket */
744 case ET_ERROR: /* error on socket */
745 Debug((DEBUG_INFO, "Auth socket %p [%p] readable", auth, ev_socket(ev)));
746 read_auth_reply(auth);
750 assert(0 && "Unrecognized event in auth_socket_callback().");
755 /** Stop an auth request completely.
756 * @param[in] auth The struct AuthRequest to cancel.
758 void destroy_auth_request(struct AuthRequest* auth)
760 Debug((DEBUG_INFO, "Deleting auth request for %p", auth->client));
762 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
763 delete_resolver_queries(auth);
766 if (-1 < s_fd(&auth->socket)) {
767 close(s_fd(&auth->socket));
768 socket_del(&auth->socket);
769 s_fd(&auth->socket) = -1;
772 if (t_active(&auth->timeout))
773 timer_del(&auth->timeout);
775 cli_auth(auth->client) = NULL;
776 auth->next = auth_freelist;
777 auth_freelist = auth;
780 /** Handle a 'ping' (authorization) timeout for a client.
781 * @param[in] cptr The client whose session authorization has timed out.
782 * @return Zero if client is kept, CPTR_KILLED if client rejected.
784 int auth_ping_timeout(struct Client *cptr)
786 struct AuthRequest *auth;
787 enum AuthRequestFlag flag;
789 auth = cli_auth(cptr);
791 /* Check whether the auth request is gone (more likely, it never
792 * existed, as in an outbound server connection). */
794 return exit_client_msg(cptr, cptr, &me, "Registration Timeout");
796 /* Check for a user-controlled timeout. */
797 for (flag = 0; flag <= AR_LAST_SCAN; ++flag) {
798 if (FlagHas(&auth->flags, flag)) {
799 /* Display message if they have sent a NICK and a USER but no
802 if (*(cli_name(cptr)) && cli_user(cptr) && *(cli_user(cptr))->username) {
803 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
804 ":Your client may not be compatible with this server.");
805 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
806 ":Compatible clients are available at %s",
807 feature_str(FEAT_URL_CLIENTS));
809 return exit_client_msg(cptr, cptr, &me, "Registration Timeout");
813 /* Check for iauth timeout. */
814 if (FlagHas(&auth->flags, AR_IAUTH_PENDING)) {
815 if (IAuthHas(iauth, IAUTH_REQUIRED)
816 && !FlagHas(&auth->flags, AR_IAUTH_SOFT_DONE)) {
817 sendheader(cptr, REPORT_FAIL_IAUTH);
818 return exit_client_msg(cptr, cptr, &me, "Authorization Timeout");
820 sendto_iauth(cptr, "T");
821 FlagClr(&auth->flags, AR_IAUTH_PENDING);
822 return check_auth_finished(auth);
825 assert(0 && "Unexpectedly reached end of auth_ping_timeout()");
829 /** Timeout a given auth request.
830 * @param[in] ev A timer event whose associated data is the expired
831 * struct AuthRequest.
833 static void auth_timeout_callback(struct Event* ev)
835 struct AuthRequest* auth;
837 assert(0 != ev_timer(ev));
838 assert(0 != t_data(ev_timer(ev)));
840 auth = (struct AuthRequest*) t_data(ev_timer(ev));
842 if (ev_type(ev) == ET_EXPIRE) {
843 /* Report the timeout in the log. */
844 log_write(LS_RESOLVER, L_INFO, 0, "Registration timeout %s",
845 get_client_name(auth->client, HIDE_IP));
847 /* Notify client if ident lookup failed. */
848 if (FlagHas(&auth->flags, AR_AUTH_PENDING)) {
849 FlagClr(&auth->flags, AR_AUTH_PENDING);
850 if (IsUserPort(auth->client))
851 sendheader(auth->client, REPORT_FAIL_ID);
854 /* Likewise if dns lookup failed. */
855 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
856 FlagClr(&auth->flags, AR_DNS_PENDING);
857 delete_resolver_queries(auth);
858 if (IsUserPort(auth->client))
859 sendheader(auth->client, REPORT_FAIL_DNS);
862 /* Try to register the client. */
863 check_auth_finished(auth);
867 /** Handle a complete DNS lookup. Send the client on it's way to a
868 * connection completion, regardless of success or failure -- unless
869 * there was a mismatch and KILL_IPMISMATCH is set.
870 * @param[in] vptr The pending struct AuthRequest.
871 * @param[in] addr IP address being resolved.
872 * @param[in] h_name Resolved name, or NULL if lookup failed.
874 static void auth_dns_callback(void* vptr, const struct irc_in_addr *addr, const char *h_name)
876 struct AuthRequest* auth = (struct AuthRequest*) vptr;
879 FlagClr(&auth->flags, AR_DNS_PENDING);
881 /* DNS entry was missing for the IP. */
882 if (IsUserPort(auth->client))
883 sendheader(auth->client, REPORT_FAIL_DNS);
884 sendto_iauth(auth->client, "d");
885 } else if (!irc_in_addr_valid(addr)
886 || (irc_in_addr_cmp(&cli_ip(auth->client), addr)
887 && irc_in_addr_cmp(&auth->original, addr))) {
888 /* IP for hostname did not match client's IP. */
889 sendto_opmask_butone(0, SNO_IPMISMATCH, "IP# Mismatch: %s != %s[%s]",
890 cli_sock_ip(auth->client), h_name,
892 if (IsUserPort(auth->client))
893 sendheader(auth->client, REPORT_IP_MISMATCH);
894 if (feature_bool(FEAT_KILL_IPMISMATCH)) {
895 exit_client(auth->client, auth->client, &me, "IP mismatch");
898 } else if (!auth_verify_hostname(h_name, HOSTLEN)) {
899 /* Hostname did not look valid. */
900 if (IsUserPort(auth->client))
901 sendheader(auth->client, REPORT_INVAL_DNS);
902 sendto_iauth(auth->client, "d");
904 /* Hostname and mappings checked out. */
905 if (IsUserPort(auth->client))
906 sendheader(auth->client, REPORT_FIN_DNS);
907 ircd_strncpy(cli_sockhost(auth->client), h_name, HOSTLEN);
908 sendto_iauth(auth->client, "N %s", h_name);
910 check_auth_finished(auth);
913 /** Flag the client to show an attempt to contact the ident server on
914 * the client's host. Should the connect or any later phase of the
915 * identifying process fail, it is aborted and the user is given a
916 * username of "unknown".
917 * @param[in] auth The request for which to start the ident lookup.
919 static void start_auth_query(struct AuthRequest* auth)
921 struct irc_sockaddr remote_addr;
922 struct irc_sockaddr local_addr;
927 assert(0 != auth->client);
930 * get the local address of the client and bind to that to
931 * make the auth request. This used to be done only for
932 * ifdef VIRTUAL_HOST, but needs to be done for all clients
933 * since the ident request must originate from that same address--
934 * and machines with multiple IP addresses are common now
936 memcpy(&local_addr, &auth->local, sizeof(local_addr));
938 memcpy(&remote_addr.addr, &cli_ip(auth->client), sizeof(remote_addr.addr));
939 remote_addr.port = 113;
940 fd = os_socket(&local_addr, SOCK_STREAM, "auth query", 0);
942 ++ServerStats->is_abad;
943 if (IsUserPort(auth->client))
944 sendheader(auth->client, REPORT_FAIL_ID);
947 if (IsUserPort(auth->client))
948 sendheader(auth->client, REPORT_DO_ID);
950 if ((result = os_connect_nonb(fd, &remote_addr)) == IO_FAILURE ||
951 !socket_add(&auth->socket, auth_sock_callback, (void*) auth,
952 result == IO_SUCCESS ? SS_CONNECTED : SS_CONNECTING,
953 SOCK_EVENT_READABLE, fd)) {
954 ++ServerStats->is_abad;
955 if (IsUserPort(auth->client))
956 sendheader(auth->client, REPORT_FAIL_ID);
961 FlagSet(&auth->flags, AR_AUTH_PENDING);
962 if (result == IO_SUCCESS)
963 send_auth_query(auth);
966 /** Initiate DNS lookup for a client.
967 * @param[in] auth The auth request for which to start the DNS lookup.
969 static void start_dns_query(struct AuthRequest *auth)
971 if (feature_bool(FEAT_NODNS)) {
972 sendto_iauth(auth->client, "d");
976 if (irc_in_addr_is_loopback(&cli_ip(auth->client))) {
977 strcpy(cli_sockhost(auth->client), cli_name(&me));
978 sendto_iauth(auth->client, "N %s", cli_sockhost(auth->client));
982 if (IsUserPort(auth->client))
983 sendheader(auth->client, REPORT_DO_DNS);
985 FlagSet(&auth->flags, AR_DNS_PENDING);
986 gethost_byaddr(&cli_ip(auth->client), auth_dns_callback, auth);
989 /** Initiate IAuth check for a client.
990 * @param[in] auth The auth request for which to star the IAuth check.
992 static void start_iauth_query(struct AuthRequest *auth)
994 FlagSet(&auth->flags, AR_IAUTH_PENDING);
995 if (!sendto_iauth(auth->client, "C %s %hu %s %hu",
996 cli_sock_ip(auth->client), auth->port,
997 ircd_ntoa(&auth->local.addr), auth->local.port))
998 FlagClr(&auth->flags, AR_IAUTH_PENDING);
1001 /** Starts auth (identd) and dns queries for a client.
1002 * @param[in] client The client for which to start queries.
1004 void start_auth(struct Client* client)
1006 struct irc_sockaddr remote;
1007 struct AuthRequest* auth;
1009 assert(0 != client);
1010 Debug((DEBUG_INFO, "Beginning auth request on client %p", client));
1012 /* Register with event handlers. */
1013 cli_lasttime(client) = CurrentTime;
1014 cli_since(client) = CurrentTime;
1015 if (cli_fd(client) > HighestFd)
1016 HighestFd = cli_fd(client);
1017 LocalClientArray[cli_fd(client)] = client;
1018 socket_events(&(cli_socket(client)), SOCK_ACTION_SET | SOCK_EVENT_READABLE);
1020 /* Allocate the AuthRequest. */
1021 auth = auth_freelist;
1023 auth_freelist = auth->next;
1025 auth = MyMalloc(sizeof(*auth));
1027 memset(auth, 0, sizeof(*auth));
1028 auth->client = client;
1029 cli_auth(client) = auth;
1030 s_fd(&auth->socket) = -1;
1031 timer_add(timer_init(&auth->timeout), auth_timeout_callback, (void*) auth,
1032 TT_RELATIVE, feature_int(FEAT_AUTH_TIMEOUT));
1034 /* Try to get socket endpoint addresses. */
1035 if (!os_get_sockname(cli_fd(client), &auth->local)
1036 || !os_get_peername(cli_fd(client), &remote)) {
1037 ++ServerStats->is_abad;
1038 if (IsUserPort(auth->client))
1039 sendheader(auth->client, REPORT_FAIL_ID);
1040 exit_client(auth->client, auth->client, &me, "Socket local/peer lookup failed");
1043 auth->port = remote.port;
1045 /* Set required client inputs for users. */
1046 if (IsUserPort(client)) {
1047 cli_user(client) = make_user(client);
1048 cli_user(client)->server = &me;
1049 FlagSet(&auth->flags, AR_NEEDS_USER);
1050 FlagSet(&auth->flags, AR_NEEDS_NICK);
1052 /* Try to start iauth lookup. */
1053 start_iauth_query(auth);
1056 /* Try to start DNS lookup. */
1057 start_dns_query(auth);
1059 /* Try to start ident lookup. */
1060 start_auth_query(auth);
1062 /* Add client to GlobalClientList. */
1063 add_client_to_list(client);
1065 /* Check which auth events remain pending. */
1066 check_auth_finished(auth);
1069 /** Mark that a user has PONGed while unregistered.
1070 * @param[in] auth Authorization request for client.
1071 * @param[in] cookie PONG cookie value sent by client.
1072 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1074 int auth_set_pong(struct AuthRequest *auth, unsigned int cookie)
1076 assert(auth != NULL);
1077 if (!FlagHas(&auth->flags, AR_NEEDS_PONG))
1079 if (cookie != auth->cookie)
1081 send_reply(auth->client, SND_EXPLICIT | ERR_BADPING,
1082 ":To connect, type /QUOTE PONG %u", auth->cookie);
1085 cli_lasttime(auth->client) = CurrentTime;
1086 FlagClr(&auth->flags, AR_NEEDS_PONG);
1087 return check_auth_finished(auth);
1090 /** Record a user's claimed username and userinfo.
1091 * @param[in] auth Authorization request for client.
1092 * @param[in] username Client's asserted username.
1093 * @param[in] hostname Third argument of USER command (client's
1094 * hostname, per RFC 1459).
1095 * @param[in] servername Fourth argument of USER command (server's
1096 * name, per RFC 1459).
1097 * @param[in] userinfo Client's asserted self-description.
1098 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1100 int auth_set_user(struct AuthRequest *auth, const char *username, const char *hostname, const char *servername, const char *userinfo)
1102 struct Client *cptr;
1104 assert(auth != NULL);
1105 if (FlagHas(&auth->flags, AR_IAUTH_HURRY))
1107 FlagClr(&auth->flags, AR_NEEDS_USER);
1108 cptr = auth->client;
1109 ircd_strncpy(cli_info(cptr), userinfo, REALLEN);
1110 clean_username(cli_user(cptr)->username, username);
1111 ircd_strncpy(cli_user(cptr)->host, cli_sockhost(cptr), HOSTLEN);
1112 if (IAuthHas(iauth, IAUTH_UNDERNET))
1113 sendto_iauth(cptr, "U %s %s %s :%s", cli_user(cptr)->username, hostname, servername, userinfo);
1114 else if (IAuthHas(iauth, IAUTH_ADDLINFO))
1115 sendto_iauth(cptr, "U %s", username);
1116 return check_auth_finished(auth);
1119 /** Handle authorization-related aspects of initial nickname selection.
1120 * This is called after verifying that the nickname is available.
1121 * @param[in] auth Authorization request for client.
1122 * @param[in] nickname Client's requested nickname.
1123 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1125 int auth_set_nick(struct AuthRequest *auth, const char *nickname)
1127 assert(auth != NULL);
1128 FlagClr(&auth->flags, AR_NEEDS_NICK);
1130 * If the client hasn't gotten a cookie-ping yet,
1131 * choose a cookie and send it. -record!jegelhof@cloud9.net
1133 if (!auth->cookie) {
1135 auth->cookie = ircrandom();
1136 } while (!auth->cookie);
1137 sendrawto_one(auth->client, "PING :%u", auth->cookie);
1138 FlagSet(&auth->flags, AR_NEEDS_PONG);
1140 if (IAuthHas(iauth, IAUTH_UNDERNET))
1141 sendto_iauth(auth->client, "n %s", nickname);
1142 return check_auth_finished(auth);
1145 /** Record a user's password.
1146 * @param[in] auth Authorization request for client.
1147 * @param[in] password Client's password.
1148 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1150 int auth_set_password(struct AuthRequest *auth, const char *password)
1152 assert(auth != NULL);
1153 if (IAuthHas(iauth, IAUTH_ADDLINFO))
1154 sendto_iauth(auth->client, "P :%s", password);
1158 /** Send exit notification for \a cptr to iauth.
1159 * @param[in] cptr Client who is exiting.
1161 void auth_send_exit(struct Client *cptr)
1163 sendto_iauth(cptr, "D");
1166 /** Forward an XREPLY on to iauth.
1167 * @param[in] sptr Source of the XREPLY.
1168 * @param[in] routing Routing information for the original XQUERY.
1169 * @param[in] reply Contents of the reply.
1171 void auth_send_xreply(struct Client *sptr, const char *routing,
1174 sendto_iauth(NULL, "X %#C %s :%s", sptr, routing, reply);
1177 /** Mark that a user has started capabilities negotiation.
1178 * This blocks authorization until auth_cap_done() is called.
1179 * @param[in] auth Authorization request for client.
1180 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1182 int auth_cap_start(struct AuthRequest *auth)
1184 assert(auth != NULL);
1185 FlagSet(&auth->flags, AR_CAP_PENDING);
1189 /** Mark that a user has completed capabilities negotiation.
1190 * This unblocks authorization if auth_cap_start() was called.
1191 * @param[in] auth Authorization request for client.
1192 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1194 int auth_cap_done(struct AuthRequest *auth)
1196 assert(auth != NULL);
1197 FlagClr(&auth->flags, AR_CAP_PENDING);
1198 return check_auth_finished(auth);
1201 /** Attempt to spawn the process for an IAuth instance.
1202 * @param[in] iauth IAuth descriptor.
1203 * @param[in] automatic If non-zero, apply sanity checks against
1204 * excessive automatic restarts.
1205 * @return 0 on success, non-zero on failure.
1207 int iauth_do_spawn(struct IAuth *iauth, int automatic)
1214 if (automatic && CurrentTime - iauth->started < 5)
1216 sendto_opmask_butone(NULL, SNO_AUTH, "IAuth crashed fast, leaving it dead.");
1220 /* Record time we tried to spawn the iauth process. */
1221 iauth->started = CurrentTime;
1223 /* Attempt to allocate a pair of sockets. */
1224 res = os_socketpair(s_io);
1227 Debug((DEBUG_INFO, "Unable to create IAuth socketpair: %s", strerror(res)));
1231 /* Mark the parent's side of the pair (element 0) as non-blocking. */
1232 res = os_set_nonblocking(s_io[0]);
1235 Debug((DEBUG_INFO, "Unable to make IAuth socket non-blocking: %s", strerror(res)));
1241 /* Initialize the socket structure to talk to the child. */
1242 res = socket_add(i_socket(iauth), iauth_sock_callback, iauth,
1243 SS_CONNECTED, SOCK_EVENT_READABLE, s_io[0]);
1246 Debug((DEBUG_INFO, "Unable to register IAuth socket: %s", strerror(res)));
1252 /* Allocate another pair for stderr. */
1253 res = os_socketpair(s_err);
1256 Debug((DEBUG_INFO, "Unable to create IAuth stderr: %s", strerror(res)));
1257 socket_del(i_socket(iauth));
1263 /* Mark parent side of this pair non-blocking, too. */
1264 res = os_set_nonblocking(s_err[0]);
1267 Debug((DEBUG_INFO, "Unable to make IAuth stderr non-blocking: %s", strerror(res)));
1270 socket_del(i_socket(iauth));
1276 /* And set up i_stderr(iauth). */
1277 res = socket_add(i_stderr(iauth), iauth_stderr_callback, iauth,
1278 SS_CONNECTED, SOCK_EVENT_READABLE, s_err[0]);
1281 Debug((DEBUG_INFO, "Unable to register IAuth stderr: %s", strerror(res)));
1284 socket_del(i_socket(iauth));
1290 /* Attempt to fork a child process. */
1293 /* Error forking the child, still in parent. */
1295 Debug((DEBUG_INFO, "Unable to fork IAuth child: %s", strerror(res)));
1296 socket_del(i_stderr(iauth));
1299 socket_del(i_socket(iauth));
1306 /* We are the parent process. Close the child's sockets. */
1309 /* Send our server name (supposedly for proxy checking purposes)
1310 * and maximum number of connections (for allocation hints).
1311 * Need to use conf_get_local() since &me may not be fully
1312 * initialized the first time we run.
1314 sendto_iauth(NULL, "M %s %d", conf_get_local()->name, MAXCONNECTIONS);
1315 /* Indicate success (until the child dies). */
1319 /* We are the child process.
1320 * Duplicate our end of the socket to stdin, stdout and stderr.
1321 * Then close all the higher-numbered FDs and exec the process.
1323 if (dup2(s_io[1], 0) == 0
1324 && dup2(s_io[1], 1) == 1
1325 && dup2(s_err[1], 2) == 2) {
1326 close_connections(0);
1327 execvp(iauth->i_argv[0], iauth->i_argv);
1330 /* If we got here, something was seriously wrong. */
1334 /** See if an %IAuth program must be spawned.
1335 * If a process is already running with the specified options, keep it.
1336 * Otherwise spawn a new child process to perform the %IAuth function.
1337 * @param[in] argc Number of parameters to use when starting process.
1338 * @param[in] argv Array of parameters to start process.
1339 * @return 0 on failure, 1 on new process, 2 on reuse of existing process.
1341 int auth_spawn(int argc, char *argv[])
1348 /* Check that incoming arguments all match pre-existing arguments. */
1349 for (ii = 0; same && (ii < argc); ++ii) {
1350 if (NULL == iauth->i_argv[ii]
1351 || 0 != strcmp(iauth->i_argv[ii], argv[ii]))
1354 /* Check that we have no more pre-existing arguments. */
1355 if (same && iauth->i_argv[ii])
1357 /* If they are the same and still connected, clear the "closing" flag and exit. */
1358 if (same && i_GetConnected(iauth)) {
1359 Debug((DEBUG_INFO, "Reusing existing IAuth process"));
1360 IAuthClr(iauth, IAUTH_CLOSING);
1363 auth_close_unused();
1366 /* Need to initialize a new connection. */
1367 iauth = MyCalloc(1, sizeof(*iauth));
1368 msgq_init(i_sendQ(iauth));
1369 /* Populate iauth's argv array. */
1370 iauth->i_argv = MyCalloc(argc + 1, sizeof(iauth->i_argv[0]));
1371 for (ii = 0; ii < argc; ++ii)
1372 DupString(iauth->i_argv[ii], argv[ii]);
1373 iauth->i_argv[ii] = NULL;
1374 /* Try to spawn it, and handle the results. */
1375 if (iauth_do_spawn(iauth, 0))
1377 IAuthClr(iauth, IAUTH_CLOSING);
1381 /** Mark all %IAuth connections as closing. */
1382 void auth_mark_closing(void)
1385 IAuthSet(iauth, IAUTH_CLOSING);
1388 /** Complete disconnection of an %IAuth connection.
1389 * @param[in] iauth %Connection to fully close.
1391 static void iauth_disconnect(struct IAuth *iauth)
1396 /* Close error socket. */
1397 if (s_fd(i_stderr(iauth)) != -1) {
1398 close(s_fd(i_stderr(iauth)));
1399 socket_del(i_stderr(iauth));
1400 s_fd(i_stderr(iauth)) = -1;
1403 /* Close main socket. */
1404 if (s_fd(i_socket(iauth)) != -1) {
1405 close(s_fd(i_socket(iauth)));
1406 socket_del(i_socket(iauth));
1407 s_fd(i_socket(iauth)) = -1;
1411 /** Close all %IAuth connections marked as closing. */
1412 void auth_close_unused(void)
1414 if (IAuthHas(iauth, IAUTH_CLOSING)) {
1416 iauth_disconnect(iauth);
1417 if (iauth->i_argv) {
1418 for (ii = 0; iauth->i_argv[ii]; ++ii)
1419 MyFree(iauth->i_argv[ii]);
1420 MyFree(iauth->i_argv);
1426 /** Send queued output to \a iauth.
1427 * @param[in] iauth Writable connection with queued data.
1429 static void iauth_write(struct IAuth *iauth)
1431 unsigned int bytes_tried, bytes_sent;
1434 if (IAuthHas(iauth, IAUTH_BLOCKED))
1436 while (MsgQLength(i_sendQ(iauth)) > 0) {
1437 iores = os_sendv_nonb(s_fd(i_socket(iauth)), i_sendQ(iauth), &bytes_tried, &bytes_sent);
1440 msgq_delete(i_sendQ(iauth), bytes_sent);
1441 iauth->i_sendB += bytes_sent;
1442 if (bytes_tried == bytes_sent)
1444 /* If bytes_sent < bytes_tried, fall through to IO_BLOCKED. */
1446 IAuthSet(iauth, IAUTH_BLOCKED);
1447 socket_events(i_socket(iauth), SOCK_ACTION_ADD | SOCK_EVENT_WRITABLE);
1450 iauth_disconnect(iauth);
1454 /* We were able to flush all events, so remove notification. */
1455 socket_events(i_socket(iauth), SOCK_ACTION_DEL | SOCK_EVENT_WRITABLE);
1458 /** Send a message to iauth.
1459 * @param[in] cptr Optional client context for message.
1460 * @param[in] format Format string for message.
1461 * @return Non-zero on successful send or buffering, zero on failure.
1463 static int sendto_iauth(struct Client *cptr, const char *format, ...)
1468 /* Do not send requests when we have no iauth. */
1469 if (!i_GetConnected(iauth))
1471 /* Do not send for clients in the NORMAL state. */
1473 && (format[0] != 'D')
1474 && (!cli_auth(cptr) || !FlagHas(&cli_auth(cptr)->flags, AR_IAUTH_PENDING)))
1477 /* Build the message buffer. */
1478 vd.vd_format = format;
1479 va_start(vd.vd_args, format);
1481 mb = msgq_make(NULL, "-1 %v", &vd);
1483 mb = msgq_make(NULL, "%d %v", cli_fd(cptr), &vd);
1486 /* Tack it onto the iauth sendq and try to write it. */
1488 msgq_add(i_sendQ(iauth), mb, 0);
1494 /** Send text to interested operators (SNO_AUTH server notice).
1495 * @param[in] iauth Active IAuth session.
1496 * @param[in] cli Client referenced by command.
1497 * @param[in] parc Number of parameters (1).
1498 * @param[in] params Text to send.
1501 static int iauth_cmd_snotice(struct IAuth *iauth, struct Client *cli,
1502 int parc, char **params)
1504 sendto_opmask_butone(NULL, SNO_AUTH, "%s", params[0]);
1508 /** Set the debug level for the session.
1509 * @param[in] iauth Active IAuth session.
1510 * @param[in] cli Client referenced by command.
1511 * @param[in] parc Number of parameters (1).
1512 * @param[in] params String starting with an integer.
1515 static int iauth_cmd_debuglevel(struct IAuth *iauth, struct Client *cli,
1516 int parc, char **params)
1520 new_level = parc > 0 ? atoi(params[0]) : 0;
1521 if (i_debug(iauth) > 0 || new_level > 0) {
1522 /* The "ia_dbg" name is borrowed from (IRCnet) ircd. */
1523 sendto_opmask_butone(NULL, SNO_AUTH, "ia_dbg = %d", new_level);
1525 i_debug(iauth) = new_level;
1529 /** Set policy options for the session.
1530 * Old policy is forgotten, and any of the following characters in \a
1531 * params enable the corresponding policy:
1532 * \li A IAUTH_ADDLINFO
1533 * \li R IAUTH_REQUIRED
1534 * \li T IAUTH_TIMEOUT
1535 * \li W IAUTH_EXTRAWAIT
1536 * \li U IAUTH_UNDERNET
1538 * @param[in] iauth Active IAuth session.
1539 * @param[in] cli Client referenced by command.
1540 * @param[in] parc Number of parameters (1).
1541 * @param[in] params Zero or more policy options.
1544 static int iauth_cmd_policy(struct IAuth *iauth, struct Client *cli,
1545 int parc, char **params)
1547 enum IAuthFlag flag;
1550 /* Erase old policy first. */
1551 for (flag = IAUTH_FIRST_OPTION; flag < IAUTH_LAST_FLAG; ++flag)
1552 IAuthClr(iauth, flag);
1554 if (parc > 0) /* only try to parse if we were given a policy string */
1555 /* Parse new policy set. */
1556 for (p = params[0]; *p; p++) switch (*p) {
1557 case 'A': IAuthSet(iauth, IAUTH_ADDLINFO); break;
1558 case 'R': IAuthSet(iauth, IAUTH_REQUIRED); break;
1559 case 'T': IAuthSet(iauth, IAUTH_TIMEOUT); break;
1560 case 'W': IAuthSet(iauth, IAUTH_EXTRAWAIT); break;
1561 case 'U': IAuthSet(iauth, IAUTH_UNDERNET); break;
1564 /* Optionally notify operators. */
1565 if (i_debug(iauth) > 0)
1566 sendto_opmask_butone(NULL, SNO_AUTH, "iauth options: %s", params[0]);
1570 /** Set the iauth program version number.
1571 * @param[in] iauth Active IAuth session.
1572 * @param[in] cli Client referenced by command.
1573 * @param[in] parc Number of parameters (1).
1574 * @param[in] params Version number or name.
1577 static int iauth_cmd_version(struct IAuth *iauth, struct Client *cli,
1578 int parc, char **params)
1580 MyFree(iauth->i_version);
1581 DupString(iauth->i_version, parc > 0 ? params[0] : "<NONE>");
1582 sendto_opmask_butone(NULL, SNO_AUTH, "iauth version %s running.",
1587 /** Paste a parameter list together into a single string.
1588 * @param[in] parc Number of parameters.
1589 * @param[in] params Parameter list to paste together.
1590 * @return Pasted parameter list.
1592 static char *paste_params(int parc, char **params)
1595 int len = 0, lengths[MAXPARA], i;
1597 /* Compute the length... */
1598 for (i = 0; i < parc; i++)
1599 len += lengths[i] = strlen(params[i]);
1601 /* Allocate memory, accounting for string lengths, spaces (parc - 1), a
1602 * sentinel, and the trailing \0
1604 str = MyMalloc(len + parc + 1);
1606 /* Build the pasted string */
1607 for (tmp = str, i = 0; i < parc; i++) {
1608 if (i) /* add space separator... */
1610 if (i == parc - 1) /* add colon sentinel */
1613 /* Copy string component... */
1614 memcpy(tmp, params[i], lengths[i]);
1615 tmp += lengths[i]; /* move to end of string */
1618 /* terminate the string... */
1621 return str; /* return the pasted string */
1624 /** Clear cached iauth configuration information.
1625 * @param[in] iauth Active IAuth session.
1626 * @param[in] cli Client referenced by command.
1627 * @param[in] parc Number of parameters (0).
1628 * @param[in] params Parameter list (ignored).
1631 static int iauth_cmd_newconfig(struct IAuth *iauth, struct Client *cli,
1632 int parc, char **params)
1637 head = iauth->i_config;
1638 iauth->i_config = NULL;
1639 for (; head; head = next) {
1641 MyFree(head->value.cp);
1644 sendto_opmask_butone(NULL, SNO_AUTH, "New iauth configuration.");
1648 /** Append iauth configuration information.
1649 * @param[in] iauth Active IAuth session.
1650 * @param[in] cli Client referenced by command.
1651 * @param[in] parc Number of parameters.
1652 * @param[in] params Description of configuration element.
1655 static int iauth_cmd_config(struct IAuth *iauth, struct Client *cli,
1656 int parc, char **params)
1660 if (iauth->i_config) {
1661 for (node = iauth->i_config; node->next; node = node->next) ;
1662 node = node->next = make_link();
1664 node = iauth->i_config = make_link();
1666 node->value.cp = paste_params(parc, params);
1667 node->next = 0; /* must be explicitly cleared */
1671 /** Clear cached iauth configuration information.
1672 * @param[in] iauth Active IAuth session.
1673 * @param[in] cli Client referenced by command.
1674 * @param[in] parc Number of parameters (0).
1675 * @param[in] params Parameter list (ignored).
1678 static int iauth_cmd_newstats(struct IAuth *iauth, struct Client *cli,
1679 int parc, char **params)
1684 head = iauth->i_stats;
1685 iauth->i_stats = NULL;
1686 for (; head; head = next) {
1688 MyFree(head->value.cp);
1691 sendto_opmask_butone(NULL, SNO_AUTH, "New iauth statistics.");
1695 /** Append iauth statistics information.
1696 * @param[in] iauth Active IAuth session.
1697 * @param[in] cli Client referenced by command.
1698 * @param[in] parc Number of parameters.
1699 * @param[in] params Statistics element.
1702 static int iauth_cmd_stats(struct IAuth *iauth, struct Client *cli,
1703 int parc, char **params)
1706 if (iauth->i_stats) {
1707 for (node = iauth->i_stats; node->next; node = node->next) ;
1708 node = node->next = make_link();
1710 node = iauth->i_stats = make_link();
1712 node->value.cp = paste_params(parc, params);
1713 node->next = 0; /* must be explicitly cleared */
1717 /** Set client's username to a trusted string even if it breaks the rules.
1718 * @param[in] iauth Active IAuth session.
1719 * @param[in] cli Client referenced by command.
1720 * @param[in] parc Number of parameters (1).
1721 * @param[in] params Forced username.
1724 static int iauth_cmd_username_forced(struct IAuth *iauth, struct Client *cli,
1725 int parc, char **params)
1727 assert(cli_auth(cli) != NULL);
1728 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
1729 if (!EmptyString(params[0])) {
1730 ircd_strncpy(cli_username(cli), params[0], USERLEN);
1732 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_USERNAME);
1733 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_FUSERNAME);
1738 /** Set client's username to a trusted 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 Trusted username.
1745 static int iauth_cmd_username_good(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_username(cli), params[0], USERLEN);
1753 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_USERNAME);
1758 /** Set client's username to an untrusted string.
1759 * @param[in] iauth Active IAuth session.
1760 * @param[in] cli Client referenced by command.
1761 * @param[in] parc Number of parameters (1).
1762 * @param[in] params Untrusted username.
1765 static int iauth_cmd_username_bad(struct IAuth *iauth, struct Client *cli,
1766 int parc, char **params)
1768 assert(cli_auth(cli) != NULL);
1769 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
1770 if (!EmptyString(params[0]))
1771 ircd_strncpy(cli_user(cli)->username, params[0], USERLEN);
1775 /** Set client's hostname.
1776 * @param[in] iauth Active IAuth session.
1777 * @param[in] cli Client referenced by command.
1778 * @param[in] parc Number of parameters (1).
1779 * @param[in] params New hostname for client.
1780 * @return Non-zero if \a cli authorization should be checked for completion.
1782 static int iauth_cmd_hostname(struct IAuth *iauth, struct Client *cli,
1783 int parc, char **params)
1785 struct AuthRequest *auth;
1787 if (EmptyString(params[0])) {
1788 sendto_iauth(cli, "E Missing :Missing hostname parameter");
1792 auth = cli_auth(cli);
1793 assert(auth != NULL);
1795 /* If a DNS request is pending, abort it. */
1796 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
1797 FlagClr(&auth->flags, AR_DNS_PENDING);
1798 delete_resolver_queries(auth);
1799 if (IsUserPort(cli))
1800 sendheader(cli, REPORT_FIN_DNS);
1802 /* Set hostname from params. */
1803 ircd_strncpy(cli_sockhost(cli), params[0], HOSTLEN);
1804 /* If we have gotten here, the user is in a "hurry" state and has
1805 * been pre-registered. Their hostname was set during that, and
1806 * needs to be overwritten now.
1808 if (FlagHas(&auth->flags, AR_IAUTH_HURRY)) {
1809 ircd_strncpy(cli_user(cli)->host, cli_sockhost(cli), HOSTLEN);
1810 ircd_strncpy(cli_user(cli)->realhost, cli_sockhost(cli), HOSTLEN);
1815 /** Set client's IP address.
1816 * @param[in] iauth Active IAuth session.
1817 * @param[in] cli Client referenced by command.
1818 * @param[in] parc Number of parameters (1).
1819 * @param[in] params New IP address for client in dotted quad or
1820 * standard IPv6 format.
1823 static int iauth_cmd_ip_address(struct IAuth *iauth, struct Client *cli,
1824 int parc, char **params)
1826 struct irc_in_addr addr;
1827 struct AuthRequest *auth;
1829 if (EmptyString(params[0])) {
1830 sendto_iauth(cli, "E Missing :Missing IP address parameter");
1834 /* Get AuthRequest for client. */
1835 auth = cli_auth(cli);
1836 assert(auth != NULL);
1838 /* Parse the client's new IP address. */
1839 if (!ircd_aton(&addr, params[0])) {
1840 sendto_iauth(cli, "E Invalid :Unable to parse IP address [%s]", params[0]);
1844 /* If this is the first IP override, save the client's original
1845 * address in case we get a DNS response later.
1847 if (!irc_in_addr_valid(&auth->original))
1848 memcpy(&auth->original, &cli_ip(cli), sizeof(auth->original));
1850 /* Undo original IP connection in IPcheck. */
1851 IPcheck_connect_fail(cli, 1);
1852 ClearIPChecked(cli);
1854 /* Update the IP and charge them as a remote connect. */
1855 memcpy(&cli_ip(cli), &addr, sizeof(cli_ip(cli)));
1856 IPcheck_remote_connect(cli, 0);
1861 /** Find a ConfItem structure for a named connection class.
1862 * @param[in] class_name Name of configuration class to find.
1863 * @return A ConfItem of type CONF_CLIENT for the class, or NULL on failure.
1865 static struct ConfItem *auth_find_class_conf(const char *class_name)
1867 static struct ConfItem *aconf_list;
1868 struct ConnectionClass *class;
1869 struct ConfItem *aconf;
1871 /* Make sure the configuration class is valid. */
1872 class = find_class(class_name);
1873 if (!class || !class->valid)
1876 /* Look for an existing ConfItem for the class. */
1877 for (aconf = aconf_list; aconf; aconf = aconf->next)
1878 if (aconf->conn_class == class)
1881 /* If no ConfItem, create one. */
1883 aconf = make_conf(CONF_CLIENT);
1885 sendto_opmask_butone(NULL, SNO_AUTH,
1886 "Unable to allocate ConfItem for class %s!",
1890 /* make_conf() "helpfully" links the conf into GlobalConfList,
1891 * which we do not want, so undo that. (Ugh.)
1893 if (aconf == GlobalConfList) {
1894 GlobalConfList = aconf->next;
1896 /* Back to business as usual. */
1897 aconf->conn_class = class;
1898 aconf->next = aconf_list;
1905 /** Tentatively accept a client in IAuth.
1906 * @param[in] iauth Active IAuth session.
1907 * @param[in] cli Client referenced by command.
1908 * @param[in] parc Number of parameters.
1909 * @param[in] params Optional class name for client.
1910 * @return Negative (CPTR_KILLED) if the connection is refused, one otherwise.
1912 static int iauth_cmd_soft_done(struct IAuth *iauth, struct Client *cli,
1913 int parc, char **params)
1915 /* Clear iauth pending flag. */
1916 assert(cli_auth(cli) != NULL);
1917 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_SOFT_DONE);
1921 /** Accept a client in IAuth.
1922 * @param[in] iauth Active IAuth session.
1923 * @param[in] cli Client referenced by command.
1924 * @param[in] parc Number of parameters.
1925 * @param[in] params Optional class name for client.
1926 * @return Negative (CPTR_KILLED) if the connection is refused, one otherwise.
1928 static int iauth_cmd_done_client(struct IAuth *iauth, struct Client *cli,
1929 int parc, char **params)
1931 static time_t warn_time;
1933 /* Clear iauth pending flag. */
1934 assert(cli_auth(cli) != NULL);
1935 FlagClr(&cli_auth(cli)->flags, AR_IAUTH_PENDING);
1937 /* If a connection class was specified (and usable), assign the client to it. */
1938 if (!EmptyString(params[0])) {
1939 struct ConfItem *aconf;
1941 aconf = auth_find_class_conf(params[0]);
1943 enum AuthorizationCheckResult acr;
1945 acr = attach_conf(cli, aconf);
1948 /* There should maybe be some way to set FLAG_DOID here.. */
1950 case ACR_TOO_MANY_IN_CLASS:
1951 ++ServerStats->is_ref;
1952 return exit_client(cli, cli, &me,
1953 "Sorry, your connection class is full - try "
1954 "again later or try another server");
1956 log_write(LS_IAUTH, L_ERROR, 0, "IAuth: Unexpected AuthorizationCheckResult %d from attach_conf()", acr);
1960 sendto_opmask_butone_ratelimited(NULL, SNO_AUTH, &warn_time,
1961 "iauth tried to use undefined class [%s]",
1968 /** Accept a client in IAuth and assign them to an account.
1969 * @param[in] iauth Active IAuth session.
1970 * @param[in] cli Client referenced by command.
1971 * @param[in] parc Number of parameters.
1972 * @param[in] params Account name and optional class name for client.
1973 * @return Negative if the connection is refused, otherwise non-zero
1974 * if \a cli authorization should be checked for completion.
1976 static int iauth_cmd_done_account(struct IAuth *iauth, struct Client *cli,
1977 int parc, char **params)
1982 if (EmptyString(params[0])) {
1983 sendto_iauth(cli, "E Missing :Missing account parameter");
1986 /* Check length of account name. */
1987 len = strcspn(params[0], ": ");
1988 if (len > ACCOUNTLEN) {
1989 sendto_iauth(cli, "E Invalid :Account parameter too long");
1992 /* If account has a creation timestamp, use it. */
1993 assert(cli_user(cli) != NULL);
1994 if (params[0][len] == ':') {
1995 cli_user(cli)->acc_create = strtoul(params[0] + len + 1, NULL, 10);
1996 params[0][len] = '\0';
1999 /* Copy account name to User structure. */
2000 ircd_strncpy(cli_user(cli)->account, params[0], ACCOUNTLEN);
2003 /* Fall through to the normal "done" handler. */
2004 return iauth_cmd_done_client(iauth, cli, parc - 1, params + 1);
2007 /** Reject a client's connection.
2008 * @param[in] iauth Active IAuth session.
2009 * @param[in] cli Client referenced by command.
2010 * @param[in] parc Number of parameters (1).
2011 * @param[in] params Optional kill message.
2014 static int iauth_cmd_kill(struct IAuth *iauth, struct Client *cli,
2015 int parc, char **params)
2018 FlagClr(&cli_auth(cli)->flags, AR_IAUTH_PENDING);
2019 if (EmptyString(params[0]))
2020 params[0] = "Access denied";
2021 exit_client(cli, cli, &me, params[0]);
2025 /** Change a client's usermode.
2026 * @param[in] iauth Active IAuth session.
2027 * @param[in] cli Client referenced by command.
2028 * @param[in] parc Number of parameters (at least one).
2029 * @param[in] params Usermode arguments for client (with the first
2030 * starting with '+').
2033 static int iauth_cmd_usermode(struct IAuth *iauth, struct Client *cli,
2034 int parc, char **params)
2036 if (params[0][0] == '+')
2038 set_user_mode(cli, cli, parc + 2, params - 2, ALLOWMODES_ANY);
2044 /** Send a challenge string to the client.
2045 * @param[in] iauth Active IAuth session.
2046 * @param[in] cli Client referenced by command.
2047 * @param[in] parc Number of parameters (1).
2048 * @param[in] params Challenge message for client.
2051 static int iauth_cmd_challenge(struct IAuth *iauth, struct Client *cli,
2052 int parc, char **params)
2054 if (!EmptyString(params[0]))
2055 sendrawto_one(cli, "NOTICE AUTH :*** %s", params[0]);
2059 /** Send an extension query to a specified remote server.
2060 * @param[in] iauth Active IAuth session.
2061 * @param[in] cli Client referenced by command.
2062 * @param[in] parc Number of parameters (3).
2063 * @param[in] params Remote server, routing information, and query.
2066 static int iauth_cmd_xquery(struct IAuth *iauth, struct Client *cli,
2067 int parc, char **params)
2070 const char *routing;
2072 struct Client *acptr;
2074 /* Process parameters */
2075 if (EmptyString(params[0])) {
2076 sendto_iauth(cli, "E Missing :Missing server parameter");
2081 if (EmptyString(params[1])) {
2082 sendto_iauth(cli, "E Missing :Missing routing parameter");
2085 routing = params[1];
2087 if (EmptyString(params[2])) {
2088 sendto_iauth(cli, "E Missing :Missing query parameter");
2093 /* Try to find the specified server */
2094 if (!(acptr = find_match_server(serv))) {
2095 sendto_iauth(cli, "x %s %s :Server not online", serv, routing);
2099 /* If it's to us, do nothing; otherwise, forward the query */
2101 /* The "iauth:" prefix helps ircu route the reply to iauth */
2102 sendcmdto_one(&me, CMD_XQUERY, acptr, "%C iauth:%s :%s", acptr, routing,
2108 /** Parse a \a message from \a iauth.
2109 * @param[in] iauth Active IAuth session.
2110 * @param[in] message Message to be parsed.
2112 static void iauth_parse(struct IAuth *iauth, char *message)
2114 char *params[MAXPARA + 1]; /* leave space for NULL */
2116 iauth_cmd_handler handler;
2117 struct AuthRequest *auth;
2122 /* Find command handler... */
2123 switch (*(message++)) {
2124 case '>': handler = iauth_cmd_snotice; has_cli = 0; break;
2125 case 'G': handler = iauth_cmd_debuglevel; has_cli = 0; break;
2126 case 'O': handler = iauth_cmd_policy; has_cli = 0; break;
2127 case 'V': handler = iauth_cmd_version; has_cli = 0; break;
2128 case 'a': handler = iauth_cmd_newconfig; has_cli = 0; break;
2129 case 'A': handler = iauth_cmd_config; has_cli = 0; break;
2130 case 's': handler = iauth_cmd_newstats; has_cli = 0; break;
2131 case 'S': handler = iauth_cmd_stats; has_cli = 0; break;
2132 case 'X': handler = iauth_cmd_xquery; has_cli = 0; break;
2133 case 'o': handler = iauth_cmd_username_forced; has_cli = 1; break;
2134 case 'U': handler = iauth_cmd_username_good; has_cli = 1; break;
2135 case 'u': handler = iauth_cmd_username_bad; has_cli = 1; break;
2136 case 'N': handler = iauth_cmd_hostname; has_cli = 1; break;
2137 case 'I': handler = iauth_cmd_ip_address; has_cli = 1; break;
2138 case 'M': handler = iauth_cmd_usermode; has_cli = 1; break;
2139 case 'C': handler = iauth_cmd_challenge; has_cli = 1; break;
2140 case 'd': handler = iauth_cmd_soft_done; has_cli = 1; break;
2141 case 'D': handler = iauth_cmd_done_client; has_cli = 1; break;
2142 case 'R': handler = iauth_cmd_done_account; has_cli = 1; break;
2143 case 'k': /* The 'k' command indicates the user should be booted
2144 * off without telling opers. There is no way to
2145 * signal that to exit_client(), so we fall through to
2146 * the case that we do implement.
2148 case 'K': handler = iauth_cmd_kill; has_cli = 2; break;
2149 case 'r': /* we handle termination directly */ return;
2150 default: sendto_iauth(NULL, "E Garbage :[%s]", message); return;
2153 while (parc < MAXPARA) {
2154 while (IsSpace(*message)) /* skip leading whitespace */
2157 if (!*message) /* hit the end of the string, break out */
2160 if (*message == ':') { /* found sentinel... */
2161 params[parc++] = message + 1;
2162 break; /* it's the last parameter anyway */
2165 params[parc++] = message; /* save the parameter */
2166 while (*message && !IsSpace(*message))
2167 message++; /* find the end of the parameter */
2169 if (*message) /* terminate the parameter */
2170 *(message++) = '\0';
2173 params[parc] = NULL; /* terminate the parameter list */
2175 /* Check to see if the command specifies a client... */
2177 /* Handler does not need a client. */
2178 handler(iauth, NULL, parc, params);
2180 /* Try to find the client associated with the request. */
2181 id = strtol(params[0], NULL, 10);
2183 sendto_iauth(NULL, "E Missing :Need <id> <ip> <port>");
2184 else if (id < 0 || id > HighestFd || !(cli = LocalClientArray[id]))
2185 /* Client no longer exists (or never existed). */
2186 sendto_iauth(NULL, "E Gone :[%s %s %s]", params[0], params[1],
2188 else if ((!(auth = cli_auth(cli)) ||
2189 !FlagHas(&auth->flags, AR_IAUTH_PENDING)) &&
2191 /* Client is done with IAuth checks. */
2192 sendto_iauth(cli, "E Done :[%s %s %s]", params[0], params[1], params[2]);
2194 struct irc_sockaddr addr;
2197 /* Parse IP address and port number from parameters */
2198 res = ipmask_parse(params[1], &addr.addr, NULL);
2199 addr.port = strtol(params[2], NULL, 10);
2201 /* Check IP address and port number against expected. */
2203 irc_in_addr_cmp(&addr.addr, &cli_ip(cli)) ||
2204 (auth && addr.port != auth->port))
2205 /* Report mismatch to iauth. */
2206 sendto_iauth(cli, "E Mismatch :[%s] != [%s]", params[1],
2207 ircd_ntoa(&cli_ip(cli)));
2208 else if (handler(iauth, cli, parc - 3, params + 3) > 0)
2209 /* Handler indicated a possible state change. */
2210 check_auth_finished(auth);
2215 /** Read input from \a iauth.
2216 * Reads up to SERVER_TCP_WINDOW bytes per pass.
2217 * @param[in] iauth Readable connection.
2219 static void iauth_read(struct IAuth *iauth)
2221 static char readbuf[SERVER_TCP_WINDOW];
2222 unsigned int length, count;
2226 /* Copy partial data to readbuf, append new data. */
2227 length = iauth->i_count;
2228 memcpy(readbuf, iauth->i_buffer, length);
2229 if (IO_SUCCESS != os_recv_nonb(s_fd(i_socket(iauth)),
2231 sizeof(readbuf) - length - 1,
2234 readbuf[length += count] = '\0';
2236 /* Parse each complete line. */
2237 for (sol = readbuf; (eol = strchr(sol, '\n')) != NULL; sol = eol + 1) {
2239 if (*(eol - 1) == '\r') /* take out carriage returns, too... */
2242 /* If spammy debug, send the message to opers. */
2243 if (i_debug(iauth) > 1)
2244 sendto_opmask_butone(NULL, SNO_AUTH, "Parsing: \"%s\"", sol);
2246 /* Parse the line... */
2247 iauth_parse(iauth, sol);
2250 /* Put unused data back into connection's buffer. */
2251 iauth->i_count = strlen(sol);
2252 if (iauth->i_count > BUFSIZE)
2253 iauth->i_count = BUFSIZE;
2254 memcpy(iauth->i_buffer, sol, iauth->i_count);
2257 /** Handle socket activity for an %IAuth connection.
2258 * @param[in] ev &Socket event; the IAuth connection is the user data
2259 * pointer for the socket.
2261 static void iauth_sock_callback(struct Event *ev)
2263 struct IAuth *iauth;
2265 assert(0 != ev_socket(ev));
2266 iauth = (struct IAuth*) s_data(ev_socket(ev));
2269 switch (ev_type(ev)) {
2271 if (!IAuthHas(iauth, IAUTH_CLOSING) && !s_active(i_stderr(iauth)))
2272 iauth_do_spawn(iauth, 1);
2278 IAuthClr(iauth, IAUTH_BLOCKED);
2282 log_write(LS_IAUTH, L_ERROR, 0, "IAuth socket error: %s", strerror(ev_data(ev)));
2283 /* and fall through to the ET_EOF case */
2285 iauth_disconnect(iauth);
2288 assert(0 && "Unrecognized event type");
2293 /** Read error input from \a iauth.
2294 * @param[in] iauth Readable connection.
2296 static void iauth_read_stderr(struct IAuth *iauth)
2298 static char readbuf[SERVER_TCP_WINDOW];
2299 unsigned int length, count;
2303 /* Copy partial data to readbuf, append new data. */
2304 length = iauth->i_errcount;
2305 memcpy(readbuf, iauth->i_errbuf, length);
2306 if (IO_SUCCESS != os_recv_nonb(s_fd(i_stderr(iauth)),
2308 sizeof(readbuf) - length - 1,
2311 readbuf[length += count] = '\0';
2313 /* Send each complete line to SNO_AUTH. */
2314 for (sol = readbuf; (eol = strchr(sol, '\n')) != NULL; sol = eol + 1) {
2316 if (*(eol - 1) == '\r') /* take out carriage returns, too... */
2318 Debug((DEBUG_ERROR, "IAuth error: %s", sol));
2319 log_write(LS_IAUTH, L_ERROR, 0, "IAuth error: %s", sol);
2320 sendto_opmask_butone(NULL, SNO_AUTH, "%s", sol);
2323 /* Put unused data back into connection's buffer. */
2324 iauth->i_errcount = strlen(sol);
2325 if (iauth->i_errcount > BUFSIZE)
2326 iauth->i_errcount = BUFSIZE;
2327 memcpy(iauth->i_errbuf, sol, iauth->i_errcount);
2330 /** Handle error socket activity for an %IAuth connection.
2331 * @param[in] ev &Socket event; the IAuth connection is the user data
2332 * pointer for the socket.
2334 static void iauth_stderr_callback(struct Event *ev)
2336 struct IAuth *iauth;
2338 assert(0 != ev_socket(ev));
2339 iauth = (struct IAuth*) s_data(ev_socket(ev));
2342 switch (ev_type(ev)) {
2344 if (!IAuthHas(iauth, IAUTH_CLOSING) && !s_active(i_socket(iauth)))
2345 iauth_do_spawn(iauth, 1);
2348 iauth_read_stderr(iauth);
2351 log_write(LS_IAUTH, L_ERROR, 0, "IAuth stderr error: %s", strerror(ev_data(ev)));
2352 /* and fall through to the ET_EOF case */
2354 iauth_disconnect(iauth);
2357 assert(0 && "Unrecognized event type");
2362 /** Report active iauth's configuration to \a cptr.
2363 * @param[in] cptr Client requesting statistics.
2364 * @param[in] sd Stats descriptor for request.
2365 * @param[in] param Extra parameter from user (may be NULL).
2367 void report_iauth_conf(struct Client *cptr, const struct StatDesc *sd, char *param)
2371 if (iauth) for (link = iauth->i_config; link; link = link->next)
2373 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":%s",
2378 /** Report active iauth's statistics to \a cptr.
2379 * @param[in] cptr Client requesting statistics.
2380 * @param[in] sd Stats descriptor for request.
2381 * @param[in] param Extra parameter from user (may be NULL).
2383 void report_iauth_stats(struct Client *cptr, const struct StatDesc *sd, char *param)
2387 if (iauth) for (link = iauth->i_stats; link; link = link->next)
2389 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":%s",