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