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