Author: Bleep <tomh@inxpress.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    * Add this local client to the IPcheck registry.
595    * If it is a connection to a user port and if the site has been throttled,
596    * reject the user.
597    */
598   if (!IPcheck_local_connect(addr.sin_addr, &next_target) && !listener->server) {
599     ++ServerStats->is_ref;
600     /*
601      * strlen(throttle_message) == 66
602      */
603     send(fd, throttle_message, 66, 0);
604     close(fd);
605     return;
606   }
607
608   new_client = make_client(NULL,
609       (listener->server) ? STAT_UNKNOWN_SERVER : STAT_UNKNOWN_USER);
610   /*
611    * Copy ascii address to 'sockhost' just in case. Then we
612    * have something valid to put into error messages...
613    */
614   ircd_ntoa_r(new_client->sock_ip, (const char*) &addr.sin_addr);   
615   strcpy(new_client->sockhost, new_client->sock_ip);
616   new_client->ip.s_addr = addr.sin_addr.s_addr;
617   new_client->port      = ntohs(addr.sin_port);
618
619   if (next_target)
620     new_client->nexttarget = next_target;
621
622   new_client->fd = fd;
623
624   if (!listener->server)
625     SetIPChecked(new_client);
626   new_client->listener = listener;
627   ++listener->ref_count;
628
629   Count_newunknown(UserStats);
630   /*
631    * if we've made it this far we can put the client on the auth query pile
632    */
633   start_auth(new_client);
634 }
635
636 /*
637  * read_packet
638  *
639  * Read a 'packet' of data from a connection and process it.  Read in 8k
640  * chunks to give a better performance rating (for server connections).
641  * Do some tricky stuff for client connections to make sure they don't do
642  * any flooding >:-) -avalon
643  */
644 static int read_packet(struct Client *cptr, int socket_ready)
645 {
646   unsigned int dolen = 0;
647   unsigned int length = 0;
648
649   if (socket_ready && !(IsUser(cptr) && DBufLength(&cptr->recvQ) > CLIENT_FLOOD)) {
650     switch (os_recv_nonb(cptr->fd, readbuf, sizeof(readbuf), &length)) {
651     case IO_SUCCESS:
652       if (length) {
653         cptr->lasttime = CurrentTime;
654         if (cptr->lasttime > cptr->since)
655           cptr->since = cptr->lasttime;
656         cptr->flags &= ~(FLAGS_PINGSENT | FLAGS_NONL);
657       }
658       break;
659     case IO_BLOCKED:
660       break;
661     case IO_FAILURE:
662       cptr->error = errno;
663       /* cptr->flags |= FLAGS_DEADSOCKET; */
664       return 0;
665     }
666   }
667
668   /*
669    * For server connections, we process as many as we can without
670    * worrying about the time of day or anything :)
671    */
672   if (length > 0 && IsServer(cptr)) {
673     return server_dopacket(cptr, readbuf, length);
674   }
675   else {
676     /*
677      * Before we even think of parsing what we just read, stick
678      * it on the end of the receive queue and do it when its
679      * turn comes around.
680      */
681     if (length > 0 && 0 == dbuf_put(&cptr->recvQ, readbuf, length)) {
682       return exit_client(cptr, cptr, &me, "dbuf_put fail");
683     }
684 #ifndef NOFLOODCONTROL
685     /*
686      * XXX - cptr will always be a user or unregistered
687      */
688     if (IsUser(cptr) && DBufLength(&cptr->recvQ) > CLIENT_FLOOD)
689       return exit_client(cptr, cptr, &me, "Excess Flood");
690
691     while (DBufLength(&cptr->recvQ) && !NoNewLine(cptr) && 
692            (IsTrusted(cptr) || cptr->since - CurrentTime < 10))
693 #else
694     while (DBufLength(&cptr->recvQ) && !NoNewLine(cptr))
695 #endif
696     {
697       /*
698        * If it has become registered as a Server
699        * then skip the per-message parsing below.
700        */
701       if (IsServer(cptr)) {
702         dolen = dbuf_get(&cptr->recvQ, readbuf, sizeof(readbuf));
703         return (dolen) ? server_dopacket(cptr, readbuf, dolen) : 1;
704       }
705       dolen = dbuf_getmsg(&cptr->recvQ, cptr->buffer, BUFSIZE);
706       /*
707        * Devious looking...whats it do ? well..if a client
708        * sends a *long* message without any CR or LF, then
709        * dbuf_getmsg fails and we pull it out using this
710        * loop which just gets the next 512 bytes and then
711        * deletes the rest of the buffer contents.
712        * -avalon
713        */
714       if (0 == dolen) {
715         if (DBufLength(&cptr->recvQ) < 510)
716           cptr->flags |= FLAGS_NONL;
717         else
718           DBufClear(&cptr->recvQ);
719       }
720       else if (CPTR_KILLED == client_dopacket(cptr, dolen))
721         return CPTR_KILLED;
722     }
723   }
724   return 1;
725 }
726
727 static int on_write_unblocked(struct Client* cptr)
728 {
729   /*
730    *  ...room for writing, empty some queue then...
731    */
732   cptr->flags &= ~FLAGS_BLOCKED;
733   if (IsConnecting(cptr)) {
734     if (!completed_connection(cptr))
735       return 0;
736   }
737   else if (cptr->listing && DBufLength(&cptr->sendQ) < 2048)
738     list_next_channels(cptr, 64);
739   send_queued(cptr);
740   return 1;
741 }
742
743 /*
744  * Select / Poll Read Algorithm for ircd
745  *
746  * We need to check the file descriptors for all the different types
747  * of things that use them, so check for reads on everything but connects
748  * and writes on connects and descriptors that are blocked
749  *
750  * for each (client in local) {
751  *   if (not connecting)
752  *     check for read;
753  *   if (connecting or blocked)
754  *     check for write;
755  * }
756  * wait for activity;
757  *
758  * for each (client in local) {
759  *   if (there are descriptors to check) {
760  *     if (write activity)
761  *       send data;
762  *     if (read activity)
763  *       read data;
764  *   }
765  *   process data read;
766  * }
767  * Note we must always process data read whether or not there has been
768  * read activity or file descriptors set, since data is buffered by the client.
769  */
770
771
772 #ifdef USE_POLL
773
774 /*
775  * poll macros
776  */
777 #if defined(POLLMSG) && defined(POLLIN) && defined(POLLRDNORM)
778 #  define POLLREADFLAGS (POLLMSG|POLLIN|POLLRDNORM)
779 #else
780 #  if defined(POLLIN) && defined(POLLRDNORM)
781 #    define POLLREADFLAGS (POLLIN|POLLRDNORM)
782 #  else
783 #    if defined(POLLIN)
784 #      define POLLREADFLAGS POLLIN
785 #    else
786 #      if defined(POLLRDNORM)
787 #        define POLLREADFLAGS POLLRDNORM
788 #      endif
789 #    endif
790 #  endif
791 #endif
792
793 #if defined(POLLOUT) && defined(POLLWRNORM)
794 #define POLLWRITEFLAGS (POLLOUT|POLLWRNORM)
795 #else
796 #  if defined(POLLOUT)
797 #    define POLLWRITEFLAGS POLLOUT
798 #  else
799 #    if defined(POLLWRNORM)
800 #      define POLLWRITEFLAGS POLLWRNORM
801 #    endif
802 #  endif
803 #endif
804
805 #ifdef POLLHUP
806 #define POLLERRORS (POLLHUP|POLLERR)
807 #else
808 #define POLLERRORS POLLERR
809 #endif
810
811 /*
812  * NOTE: pfd and pfd_count are local variable names in read_message
813  */
814 #define PFD_SETR(xfd) \
815   do { CHECK_ADD_PFD(xfd) pfd->events |= POLLREADFLAGS; } while(0)
816 #define PFD_SETW(xfd) \
817   do { CHECK_ADD_PFD(xfd) pfd->events |= POLLWRITEFLAGS; } while(0)
818
819 #define CHECK_ADD_PFD(xfd) \
820   if (pfd->fd != xfd) { \
821     pfd = &poll_fds[pfd_count++]; \
822     poll_fds[pfd_count].fd = -1; \
823     pfd->fd = xfd; \
824     pfd->events = 0; \
825   }
826
827 /*
828  * Check all connections for new connections and input data that is to be
829  * processed. Also check for connections with data queued and whether we can
830  * write it out.
831  *
832  * Don't ever use ZERO for `delay', unless you mean to poll and then
833  * you have to have sleep/wait somewhere else in the code.--msa
834  */
835 int read_message(time_t delay)
836 {
837   struct pollfd poll_fds[MAXCONNECTIONS + 1];
838   struct Client*      cptr;
839   struct Listener*    listener   = 0;
840   struct AuthRequest* auth       = 0;
841   struct AuthRequest* auth_next  = 0;
842   struct UPing*       uping      = 0;
843   struct UPing*       uping_next = 0;
844   time_t delay2 = delay;
845   int nfds;
846   int length;
847   int i;
848   int res = 0;
849   int pfd_count;
850   struct pollfd* pfd;
851   struct pollfd* res_pfd;
852   struct pollfd* uping_pfd;
853   int read_ready;
854   int write_ready;
855
856   unsigned int timeout;
857
858   for ( ; ; ) {
859     pfd_count = 0;
860     pfd = poll_fds;
861     res_pfd = 0;
862     uping_pfd = 0;
863     pfd->fd = -1;
864
865     if (-1 < ResolverFileDescriptor) {
866       PFD_SETR(ResolverFileDescriptor);
867       res_pfd = pfd;
868     }
869     if (-1 < UPingFileDescriptor) {
870       PFD_SETR(UPingFileDescriptor);
871       uping_pfd = pfd;
872     }
873     /*
874      * add uping descriptors
875      */
876     for (uping = uping_begin(); uping; uping = uping_next) {
877       uping_next = uping->next;
878       if (uping->active) {
879         delay2 = 1;
880        if (uping->lastsent && CurrentTime > uping->timeout) {
881           uping_end(uping);
882           continue;
883         }
884         uping->index = pfd_count;
885         PFD_SETR(uping->fd);
886       }
887     }
888     /*
889      * add auth file descriptors
890      */
891     for (auth = AuthPollList; auth; auth = auth->next) {
892       assert(-1 < auth->fd);
893       auth->index = pfd_count;
894       if (IsAuthConnect(auth))
895         PFD_SETW(auth->fd);
896       else
897         PFD_SETR(auth->fd);
898     }
899     /*
900      * add listener file descriptors
901      */    
902     for (listener = ListenerPollList; listener; listener = listener->next) {
903       assert(-1 < listener->fd);
904       /*
905        * pfd_count is incremented by PFD_SETR so we need to save the 
906        * index first 
907        */
908       listener->index = pfd_count;
909       PFD_SETR(listener->fd);
910     }
911
912     for (i = HighestFd; -1 < i; --i) {
913       if ((cptr = LocalClientArray[i])) {
914
915         if (DBufLength(&cptr->recvQ))
916           delay2 = 1;
917         if (DBufLength(&cptr->recvQ) < 4088 || IsServer(cptr)) {
918           PFD_SETR(i);
919         }
920         if (DBufLength(&cptr->sendQ) || IsConnecting(cptr) ||
921             (cptr->listing && DBufLength(&cptr->sendQ) < 2048)) {
922           PFD_SETW(i);
923         }
924       }
925     }
926
927     Debug((DEBUG_INFO, "poll: %d %d", delay, delay2));
928
929     timeout = (IRCD_MIN(delay2, delay)) * 1000;
930
931     nfds = poll(poll_fds, pfd_count, timeout);
932
933     CurrentTime = time(0);
934     if (-1 < nfds)
935       break;
936
937     if (EINTR == errno)
938       return -1;
939     report_error(POLL_ERROR_MSG, me.name, errno);
940     ++res;
941     if (res > 5)
942       server_restart("too many poll errors");
943     sleep(1);
944     CurrentTime = time(0);
945   }
946
947   if (uping_pfd && (uping_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
948     uping_echo();
949     --nfds;
950   }
951   /*
952    * check uping replies
953    */
954   for (uping = uping_begin(); uping; uping = uping_next) {
955     uping_next = uping->next;
956     if (uping->active) {
957       assert(-1 < uping->index);
958       if (poll_fds[uping->index].revents) {
959         uping_read(uping);
960         if (0 == --nfds)
961           break;
962       }
963       else if (CurrentTime > uping->lastsent) {
964         uping->lastsent = CurrentTime;
965         uping_send(uping);
966       }
967     }
968   }
969
970   if (res_pfd && (res_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
971     resolver_read();
972     --nfds;
973   }
974   /*
975    * check auth queries
976    */
977   for (auth = AuthPollList; auth; auth = auth_next) {
978     auth_next = auth->next;
979     i = auth->index;
980     /*
981      * check for any event, we only ask for one at a time
982      */
983     if (poll_fds[i].revents) {
984       if (IsAuthConnect(auth))
985         send_auth_query(auth);
986       else
987         read_auth_reply(auth);
988       if (0 == --nfds)
989         break;
990     }
991   }
992   /*
993    * check listeners
994    */
995   for (listener = ListenerPollList; listener; listener = listener->next) {
996     i = listener->index;
997     if (poll_fds[i].revents) {
998       accept_connection(listener);
999       if (0 == --nfds)
1000         break;
1001     }
1002   }
1003   /*
1004    * i contains the next non-auth/non-listener index, since we put the
1005    * resolver, auth and listener, file descriptors in poll_fds first,
1006    * the very next one should be the start of the clients
1007    */
1008   pfd = &poll_fds[++i];
1009
1010   for ( ; (i < pfd_count); ++i, ++pfd) {
1011     if (!(cptr = LocalClientArray[pfd->fd]))
1012       continue;
1013     read_ready = write_ready = 0;
1014
1015     if (0 < nfds && pfd->revents) {
1016       --nfds;
1017     
1018       read_ready  = pfd->revents & POLLREADFLAGS;
1019       write_ready = pfd->revents & POLLWRITEFLAGS;
1020
1021       if (pfd->revents & POLLERRORS) {
1022         if (pfd->events & POLLREADFLAGS)
1023           ++read_ready;
1024         if (pfd->events & POLLWRITEFLAGS)
1025           ++write_ready;
1026       }
1027     }
1028     if (write_ready) {
1029       if (!on_write_unblocked(cptr) || IsDead(cptr)) {
1030         const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
1031         if (!msg)
1032           msg = "Unknown error";
1033         exit_client(cptr, cptr, &me, msg);
1034         continue;
1035       }
1036     }
1037     length = 1;                 /* for fall through case */
1038     if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1039       if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1040         continue;
1041     }
1042 #if 0
1043     /* Bullshit, why would we want to flush sockets while using non-blocking?
1044      * This uses > 4% cpu! --Run */
1045     if (length > 0)
1046       flush_connections(poll_cptr[i]);
1047 #endif
1048     if (IsDead(cptr)) {
1049       const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
1050       if (!msg)
1051         msg = "Unknown error";
1052       exit_client(cptr, cptr, &me, (char*) msg);
1053       continue;
1054     }
1055     if (length > 0)
1056       continue;
1057     cptr->flags |= FLAGS_DEADSOCKET;
1058     /*
1059      * ...hmm, with non-blocking sockets we might get
1060      * here from quite valid reasons, although.. why
1061      * would select report "data available" when there
1062      * wasn't... So, this must be an error anyway...  --msa
1063      * actually, EOF occurs when read() returns 0 and
1064      * in due course, select() returns that fd as ready
1065      * for reading even though it ends up being an EOF. -avalon
1066      */
1067     Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", pfd->fd, errno, length));
1068
1069     if ((IsServer(cptr) || IsHandshake(cptr)) && cptr->error == 0 && length == 0)
1070       exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1071                       cptr->name, cptr->serv->last_error_msg);
1072     else {
1073       const char* msg = (cptr->error) ? strerror(cptr->error) : "EOF from client";
1074       if (!msg)
1075         msg = "Unknown error";
1076       exit_client_msg(cptr, cptr, &me, "Read error to %s: %s",
1077                       get_client_name(cptr, HIDE_IP), msg);
1078     }
1079   }
1080   return 0;
1081 }
1082 #else /* USE_SELECT */
1083
1084 /*
1085  * Check all connections for new connections and input data that is to be
1086  * processed. Also check for connections with data queued and whether we can
1087  * write it out.
1088  *
1089  * Don't ever use ZERO for `delay', unless you mean to poll and then
1090  * you have to have sleep/wait somewhere else in the code.--msa
1091  */
1092 int read_message(time_t delay)
1093 {
1094   struct Client*   cptr;
1095   struct Listener* listener;
1096   struct AuthRequest* auth = 0;
1097   struct AuthRequest* auth_next = 0;
1098   struct UPing*       uping;
1099   struct UPing*       uping_next;
1100   int              nfds;
1101   struct timeval   wait;
1102   time_t           delay2 = delay;
1103   unsigned int     usec = 0;
1104   int              res = 0;
1105   int              length;
1106   int              i;
1107   int              read_ready;
1108   fd_set           read_set;
1109   fd_set           write_set;
1110
1111   for ( ; ; )
1112   {
1113     FD_ZERO(&read_set);
1114     FD_ZERO(&write_set);
1115
1116     if (-1 < ResolverFileDescriptor)
1117       FD_SET(ResolverFileDescriptor, &read_set);
1118     if (-1 < UPingFileDescriptor)
1119       FD_SET(UPingFileDescriptor, &read_set);
1120     /*
1121      * set up uping file descriptors
1122      */
1123     for (uping = uping_begin(); uping; uping = uping_next) {
1124       uping_next = uping->next;
1125       if (uping->active) {
1126         delay2 = 1;
1127         if (uping->lastsent && CurrentTime > uping->timeout) {
1128           uping_end(uping);
1129           continue;
1130         }
1131         assert(-1 < uping->fd);
1132         FD_SET(uping->fd, &read_set);
1133       }
1134     }
1135     /*
1136      * set auth file descriptors
1137      */
1138     for (auth = AuthPollList; auth; auth = auth->next) {
1139       assert(-1 < auth->fd);
1140       if (IsAuthConnect(auth))
1141         FD_SET(auth->fd, &write_set);
1142       else /* if (IsAuthPending(auth)) */
1143         FD_SET(auth->fd, &read_set);
1144     }
1145     /*
1146      * set listener file descriptors
1147      */
1148     for (listener = ListenerPollList; listener; listener = listener->next) {
1149       assert(-1 < listener->fd);
1150       FD_SET(listener->fd, &read_set);
1151     }
1152
1153     for (i = HighestFd; i > -1; --i) {
1154       if ((cptr = LocalClientArray[i])) {
1155         if (DBufLength(&cptr->recvQ))
1156           delay2 = 1;
1157         if (DBufLength(&cptr->recvQ) < 4088 || IsServer(cptr))
1158           FD_SET(i, &read_set);
1159         if (DBufLength(&cptr->sendQ) || IsConnecting(cptr) ||
1160             (cptr->listing && DBufLength(&cptr->sendQ) < 2048))
1161           FD_SET(i, &write_set);
1162       }
1163     }
1164
1165     wait.tv_sec = IRCD_MIN(delay2, delay);
1166     wait.tv_usec = usec;
1167
1168     Debug((DEBUG_INFO, "select: %d %d", delay, delay2));
1169
1170     nfds = select(FD_SETSIZE, &read_set, &write_set, 0, &wait);
1171
1172     CurrentTime = time(0);
1173
1174     if (-1 < nfds)
1175       break;
1176
1177     if (errno == EINTR)
1178       return -1;
1179     report_error(SELECT_ERROR_MSG, me.name, errno);
1180     if (++res > 5)
1181       server_restart("too many select errors");
1182     sleep(1);
1183     CurrentTime = time(0);
1184   }
1185
1186   if (-1 < UPingFileDescriptor && FD_ISSET(UPingFileDescriptor, &read_set)) {
1187     uping_echo();
1188     --nfds;
1189   }
1190   for (uping = uping_begin(); uping; uping = uping_next) {
1191     uping_next = uping->next;
1192     if (uping->active) {
1193       assert(-1 < uping->fd);
1194       if (FD_ISSET(uping->fd, &read_set)) {
1195         uping_read(uping);
1196         if (0 == --nfds)
1197           break;
1198       }
1199       else if (CurrentTime > uping->lastsent) {
1200         uping->lastsent = CurrentTime;
1201         uping_send(uping);
1202       }
1203     }
1204   }
1205   if (-1 < ResolverFileDescriptor && FD_ISSET(ResolverFileDescriptor, &read_set)) {
1206     resolver_read();
1207     --nfds;
1208   }
1209   /*
1210    * Check fd sets for the auth fd's (if set and valid!) first
1211    * because these can not be processed using the normal loops below.
1212    * -avalon
1213    */
1214   for (auth = AuthPollList; auth; auth = auth_next) {
1215     auth_next = auth->next;
1216     assert(-1 < auth->fd);
1217     if (IsAuthConnect(auth) && FD_ISSET(auth->fd, &write_set)) {
1218       send_auth_query(auth);
1219       if (0 == --nfds)
1220         break;
1221     }
1222     else if (FD_ISSET(auth->fd, &read_set)) {
1223       read_auth_reply(auth);
1224       if (0 == --nfds)
1225         break;
1226     }
1227   }
1228   /*
1229    * next accept connections from active listeners
1230    */
1231   for (listener = ListenerPollList; listener; listener = listener->next) {
1232     assert(-1 < listener->fd);
1233     if (0 < nfds && FD_ISSET(listener->fd, &read_set))
1234       accept_connection(listener);
1235   } 
1236
1237   for (i = HighestFd; -1 < i; --i) {
1238     if (!(cptr = LocalClientArray[i]))
1239       continue;
1240     read_ready = 0;
1241     if (0 < nfds) {
1242       if (FD_ISSET(i, &write_set)) {
1243         --nfds;
1244         if (!on_write_unblocked(cptr) || IsDead(cptr)) {
1245           const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
1246           if (!msg)
1247             msg = "Unknown error";
1248           if (FD_ISSET(i, &read_set))
1249             --nfds;
1250           exit_client(cptr, cptr, &me, msg);
1251           continue;
1252         }
1253       }
1254       if ((read_ready = FD_ISSET(i, &read_set)))
1255         --nfds;
1256     }
1257     length = 1;                 /* for fall through case */
1258     if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1259       if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1260         continue;
1261     }
1262 #if 0
1263     /* Bullshit, why would we want to flush sockets while using non-blocking?
1264      * This uses > 4% cpu! --Run */
1265     if (length > 0)
1266       flush_connections(LocalClientArray[i]);
1267 #endif
1268     if (IsDead(cptr)) {
1269       const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
1270       if (!msg)
1271         msg = "Unknown error";
1272       exit_client(cptr, cptr, &me, msg);
1273       continue;
1274     }
1275     if (length > 0)
1276       continue;
1277
1278     /*
1279      * ...hmm, with non-blocking sockets we might get
1280      * here from quite valid reasons, although.. why
1281      * would select report "data available" when there
1282      * wasn't... So, this must be an error anyway...  --msa
1283      * actually, EOF occurs when read() returns 0 and
1284      * in due course, select() returns that fd as ready
1285      * for reading even though it ends up being an EOF. -avalon
1286      */
1287     Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", i, cptr->error, length));
1288
1289     if ((IsServer(cptr) || IsHandshake(cptr)) && cptr->error == 0 && length == 0)
1290       exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1291                       cptr->name, cptr->serv->last_error_msg);
1292     else {
1293       const char* msg = (cptr->error) ? strerror(cptr->error) : "EOF from client";
1294       if (!msg)
1295         msg = "Unknown error";
1296       exit_client_msg(cptr, cptr, &me, "Read error to %s: %s",
1297                       get_client_name(cptr, HIDE_IP), msg);
1298     }
1299   }
1300   return 0;
1301 }
1302
1303 #endif /* USE_SELECT */
1304
1305 /*
1306  * connect_server - start or complete a connection to another server
1307  * returns true (1) if successful, false (0) otherwise
1308  *
1309  * aconf must point to a valid C:line
1310  * m_connect            calls this with a valid by client and a null reply
1311  * try_connections      calls this with a null by client, and a null reply
1312  * connect_dns_callback call this with a null by client, and a valid reply
1313  *
1314  * XXX - if this comes from an m_connect message and a dns query needs to
1315  * be done, we loose the information about who started the connection and
1316  * it's considered an auto connect.
1317  */
1318 int connect_server(struct ConfItem* aconf, struct Client* by,
1319                    struct DNSReply* reply)
1320 {
1321   struct Client*   cptr = 0;
1322   assert(0 != aconf);
1323
1324   if (aconf->dns_pending) {
1325     sendto_ops("Server %s connect DNS pending");
1326     return 0;
1327   }
1328   Debug((DEBUG_NOTICE, "Connect to %s[@%s]", aconf->name,
1329          ircd_ntoa((const char*) &aconf->ipnum)));
1330
1331   if ((cptr = FindClient(aconf->name))) {
1332     if (IsServer(cptr) || IsMe(cptr)) {
1333       sendto_ops("Server %s already present from %s", 
1334                  aconf->name, cptr->from->name);
1335       if (by && IsUser(by) && !MyUser(by)) {
1336         sendto_one(by, "%s NOTICE %s%s :Server %s already present from %s",
1337                      NumServ(&me), NumNick(by), aconf->name, cptr->from->name);
1338       }
1339       return 0;
1340     }
1341     else if (IsHandshake(cptr) || IsConnecting(cptr)) {
1342       if (by && IsUser(by)) {
1343         if (MyUser(by))
1344           sendto_one(by, ":%s NOTICE %s :Connection to %s already in progress",
1345                      me.name, by->name, cptr->name);
1346         else
1347           sendto_one(by, "%s NOTICE %s%s :Connection to %s already in progress",
1348                      NumServ(&me), NumNick(by), cptr->name);
1349       }
1350       return 0;
1351     }
1352   }
1353   /*
1354    * If we dont know the IP# for this host and itis a hostname and
1355    * not a ip# string, then try and find the appropriate host record.
1356    */
1357   if (INADDR_NONE == aconf->ipnum.s_addr) {
1358     char buf[HOSTLEN + 1];
1359     assert(0 == reply);
1360     if (INADDR_NONE == (aconf->ipnum.s_addr = inet_addr(aconf->host))) {
1361       struct DNSQuery  query;
1362
1363       query.vptr     = aconf;
1364       query.callback = connect_dns_callback;
1365       host_from_uh(buf, aconf->host, HOSTLEN);
1366       buf[HOSTLEN] = '\0';
1367
1368       reply = gethost_byname(buf, &query);
1369
1370       if (!reply) {
1371         aconf->dns_pending = 1;
1372         return 0;
1373       }
1374       memcpy(&aconf->ipnum, reply->hp->h_addr, sizeof(struct in_addr));
1375     }
1376   }
1377   cptr = make_client(NULL, STAT_UNKNOWN_SERVER);
1378   if (reply)
1379     ++reply->ref_count;
1380   cptr->dns_reply = reply;
1381
1382   /*
1383    * Copy these in so we have something for error detection.
1384    */
1385   ircd_strncpy(cptr->name, aconf->name, HOSTLEN);
1386   ircd_strncpy(cptr->sockhost, aconf->host, HOSTLEN);
1387
1388   /*
1389    * Attach config entries to client here rather than in
1390    * completed_connection. This to avoid null pointer references
1391    */
1392   attach_confs_byhost(cptr, aconf->host, CONF_SERVER);
1393
1394   if (!find_conf_byhost(cptr->confs, aconf->host, CONF_SERVER)) {
1395     sendto_ops("Host %s is not enabled for connecting: no C-line", aconf->name);
1396     if (by && IsUser(by) && !MyUser(by)) {
1397       sendto_one(by, "%s NOTICE %s%s :Connect to host %s failed: no C-line",
1398                  NumServ(&me), NumNick(by), aconf->name);
1399     }
1400     det_confs_butmask(cptr, 0);
1401     free_client(cptr);
1402     return 0;
1403   }
1404   /*
1405    * attempt to connect to the server in the conf line
1406    */
1407   if (!connect_inet(aconf, cptr)) {
1408     if (by && IsUser(by) && !MyUser(by)) {
1409       sendto_one(by, "%s NOTICE %s%s :Couldn't connect to %s",
1410                  NumServ(&me), NumNick(by), cptr->name);
1411     }
1412     det_confs_butmask(cptr, 0);
1413     free_client(cptr);
1414     return 0;
1415   }
1416   /*
1417    * NOTE: if we're here we have a valid C:Line and the client should
1418    * have started the connection and stored the remote address/port and
1419    * ip address name in itself
1420    *
1421    * The socket has been connected or connect is in progress.
1422    */
1423   make_server(cptr);
1424   if (by && IsUser(by)) {
1425     sprintf_irc(cptr->serv->by, "%s%s", NumNick(by));
1426     assert(0 == cptr->serv->user);
1427     cptr->serv->user = by->user;
1428     by->user->refcnt++;
1429   }
1430   else {
1431     *cptr->serv->by = '\0';
1432     /* strcpy(cptr->serv->by, "Auto"); */
1433   }
1434   cptr->serv->up = &me;
1435   SetConnecting(cptr);
1436
1437   if (cptr->fd > HighestFd)
1438     HighestFd = cptr->fd;
1439   LocalClientArray[cptr->fd] = cptr;
1440
1441   Count_newunknown(UserStats);
1442   add_client_to_list(cptr);
1443   hAddClient(cptr);
1444   nextping = CurrentTime;
1445
1446   return 1;
1447 }
1448
1449 /*
1450  * Setup local socket structure to use for binding to.
1451  */
1452 void init_virtual_host(const struct ConfItem* conf)
1453 {
1454   assert(0 != conf);
1455
1456   memset(&VirtualHost, 0, sizeof(VirtualHost));
1457   VirtualHost.sin_family = AF_INET;
1458   VirtualHost.sin_addr.s_addr = INADDR_ANY;
1459
1460   if (EmptyString(conf->passwd) || 0 == strcmp(conf->passwd, "*"))
1461     return;
1462   VirtualHost.sin_addr.s_addr = inet_addr(conf->passwd);
1463
1464   if (INADDR_NONE == VirtualHost.sin_addr.s_addr)
1465     VirtualHost.sin_addr.s_addr = INADDR_ANY;
1466 }  
1467
1468 /*
1469  * Find the real hostname for the host running the server (or one which
1470  * matches the server's name) and its primary IP#.  Hostname is stored
1471  * in the client structure passed as a pointer.
1472  */
1473 int init_server_identity()
1474 {
1475   struct ConfItem* conf = find_me();
1476
1477   if (!conf || EmptyString(conf->host))
1478     return 0;
1479
1480   ircd_strncpy(me.name, conf->host, HOSTLEN);
1481
1482   init_virtual_host(conf);
1483   return 1;
1484 }
1485
1486