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