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