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