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