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