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