Rewrite DNS lookup API to remove a memory leak and keep it from coming back.
[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 /** @file
21  * @brief Functions that now (or in the past) relied on BSD APIs.
22  * @version $Id$
23  */
24 #include "config.h"
25
26 #include "s_bsd.h"
27 #include "client.h"
28 #include "IPcheck.h"
29 #include "channel.h"
30 #include "class.h"
31 #include "hash.h"
32 #include "ircd_alloc.h"
33 #include "ircd_log.h"
34 #include "ircd_features.h"
35 #include "ircd_osdep.h"
36 #include "ircd_reply.h"
37 #include "ircd_snprintf.h"
38 #include "ircd_string.h"
39 #include "ircd.h"
40 #include "list.h"
41 #include "listener.h"
42 #include "msg.h"
43 #include "msgq.h"
44 #include "numeric.h"
45 #include "numnicks.h"
46 #include "packet.h"
47 #include "parse.h"
48 #include "querycmds.h"
49 #include "res.h"
50 #include "s_auth.h"
51 #include "s_conf.h"
52 #include "s_debug.h"
53 #include "s_misc.h"
54 #include "s_user.h"
55 #include "send.h"
56 #include "struct.h"
57 #include "sys.h"
58 #include "uping.h"
59 #include "version.h"
60
61 /* #include <assert.h> -- Now using assert in ircd_log.h */
62 #include <errno.h>
63 #include <fcntl.h>
64 #include <netdb.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <sys/ioctl.h>
69 #include <sys/socket.h>
70 #include <sys/time.h>
71 #include <sys/utsname.h>
72 #include <unistd.h>
73
74 #ifdef USE_POLL
75 #include <sys/poll.h>
76 #endif /* USE_POLL */
77
78 /** Array of my own clients, indexed by file descriptor. */
79 struct Client*            LocalClientArray[MAXCONNECTIONS];
80 /** Maximum file descriptor in current use. */
81 int                       HighestFd = -1;
82 /** Default local address for outbound IPv4 connections. */
83 struct irc_sockaddr       VirtualHost_v4;
84 /** Default local address for outbound IPv6 connections. */
85 struct irc_sockaddr       VirtualHost_v6;
86 /** Temporary buffer for reading data from a peer. */
87 static char               readbuf[SERVER_TCP_WINDOW];
88
89 /*
90  * report_error text constants
91  */
92 const char* const ACCEPT_ERROR_MSG    = "error accepting connection for %s: %s";
93 const char* const BIND_ERROR_MSG      = "bind error for %s: %s";
94 const char* const CONNECT_ERROR_MSG   = "connect to host %s failed: %s";
95 const char* const CONNLIMIT_ERROR_MSG = "connect limit exceeded for %s: %s";
96 const char* const LISTEN_ERROR_MSG    = "listen error for %s: %s";
97 const char* const NONB_ERROR_MSG      = "error setting non-blocking for %s: %s";
98 const char* const PEERNAME_ERROR_MSG  = "getpeername failed for %s: %s";
99 const char* const POLL_ERROR_MSG      = "poll error for %s: %s";
100 const char* const REGISTER_ERROR_MSG  = "registering %s: %s";
101 const char* const REUSEADDR_ERROR_MSG = "error setting SO_REUSEADDR for %s: %s";
102 const char* const SELECT_ERROR_MSG    = "select error for %s: %s";
103 const char* const SETBUFS_ERROR_MSG   = "error setting buffer size for %s: %s";
104 const char* const SOCKET_ERROR_MSG    = "error creating socket for %s: %s";
105 const char* const TOS_ERROR_MSG       = "error setting TOS for %s: %s";
106
107
108 static void client_sock_callback(struct Event* ev);
109 static void client_timer_callback(struct Event* ev);
110
111 #if !defined(USE_POLL)
112 #if FD_SETSIZE < (MAXCONNECTIONS + 4)
113 /*
114  * Sanity check
115  *
116  * All operating systems work when MAXCONNECTIONS <= 252.
117  * Most operating systems work when MAXCONNECTIONS <= 1020 and FD_SETSIZE is
118  *   updated correctly in the system headers (on BSD systems our sys.h has
119  *   defined FD_SETSIZE to MAXCONNECTIONS+4 before including the system's headers 
120  *   but sys/types.h might have abruptly redefined it so the check is still 
121  *   done), you might already need to recompile your kernel.
122  * For larger FD_SETSIZE your mileage may vary (kernel patches may be needed).
123  * The check is _NOT_ done if we will not use FD_SETS at all (USE_POLL)
124  */
125 #error "FD_SETSIZE is too small or MAXCONNECTIONS too large."
126 #endif
127 #endif
128
129
130 /*
131  * Cannot use perror() within daemon. stderr is closed in
132  * ircd and cannot be used. And, worse yet, it might have
133  * been reassigned to a normal connection...
134  */
135
136 /** Replacement for perror(). Record error to log.  Send a copy to all
137  * *LOCAL* opers, but only if no errors were sent to them in the last
138  * 20 seconds.
139  * @param text A *format* string for outputting error. It must contain
140  * only two '%s', the first will be replaced by the sockhost from the
141  * cptr, and the latter will be taken from sys_errlist[errno].
142  * @param who The client associated with the error.
143  * @param err The errno value to display.
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 /** Called when resolver query finishes.  If the DNS lookup was
170  * successful, start the connection; otherwise notify opers of the
171  * failure.
172  * @param vptr The struct ConfItem representing the Connect block.
173  * @param hp A pointer to the DNS lookup results (NULL on failure).
174  */
175 static void connect_dns_callback(void* vptr, const struct irc_in_addr *addr, const char *h_name)
176 {
177   struct ConfItem* aconf = (struct ConfItem*) vptr;
178   assert(aconf);
179   aconf->dns_pending = 0;
180   if (addr) {
181     memcpy(&aconf->address, addr, sizeof(aconf->address));
182     connect_server(aconf, 0);
183   }
184   else
185     sendto_opmask_butone(0, SNO_OLDSNO, "Connect to %s failed: host lookup",
186                          aconf->name);
187 }
188
189 /** Closes all file descriptors.
190  * @param close_stderr If non-zero, also close stderr.
191  */
192 void close_connections(int close_stderr)
193 {
194   int i;
195   if (close_stderr)
196   {
197     close(0);
198     close(1);
199     close(2);
200   }
201   for (i = 3; i < MAXCONNECTIONS; ++i)
202     close(i);
203 }
204
205 /** Initialize process fd limit to 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 /** Set up address and port and make a connection.
224  * @param aconf Provides the connection information.
225  * @param cptr Client structure for the peer.
226  * @return Non-zero on success; zero on failure.
227  */
228 static int connect_inet(struct ConfItem* aconf, struct Client* cptr)
229 {
230   const struct irc_sockaddr *local;
231   IOResult result;
232   assert(0 != aconf);
233   assert(0 != cptr);
234   /*
235    * Might as well get sockhost from here, the connection is attempted
236    * with it so if it fails its useless.
237    */
238   if (irc_in_addr_valid(&aconf->origin.addr))
239     local = &aconf->origin;
240   else if (irc_in_addr_is_ipv4(&aconf->address.addr))
241     local = &VirtualHost_v4;
242   else
243     local = &VirtualHost_v6;
244   cli_fd(cptr) = os_socket(local, SOCK_STREAM, cli_name(cptr));
245   if (cli_fd(cptr) < 0)
246     return 0;
247
248   /*
249    * save connection info in client
250    */
251   memcpy(&cli_ip(cptr), &aconf->address.addr, sizeof(cli_ip(cptr)));
252   ircd_ntoa_r(cli_sock_ip(cptr), &cli_ip(cptr));
253   /*
254    * we want a big buffer for server connections
255    */
256   if (!os_set_sockbufs(cli_fd(cptr), feature_int(FEAT_SOCKSENDBUF), feature_int(FEAT_SOCKRECVBUF))) {
257     cli_error(cptr) = errno;
258     report_error(SETBUFS_ERROR_MSG, cli_name(cptr), errno);
259     close(cli_fd(cptr));
260     cli_fd(cptr) = -1;
261     return 0;
262   }
263   /*
264    * Set the TOS bits - this is nonfatal if it doesn't stick.
265    */
266   if (!os_set_tos(cli_fd(cptr), FEAT_TOS_SERVER)) {
267     report_error(TOS_ERROR_MSG, cli_name(cptr), errno);
268   }
269   if ((result = os_connect_nonb(cli_fd(cptr), &aconf->address)) == IO_FAILURE) {
270     cli_error(cptr) = errno;
271     report_error(CONNECT_ERROR_MSG, cli_name(cptr), errno);
272     close(cli_fd(cptr));
273     cli_fd(cptr) = -1;
274     return 0;
275   }
276   if (!socket_add(&(cli_socket(cptr)), client_sock_callback,
277                   (void*) cli_connect(cptr),
278                   (result == IO_SUCCESS) ? SS_CONNECTED : SS_CONNECTING,
279                   SOCK_EVENT_READABLE, cli_fd(cptr))) {
280     cli_error(cptr) = ENFILE;
281     report_error(REGISTER_ERROR_MSG, cli_name(cptr), ENFILE);
282     close(cli_fd(cptr));
283     cli_fd(cptr) = -1;
284     return 0;
285   }
286   cli_freeflag(cptr) |= FREEFLAG_SOCKET;
287   return 1;
288 }
289
290 /** Attempt to send a sequence of bytes to the connection.
291  * As a side effect, updates \a cptr's FLAG_BLOCKED setting
292  * and sendB/sendK fields.
293  * @param cptr Client that should receive data.
294  * @param buf Message buffer to send to client.
295  * @return Negative on connection-fatal error; otherwise
296  *  number of bytes sent.
297  */
298 unsigned int deliver_it(struct Client *cptr, struct MsgQ *buf)
299 {
300   unsigned int bytes_written = 0;
301   unsigned int bytes_count = 0;
302   assert(0 != cptr);
303
304   switch (os_sendv_nonb(cli_fd(cptr), buf, &bytes_count, &bytes_written)) {
305   case IO_SUCCESS:
306     ClrFlag(cptr, FLAG_BLOCKED);
307
308     cli_sendB(cptr) += bytes_written;
309     cli_sendB(&me)  += bytes_written;
310     /* A partial write implies that future writes will block. */
311     if (bytes_written < bytes_count)
312       SetFlag(cptr, FLAG_BLOCKED);
313     break;
314   case IO_BLOCKED:
315     SetFlag(cptr, FLAG_BLOCKED);
316     break;
317   case IO_FAILURE:
318     cli_error(cptr) = errno;
319     SetFlag(cptr, FLAG_DEADSOCKET);
320     break;
321   }
322   return bytes_written;
323 }
324
325 /** Complete non-blocking connect()-sequence. Check access and
326  * terminate connection, if trouble detected.
327  * @param cptr Client to which we have connected, with all ConfItem structs attached.
328  * @return Zero on failure (caller should exit_client()), non-zero on success.
329  */
330 static int completed_connection(struct Client* cptr)
331 {
332   struct ConfItem *aconf;
333   time_t newts;
334   struct Client *acptr;
335   int i;
336
337   assert(0 != cptr);
338
339   /*
340    * get the socket status from the fd first to check if
341    * connection actually succeeded
342    */
343   if ((cli_error(cptr) = os_get_sockerr(cli_fd(cptr)))) {
344     const char* msg = strerror(cli_error(cptr));
345     if (!msg)
346       msg = "Unknown error";
347     sendto_opmask_butone(0, SNO_OLDSNO, "Connection failed to %s: %s",
348                          cli_name(cptr), msg);
349     return 0;
350   }
351   if (!(aconf = find_conf_byname(cli_confs(cptr), cli_name(cptr), CONF_SERVER))) {
352     sendto_opmask_butone(0, SNO_OLDSNO, "Lost Server Line for %s", cli_name(cptr));
353     return 0;
354   }
355   if (s_state(&(cli_socket(cptr))) == SS_CONNECTING)
356     socket_state(&(cli_socket(cptr)), SS_CONNECTED);
357
358   if (!EmptyString(aconf->passwd))
359     sendrawto_one(cptr, MSG_PASS " :%s", aconf->passwd);
360
361   /*
362    * Create a unique timestamp
363    */
364   newts = TStime();
365   for (i = HighestFd; i > -1; --i) {
366     if ((acptr = LocalClientArray[i]) && 
367         (IsServer(acptr) || IsHandshake(acptr))) {
368       if (cli_serv(acptr)->timestamp >= newts)
369         newts = cli_serv(acptr)->timestamp + 1;
370     }
371   }
372   assert(0 != cli_serv(cptr));
373
374   cli_serv(cptr)->timestamp = newts;
375   SetHandshake(cptr);
376   /*
377    * Make us timeout after twice the timeout for DNS look ups
378    */
379   cli_lasttime(cptr) = CurrentTime;
380   SetFlag(cptr, FLAG_PINGSENT);
381
382   sendrawto_one(cptr, MSG_SERVER " %s 1 %Tu %Tu J%s %s%s +%s6 :%s",
383                 cli_name(&me), cli_serv(&me)->timestamp, newts,
384                 MAJOR_PROTOCOL, NumServCap(&me),
385                 feature_bool(FEAT_HUB) ? "h" : "", cli_info(&me));
386
387   return (IsDead(cptr)) ? 0 : 1;
388 }
389
390 /** Close the physical connection.  Side effects: MyConnect(cptr)
391  * becomes false and cptr->from becomes NULL.
392  * @param cptr Client to disconnect.
393  */
394 void close_connection(struct Client *cptr)
395 {
396   struct ConfItem* aconf;
397
398   if (IsServer(cptr)) {
399     ServerStats->is_sv++;
400     ServerStats->is_sbs += cli_sendB(cptr);
401     ServerStats->is_sbr += cli_receiveB(cptr);
402     ServerStats->is_sti += CurrentTime - cli_firsttime(cptr);
403     /*
404      * If the connection has been up for a long amount of time, schedule
405      * a 'quick' reconnect, else reset the next-connect cycle.
406      */
407     if ((aconf = find_conf_exact(cli_name(cptr), cptr, CONF_SERVER))) {
408       /*
409        * Reschedule a faster reconnect, if this was a automatically
410        * connected configuration entry. (Note that if we have had
411        * a rehash in between, the status has been changed to
412        * CONF_ILLEGAL). But only do this if it was a "good" link.
413        */
414       aconf->hold = CurrentTime;
415       aconf->hold += ((aconf->hold - cli_since(cptr) >
416                        feature_int(FEAT_HANGONGOODLINK)) ?
417                       feature_int(FEAT_HANGONRETRYDELAY) : ConfConFreq(aconf));
418 /*        if (nextconnect > aconf->hold) */
419 /*          nextconnect = aconf->hold; */
420     }
421   }
422   else if (IsUser(cptr)) {
423     ServerStats->is_cl++;
424     ServerStats->is_cbs += cli_sendB(cptr);
425     ServerStats->is_cbr += cli_receiveB(cptr);
426     ServerStats->is_cti += CurrentTime - cli_firsttime(cptr);
427   }
428   else
429     ServerStats->is_ni++;
430
431   if (-1 < cli_fd(cptr)) {
432     flush_connections(cptr);
433     LocalClientArray[cli_fd(cptr)] = 0;
434     close(cli_fd(cptr));
435     socket_del(&(cli_socket(cptr))); /* queue a socket delete */
436     cli_fd(cptr) = -1;
437   }
438   SetFlag(cptr, FLAG_DEADSOCKET);
439
440   MsgQClear(&(cli_sendQ(cptr)));
441   client_drop_sendq(cli_connect(cptr));
442   DBufClear(&(cli_recvQ(cptr)));
443   memset(cli_passwd(cptr), 0, sizeof(cli_passwd(cptr)));
444   set_snomask(cptr, 0, SNO_SET);
445
446   det_confs_butmask(cptr, 0);
447
448   if (cli_listener(cptr)) {
449     release_listener(cli_listener(cptr));
450     cli_listener(cptr) = 0;
451   }
452
453   for ( ; HighestFd > 0; --HighestFd) {
454     if (LocalClientArray[HighestFd])
455       break;
456   }
457 }
458
459 /** Close all unregistered connections.
460  * @param source Oper who requested the close.
461  * @return Number of closed connections.
462  */
463 int net_close_unregistered_connections(struct Client* source)
464 {
465   int            i;
466   struct Client* cptr;
467   int            count = 0;
468   assert(0 != source);
469
470   for (i = HighestFd; i > 0; --i) {
471     if ((cptr = LocalClientArray[i]) && !IsRegistered(cptr)) {
472       send_reply(source, RPL_CLOSING, get_client_name(source, HIDE_IP));
473       exit_client(source, cptr, &me, "Oper Closing");
474       ++count;
475     }
476   }
477   return count;
478 }
479
480 /** Creates a client which has just connected to us on the given fd.
481  * The sockhost field is initialized with the ip# of the host.
482  * The client is not added to the linked list of clients, it is
483  * passed off to the auth handler for dns and ident queries.
484  * @param listener Listening socket that received the connection.
485  * @param fd File descriptor of new connection.
486  */
487 void add_connection(struct Listener* listener, int fd) {
488   struct irc_sockaddr addr;
489   struct Client      *new_client;
490   time_t             next_target = 0;
491
492   const char* const throttle_message =
493          "ERROR :Your host is trying to (re)connect too fast -- throttled\r\n";
494        /* 12345678901234567890123456789012345679012345678901234567890123456 */
495   const char* const register_message =
496          "ERROR :Unable to complete your registration\r\n";
497
498   assert(0 != listener);
499
500   /*
501    * Removed preliminary access check. Full check is performed in m_server and
502    * m_user instead. Also connection time out help to get rid of unwanted
503    * connections.
504    */
505   if (!os_get_peername(fd, &addr) || !os_set_nonblocking(fd)) {
506     ++ServerStats->is_ref;
507     close(fd);
508     return;
509   }
510   /*
511    * Disable IP (*not* TCP) options.  In particular, this makes it impossible
512    * to use source routing to connect to the server.  If we didn't do this
513    * (and if intermediate networks didn't drop source-routed packets), an
514    * attacker could successfully IP spoof us...and even return the anti-spoof
515    * ping, because the options would cause the packet to be routed back to
516    * the spoofer's machine.  When we disable the IP options, we delete the
517    * source route, and the normal routing takes over.
518    */
519   os_disable_options(fd);
520
521   /*
522    * Add this local client to the IPcheck registry.
523    *
524    * If they're throttled, murder them, but tell them why first.
525    */
526   if (!IPcheck_local_connect(&addr.addr, &next_target) && !listener->server)
527   {
528     ++ServerStats->is_ref;
529     write(fd, throttle_message, strlen(throttle_message));
530     close(fd);
531     return;
532   }
533
534   new_client = make_client(0, ((listener->server) ?
535                                STAT_UNKNOWN_SERVER : STAT_UNKNOWN_USER));
536
537   /*
538    * Copy ascii address to 'sockhost' just in case. Then we have something
539    * valid to put into error messages...
540    */
541   SetIPChecked(new_client);
542   ircd_ntoa_r(cli_sock_ip(new_client), &addr.addr);
543   strcpy(cli_sockhost(new_client), cli_sock_ip(new_client));
544   memcpy(&cli_ip(new_client), &addr.addr, sizeof(cli_ip(new_client)));
545
546   if (next_target)
547     cli_nexttarget(new_client) = next_target;
548
549   cli_fd(new_client) = fd;
550   if (!socket_add(&(cli_socket(new_client)), client_sock_callback,
551                   (void*) cli_connect(new_client), SS_CONNECTED, 0, fd)) {
552     ++ServerStats->is_ref;
553     write(fd, register_message, strlen(register_message));
554     close(fd);
555     cli_fd(new_client) = -1;
556     return;
557   }
558   cli_freeflag(new_client) |= FREEFLAG_SOCKET;
559   cli_listener(new_client) = listener;
560   ++listener->ref_count;
561
562   Count_newunknown(UserStats);
563   /* if we've made it this far we can put the client on the auth query pile */
564   start_auth(new_client);
565 }
566
567 /** Determines whether to tell the events engine we're interested in
568  * writable events.
569  * @param cptr Client for which to decide this.
570  */
571 void update_write(struct Client* cptr)
572 {
573   /* If there are messages that need to be sent along, or if the client
574    * is in the middle of a /list, then we need to tell the engine that
575    * we're interested in writable events--otherwise, we need to drop
576    * that interest.
577    */
578   socket_events(&(cli_socket(cptr)),
579                 ((MsgQLength(&cli_sendQ(cptr)) || cli_listing(cptr)) ?
580                  SOCK_ACTION_ADD : SOCK_ACTION_DEL) | SOCK_EVENT_WRITABLE);
581 }
582
583 /** Read a 'packet' of data from a connection and process it.  Read in
584  * 8k chunks to give a better performance rating (for server
585  * connections).  Do some tricky stuff for client connections to make
586  * sure they don't do any flooding >:-) -avalon
587  * @param cptr Client from which to read data.
588  * @param socket_ready If non-zero, more data can be read from the client's socket.
589  * @return Positive number on success, zero on connection-fatal failure, negative
590  *   if user is killed.
591  */
592 static int read_packet(struct Client *cptr, int socket_ready)
593 {
594   unsigned int dolen = 0;
595   unsigned int length = 0;
596
597   if (socket_ready &&
598       !(IsUser(cptr) &&
599         DBufLength(&(cli_recvQ(cptr))) > feature_int(FEAT_CLIENT_FLOOD))) {
600     switch (os_recv_nonb(cli_fd(cptr), readbuf, sizeof(readbuf), &length)) {
601     case IO_SUCCESS:
602       if (length)
603       {
604         if (!IsServer(cptr))
605           cli_lasttime(cptr) = CurrentTime;
606         if (cli_lasttime(cptr) > cli_since(cptr))
607           cli_since(cptr) = cli_lasttime(cptr);
608         ClrFlag(cptr, FLAG_PINGSENT);
609         ClrFlag(cptr, FLAG_NONL);
610       }
611       break;
612     case IO_BLOCKED:
613       break;
614     case IO_FAILURE:
615       cli_error(cptr) = errno;
616       /* SetFlag(cptr, FLAG_DEADSOCKET); */
617       return 0;
618     }
619   }
620
621   /*
622    * For server connections, we process as many as we can without
623    * worrying about the time of day or anything :)
624    */
625   if (length > 0 && IsServer(cptr))
626     return server_dopacket(cptr, readbuf, length);
627   else if (length > 0 && (IsHandshake(cptr) || IsConnecting(cptr)))
628     return connect_dopacket(cptr, readbuf, length);
629   else
630   {
631     /*
632      * Before we even think of parsing what we just read, stick
633      * it on the end of the receive queue and do it when its
634      * turn comes around.
635      */
636     if (length > 0 && dbuf_put(&(cli_recvQ(cptr)), readbuf, length) == 0)
637       return exit_client(cptr, cptr, &me, "dbuf_put fail");
638
639     if (DBufLength(&(cli_recvQ(cptr))) > feature_int(FEAT_CLIENT_FLOOD))
640       return exit_client(cptr, cptr, &me, "Excess Flood");
641
642     while (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) && 
643            (IsTrusted(cptr) || cli_since(cptr) - CurrentTime < 10))
644     {
645       dolen = dbuf_getmsg(&(cli_recvQ(cptr)), cli_buffer(cptr), BUFSIZE);
646       /*
647        * Devious looking...whats it do ? well..if a client
648        * sends a *long* message without any CR or LF, then
649        * dbuf_getmsg fails and we pull it out using this
650        * loop which just gets the next 512 bytes and then
651        * deletes the rest of the buffer contents.
652        * -avalon
653        */
654       if (dolen == 0)
655       {
656         if (DBufLength(&(cli_recvQ(cptr))) < 510)
657           SetFlag(cptr, FLAG_NONL);
658         else
659           DBufClear(&(cli_recvQ(cptr)));
660       }
661       else if (client_dopacket(cptr, dolen) == CPTR_KILLED)
662         return CPTR_KILLED;
663       /*
664        * If it has become registered as a Server
665        * then skip the per-message parsing below.
666        */
667       if (IsHandshake(cptr) || IsServer(cptr))
668       {
669         while (-1)
670         {
671           dolen = dbuf_get(&(cli_recvQ(cptr)), readbuf, sizeof(readbuf));
672           if (dolen <= 0)
673             return 1;
674           else if (dolen == 0)
675           {
676             if (DBufLength(&(cli_recvQ(cptr))) < 510)
677               SetFlag(cptr, FLAG_NONL);
678             else
679               DBufClear(&(cli_recvQ(cptr)));
680           }
681           else if ((IsServer(cptr) &&
682                     server_dopacket(cptr, readbuf, dolen) == CPTR_KILLED) ||
683                    (!IsServer(cptr) &&
684                     connect_dopacket(cptr, readbuf, dolen) == CPTR_KILLED))
685             return CPTR_KILLED;
686         }
687       }
688     }
689
690     /* If there's still data to process, wait 2 seconds first */
691     if (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) &&
692         !t_onqueue(&(cli_proc(cptr))))
693     {
694       Debug((DEBUG_LIST, "Adding client process timer for %C", cptr));
695       cli_freeflag(cptr) |= FREEFLAG_TIMER;
696       timer_add(&(cli_proc(cptr)), client_timer_callback, cli_connect(cptr),
697                 TT_RELATIVE, 2);
698     }
699   }
700   return 1;
701 }
702
703 /** Start a connection to another server.
704  * @param aconf Connect block data for target server.
705  * @param by Client who requested the connection (if any).
706  * @return Non-zero on success; zero on failure.
707  */
708 int connect_server(struct ConfItem* aconf, struct Client* by)
709 {
710   struct Client*   cptr = 0;
711   assert(0 != aconf);
712
713   if (aconf->dns_pending) {
714     sendto_opmask_butone(0, SNO_OLDSNO, "Server %s connect DNS pending",
715                          aconf->name);
716     return 0;
717   }
718   Debug((DEBUG_NOTICE, "Connect to %s[@%s]", aconf->name,
719          ircd_ntoa(&aconf->address.addr)));
720
721   if ((cptr = FindClient(aconf->name))) {
722     if (IsServer(cptr) || IsMe(cptr)) {
723       sendto_opmask_butone(0, SNO_OLDSNO, "Server %s already present from %s", 
724                            aconf->name, cli_name(cli_from(cptr)));
725       if (by && IsUser(by) && !MyUser(by)) {
726         sendcmdto_one(&me, CMD_NOTICE, by, "%C :Server %s already present "
727                       "from %s", by, aconf->name, cli_name(cli_from(cptr)));
728       }
729       return 0;
730     }
731     else if (IsHandshake(cptr) || IsConnecting(cptr)) {
732       if (by && IsUser(by)) {
733         sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connection to %s already in "
734                       "progress", by, cli_name(cptr));
735       }
736       return 0;
737     }
738   }
739   /*
740    * If we don't know the IP# for this host and it is a hostname and
741    * not a ip# string, then try and find the appropriate host record.
742    */
743   if (!irc_in_addr_valid(&aconf->address.addr)
744       && !ircd_aton(&aconf->address.addr, aconf->host)) {
745     char buf[HOSTLEN + 1];
746
747     host_from_uh(buf, aconf->host, HOSTLEN);
748     gethost_byname(buf, connect_dns_callback, aconf);
749     aconf->dns_pending = 1;
750     return 0;
751   }
752   cptr = make_client(NULL, STAT_UNKNOWN_SERVER);
753
754   /*
755    * Copy these in so we have something for error detection.
756    */
757   ircd_strncpy(cli_name(cptr), aconf->name, HOSTLEN);
758   ircd_strncpy(cli_sockhost(cptr), aconf->host, HOSTLEN);
759
760   /*
761    * Attach config entries to client here rather than in
762    * completed_connection. This to avoid null pointer references
763    */
764   attach_confs_byhost(cptr, aconf->host, CONF_SERVER);
765
766   if (!find_conf_byhost(cli_confs(cptr), aconf->host, CONF_SERVER)) {
767     sendto_opmask_butone(0, SNO_OLDSNO, "Host %s is not enabled for "
768                          "connecting: no Connect block", aconf->name);
769     if (by && IsUser(by) && !MyUser(by)) {
770       sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connect to host %s failed: no "
771                     "Connect block", by, aconf->name);
772     }
773     det_confs_butmask(cptr, 0);
774     free_client(cptr);
775     return 0;
776   }
777   /*
778    * attempt to connect to the server in the conf line
779    */
780   if (!connect_inet(aconf, cptr)) {
781     if (by && IsUser(by) && !MyUser(by)) {
782       sendcmdto_one(&me, CMD_NOTICE, by, "%C :Couldn't connect to %s", by,
783                     cli_name(cptr));
784     }
785     det_confs_butmask(cptr, 0);
786     free_client(cptr);
787     return 0;
788   }
789   /*
790    * NOTE: if we're here we have a valid C:Line and the client should
791    * have started the connection and stored the remote address/port and
792    * ip address name in itself
793    *
794    * The socket has been connected or connect is in progress.
795    */
796   make_server(cptr);
797   if (by && IsUser(by)) {
798     ircd_snprintf(0, cli_serv(cptr)->by, sizeof(cli_serv(cptr)->by), "%s%s",
799                   NumNick(by));
800     assert(0 == cli_serv(cptr)->user);
801     cli_serv(cptr)->user = cli_user(by);
802     cli_user(by)->refcnt++;
803   }
804   else {
805     *(cli_serv(cptr))->by = '\0';
806     /* strcpy(cptr->serv->by, "Auto"); */
807   }
808   cli_serv(cptr)->up = &me;
809   SetConnecting(cptr);
810
811   if (cli_fd(cptr) > HighestFd)
812     HighestFd = cli_fd(cptr);
813
814   LocalClientArray[cli_fd(cptr)] = cptr;
815
816   Count_newunknown(UserStats);
817   /* Actually we lie, the connect hasn't succeeded yet, but we have a valid
818    * cptr, so we register it now.
819    * Maybe these two calls should be merged.
820    */
821   add_client_to_list(cptr);
822   hAddClient(cptr);
823 /*    nextping = CurrentTime; */
824
825   return (s_state(&cli_socket(cptr)) == SS_CONNECTED) ?
826     completed_connection(cptr) : 1;
827 }
828
829 /** Find the real hostname for the host running the server (or one which
830  * matches the server's name) and its primary IP#.  Hostname is stored
831  * in the client structure passed as a pointer.
832  */
833 void init_server_identity(void)
834 {
835   const struct LocalConf* conf = conf_get_local();
836   assert(0 != conf);
837
838   ircd_strncpy(cli_name(&me), conf->name, HOSTLEN);
839   SetYXXServerName(&me, conf->numeric);
840 }
841
842 /** Process events on a client socket.
843  * @param ev Socket event structure that has a struct Connection as
844  *   its associated data.
845  */
846 static void client_sock_callback(struct Event* ev)
847 {
848   struct Client* cptr;
849   struct Connection* con;
850   char *fmt = "%s";
851   char *fallback = 0;
852
853   assert(0 != ev_socket(ev));
854   assert(0 != s_data(ev_socket(ev)));
855
856   con = (struct Connection*) s_data(ev_socket(ev));
857
858   assert(0 != con_client(con) || ev_type(ev) == ET_DESTROY);
859
860   cptr = con_client(con);
861
862   assert(0 == cptr || con == cli_connect(cptr));
863
864   switch (ev_type(ev)) {
865   case ET_DESTROY:
866     con_freeflag(con) &= ~FREEFLAG_SOCKET;
867
868     if (!con_freeflag(con) && !cptr)
869       free_connection(con);
870     break;
871
872   case ET_CONNECT: /* socket connection completed */
873     if (!completed_connection(cptr) || IsDead(cptr))
874       fallback = cli_info(cptr);
875     break;
876
877   case ET_ERROR: /* an error occurred */
878     fallback = cli_info(cptr);
879     cli_error(cptr) = ev_data(ev);
880     if (s_state(&(con_socket(con))) == SS_CONNECTING) {
881       completed_connection(cptr);
882       /* for some reason, the os_get_sockerr() in completed_connect()
883        * can return 0 even when ev_data(ev) indicates a real error, so
884        * re-assign the client error here.
885        */
886       cli_error(cptr) = ev_data(ev);
887       break;
888     }
889     /*FALLTHROUGH*/
890   case ET_EOF: /* end of file on socket */
891     Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d", cli_fd(cptr),
892            cli_error(cptr)));
893     SetFlag(cptr, FLAG_DEADSOCKET);
894     if ((IsServer(cptr) || IsHandshake(cptr)) && cli_error(cptr) == 0) {
895       exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
896                       cli_name(cptr), cli_serv(cptr)->last_error_msg);
897       return;
898     } else {
899       fmt = "Read error: %s";
900       fallback = "EOF from client";
901     }
902     break;
903
904   case ET_WRITE: /* socket is writable */
905     ClrFlag(cptr, FLAG_BLOCKED);
906     if (cli_listing(cptr) && MsgQLength(&(cli_sendQ(cptr))) < 2048)
907       list_next_channels(cptr);
908     Debug((DEBUG_SEND, "Sending queued data to %C", cptr));
909     send_queued(cptr);
910     break;
911
912   case ET_READ: /* socket is readable */
913     if (!IsDead(cptr)) {
914       Debug((DEBUG_DEBUG, "Reading data from %C", cptr));
915       if (read_packet(cptr, 1) == 0) /* error while reading packet */
916         fallback = "EOF from client";
917     }
918     break;
919
920   default:
921     assert(0 && "Unrecognized socket event in client_sock_callback()");
922     break;
923   }
924
925   assert(0 == cptr || 0 == cli_connect(cptr) || con == cli_connect(cptr));
926
927   if (fallback) {
928     const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : fallback;
929     if (!msg)
930       msg = "Unknown error";
931     exit_client_msg(cptr, cptr, &me, fmt, msg);
932   }
933 }
934
935 /** Process a timer on client socket.
936  * @param ev Timer event that has a struct Connection as its
937  * associated data.
938  */
939 static void client_timer_callback(struct Event* ev)
940 {
941   struct Client* cptr;
942   struct Connection* con;
943
944   assert(0 != ev_timer(ev));
945   assert(0 != t_data(ev_timer(ev)));
946   assert(ET_DESTROY == ev_type(ev) || ET_EXPIRE == ev_type(ev));
947
948   con = (struct Connection*) t_data(ev_timer(ev));
949
950   assert(0 != con_client(con) || ev_type(ev) == ET_DESTROY);
951
952   cptr = con_client(con);
953
954   assert(0 == cptr || con == cli_connect(cptr));
955
956   if (ev_type(ev)== ET_DESTROY) {
957     con_freeflag(con) &= ~FREEFLAG_TIMER; /* timer has expired... */
958
959     if (!con_freeflag(con) && !cptr)
960       free_connection(con); /* client is being destroyed */
961   } else {
962     Debug((DEBUG_LIST, "Client process timer for %C expired; processing",
963            cptr));
964     read_packet(cptr, 0); /* read_packet will re-add timer if needed */
965   }
966
967   assert(0 == cptr || 0 == cli_connect(cptr) || con == cli_connect(cptr));
968 }