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