]> jfr.im git - irc/quakenet/snircd.git/blame - ircd/s_bsd.c
Update my e-mail address.
[irc/quakenet/snircd.git] / ircd / s_bsd.c
CommitLineData
189935b1 1/*
2 * IRC - Internet Relay Chat, ircd/s_bsd.c
3 * Copyright (C) 1990 Jarkko Oikarinen and
4 * University of Oulu, Computing Center
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 1, or (at your option)
9 * any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 */
20/** @file
21 * @brief Functions that now (or in the past) relied on BSD APIs.
64f5e964 22 * @version $Id: s_bsd.c,v 1.80.2.4 2007/05/29 03:08:33 entrope Exp $
189935b1 23 */
24#include "config.h"
25
26#include "s_bsd.h"
27#include "client.h"
28#include "IPcheck.h"
29#include "channel.h"
30#include "class.h"
31#include "hash.h"
32#include "ircd_alloc.h"
33#include "ircd_log.h"
34#include "ircd_features.h"
35#include "ircd_osdep.h"
36#include "ircd_reply.h"
37#include "ircd_snprintf.h"
38#include "ircd_string.h"
39#include "ircd.h"
40#include "list.h"
41#include "listener.h"
42#include "msg.h"
43#include "msgq.h"
44#include "numeric.h"
45#include "numnicks.h"
46#include "packet.h"
47#include "parse.h"
48#include "querycmds.h"
49#include "res.h"
50#include "s_auth.h"
51#include "s_conf.h"
52#include "s_debug.h"
53#include "s_misc.h"
54#include "s_user.h"
55#include "send.h"
56#include "struct.h"
57#include "sys.h"
58#include "uping.h"
59#include "version.h"
60
61/* #include <assert.h> -- Now using assert in ircd_log.h */
62#include <errno.h>
63#include <fcntl.h>
64#include <netdb.h>
65#include <stdio.h>
66#include <stdlib.h>
67#include <string.h>
68#include <sys/ioctl.h>
69#include <sys/socket.h>
70#include <sys/time.h>
71#include <sys/utsname.h>
72#include <unistd.h>
73
74/** Array of my own clients, indexed by file descriptor. */
75struct Client* LocalClientArray[MAXCONNECTIONS];
76/** Maximum file descriptor in current use. */
77int HighestFd = -1;
78/** Default local address for outbound IPv4 connections. */
79struct irc_sockaddr VirtualHost_v4;
80/** Default local address for outbound IPv6 connections. */
81struct irc_sockaddr VirtualHost_v6;
82/** Temporary buffer for reading data from a peer. */
83static char readbuf[SERVER_TCP_WINDOW];
84
85/*
86 * report_error text constants
87 */
88const char* const ACCEPT_ERROR_MSG = "error accepting connection for %s: %s";
89const char* const BIND_ERROR_MSG = "bind error for %s: %s";
90const char* const CONNECT_ERROR_MSG = "connect to host %s failed: %s";
91const char* const CONNLIMIT_ERROR_MSG = "connect limit exceeded for %s: %s";
92const char* const LISTEN_ERROR_MSG = "listen error for %s: %s";
93const char* const NONB_ERROR_MSG = "error setting non-blocking for %s: %s";
94const char* const PEERNAME_ERROR_MSG = "getpeername failed for %s: %s";
95const char* const POLL_ERROR_MSG = "poll error for %s: %s";
96const char* const REGISTER_ERROR_MSG = "registering %s: %s";
97const char* const REUSEADDR_ERROR_MSG = "error setting SO_REUSEADDR for %s: %s";
98const char* const SELECT_ERROR_MSG = "select error for %s: %s";
99const char* const SETBUFS_ERROR_MSG = "error setting buffer size for %s: %s";
100const char* const SOCKET_ERROR_MSG = "error creating socket for %s: %s";
101const char* const TOS_ERROR_MSG = "error setting TOS for %s: %s";
102
103
104static void client_sock_callback(struct Event* ev);
105static void client_timer_callback(struct Event* ev);
106
107
108/*
109 * Cannot use perror() within daemon. stderr is closed in
110 * ircd and cannot be used. And, worse yet, it might have
111 * been reassigned to a normal connection...
112 */
113
114/** Replacement for perror(). Record error to log. Send a copy to all
115 * *LOCAL* opers, but only if no errors were sent to them in the last
116 * 20 seconds.
117 * @param text A *format* string for outputting error. It must contain
118 * only two '%s', the first will be replaced by the sockhost from the
119 * cptr, and the latter will be taken from sys_errlist[errno].
120 * @param who The client associated with the error.
121 * @param err The errno value to display.
122 */
123void report_error(const char* text, const char* who, int err)
124{
125 static time_t last_notice = 0;
126 int errtmp = errno; /* debug may change 'errno' */
127 const char* errmsg = (err) ? strerror(err) : "";
128
129 if (!errmsg)
130 errmsg = "Unknown error";
131
132 if (EmptyString(who))
133 who = "unknown";
134
0c466275 135 sendto_opmask_butone_ratelimited(0, SNO_OLDSNO, &last_notice, text, who, errmsg);
189935b1 136 log_write(LS_SOCKET, L_ERROR, 0, text, who, errmsg);
137 errno = errtmp;
138}
139
140
141/** Called when resolver query finishes. If the DNS lookup was
142 * successful, start the connection; otherwise notify opers of the
143 * failure.
144 * @param vptr The struct ConfItem representing the Connect block.
145 * @param hp A pointer to the DNS lookup results (NULL on failure).
146 */
147static void connect_dns_callback(void* vptr, const struct irc_in_addr *addr, const char *h_name)
148{
149 struct ConfItem* aconf = (struct ConfItem*) vptr;
150 assert(aconf);
151 aconf->dns_pending = 0;
152 if (addr) {
153 memcpy(&aconf->address, addr, sizeof(aconf->address));
154 connect_server(aconf, 0);
155 }
156 else
157 sendto_opmask_butone(0, SNO_OLDSNO, "Connect to %s failed: host lookup",
158 aconf->name);
159}
160
161/** Closes all file descriptors.
162 * @param close_stderr If non-zero, also close stderr.
163 */
164void close_connections(int close_stderr)
165{
166 int i;
167 if (close_stderr)
168 {
169 close(0);
170 close(1);
171 close(2);
172 }
173 for (i = 3; i < MAXCONNECTIONS; ++i)
174 close(i);
175}
176
177/** Initialize process fd limit to MAXCONNECTIONS.
178 */
179int init_connection_limits(void)
180{
181 int limit = os_set_fdlimit(MAXCONNECTIONS);
182 if (0 == limit)
183 return 1;
184 if (limit < 0) {
185 fprintf(stderr, "error setting max fd's to %d\n", limit);
186 }
187 else if (limit > 0) {
188 fprintf(stderr, "ircd fd table too big\nHard Limit: %d IRC max: %d\n",
189 limit, MAXCONNECTIONS);
190 fprintf(stderr, "set MAXCONNECTIONS to a smaller value");
191 }
192 return 0;
193}
194
195/** Set up address and port and make a connection.
196 * @param aconf Provides the connection information.
197 * @param cptr Client structure for the peer.
198 * @return Non-zero on success; zero on failure.
199 */
200static int connect_inet(struct ConfItem* aconf, struct Client* cptr)
201{
202 const struct irc_sockaddr *local;
203 IOResult result;
9f8856e9 204 int family = 0;
205
189935b1 206 assert(0 != aconf);
207 assert(0 != cptr);
208 /*
209 * Might as well get sockhost from here, the connection is attempted
210 * with it so if it fails its useless.
211 */
212 if (irc_in_addr_valid(&aconf->origin.addr))
213 local = &aconf->origin;
9f8856e9 214 else if (irc_in_addr_is_ipv4(&aconf->address.addr)) {
189935b1 215 local = &VirtualHost_v4;
9f8856e9 216 family = AF_INET;
217 } else
189935b1 218 local = &VirtualHost_v6;
9f8856e9 219 cli_fd(cptr) = os_socket(local, SOCK_STREAM, cli_name(cptr), family);
189935b1 220 if (cli_fd(cptr) < 0)
221 return 0;
222
223 /*
224 * save connection info in client
225 */
226 memcpy(&cli_ip(cptr), &aconf->address.addr, sizeof(cli_ip(cptr)));
227 ircd_ntoa_r(cli_sock_ip(cptr), &cli_ip(cptr));
228 /*
229 * we want a big buffer for server connections
230 */
231 if (!os_set_sockbufs(cli_fd(cptr), feature_int(FEAT_SOCKSENDBUF), feature_int(FEAT_SOCKRECVBUF))) {
232 cli_error(cptr) = errno;
233 report_error(SETBUFS_ERROR_MSG, cli_name(cptr), errno);
234 close(cli_fd(cptr));
235 cli_fd(cptr) = -1;
236 return 0;
237 }
238 /*
239 * Set the TOS bits - this is nonfatal if it doesn't stick.
240 */
241 if (!os_set_tos(cli_fd(cptr), FEAT_TOS_SERVER)) {
242 report_error(TOS_ERROR_MSG, cli_name(cptr), errno);
243 }
244 if ((result = os_connect_nonb(cli_fd(cptr), &aconf->address)) == IO_FAILURE) {
245 cli_error(cptr) = errno;
246 report_error(CONNECT_ERROR_MSG, cli_name(cptr), errno);
247 close(cli_fd(cptr));
248 cli_fd(cptr) = -1;
249 return 0;
250 }
251 if (!socket_add(&(cli_socket(cptr)), client_sock_callback,
252 (void*) cli_connect(cptr),
253 (result == IO_SUCCESS) ? SS_CONNECTED : SS_CONNECTING,
254 SOCK_EVENT_READABLE, cli_fd(cptr))) {
255 cli_error(cptr) = ENFILE;
256 report_error(REGISTER_ERROR_MSG, cli_name(cptr), ENFILE);
257 close(cli_fd(cptr));
258 cli_fd(cptr) = -1;
259 return 0;
260 }
261 cli_freeflag(cptr) |= FREEFLAG_SOCKET;
262 return 1;
263}
264
265/** Attempt to send a sequence of bytes to the connection.
266 * As a side effect, updates \a cptr's FLAG_BLOCKED setting
267 * and sendB/sendK fields.
268 * @param cptr Client that should receive data.
269 * @param buf Message buffer to send to client.
270 * @return Negative on connection-fatal error; otherwise
271 * number of bytes sent.
272 */
273unsigned int deliver_it(struct Client *cptr, struct MsgQ *buf)
274{
275 unsigned int bytes_written = 0;
276 unsigned int bytes_count = 0;
277 assert(0 != cptr);
278
279 switch (os_sendv_nonb(cli_fd(cptr), buf, &bytes_count, &bytes_written)) {
280 case IO_SUCCESS:
281 ClrFlag(cptr, FLAG_BLOCKED);
282
283 cli_sendB(cptr) += bytes_written;
284 cli_sendB(&me) += bytes_written;
285 /* A partial write implies that future writes will block. */
286 if (bytes_written < bytes_count)
287 SetFlag(cptr, FLAG_BLOCKED);
288 break;
289 case IO_BLOCKED:
290 SetFlag(cptr, FLAG_BLOCKED);
291 break;
292 case IO_FAILURE:
293 cli_error(cptr) = errno;
294 SetFlag(cptr, FLAG_DEADSOCKET);
295 break;
296 }
297 return bytes_written;
298}
299
300/** Complete non-blocking connect()-sequence. Check access and
301 * terminate connection, if trouble detected.
302 * @param cptr Client to which we have connected, with all ConfItem structs attached.
303 * @return Zero on failure (caller should exit_client()), non-zero on success.
304 */
305static int completed_connection(struct Client* cptr)
306{
307 struct ConfItem *aconf;
308 time_t newts;
309 struct Client *acptr;
310 int i;
311
312 assert(0 != cptr);
313
314 /*
315 * get the socket status from the fd first to check if
316 * connection actually succeeded
317 */
318 if ((cli_error(cptr) = os_get_sockerr(cli_fd(cptr)))) {
319 const char* msg = strerror(cli_error(cptr));
320 if (!msg)
321 msg = "Unknown error";
322 sendto_opmask_butone(0, SNO_OLDSNO, "Connection failed to %s: %s",
323 cli_name(cptr), msg);
324 return 0;
325 }
326 if (!(aconf = find_conf_byname(cli_confs(cptr), cli_name(cptr), CONF_SERVER))) {
327 sendto_opmask_butone(0, SNO_OLDSNO, "Lost Server Line for %s", cli_name(cptr));
328 return 0;
329 }
330 if (s_state(&(cli_socket(cptr))) == SS_CONNECTING)
331 socket_state(&(cli_socket(cptr)), SS_CONNECTED);
332
333 if (!EmptyString(aconf->passwd))
334 sendrawto_one(cptr, MSG_PASS " :%s", aconf->passwd);
335
336 /*
337 * Create a unique timestamp
338 */
339 newts = TStime();
340 for (i = HighestFd; i > -1; --i) {
341 if ((acptr = LocalClientArray[i]) &&
342 (IsServer(acptr) || IsHandshake(acptr))) {
343 if (cli_serv(acptr)->timestamp >= newts)
344 newts = cli_serv(acptr)->timestamp + 1;
345 }
346 }
347 assert(0 != cli_serv(cptr));
348
349 cli_serv(cptr)->timestamp = newts;
350 SetHandshake(cptr);
351 /*
352 * Make us timeout after twice the timeout for DNS look ups
353 */
354 cli_lasttime(cptr) = CurrentTime;
c676699a 355 ClearPingSent(cptr);
189935b1 356
49f8e96a 357 sendrawto_one(cptr, MSG_SERVER " %s 1 %Tu %Tu J%s %s%s +%s6n :%s",
189935b1 358 cli_name(&me), cli_serv(&me)->timestamp, newts,
359 MAJOR_PROTOCOL, NumServCap(&me),
360 feature_bool(FEAT_HUB) ? "h" : "", cli_info(&me));
361
362 return (IsDead(cptr)) ? 0 : 1;
363}
364
365/** Close the physical connection. Side effects: MyConnect(cptr)
366 * becomes false and cptr->from becomes NULL.
367 * @param cptr Client to disconnect.
368 */
369void close_connection(struct Client *cptr)
370{
371 struct ConfItem* aconf;
372
373 if (IsServer(cptr)) {
374 ServerStats->is_sv++;
375 ServerStats->is_sbs += cli_sendB(cptr);
376 ServerStats->is_sbr += cli_receiveB(cptr);
377 ServerStats->is_sti += CurrentTime - cli_firsttime(cptr);
378 /*
379 * If the connection has been up for a long amount of time, schedule
380 * a 'quick' reconnect, else reset the next-connect cycle.
381 */
382 if ((aconf = find_conf_exact(cli_name(cptr), cptr, CONF_SERVER))) {
383 /*
384 * Reschedule a faster reconnect, if this was a automatically
385 * connected configuration entry. (Note that if we have had
386 * a rehash in between, the status has been changed to
387 * CONF_ILLEGAL). But only do this if it was a "good" link.
388 */
389 aconf->hold = CurrentTime;
390 aconf->hold += ((aconf->hold - cli_since(cptr) >
391 feature_int(FEAT_HANGONGOODLINK)) ?
392 feature_int(FEAT_HANGONRETRYDELAY) : ConfConFreq(aconf));
393/* if (nextconnect > aconf->hold) */
394/* nextconnect = aconf->hold; */
395 }
396 }
397 else if (IsUser(cptr)) {
398 ServerStats->is_cl++;
399 ServerStats->is_cbs += cli_sendB(cptr);
400 ServerStats->is_cbr += cli_receiveB(cptr);
401 ServerStats->is_cti += CurrentTime - cli_firsttime(cptr);
402 }
403 else
404 ServerStats->is_ni++;
405
406 if (-1 < cli_fd(cptr)) {
407 flush_connections(cptr);
408 LocalClientArray[cli_fd(cptr)] = 0;
409 close(cli_fd(cptr));
410 socket_del(&(cli_socket(cptr))); /* queue a socket delete */
411 cli_fd(cptr) = -1;
412 }
413 SetFlag(cptr, FLAG_DEADSOCKET);
414
415 MsgQClear(&(cli_sendQ(cptr)));
416 client_drop_sendq(cli_connect(cptr));
417 DBufClear(&(cli_recvQ(cptr)));
418 memset(cli_passwd(cptr), 0, sizeof(cli_passwd(cptr)));
419 set_snomask(cptr, 0, SNO_SET);
420
421 det_confs_butmask(cptr, 0);
422
423 if (cli_listener(cptr)) {
424 release_listener(cli_listener(cptr));
425 cli_listener(cptr) = 0;
426 }
427
428 for ( ; HighestFd > 0; --HighestFd) {
429 if (LocalClientArray[HighestFd])
430 break;
431 }
432}
433
434/** Close all unregistered connections.
435 * @param source Oper who requested the close.
436 * @return Number of closed connections.
437 */
438int net_close_unregistered_connections(struct Client* source)
439{
440 int i;
441 struct Client* cptr;
442 int count = 0;
443 assert(0 != source);
444
445 for (i = HighestFd; i > 0; --i) {
446 if ((cptr = LocalClientArray[i]) && !IsRegistered(cptr)) {
447 send_reply(source, RPL_CLOSING, get_client_name(source, HIDE_IP));
448 exit_client(source, cptr, &me, "Oper Closing");
449 ++count;
450 }
451 }
452 return count;
453}
454
455/** Creates a client which has just connected to us on the given fd.
456 * The sockhost field is initialized with the ip# of the host.
457 * The client is not added to the linked list of clients, it is
458 * passed off to the auth handler for dns and ident queries.
459 * @param listener Listening socket that received the connection.
460 * @param fd File descriptor of new connection.
461 */
462void add_connection(struct Listener* listener, int fd) {
463 struct irc_sockaddr addr;
464 struct Client *new_client;
465 time_t next_target = 0;
466
467 const char* const throttle_message =
468 "ERROR :Your host is trying to (re)connect too fast -- throttled\r\n";
469 /* 12345678901234567890123456789012345679012345678901234567890123456 */
470 const char* const register_message =
471 "ERROR :Unable to complete your registration\r\n";
472
473 assert(0 != listener);
474
475 /*
476 * Removed preliminary access check. Full check is performed in m_server and
477 * m_user instead. Also connection time out help to get rid of unwanted
478 * connections.
479 */
480 if (!os_get_peername(fd, &addr) || !os_set_nonblocking(fd)) {
481 ++ServerStats->is_ref;
482 close(fd);
483 return;
484 }
485 /*
486 * Disable IP (*not* TCP) options. In particular, this makes it impossible
487 * to use source routing to connect to the server. If we didn't do this
488 * (and if intermediate networks didn't drop source-routed packets), an
489 * attacker could successfully IP spoof us...and even return the anti-spoof
490 * ping, because the options would cause the packet to be routed back to
491 * the spoofer's machine. When we disable the IP options, we delete the
492 * source route, and the normal routing takes over.
493 */
494 os_disable_options(fd);
495
0c466275 496 if (listener_server(listener))
189935b1 497 {
498 new_client = make_client(0, STAT_UNKNOWN_SERVER);
499 }
500 else
501 {
502 /*
503 * Add this local client to the IPcheck registry.
504 *
505 * If they're throttled, murder them, but tell them why first.
506 */
507 if (!IPcheck_local_connect(&addr.addr, &next_target))
508 {
509 ++ServerStats->is_ref;
510 write(fd, throttle_message, strlen(throttle_message));
511 close(fd);
512 return;
513 }
514 new_client = make_client(0, STAT_UNKNOWN_USER);
515 SetIPChecked(new_client);
516 }
517
518 /*
519 * Copy ascii address to 'sockhost' just in case. Then we have something
520 * valid to put into error messages...
521 */
522 ircd_ntoa_r(cli_sock_ip(new_client), &addr.addr);
523 strcpy(cli_sockhost(new_client), cli_sock_ip(new_client));
524 memcpy(&cli_ip(new_client), &addr.addr, sizeof(cli_ip(new_client)));
525
526 if (next_target)
527 cli_nexttarget(new_client) = next_target;
528
529 cli_fd(new_client) = fd;
530 if (!socket_add(&(cli_socket(new_client)), client_sock_callback,
531 (void*) cli_connect(new_client), SS_CONNECTED, 0, fd)) {
532 ++ServerStats->is_ref;
533 write(fd, register_message, strlen(register_message));
534 close(fd);
535 cli_fd(new_client) = -1;
536 return;
537 }
538 cli_freeflag(new_client) |= FREEFLAG_SOCKET;
539 cli_listener(new_client) = listener;
540 ++listener->ref_count;
541
542 Count_newunknown(UserStats);
543 /* if we've made it this far we can put the client on the auth query pile */
544 start_auth(new_client);
545}
546
547/** Determines whether to tell the events engine we're interested in
548 * writable events.
549 * @param cptr Client for which to decide this.
550 */
551void update_write(struct Client* cptr)
552{
553 /* If there are messages that need to be sent along, or if the client
554 * is in the middle of a /list, then we need to tell the engine that
555 * we're interested in writable events--otherwise, we need to drop
556 * that interest.
557 */
558 socket_events(&(cli_socket(cptr)),
559 ((MsgQLength(&cli_sendQ(cptr)) || cli_listing(cptr)) ?
560 SOCK_ACTION_ADD : SOCK_ACTION_DEL) | SOCK_EVENT_WRITABLE);
561}
562
563/** Read a 'packet' of data from a connection and process it. Read in
564 * 8k chunks to give a better performance rating (for server
565 * connections). Do some tricky stuff for client connections to make
566 * sure they don't do any flooding >:-) -avalon
567 * @param cptr Client from which to read data.
568 * @param socket_ready If non-zero, more data can be read from the client's socket.
569 * @return Positive number on success, zero on connection-fatal failure, negative
570 * if user is killed.
571 */
572static int read_packet(struct Client *cptr, int socket_ready)
573{
574 unsigned int dolen = 0;
575 unsigned int length = 0;
576
577 if (socket_ready &&
d8e74551 578 !(IsUser(cptr) && !IsOper(cptr) &&
189935b1 579 DBufLength(&(cli_recvQ(cptr))) > feature_int(FEAT_CLIENT_FLOOD))) {
580 switch (os_recv_nonb(cli_fd(cptr), readbuf, sizeof(readbuf), &length)) {
581 case IO_SUCCESS:
582 if (length)
583 {
c676699a 584 cli_lasttime(cptr) = CurrentTime;
585 ClearPingSent(cptr);
586 ClrFlag(cptr, FLAG_NONL);
189935b1 587 if (cli_lasttime(cptr) > cli_since(cptr))
588 cli_since(cptr) = cli_lasttime(cptr);
189935b1 589 }
590 break;
591 case IO_BLOCKED:
592 break;
593 case IO_FAILURE:
594 cli_error(cptr) = errno;
595 /* SetFlag(cptr, FLAG_DEADSOCKET); */
596 return 0;
597 }
598 }
599
600 /*
601 * For server connections, we process as many as we can without
602 * worrying about the time of day or anything :)
603 */
604 if (length > 0 && IsServer(cptr))
605 return server_dopacket(cptr, readbuf, length);
606 else if (length > 0 && (IsHandshake(cptr) || IsConnecting(cptr)))
607 return connect_dopacket(cptr, readbuf, length);
608 else
609 {
610 /*
611 * Before we even think of parsing what we just read, stick
612 * it on the end of the receive queue and do it when its
613 * turn comes around.
614 */
615 if (length > 0 && dbuf_put(&(cli_recvQ(cptr)), readbuf, length) == 0)
616 return exit_client(cptr, cptr, &me, "dbuf_put fail");
617
d8e74551 618 if (IsUser(cptr)) {
619 if (DBufLength(&(cli_recvQ(cptr))) > feature_int(FEAT_CLIENT_FLOOD)
620 && !IsOper(cptr))
189935b1 621 return exit_client(cptr, cptr, &me, "Excess Flood");
d8e74551 622 }
189935b1 623
624 while (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) &&
625 (IsTrusted(cptr) || cli_since(cptr) - CurrentTime < 10))
626 {
627 dolen = dbuf_getmsg(&(cli_recvQ(cptr)), cli_buffer(cptr), BUFSIZE);
628 /*
629 * Devious looking...whats it do ? well..if a client
630 * sends a *long* message without any CR or LF, then
631 * dbuf_getmsg fails and we pull it out using this
632 * loop which just gets the next 512 bytes and then
633 * deletes the rest of the buffer contents.
634 * -avalon
635 */
636 if (dolen == 0)
637 {
638 if (DBufLength(&(cli_recvQ(cptr))) < 510)
639 SetFlag(cptr, FLAG_NONL);
640 else
64f5e964 641 {
642 /* More than 512 bytes in the line - drop the input and yell
643 * at the client.
644 */
189935b1 645 DBufClear(&(cli_recvQ(cptr)));
64f5e964 646 send_reply(cptr, ERR_INPUTTOOLONG);
647 }
189935b1 648 }
649 else if (client_dopacket(cptr, dolen) == CPTR_KILLED)
650 return CPTR_KILLED;
651 /*
652 * If it has become registered as a Server
653 * then skip the per-message parsing below.
654 */
655 if (IsHandshake(cptr) || IsServer(cptr))
656 {
657 while (-1)
658 {
659 dolen = dbuf_get(&(cli_recvQ(cptr)), readbuf, sizeof(readbuf));
660 if (dolen <= 0)
661 return 1;
662 else if (dolen == 0)
663 {
664 if (DBufLength(&(cli_recvQ(cptr))) < 510)
665 SetFlag(cptr, FLAG_NONL);
666 else
667 DBufClear(&(cli_recvQ(cptr)));
668 }
669 else if ((IsServer(cptr) &&
670 server_dopacket(cptr, readbuf, dolen) == CPTR_KILLED) ||
671 (!IsServer(cptr) &&
672 connect_dopacket(cptr, readbuf, dolen) == CPTR_KILLED))
673 return CPTR_KILLED;
674 }
675 }
676 }
677
678 /* If there's still data to process, wait 2 seconds first */
679 if (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) &&
680 !t_onqueue(&(cli_proc(cptr))))
681 {
682 Debug((DEBUG_LIST, "Adding client process timer for %C", cptr));
683 cli_freeflag(cptr) |= FREEFLAG_TIMER;
684 timer_add(&(cli_proc(cptr)), client_timer_callback, cli_connect(cptr),
685 TT_RELATIVE, 2);
686 }
687 }
688 return 1;
689}
690
691/** Start a connection to another server.
692 * @param aconf Connect block data for target server.
693 * @param by Client who requested the connection (if any).
694 * @return Non-zero on success; zero on failure.
695 */
696int connect_server(struct ConfItem* aconf, struct Client* by)
697{
698 struct Client* cptr = 0;
699 assert(0 != aconf);
700
701 if (aconf->dns_pending) {
702 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s connect DNS pending",
703 aconf->name);
704 return 0;
705 }
706 Debug((DEBUG_NOTICE, "Connect to %s[@%s]", aconf->name,
707 ircd_ntoa(&aconf->address.addr)));
708
709 if ((cptr = FindClient(aconf->name))) {
710 if (IsServer(cptr) || IsMe(cptr)) {
711 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s already present from %s",
712 aconf->name, cli_name(cli_from(cptr)));
713 if (by && IsUser(by) && !MyUser(by)) {
714 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Server %s already present "
715 "from %s", by, aconf->name, cli_name(cli_from(cptr)));
716 }
717 return 0;
718 }
719 else if (IsHandshake(cptr) || IsConnecting(cptr)) {
720 if (by && IsUser(by)) {
721 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connection to %s already in "
722 "progress", by, cli_name(cptr));
723 }
724 return 0;
725 }
726 }
727 /*
728 * If we don't know the IP# for this host and it is a hostname and
729 * not a ip# string, then try and find the appropriate host record.
730 */
731 if (!irc_in_addr_valid(&aconf->address.addr)
732 && !ircd_aton(&aconf->address.addr, aconf->host)) {
733 char buf[HOSTLEN + 1];
734
735 host_from_uh(buf, aconf->host, HOSTLEN);
736 gethost_byname(buf, connect_dns_callback, aconf);
737 aconf->dns_pending = 1;
738 return 0;
739 }
740 cptr = make_client(NULL, STAT_UNKNOWN_SERVER);
741
742 /*
743 * Copy these in so we have something for error detection.
744 */
745 ircd_strncpy(cli_name(cptr), aconf->name, HOSTLEN);
746 ircd_strncpy(cli_sockhost(cptr), aconf->host, HOSTLEN);
747
748 /*
749 * Attach config entries to client here rather than in
750 * completed_connection. This to avoid null pointer references
751 */
752 attach_confs_byhost(cptr, aconf->host, CONF_SERVER);
753
754 if (!find_conf_byhost(cli_confs(cptr), aconf->host, CONF_SERVER)) {
755 sendto_opmask_butone(0, SNO_OLDSNO, "Host %s is not enabled for "
756 "connecting: no Connect block", aconf->name);
757 if (by && IsUser(by) && !MyUser(by)) {
758 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connect to host %s failed: no "
759 "Connect block", by, aconf->name);
760 }
761 det_confs_butmask(cptr, 0);
762 free_client(cptr);
763 return 0;
764 }
765 /*
766 * attempt to connect to the server in the conf line
767 */
768 if (!connect_inet(aconf, cptr)) {
769 if (by && IsUser(by) && !MyUser(by)) {
770 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Couldn't connect to %s", by,
771 cli_name(cptr));
772 }
773 det_confs_butmask(cptr, 0);
774 free_client(cptr);
775 return 0;
776 }
777 /*
778 * NOTE: if we're here we have a valid C:Line and the client should
779 * have started the connection and stored the remote address/port and
780 * ip address name in itself
781 *
782 * The socket has been connected or connect is in progress.
783 */
784 make_server(cptr);
785 if (by && IsUser(by)) {
786 ircd_snprintf(0, cli_serv(cptr)->by, sizeof(cli_serv(cptr)->by), "%s%s",
787 NumNick(by));
788 assert(0 == cli_serv(cptr)->user);
789 cli_serv(cptr)->user = cli_user(by);
790 cli_user(by)->refcnt++;
791 }
792 else {
793 *(cli_serv(cptr))->by = '\0';
794 /* strcpy(cptr->serv->by, "Auto"); */
795 }
796 cli_serv(cptr)->up = &me;
797 SetConnecting(cptr);
798
799 if (cli_fd(cptr) > HighestFd)
800 HighestFd = cli_fd(cptr);
801
802 LocalClientArray[cli_fd(cptr)] = cptr;
803
804 Count_newunknown(UserStats);
805 /* Actually we lie, the connect hasn't succeeded yet, but we have a valid
806 * cptr, so we register it now.
807 * Maybe these two calls should be merged.
808 */
809 add_client_to_list(cptr);
810 hAddClient(cptr);
811/* nextping = CurrentTime; */
812
813 return (s_state(&cli_socket(cptr)) == SS_CONNECTED) ?
814 completed_connection(cptr) : 1;
815}
816
817/** Find the real hostname for the host running the server (or one which
818 * matches the server's name) and its primary IP#. Hostname is stored
819 * in the client structure passed as a pointer.
820 */
821void init_server_identity(void)
822{
823 const struct LocalConf* conf = conf_get_local();
824 assert(0 != conf);
825
826 ircd_strncpy(cli_name(&me), conf->name, HOSTLEN);
827 SetYXXServerName(&me, conf->numeric);
828}
829
830/** Process events on a client socket.
831 * @param ev Socket event structure that has a struct Connection as
832 * its associated data.
833 */
834static void client_sock_callback(struct Event* ev)
835{
836 struct Client* cptr;
837 struct Connection* con;
838 char *fmt = "%s";
839 char *fallback = 0;
840
841 assert(0 != ev_socket(ev));
842 assert(0 != s_data(ev_socket(ev)));
843
844 con = (struct Connection*) s_data(ev_socket(ev));
845
846 assert(0 != con_client(con) || ev_type(ev) == ET_DESTROY);
847
848 cptr = con_client(con);
849
850 assert(0 == cptr || con == cli_connect(cptr));
851
852 switch (ev_type(ev)) {
853 case ET_DESTROY:
854 con_freeflag(con) &= ~FREEFLAG_SOCKET;
855
856 if (!con_freeflag(con) && !cptr)
857 free_connection(con);
858 break;
859
860 case ET_CONNECT: /* socket connection completed */
861 if (!completed_connection(cptr) || IsDead(cptr))
862 fallback = cli_info(cptr);
863 break;
864
865 case ET_ERROR: /* an error occurred */
866 fallback = cli_info(cptr);
867 cli_error(cptr) = ev_data(ev);
868 if (s_state(&(con_socket(con))) == SS_CONNECTING) {
869 completed_connection(cptr);
870 /* for some reason, the os_get_sockerr() in completed_connect()
871 * can return 0 even when ev_data(ev) indicates a real error, so
872 * re-assign the client error here.
873 */
874 cli_error(cptr) = ev_data(ev);
875 break;
876 }
877 /*FALLTHROUGH*/
878 case ET_EOF: /* end of file on socket */
879 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d", cli_fd(cptr),
880 cli_error(cptr)));
881 SetFlag(cptr, FLAG_DEADSOCKET);
882 if ((IsServer(cptr) || IsHandshake(cptr)) && cli_error(cptr) == 0) {
883 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
884 cli_name(cptr), cli_serv(cptr)->last_error_msg);
885 return;
886 } else {
887 fmt = "Read error: %s";
888 fallback = "EOF from client";
889 }
890 break;
891
892 case ET_WRITE: /* socket is writable */
893 ClrFlag(cptr, FLAG_BLOCKED);
894 if (cli_listing(cptr) && MsgQLength(&(cli_sendQ(cptr))) < 2048)
895 list_next_channels(cptr);
896 Debug((DEBUG_SEND, "Sending queued data to %C", cptr));
897 send_queued(cptr);
898 break;
899
900 case ET_READ: /* socket is readable */
901 if (!IsDead(cptr)) {
902 Debug((DEBUG_DEBUG, "Reading data from %C", cptr));
903 if (read_packet(cptr, 1) == 0) /* error while reading packet */
904 fallback = "EOF from client";
905 }
906 break;
907
908 default:
909 assert(0 && "Unrecognized socket event in client_sock_callback()");
910 break;
911 }
912
913 assert(0 == cptr || 0 == cli_connect(cptr) || con == cli_connect(cptr));
914
915 if (fallback) {
916 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : fallback;
917 if (!msg)
918 msg = "Unknown error";
919 exit_client_msg(cptr, cptr, &me, fmt, msg);
920 }
921}
922
923/** Process a timer on client socket.
924 * @param ev Timer event that has a struct Connection as its
925 * associated data.
926 */
927static void client_timer_callback(struct Event* ev)
928{
929 struct Client* cptr;
930 struct Connection* con;
931
932 assert(0 != ev_timer(ev));
933 assert(0 != t_data(ev_timer(ev)));
934 assert(ET_DESTROY == ev_type(ev) || ET_EXPIRE == ev_type(ev));
935
936 con = (struct Connection*) t_data(ev_timer(ev));
937
938 assert(0 != con_client(con) || ev_type(ev) == ET_DESTROY);
939
940 cptr = con_client(con);
941
942 assert(0 == cptr || con == cli_connect(cptr));
943
944 if (ev_type(ev)== ET_DESTROY) {
945 con_freeflag(con) &= ~FREEFLAG_TIMER; /* timer has expired... */
946
947 if (!con_freeflag(con) && !cptr)
948 free_connection(con); /* client is being destroyed */
949 } else {
950 Debug((DEBUG_LIST, "Client process timer for %C expired; processing",
951 cptr));
952 read_packet(cptr, 0); /* read_packet will re-add timer if needed */
953 }
954
955 assert(0 == cptr || 0 == cli_connect(cptr) || con == cli_connect(cptr));
956}