Author: Isomer <isomer@coders.net>
[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 "s_bsd.h"
23 #include "client.h"
24 #include "IPcheck.h"
25 #include "channel.h"
26 #include "class.h"
27 #include "hash.h"
28 #include "ircd_log.h"
29 #include "ircd_osdep.h"
30 #include "ircd_string.h"
31 #include "ircd.h"
32 #include "list.h"
33 #include "listener.h"
34 #include "numeric.h"
35 #include "numnicks.h"
36 #include "packet.h"
37 #include "parse.h"
38 #include "querycmds.h"
39 #include "res.h"
40 #include "s_auth.h"
41 #include "s_conf.h"
42 #include "s_debug.h"
43 #include "s_misc.h"
44 #include "s_user.h"
45 #include "send.h"
46 #include "sprintf_irc.h"
47 #include "struct.h"
48 #include "support.h"
49 #include "sys.h"
50 #include "uping.h"
51 #include "version.h"
52
53 #include <arpa/inet.h>
54 #include <arpa/nameser.h>
55 #include <assert.h>
56 #include <errno.h>
57 #include <fcntl.h>
58 #include <netdb.h>
59 #include <resolv.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <sys/ioctl.h>
64 #include <sys/socket.h>
65 #include <sys/time.h>
66 #include <sys/utsname.h>
67 #include <unistd.h>
68
69 #ifdef USE_POLL
70 #include <sys/poll.h>
71 #endif /* USE_POLL */
72
73 #ifndef INADDR_NONE
74 #define INADDR_NONE 0xffffffff
75 #endif
76
77 struct Client*            LocalClientArray[MAXCONNECTIONS];
78 int                       HighestFd = -1;
79 struct sockaddr_in        VirtualHost;
80 static char               readbuf[SERVER_TCP_WINDOW];
81 static int                running_in_background;
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 REUSEADDR_ERROR_MSG = "error setting SO_REUSEADDR for %s: %s";
95 const char* const SELECT_ERROR_MSG    = "select error for %s: %s";
96 const char* const SETBUFS_ERROR_MSG   = "error setting buffer size for %s: %s";
97 const char* const SOCKET_ERROR_MSG    = "error creating socket for %s: %s";
98
99
100 #ifdef GODMODE
101 #ifndef NODNS
102 #define NODNS
103 #endif
104 #ifndef NOFLOODCONTROL
105 #define NOFLOODCONTROL
106 #endif
107 #endif
108
109 #if !defined(USE_POLL)
110 #if FD_SETSIZE < (MAXCONNECTIONS + 4)
111 /*
112  * Sanity check
113  *
114  * All operating systems work when MAXCONNECTIONS <= 252.
115  * Most operating systems work when MAXCONNECTIONS <= 1020 and FD_SETSIZE is
116  *   updated correctly in the system headers (on BSD systems our sys.h has
117  *   defined FD_SETSIZE to MAXCONNECTIONS+4 before including the system's headers 
118  *   but sys/types.h might have abruptly redefined it so the check is still 
119  *   done), you might already need to recompile your kernel.
120  * For larger FD_SETSIZE your milage may vary (kernel patches may be needed).
121  * The check is _NOT_ done if we will not use FD_SETS at all (USE_POLL)
122  */
123 #error "FD_SETSIZE is too small or MAXCONNECTIONS too large."
124 #endif
125 #endif
126
127
128 /*
129  * Cannot use perror() within daemon. stderr is closed in
130  * ircd and cannot be used. And, worse yet, it might have
131  * been reassigned to a normal connection...
132  */
133
134 /*
135  * report_error
136  *
137  * This a replacement for perror(). Record error to log and
138  * also send a copy to all *LOCAL* opers online.
139  *
140  * text    is a *format* string for outputting error. It must
141  *         contain only two '%s', the first will be replaced
142  *         by the sockhost from the cptr, and the latter will
143  *         be taken from sys_errlist[errno].
144  *
145  * cptr    if not NULL, is the *LOCAL* client associated with
146  *         the error.
147  */
148 void report_error(const char* text, const char* who, int err)
149 {
150   static time_t last_notice = 0;
151   int           errtmp = errno;   /* debug may change 'errno' */
152   const char*   errmsg = (err) ? strerror(err) : "";
153   if (!errmsg)
154     errmsg = "Unknown error"; 
155
156   if (!who)
157     who = "unknown";
158
159   if (last_notice + 20 < CurrentTime) {
160     /*
161      * pace error messages so opers don't get flooded by transients
162      */
163     sendto_ops(text, who, errmsg);
164     last_notice = CurrentTime;
165   }
166
167   ircd_log(L_ERROR, text, who, errmsg);
168
169   if (!running_in_background) {
170     fprintf(stderr, text, who, errmsg);
171     fprintf(stderr, "\n");
172   }
173   errno = errtmp;
174 }
175
176
177 /*
178  * connect_dns_callback - called when resolver query finishes
179  * if the query resulted in a successful search, reply will contain
180  * a non-null pointer, otherwise reply will be null.
181  * if successful start the connection, otherwise notify opers
182  */
183 static void connect_dns_callback(void* vptr, struct DNSReply* reply)
184 {
185   struct ConfItem* aconf = (struct ConfItem*) vptr;
186   aconf->dns_pending = 0;
187   if (reply) {
188     memcpy(&aconf->ipnum, reply->hp->h_addr, sizeof(struct in_addr));
189     connect_server(aconf, 0, reply);
190   }
191   else
192     sendto_ops("Connect to %s failed: host lookup", aconf->name);
193 }
194
195
196 /*
197  * connect_inet - set up address and port and make a connection
198  */
199 static int connect_inet(struct ConfItem* aconf, struct Client* cptr)
200 {
201   static struct sockaddr_in sin;
202   assert(0 != aconf);
203   assert(0 != cptr);
204   /*
205    * Might as well get sockhost from here, the connection is attempted
206    * with it so if it fails its useless.
207    */
208   cptr->fd = socket(AF_INET, SOCK_STREAM, 0);
209   if (-1 == cptr->fd) {
210     cptr->error = errno;
211     report_error(SOCKET_ERROR_MSG, cptr->name, errno);
212     return 0;
213   }
214   if (cptr->fd >= MAXCLIENTS) {
215     report_error(CONNLIMIT_ERROR_MSG, cptr->name, 0);
216     close(cptr->fd);
217     cptr->fd = -1;
218     return 0;
219   }
220   /*
221    * Bind to a local IP# (with unknown port - let unix decide) so
222    * we have some chance of knowing the IP# that gets used for a host
223    * with more than one IP#.
224    *
225    * No we don't bind it, not all OS's can handle connecting with
226    * an already bound socket, different ip# might occur anyway
227    * leading to a freezing select() on this side for some time.
228    * I had this on my Linux 1.1.88 --Run
229    */
230 #ifdef VIRTUAL_HOST
231   /*
232    * No, we do bind it if we have virtual host support. If we don't
233    * explicitly bind it, it will default to IN_ADDR_ANY and we lose
234    * due to the other server not allowing our base IP --smg
235    */
236   if (bind(cptr->fd, (struct sockaddr*) &VirtualHost, sizeof(VirtualHost))) {
237     report_error(BIND_ERROR_MSG, cptr->name, errno);
238     return 0;
239   }
240 #endif
241
242   memset(&sin, 0, sizeof(sin));
243   sin.sin_family      = AF_INET;
244   sin.sin_addr.s_addr = aconf->ipnum.s_addr;
245   sin.sin_port        = htons(aconf->port);
246   /*
247    * save connection info in client
248    */
249   cptr->ip.s_addr = aconf->ipnum.s_addr;
250   cptr->port      = aconf->port;
251   ircd_ntoa_r(cptr->sock_ip, (const char*) &cptr->ip);
252   /*
253    * we want a big buffer for server connections
254    */
255   if (!os_set_sockbufs(cptr->fd, SERVER_TCP_WINDOW)) {
256     cptr->error = errno;
257     report_error(SETBUFS_ERROR_MSG, cptr->name, errno);
258     return 0;
259   }
260   /*
261    * ALWAYS set sockets non-blocking
262    */
263   if (!os_set_nonblocking(cptr->fd)) {
264     cptr->error = errno;
265     report_error(NONB_ERROR_MSG, cptr->name, errno);
266     return 0;
267   }
268   if (!os_connect_nonb(cptr->fd, &sin)) {
269     cptr->error = errno;
270     report_error(CONNECT_ERROR_MSG, cptr->name, errno);
271     return 0;
272   }
273   return 1;
274 }
275
276 /*
277  * deliver_it
278  *   Attempt to send a sequence of bytes to the connection.
279  *   Returns
280  *
281  *   < 0     Some fatal error occurred, (but not EWOULDBLOCK).
282  *           This return is a request to close the socket and
283  *           clean up the link.
284  *
285  *   >= 0    No real error occurred, returns the number of
286  *           bytes actually transferred. EWOULDBLOCK and other
287  *           possibly similar conditions should be mapped to
288  *           zero return. Upper level routine will have to
289  *           decide what to do with those unwritten bytes...
290  *
291  *   *NOTE*  alarm calls have been preserved, so this should
292  *           work equally well whether blocking or non-blocking
293  *           mode is used...
294  *
295  *   We don't use blocking anymore, that is impossible with the
296  *      net.loads today anyway. Commented out the alarms to save cpu.
297  *      --Run
298  */
299 unsigned int deliver_it(struct Client *cptr, const char *str, unsigned int len)
300 {
301   unsigned int bytes_written = 0;
302   assert(0 != cptr);
303
304   switch (os_send_nonb(cptr->fd, str, len, &bytes_written)) {
305   case IO_SUCCESS:
306     cptr->flags &= ~FLAGS_BLOCKED;
307
308     cptr->sendB += bytes_written;
309     me.sendB    += bytes_written;
310     if (cptr->sendB > 1023) {
311       cptr->sendK += (cptr->sendB >> 10);
312       cptr->sendB &= 0x03ff;    /* 2^10 = 1024, 3ff = 1023 */
313     }
314     if (me.sendB > 1023) {
315       me.sendK += (me.sendB >> 10);
316       me.sendB &= 0x03ff;
317     }
318     if (bytes_written < len)
319       cptr->flags |= FLAGS_BLOCKED;
320     break;
321   case IO_BLOCKED:
322     cptr->flags |= FLAGS_BLOCKED;
323     break;
324   case IO_FAILURE:
325     cptr->error = errno;
326     cptr->flags |= FLAGS_DEADSOCKET;
327     break;
328   }
329   return bytes_written;
330 }
331
332 /*
333  * init_sys
334  */
335 void init_sys(void)
336 {
337   int fd;
338   int limit = os_set_fdlimit(MAXCONNECTIONS);
339   if (limit < 0) {
340     fprintf(stderr, "error setting max fd's to %d\n", limit);
341     exit(2);
342   }
343   else if (limit > 0) {
344     fprintf(stderr, "ircd fd table too big\nHard Limit: %d IRC max: %d\n",
345             limit, MAXCONNECTIONS);
346     fprintf(stderr, "set MAXCONNECTIONS to a smaller value");
347     exit(2);
348   }
349
350   for (fd = 3; fd < MAXCONNECTIONS; ++fd)
351   {
352     close(fd);
353     LocalClientArray[fd] = NULL;
354   }
355   LocalClientArray[2] = 0;
356   LocalClientArray[1] = 0;
357   LocalClientArray[0] = 0;
358   close(1);
359   close(0);
360
361   if (bootopt & BOOT_TTY) {
362     /* debugging is going to a tty */
363     init_resolver();
364     return;
365   }
366   if (!(bootopt & BOOT_DEBUG))
367     close(2);
368
369   if (fork())
370     exit(0);
371   running_in_background = 1;
372 #ifdef TIOCNOTTY
373   if ((fd = open("/dev/tty", O_RDWR)) > -1) {
374     ioctl(fd, TIOCNOTTY, 0);
375     close(fd);
376   }
377 #endif
378   setsid();
379   init_resolver();
380 }
381
382 void release_dns_reply(struct Client* cptr)
383 {
384   assert(0 != cptr);
385   assert(MyConnect(cptr));
386
387   if (cptr->dns_reply) {
388     assert(0 < cptr->dns_reply->ref_count);
389     --cptr->dns_reply->ref_count;
390     cptr->dns_reply = 0;
391   }
392 }
393
394 /*
395  * completed_connection
396  *
397  * Complete non-blocking connect()-sequence. Check access and
398  * terminate connection, if trouble detected.
399  *
400  * Return  TRUE, if successfully completed
401  *        FALSE, if failed and ClientExit
402  */
403 static int completed_connection(struct Client* cptr)
404 {
405   struct ConfItem *aconf;
406   time_t newts;
407   struct Client *acptr;
408   int i;
409
410   assert(0 != cptr);
411
412   /*
413    * get the socket status from the fd first to check if
414    * connection actually succeeded
415    */
416   if ((cptr->error = os_get_sockerr(cptr->fd))) {
417     const char* msg = strerror(cptr->error);
418     if (!msg)
419       msg = "Unknown error";
420     sendto_ops("Connection failed to %s: %s", cptr->name, msg);
421     return 0;
422   }
423   if (!(aconf = find_conf_byname(cptr->confs, cptr->name, CONF_SERVER))) {
424     sendto_ops("Lost Server Line for %s", cptr->name);
425     return 0;
426   }
427   if (!EmptyString(aconf->passwd))
428     sendto_one(cptr, "PASS :%s", aconf->passwd);
429
430 #if 0 
431   /* dead code, already done in connect_server */
432   make_server(cptr);
433 #endif
434   /*
435    * Create a unique timestamp
436    */
437   newts = TStime();
438   for (i = HighestFd; i > -1; --i) {
439     if ((acptr = LocalClientArray[i]) && 
440         (IsServer(acptr) || IsHandshake(acptr))) {
441       if (acptr->serv->timestamp >= newts)
442         newts = acptr->serv->timestamp + 1;
443     }
444   }
445   assert(0 != cptr->serv);
446
447   cptr->serv->timestamp = newts;
448   SetHandshake(cptr);
449   /*
450    * Make us timeout after twice the timeout for DNS look ups
451    */
452   cptr->lasttime = CurrentTime;
453   cptr->flags |= FLAGS_PINGSENT;
454   sendto_one(cptr, "SERVER %s 1 " TIME_T_FMT " " TIME_T_FMT " J%s %s%s :%s",
455              me.name, me.serv->timestamp, newts, MAJOR_PROTOCOL, 
456              NumServCap(&me), me.info);
457
458   return (IsDead(cptr)) ? 0 : 1;
459 }
460
461 /*
462  * close_connection
463  *
464  * Close the physical connection. This function must make
465  * MyConnect(cptr) == FALSE, and set cptr->from == NULL.
466  */
467 void close_connection(struct Client *cptr)
468 {
469   struct ConfItem* aconf;
470
471   if (IsServer(cptr)) {
472     ServerStats->is_sv++;
473     ServerStats->is_sbs += cptr->sendB;
474     ServerStats->is_sbr += cptr->receiveB;
475     ServerStats->is_sks += cptr->sendK;
476     ServerStats->is_skr += cptr->receiveK;
477     ServerStats->is_sti += CurrentTime - cptr->firsttime;
478     if (ServerStats->is_sbs > 1023) {
479       ServerStats->is_sks += (ServerStats->is_sbs >> 10);
480       ServerStats->is_sbs &= 0x3ff;
481     }
482     if (ServerStats->is_sbr > 1023) {
483       ServerStats->is_skr += (ServerStats->is_sbr >> 10);
484       ServerStats->is_sbr &= 0x3ff;
485     }
486     /*
487      * If the connection has been up for a long amount of time, schedule
488      * a 'quick' reconnect, else reset the next-connect cycle.
489      */
490     if ((aconf = find_conf_exact(cptr->name, 0, cptr->sockhost, CONF_SERVER))) {
491       /*
492        * Reschedule a faster reconnect, if this was a automaticly
493        * connected configuration entry. (Note that if we have had
494        * a rehash in between, the status has been changed to
495        * CONF_ILLEGAL). But only do this if it was a "good" link.
496        */
497       aconf->hold = CurrentTime;
498       aconf->hold += (aconf->hold - cptr->since > HANGONGOODLINK) ?
499                      HANGONRETRYDELAY : ConfConFreq(aconf);
500       if (nextconnect > aconf->hold)
501         nextconnect = aconf->hold;
502     }
503   }
504   else if (IsUser(cptr)) {
505     ServerStats->is_cl++;
506     ServerStats->is_cbs += cptr->sendB;
507     ServerStats->is_cbr += cptr->receiveB;
508     ServerStats->is_cks += cptr->sendK;
509     ServerStats->is_ckr += cptr->receiveK;
510     ServerStats->is_cti += CurrentTime - cptr->firsttime;
511     if (ServerStats->is_cbs > 1023) {
512       ServerStats->is_cks += (ServerStats->is_cbs >> 10);
513       ServerStats->is_cbs &= 0x3ff;
514     }
515     if (ServerStats->is_cbr > 1023) {
516       ServerStats->is_ckr += (ServerStats->is_cbr >> 10);
517       ServerStats->is_cbr &= 0x3ff;
518     }
519   }
520   else
521     ServerStats->is_ni++;
522
523   if (-1 < cptr->fd) {
524     flush_connections(cptr);
525     LocalClientArray[cptr->fd] = 0;
526     close(cptr->fd);
527     cptr->fd = -1;
528   }
529   cptr->flags |= FLAGS_DEADSOCKET;
530
531   DBufClear(&cptr->sendQ);
532   DBufClear(&cptr->recvQ);
533   memset(cptr->passwd, 0, sizeof(cptr->passwd));
534   set_snomask(cptr, 0, SNO_SET);
535
536   det_confs_butmask(cptr, 0);
537
538   if (cptr->listener) {
539     release_listener(cptr->listener);
540     cptr->listener = 0;
541   }
542
543   for ( ; HighestFd > 0; --HighestFd) {
544     if (LocalClientArray[HighestFd])
545       break;
546   }
547 }
548
549 int net_close_unregistered_connections(struct Client* source)
550 {
551   int            i;
552   struct Client* cptr;
553   int            count = 0;
554   assert(0 != source);
555
556   for (i = HighestFd; i > 0; --i) {
557     if ((cptr = LocalClientArray[i]) && !IsRegistered(cptr)) {
558       sendto_one(source, rpl_str(RPL_CLOSING), me.name, source->name,
559                  get_client_name(source, HIDE_IP), cptr->status);
560       exit_client(source, cptr, &me, "Oper Closing");
561       ++count;
562     }
563   }
564   return count;
565 }
566
567 /*
568  * Creates a client which has just connected to us on the given fd.
569  * The sockhost field is initialized with the ip# of the host.
570  * The client is not added to the linked list of clients, it is
571  * passed off to the auth handler for dns and ident queries.
572  */
573 void add_connection(struct Listener* listener, int fd)
574 {
575   struct sockaddr_in addr;
576   struct Client*     new_client;
577   time_t             next_target = 0;
578   const char* const throttle_message =
579          "ERROR: Your host is trying to (re)connect too fast -- throttled\r\n";
580        /* 12345678901234567890123456789012345679012345678901234567890123456 */
581   
582   assert(0 != listener);
583   /*
584    * Removed preliminary access check. Full check is performed in
585    * m_server and m_user instead. Also connection time out help to
586    * get rid of unwanted connections.
587    */
588   if (!os_get_peername(fd, &addr) || !os_set_nonblocking(fd)) {
589     ++ServerStats->is_ref;
590     close(fd);
591     return;
592   }
593   /*
594    * XXX - do we really want to do this? is it needed?
595    */
596   os_disable_options(fd);
597
598   /*
599    * Add this local client to the IPcheck registry.
600    * If it is a connection to a user port and if the site has been throttled,
601    * reject the user.
602    */
603   if (!IPcheck_local_connect(addr.sin_addr, &next_target) && !listener->server) {
604     ++ServerStats->is_ref;
605     /*
606      * strlen(throttle_message) == 66
607      */
608     send(fd, throttle_message, 66, 0);
609     close(fd);
610     return;
611   }
612
613   new_client = make_client(NULL,
614       (listener->server) ? STAT_UNKNOWN_SERVER : STAT_UNKNOWN_USER);
615   /*
616    * Copy ascii address to 'sockhost' just in case. Then we
617    * have something valid to put into error messages...
618    */
619   ircd_ntoa_r(new_client->sock_ip, (const char*) &addr.sin_addr);   
620   strcpy(new_client->sockhost, new_client->sock_ip);
621   new_client->ip.s_addr = addr.sin_addr.s_addr;
622   new_client->port      = ntohs(addr.sin_port);
623
624   if (next_target)
625     new_client->nexttarget = next_target;
626
627   new_client->fd = fd;
628
629   if (!listener->server)
630     SetIPChecked(new_client);
631   new_client->listener = listener;
632   ++listener->ref_count;
633
634   Count_newunknown(UserStats);
635   /*
636    * if we've made it this far we can put the client on the auth query pile
637    */
638   start_auth(new_client);
639 }
640
641 /*
642  * read_packet
643  *
644  * Read a 'packet' of data from a connection and process it.  Read in 8k
645  * chunks to give a better performance rating (for server connections).
646  * Do some tricky stuff for client connections to make sure they don't do
647  * any flooding >:-) -avalon
648  */
649 static int read_packet(struct Client *cptr, int socket_ready)
650 {
651   unsigned int dolen = 0;
652   unsigned int length = 0;
653
654   if (socket_ready && !(IsUser(cptr) && DBufLength(&cptr->recvQ) > CLIENT_FLOOD)) {
655     switch (os_recv_nonb(cptr->fd, readbuf, sizeof(readbuf), &length)) {
656     case IO_SUCCESS:
657       if (length) {
658         cptr->lasttime = CurrentTime;
659         if (cptr->lasttime > cptr->since)
660           cptr->since = cptr->lasttime;
661         cptr->flags &= ~(FLAGS_PINGSENT | FLAGS_NONL);
662       }
663       break;
664     case IO_BLOCKED:
665       break;
666     case IO_FAILURE:
667       cptr->error = errno;
668       /* cptr->flags |= FLAGS_DEADSOCKET; */
669       return 0;
670     }
671   }
672
673   /*
674    * For server connections, we process as many as we can without
675    * worrying about the time of day or anything :)
676    */
677   if (length > 0 && IsServer(cptr)) {
678     return server_dopacket(cptr, readbuf, length);
679   }
680   else {
681     /*
682      * Before we even think of parsing what we just read, stick
683      * it on the end of the receive queue and do it when its
684      * turn comes around.
685      */
686     if (length > 0 && 0 == dbuf_put(&cptr->recvQ, readbuf, length)) {
687       return exit_client(cptr, cptr, &me, "dbuf_put fail");
688     }
689 #ifndef NOFLOODCONTROL
690     /*
691      * XXX - cptr will always be a user or unregistered
692      */
693     if (IsUser(cptr) && DBufLength(&cptr->recvQ) > CLIENT_FLOOD)
694       return exit_client(cptr, cptr, &me, "Excess Flood");
695
696     while (DBufLength(&cptr->recvQ) && !NoNewLine(cptr) && 
697            (IsTrusted(cptr) || cptr->since - CurrentTime < 10))
698 #else
699     while (DBufLength(&cptr->recvQ) && !NoNewLine(cptr))
700 #endif
701     {
702       /*
703        * If it has become registered as a Server
704        * then skip the per-message parsing below.
705        */
706       if (IsServer(cptr)) {
707         dolen = dbuf_get(&cptr->recvQ, readbuf, sizeof(readbuf));
708         return (dolen) ? server_dopacket(cptr, readbuf, dolen) : 1;
709       }
710       dolen = dbuf_getmsg(&cptr->recvQ, cptr->buffer, BUFSIZE);
711       /*
712        * Devious looking...whats it do ? well..if a client
713        * sends a *long* message without any CR or LF, then
714        * dbuf_getmsg fails and we pull it out using this
715        * loop which just gets the next 512 bytes and then
716        * deletes the rest of the buffer contents.
717        * -avalon
718        */
719       if (0 == dolen) {
720         if (DBufLength(&cptr->recvQ) < 510)
721           cptr->flags |= FLAGS_NONL;
722         else
723           DBufClear(&cptr->recvQ);
724       }
725       else if (CPTR_KILLED == client_dopacket(cptr, dolen))
726         return CPTR_KILLED;
727     }
728   }
729   return 1;
730 }
731
732 static int on_write_unblocked(struct Client* cptr)
733 {
734   /*
735    *  ...room for writing, empty some queue then...
736    */
737   cptr->flags &= ~FLAGS_BLOCKED;
738   if (IsConnecting(cptr)) {
739     if (!completed_connection(cptr))
740       return 0;
741   }
742   else if (cptr->listing && DBufLength(&cptr->sendQ) < 2048)
743     list_next_channels(cptr, 64);
744   send_queued(cptr);
745   return 1;
746 }
747
748 /*
749  * Select / Poll Read Algorithm for ircd
750  *
751  * We need to check the file descriptors for all the different types
752  * of things that use them, so check for reads on everything but connects
753  * and writes on connects and descriptors that are blocked
754  *
755  * for each (client in local) {
756  *   if (not connecting)
757  *     check for read;
758  *   if (connecting or blocked)
759  *     check for write;
760  * }
761  * wait for activity;
762  *
763  * for each (client in local) {
764  *   if (there are descriptors to check) {
765  *     if (write activity)
766  *       send data;
767  *     if (read activity)
768  *       read data;
769  *   }
770  *   process data read;
771  * }
772  * Note we must always process data read whether or not there has been
773  * read activity or file descriptors set, since data is buffered by the client.
774  */
775
776
777 #ifdef USE_POLL
778
779 /*
780  * poll macros
781  */
782 #if defined(POLLMSG) && defined(POLLIN) && defined(POLLRDNORM)
783 #  define POLLREADFLAGS (POLLMSG|POLLIN|POLLRDNORM)
784 #else
785 #  if defined(POLLIN) && defined(POLLRDNORM)
786 #    define POLLREADFLAGS (POLLIN|POLLRDNORM)
787 #  else
788 #    if defined(POLLIN)
789 #      define POLLREADFLAGS POLLIN
790 #    else
791 #      if defined(POLLRDNORM)
792 #        define POLLREADFLAGS POLLRDNORM
793 #      endif
794 #    endif
795 #  endif
796 #endif
797
798 #if defined(POLLOUT) && defined(POLLWRNORM)
799 #define POLLWRITEFLAGS (POLLOUT|POLLWRNORM)
800 #else
801 #  if defined(POLLOUT)
802 #    define POLLWRITEFLAGS POLLOUT
803 #  else
804 #    if defined(POLLWRNORM)
805 #      define POLLWRITEFLAGS POLLWRNORM
806 #    endif
807 #  endif
808 #endif
809
810 #ifdef POLLHUP
811 #define POLLERRORS (POLLHUP|POLLERR)
812 #else
813 #define POLLERRORS POLLERR
814 #endif
815
816 /*
817  * NOTE: pfd and pfd_count are local variable names in read_message
818  */
819 #define PFD_SETR(xfd) \
820   do { CHECK_ADD_PFD(xfd) pfd->events |= POLLREADFLAGS; } while(0)
821 #define PFD_SETW(xfd) \
822   do { CHECK_ADD_PFD(xfd) pfd->events |= POLLWRITEFLAGS; } while(0)
823
824 #define CHECK_ADD_PFD(xfd) \
825   if (pfd->fd != xfd) { \
826     pfd = &poll_fds[pfd_count++]; \
827     poll_fds[pfd_count].fd = -1; \
828     pfd->fd = xfd; \
829     pfd->events = 0; \
830   }
831
832 /*
833  * Check all connections for new connections and input data that is to be
834  * processed. Also check for connections with data queued and whether we can
835  * write it out.
836  *
837  * Don't ever use ZERO for `delay', unless you mean to poll and then
838  * you have to have sleep/wait somewhere else in the code.--msa
839  */
840 int read_message(time_t delay)
841 {
842   struct pollfd poll_fds[MAXCONNECTIONS + 1];
843   struct Client*      cptr;
844   struct Listener*    listener   = 0;
845   struct AuthRequest* auth       = 0;
846   struct AuthRequest* auth_next  = 0;
847   struct UPing*       uping      = 0;
848   struct UPing*       uping_next = 0;
849   time_t delay2 = delay;
850   int nfds;
851   int length;
852   int i;
853   int res = 0;
854   int pfd_count;
855   struct pollfd* pfd;
856   struct pollfd* res_pfd;
857   struct pollfd* uping_pfd;
858   int read_ready;
859   int write_ready;
860
861   unsigned int timeout;
862
863   for ( ; ; ) {
864     pfd_count = 0;
865     pfd = poll_fds;
866     res_pfd = 0;
867     uping_pfd = 0;
868     pfd->fd = -1;
869
870     if (-1 < ResolverFileDescriptor) {
871       PFD_SETR(ResolverFileDescriptor);
872       res_pfd = pfd;
873     }
874     if (-1 < UPingFileDescriptor) {
875       PFD_SETR(UPingFileDescriptor);
876       uping_pfd = pfd;
877     }
878     /*
879      * add uping descriptors
880      */
881     for (uping = uping_begin(); uping; uping = uping_next) {
882       uping_next = uping->next;
883       if (uping->active) {
884         delay2 = 1;
885        if (uping->lastsent && CurrentTime > uping->timeout) {
886           uping_end(uping);
887           continue;
888         }
889         uping->index = pfd_count;
890         PFD_SETR(uping->fd);
891       }
892     }
893     /*
894      * add auth file descriptors
895      */
896     for (auth = AuthPollList; auth; auth = auth->next) {
897       assert(-1 < auth->fd);
898       auth->index = pfd_count;
899       if (IsAuthConnect(auth))
900         PFD_SETW(auth->fd);
901       else
902         PFD_SETR(auth->fd);
903     }
904     /*
905      * add listener file descriptors
906      */    
907     for (listener = ListenerPollList; listener; listener = listener->next) {
908       assert(-1 < listener->fd);
909       /*
910        * pfd_count is incremented by PFD_SETR so we need to save the 
911        * index first 
912        */
913       listener->index = pfd_count;
914       PFD_SETR(listener->fd);
915     }
916
917     for (i = HighestFd; -1 < i; --i) {
918       if ((cptr = LocalClientArray[i])) {
919
920         if (DBufLength(&cptr->recvQ))
921           delay2 = 1;
922         if (DBufLength(&cptr->recvQ) < 4088 || IsServer(cptr)) {
923           PFD_SETR(i);
924         }
925         if (DBufLength(&cptr->sendQ) || IsConnecting(cptr) ||
926             (cptr->listing && DBufLength(&cptr->sendQ) < 2048)) {
927           PFD_SETW(i);
928         }
929       }
930     }
931
932     Debug((DEBUG_INFO, "poll: %d %d", delay, delay2));
933
934     timeout = (IRCD_MIN(delay2, delay)) * 1000;
935
936     nfds = poll(poll_fds, pfd_count, timeout);
937
938     CurrentTime = time(0);
939     if (-1 < nfds)
940       break;
941
942     if (EINTR == errno)
943       return -1;
944     report_error(POLL_ERROR_MSG, me.name, errno);
945     ++res;
946     if (res > 5)
947       server_restart("too many poll errors");
948     sleep(1);
949     CurrentTime = time(0);
950   }
951
952   if (uping_pfd && (uping_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
953     uping_echo();
954     --nfds;
955   }
956   /*
957    * check uping replies
958    */
959   for (uping = uping_begin(); uping; uping = uping_next) {
960     uping_next = uping->next;
961     if (uping->active) {
962       assert(-1 < uping->index);
963       if (poll_fds[uping->index].revents) {
964         uping_read(uping);
965         if (0 == --nfds)
966           break;
967       }
968       else if (CurrentTime > uping->lastsent) {
969         uping->lastsent = CurrentTime;
970         uping_send(uping);
971       }
972     }
973   }
974
975   if (res_pfd && (res_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
976     resolver_read();
977     --nfds;
978   }
979   /*
980    * check auth queries
981    */
982   for (auth = AuthPollList; auth; auth = auth_next) {
983     auth_next = auth->next;
984     i = auth->index;
985     /*
986      * check for any event, we only ask for one at a time
987      */
988     if (poll_fds[i].revents) {
989       if (IsAuthConnect(auth))
990         send_auth_query(auth);
991       else
992         read_auth_reply(auth);
993       if (0 == --nfds)
994         break;
995     }
996   }
997   /*
998    * check listeners
999    */
1000   for (listener = ListenerPollList; listener; listener = listener->next) {
1001     i = listener->index;
1002     if (poll_fds[i].revents) {
1003       accept_connection(listener);
1004       if (0 == --nfds)
1005         break;
1006     }
1007   }
1008   /*
1009    * i contains the next non-auth/non-listener index, since we put the
1010    * resolver, auth and listener, file descriptors in poll_fds first,
1011    * the very next one should be the start of the clients
1012    */
1013   pfd = &poll_fds[++i];
1014
1015   for ( ; (i < pfd_count); ++i, ++pfd) {
1016     if (!(cptr = LocalClientArray[pfd->fd]))
1017       continue;
1018     read_ready = write_ready = 0;
1019
1020     if (0 < nfds && pfd->revents) {
1021       --nfds;
1022     
1023       read_ready  = pfd->revents & POLLREADFLAGS;
1024       write_ready = pfd->revents & POLLWRITEFLAGS;
1025
1026       if (pfd->revents & POLLERRORS) {
1027         if (pfd->events & POLLREADFLAGS)
1028           ++read_ready;
1029         if (pfd->events & POLLWRITEFLAGS)
1030           ++write_ready;
1031       }
1032     }
1033     if (write_ready) {
1034       if (!on_write_unblocked(cptr) || IsDead(cptr)) {
1035         const char* msg = (cptr->error) ? strerror(cptr->error) : LastDeadComment(cptr);
1036         if (!msg)
1037           msg = "Unknown error";
1038         exit_client(cptr, cptr, &me, (char*) msg);
1039         continue;
1040       }
1041     }
1042     length = 1;                 /* for fall through case */
1043     if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1044       if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1045         continue;
1046     }
1047 #if 0
1048     /* Bullshit, why would we want to flush sockets while using non-blocking?
1049      * This uses > 4% cpu! --Run */
1050     if (length > 0)
1051       flush_connections(poll_cptr[i]);
1052 #endif
1053     if (IsDead(cptr)) {
1054       const char* msg = (cptr->error) ? strerror(cptr->error) : LastDeadComment(cptr);
1055       if (!msg)
1056         msg = "Unknown error";
1057       exit_client(cptr, cptr, &me, (char*) msg);
1058       continue;
1059     }
1060     if (length > 0)
1061       continue;
1062     cptr->flags |= FLAGS_DEADSOCKET;
1063     /*
1064      * ...hmm, with non-blocking sockets we might get
1065      * here from quite valid reasons, although.. why
1066      * would select report "data available" when there
1067      * wasn't... So, this must be an error anyway...  --msa
1068      * actually, EOF occurs when read() returns 0 and
1069      * in due course, select() returns that fd as ready
1070      * for reading even though it ends up being an EOF. -avalon
1071      */
1072     Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", pfd->fd, errno, length));
1073
1074     if ((IsServer(cptr) || IsHandshake(cptr)) && cptr->error == 0 && length == 0)
1075       exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1076                       cptr->name, cptr->serv->last_error_msg);
1077     else {
1078       const char* msg = (cptr->error) ? strerror(cptr->error) : "EOF from client";
1079       if (!msg)
1080         msg = "Unknown error";
1081       exit_client_msg(cptr, cptr, &me, "Read error to %s: %s",
1082                       get_client_name(cptr, HIDE_IP), msg);
1083     }
1084   }
1085   return 0;
1086 }
1087 #else /* USE_SELECT */
1088
1089 /*
1090  * Check all connections for new connections and input data that is to be
1091  * processed. Also check for connections with data queued and whether we can
1092  * write it out.
1093  *
1094  * Don't ever use ZERO for `delay', unless you mean to poll and then
1095  * you have to have sleep/wait somewhere else in the code.--msa
1096  */
1097 int read_message(time_t delay)
1098 {
1099   struct Client*   cptr;
1100   struct Listener* listener;
1101   struct AuthRequest* auth = 0;
1102   struct AuthRequest* auth_next = 0;
1103   struct UPing*       uping;
1104   struct UPing*       uping_next;
1105   int              nfds;
1106   struct timeval   wait;
1107   time_t           delay2 = delay;
1108   unsigned int     usec = 0;
1109   int              res = 0;
1110   int              length;
1111   int              i;
1112   int              read_ready;
1113   fd_set           read_set;
1114   fd_set           write_set;
1115
1116   for ( ; ; )
1117   {
1118     FD_ZERO(&read_set);
1119     FD_ZERO(&write_set);
1120
1121     if (-1 < ResolverFileDescriptor)
1122       FD_SET(ResolverFileDescriptor, &read_set);
1123     if (-1 < UPingFileDescriptor)
1124       FD_SET(UPingFileDescriptor, &read_set);
1125     /*
1126      * set up uping file descriptors
1127      */
1128     for (uping = uping_begin(); uping; uping = uping_next) {
1129       uping_next = uping->next;
1130       if (uping->active) {
1131         delay2 = 1;
1132         if (uping->lastsent && CurrentTime > uping->timeout) {
1133           uping_end(uping);
1134           continue;
1135         }
1136         assert(-1 < uping->fd);
1137         FD_SET(uping->fd, &read_set);
1138       }
1139     }
1140     /*
1141      * set auth file descriptors
1142      */
1143     for (auth = AuthPollList; auth; auth = auth->next) {
1144       assert(-1 < auth->fd);
1145       if (IsAuthConnect(auth))
1146         FD_SET(auth->fd, &write_set);
1147       else /* if (IsAuthPending(auth)) */
1148         FD_SET(auth->fd, &read_set);
1149     }
1150     /*
1151      * set listener file descriptors
1152      */
1153     for (listener = ListenerPollList; listener; listener = listener->next) {
1154       assert(-1 < listener->fd);
1155       FD_SET(listener->fd, &read_set);
1156     }
1157
1158     for (i = HighestFd; i > -1; --i) {
1159       if ((cptr = LocalClientArray[i])) {
1160         if (DBufLength(&cptr->recvQ))
1161           delay2 = 1;
1162         if (DBufLength(&cptr->recvQ) < 4088 || IsServer(cptr))
1163           FD_SET(i, &read_set);
1164         if (DBufLength(&cptr->sendQ) || IsConnecting(cptr) ||
1165             (cptr->listing && DBufLength(&cptr->sendQ) < 2048))
1166           FD_SET(i, &write_set);
1167       }
1168     }
1169
1170     wait.tv_sec = IRCD_MIN(delay2, delay);
1171     wait.tv_usec = usec;
1172
1173     Debug((DEBUG_INFO, "select: %d %d", delay, delay2));
1174
1175     nfds = select(FD_SETSIZE, &read_set, &write_set, 0, &wait);
1176
1177     CurrentTime = time(0);
1178
1179     if (-1 < nfds)
1180       break;
1181
1182     if (errno == EINTR)
1183       return -1;
1184     report_error(SELECT_ERROR_MSG, me.name, errno);
1185     if (++res > 5)
1186       server_restart("too many select errors");
1187     sleep(1);
1188     CurrentTime = time(0);
1189   }
1190
1191   if (-1 < UPingFileDescriptor && FD_ISSET(UPingFileDescriptor, &read_set)) {
1192     uping_echo();
1193     --nfds;
1194   }
1195   for (uping = uping_begin(); uping; uping = uping_next) {
1196     uping_next = uping->next;
1197     if (uping->active) {
1198       assert(-1 < uping->fd);
1199       if (FD_ISSET(uping->fd, &read_set)) {
1200         uping_read(uping);
1201         if (0 == --nfds)
1202           break;
1203       }
1204       else if (CurrentTime > uping->lastsent) {
1205         uping->lastsent = CurrentTime;
1206         uping_send(uping);
1207       }
1208     }
1209   }
1210   if (-1 < ResolverFileDescriptor && FD_ISSET(ResolverFileDescriptor, &read_set)) {
1211     resolver_read();
1212     --nfds;
1213   }
1214   /*
1215    * Check fd sets for the auth fd's (if set and valid!) first
1216    * because these can not be processed using the normal loops below.
1217    * -avalon
1218    */
1219   for (auth = AuthPollList; auth; auth = auth_next) {
1220     auth_next = auth->next;
1221     assert(-1 < auth->fd);
1222     if (IsAuthConnect(auth) && FD_ISSET(auth->fd, &write_set)) {
1223       send_auth_query(auth);
1224       if (0 == --nfds)
1225         break;
1226     }
1227     else if (FD_ISSET(auth->fd, &read_set)) {
1228       read_auth_reply(auth);
1229       if (0 == --nfds)
1230         break;
1231     }
1232   }
1233   /*
1234    * next accept connections from active listeners
1235    */
1236   for (listener = ListenerPollList; listener; listener = listener->next) {
1237     assert(-1 < listener->fd);
1238     if (0 < nfds && FD_ISSET(listener->fd, &read_set))
1239       accept_connection(listener);
1240   } 
1241
1242   for (i = HighestFd; -1 < i; --i) {
1243     if (!(cptr = LocalClientArray[i]))
1244       continue;
1245     read_ready = 0;
1246     if (0 < nfds) {
1247       if (FD_ISSET(i, &write_set)) {
1248         --nfds;
1249         if (!on_write_unblocked(cptr) || IsDead(cptr)) {
1250           const char* msg = (cptr->error) ? strerror(cptr->error) : LastDeadComment(cptr);
1251           if (!msg)
1252             msg = "Unknown error";
1253           if (FD_ISSET(i, &read_set))
1254             --nfds;
1255           exit_client(cptr, cptr, &me, msg);
1256           continue;
1257         }
1258       }
1259       if ((read_ready = FD_ISSET(i, &read_set)))
1260         --nfds;
1261     }
1262     length = 1;                 /* for fall through case */
1263     if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1264       if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1265         continue;
1266     }
1267 #if 0
1268     /* Bullshit, why would we want to flush sockets while using non-blocking?
1269      * This uses > 4% cpu! --Run */
1270     if (length > 0)
1271       flush_connections(LocalClientArray[i]);
1272 #endif
1273     if (IsDead(cptr)) {
1274       const char* msg = (cptr->error) ? strerror(cptr->error) : LastDeadComment(cptr);
1275       if (!msg)
1276         msg = "Unknown error";
1277       exit_client(cptr, cptr, &me, msg);
1278       continue;
1279     }
1280     if (length > 0)
1281       continue;
1282
1283     /*
1284      * ...hmm, with non-blocking sockets we might get
1285      * here from quite valid reasons, although.. why
1286      * would select report "data available" when there
1287      * wasn't... So, this must be an error anyway...  --msa
1288      * actually, EOF occurs when read() returns 0 and
1289      * in due course, select() returns that fd as ready
1290      * for reading even though it ends up being an EOF. -avalon
1291      */
1292     Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", i, cptr->error, length));
1293
1294     if ((IsServer(cptr) || IsHandshake(cptr)) && cptr->error == 0 && length == 0)
1295       exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1296                       cptr->name, cptr->serv->last_error_msg);
1297     else {
1298       const char* msg = (cptr->error) ? strerror(cptr->error) : "EOF from client";
1299       if (!msg)
1300         msg = "Unknown error";
1301       exit_client_msg(cptr, cptr, &me, "Read error to %s: %s",
1302                       get_client_name(cptr, HIDE_IP), msg);
1303     }
1304   }
1305   return 0;
1306 }
1307
1308 #endif /* USE_SELECT */
1309
1310 /*
1311  * connect_server - start or complete a connection to another server
1312  * returns true (1) if successful, false (0) otherwise
1313  *
1314  * aconf must point to a valid C:line
1315  * m_connect            calls this with a valid by client and a null reply
1316  * try_connections      calls this with a null by client, and a null reply
1317  * connect_dns_callback call this with a null by client, and a valid reply
1318  *
1319  * XXX - if this comes from an m_connect message and a dns query needs to
1320  * be done, we loose the information about who started the connection and
1321  * it's considered an auto connect.
1322  */
1323 int connect_server(struct ConfItem* aconf, struct Client* by,
1324                    struct DNSReply* reply)
1325 {
1326   struct Client*   cptr = 0;
1327   assert(0 != aconf);
1328
1329   if (aconf->dns_pending) {
1330     sendto_ops("Server %s connect DNS pending");
1331     return 0;
1332   }
1333   Debug((DEBUG_NOTICE, "Connect to %s[@%s]", aconf->name,
1334          ircd_ntoa((const char*) &aconf->ipnum)));
1335
1336   if ((cptr = FindClient(aconf->name))) {
1337     if (IsServer(cptr) || IsMe(cptr)) {
1338       sendto_ops("Server %s already present from %s", 
1339                  aconf->name, cptr->from->name);
1340       if (by && IsUser(by) && !MyUser(by)) {
1341         sendto_one(by, "%s NOTICE %s%s :Server %s already present from %s",
1342                      NumServ(&me), NumNick(by), aconf->name, cptr->from->name);
1343       }
1344       return 0;
1345     }
1346     else if (IsHandshake(cptr) || IsConnecting(cptr)) {
1347       if (by && IsUser(by)) {
1348         if (MyUser(by))
1349           sendto_one(by, ":%s NOTICE %s :Connection to %s already in progress",
1350                      me.name, by->name, cptr->name);
1351         else
1352           sendto_one(by, "%s NOTICE %s%s :Connection to %s already in progress",
1353                      NumServ(&me), NumNick(by), cptr->name);
1354       }
1355       return 0;
1356     }
1357   }
1358   /*
1359    * If we dont know the IP# for this host and itis a hostname and
1360    * not a ip# string, then try and find the appropriate host record.
1361    */
1362   if (INADDR_NONE == aconf->ipnum.s_addr) {
1363     char buf[HOSTLEN + 1];
1364     assert(0 == reply);
1365     if (INADDR_NONE == (aconf->ipnum.s_addr = inet_addr(aconf->host))) {
1366       struct DNSQuery  query;
1367
1368       query.vptr     = aconf;
1369       query.callback = connect_dns_callback;
1370       host_from_uh(buf, aconf->host, HOSTLEN);
1371       buf[HOSTLEN] = '\0';
1372
1373       reply = gethost_byname(buf, &query);
1374
1375       if (!reply) {
1376         aconf->dns_pending = 1;
1377         return 0;
1378       }
1379       memcpy(&aconf->ipnum, reply->hp->h_addr, sizeof(struct in_addr));
1380     }
1381   }
1382   cptr = make_client(NULL, STAT_UNKNOWN_SERVER);
1383   if (reply)
1384     ++reply->ref_count;
1385   cptr->dns_reply = reply;
1386
1387   /*
1388    * Copy these in so we have something for error detection.
1389    */
1390   ircd_strncpy(cptr->name, aconf->name, HOSTLEN);
1391   ircd_strncpy(cptr->sockhost, aconf->host, HOSTLEN);
1392
1393   /*
1394    * Attach config entries to client here rather than in
1395    * completed_connection. This to avoid null pointer references
1396    */
1397   attach_confs_byhost(cptr, aconf->host, CONF_SERVER);
1398
1399   if (!find_conf_byhost(cptr->confs, aconf->host, CONF_SERVER)) {
1400     sendto_ops("Host %s is not enabled for connecting: no C-line", aconf->name);
1401     if (by && IsUser(by) && !MyUser(by)) {
1402       sendto_one(by, "%s NOTICE %s%s :Connect to host %s failed: no C-line",
1403                  NumServ(&me), NumNick(by), aconf->name);
1404     }
1405     det_confs_butmask(cptr, 0);
1406     free_client(cptr);
1407     return 0;
1408   }
1409   /*
1410    * attempt to connect to the server in the conf line
1411    */
1412   if (!connect_inet(aconf, cptr)) {
1413     if (by && IsUser(by) && !MyUser(by)) {
1414       sendto_one(by, "%s NOTICE %s%s :Couldn't connect to %s",
1415                  NumServ(&me), NumNick(by), cptr->name);
1416     }
1417     det_confs_butmask(cptr, 0);
1418     free_client(cptr);
1419     return 0;
1420   }
1421   /*
1422    * NOTE: if we're here we have a valid C:Line and the client should
1423    * have started the connection and stored the remote address/port and
1424    * ip address name in itself
1425    *
1426    * The socket has been connected or connect is in progress.
1427    */
1428   make_server(cptr);
1429   if (by && IsUser(by)) {
1430     sprintf_irc(cptr->serv->by, "%s%s", NumNick(by));
1431     assert(0 == cptr->serv->user);
1432     cptr->serv->user = by->user;
1433     by->user->refcnt++;
1434   }
1435   else {
1436     *cptr->serv->by = '\0';
1437     /* strcpy(cptr->serv->by, "Auto"); */
1438   }
1439   cptr->serv->up = &me;
1440   SetConnecting(cptr);
1441
1442   if (cptr->fd > HighestFd)
1443     HighestFd = cptr->fd;
1444   LocalClientArray[cptr->fd] = cptr;
1445
1446   Count_newunknown(UserStats);
1447   add_client_to_list(cptr);
1448   hAddClient(cptr);
1449   nextping = CurrentTime;
1450
1451   return 1;
1452 }
1453
1454 /*
1455  * Setup local socket structure to use for binding to.
1456  */
1457 void init_virtual_host(const struct ConfItem* conf)
1458 {
1459   assert(0 != conf);
1460
1461   memset(&VirtualHost, 0, sizeof(VirtualHost));
1462   VirtualHost.sin_family = AF_INET;
1463   VirtualHost.sin_addr.s_addr = INADDR_ANY;
1464
1465   if (EmptyString(conf->passwd) || 0 == strcmp(conf->passwd, "*"))
1466     return;
1467   VirtualHost.sin_addr.s_addr = inet_addr(conf->passwd);
1468
1469   if (INADDR_NONE == VirtualHost.sin_addr.s_addr)
1470     VirtualHost.sin_addr.s_addr = INADDR_ANY;
1471 }  
1472
1473 /*
1474  * Find the real hostname for the host running the server (or one which
1475  * matches the server's name) and its primary IP#.  Hostname is stored
1476  * in the client structure passed as a pointer.
1477  */
1478 int init_server_identity()
1479 {
1480   struct ConfItem* conf = find_me();
1481
1482   if (!conf || EmptyString(conf->host))
1483     return 0;
1484
1485   ircd_strncpy(me.name, conf->host, HOSTLEN);
1486
1487   init_virtual_host(conf);
1488   return 1;
1489 }
1490
1491