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