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