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