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