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