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