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