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