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     if (DBufLength(&(cli_recvQ(cptr))) > feature_int(FEAT_CLIENT_FLOOD))
669       return exit_client(cptr, cptr, &me, "Excess Flood");
670
671     while (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) && 
672            (IsTrusted(cptr) || cli_since(cptr) - CurrentTime < 10))
673     {
674       dolen = dbuf_getmsg(&(cli_recvQ(cptr)), cli_buffer(cptr), BUFSIZE);
675       /*
676        * Devious looking...whats it do ? well..if a client
677        * sends a *long* message without any CR or LF, then
678        * dbuf_getmsg fails and we pull it out using this
679        * loop which just gets the next 512 bytes and then
680        * deletes the rest of the buffer contents.
681        * -avalon
682        */
683       if (dolen == 0)
684       {
685         if (DBufLength(&(cli_recvQ(cptr))) < 510)
686           SetFlag(cptr, FLAG_NONL);
687         else
688         {
689           /* More than 512 bytes in the line - drop the input and yell
690            * at the client.
691            */
692           DBufClear(&(cli_recvQ(cptr)));
693           send_reply(cptr, ERR_INPUTTOOLONG);
694         }
695       }
696       else if (client_dopacket(cptr, dolen) == CPTR_KILLED)
697         return CPTR_KILLED;
698       /*
699        * If it has become registered as a Server
700        * then skip the per-message parsing below.
701        */
702       if (IsHandshake(cptr) || IsServer(cptr))
703       {
704         while (-1)
705         {
706           dolen = dbuf_get(&(cli_recvQ(cptr)), readbuf, sizeof(readbuf));
707           if (dolen <= 0)
708             return 1;
709           else if (dolen == 0)
710           {
711             if (DBufLength(&(cli_recvQ(cptr))) < 510)
712               SetFlag(cptr, FLAG_NONL);
713             else
714               DBufClear(&(cli_recvQ(cptr)));
715           }
716           else if ((IsServer(cptr) &&
717                     server_dopacket(cptr, readbuf, dolen) == CPTR_KILLED) ||
718                    (!IsServer(cptr) &&
719                     connect_dopacket(cptr, readbuf, dolen) == CPTR_KILLED))
720             return CPTR_KILLED;
721         }
722       }
723     }
724
725     /* If there's still data to process, wait 2 seconds first */
726     if (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) &&
727         !t_onqueue(&(cli_proc(cptr))))
728     {
729       Debug((DEBUG_LIST, "Adding client process timer for %C", cptr));
730       cli_freeflag(cptr) |= FREEFLAG_TIMER;
731       timer_add(&(cli_proc(cptr)), client_timer_callback, cli_connect(cptr),
732                 TT_RELATIVE, 2);
733     }
734   }
735   return 1;
736 }
737
738 /** Start a connection to another server.
739  * @param aconf Connect block data for target server.
740  * @param by Client who requested the connection (if any).
741  * @return Non-zero on success; zero on failure.
742  */
743 int connect_server(struct ConfItem* aconf, struct Client* by)
744 {
745   struct Client*   cptr = 0;
746   assert(0 != aconf);
747
748   if (aconf->dns_pending) {
749     sendto_opmask_butone(0, SNO_OLDSNO, "Server %s connect DNS pending",
750                          aconf->name);
751     return 0;
752   }
753   Debug((DEBUG_NOTICE, "Connect to %s[@%s]", aconf->name,
754          ircd_ntoa(&aconf->address.addr)));
755
756   if ((cptr = FindClient(aconf->name))) {
757     if (IsServer(cptr) || IsMe(cptr)) {
758       sendto_opmask_butone(0, SNO_OLDSNO, "Server %s already present from %s", 
759                            aconf->name, cli_name(cli_from(cptr)));
760       if (by && IsUser(by) && !MyUser(by)) {
761         sendcmdto_one(&me, CMD_NOTICE, by, "%C :Server %s already present "
762                       "from %s", by, aconf->name, cli_name(cli_from(cptr)));
763       }
764       return 0;
765     }
766     else if (IsHandshake(cptr) || IsConnecting(cptr)) {
767       if (by && IsUser(by)) {
768         sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connection to %s already in "
769                       "progress", by, cli_name(cptr));
770       }
771       return 0;
772     }
773   }
774   /*
775    * If we don't know the IP# for this host and it is a hostname and
776    * not a ip# string, then try and find the appropriate host record.
777    */
778   if (!irc_in_addr_valid(&aconf->address.addr)
779       && !ircd_aton(&aconf->address.addr, aconf->host)) {
780     char buf[HOSTLEN + 1];
781
782     host_from_uh(buf, aconf->host, HOSTLEN);
783     gethost_byname(buf, connect_dns_callback, aconf);
784     aconf->dns_pending = 1;
785     return 0;
786   }
787   cptr = make_client(NULL, STAT_UNKNOWN_SERVER);
788
789   /*
790    * Copy these in so we have something for error detection.
791    */
792   ircd_strncpy(cli_name(cptr), aconf->name, HOSTLEN);
793   ircd_strncpy(cli_sockhost(cptr), aconf->host, HOSTLEN);
794
795   /*
796    * Attach config entries to client here rather than in
797    * completed_connection. This to avoid null pointer references
798    */
799   attach_confs_byhost(cptr, aconf->host, CONF_SERVER);
800
801   if (!find_conf_byhost(cli_confs(cptr), aconf->host, CONF_SERVER)) {
802     sendto_opmask_butone(0, SNO_OLDSNO, "Host %s is not enabled for "
803                          "connecting: no Connect block", aconf->name);
804     if (by && IsUser(by) && !MyUser(by)) {
805       sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connect to host %s failed: no "
806                     "Connect block", by, aconf->name);
807     }
808     det_confs_butmask(cptr, 0);
809     free_client(cptr);
810     return 0;
811   }
812   /*
813    * attempt to connect to the server in the conf line
814    */
815   if (!connect_inet(aconf, cptr)) {
816     if (by && IsUser(by) && !MyUser(by)) {
817       sendcmdto_one(&me, CMD_NOTICE, by, "%C :Couldn't connect to %s", by,
818                     cli_name(cptr));
819     }
820     det_confs_butmask(cptr, 0);
821     free_client(cptr);
822     return 0;
823   }
824   /*
825    * NOTE: if we're here we have a valid C:Line and the client should
826    * have started the connection and stored the remote address/port and
827    * ip address name in itself
828    *
829    * The socket has been connected or connect is in progress.
830    */
831   make_server(cptr);
832   if (by && IsUser(by)) {
833     ircd_snprintf(0, cli_serv(cptr)->by, sizeof(cli_serv(cptr)->by), "%s%s",
834                   NumNick(by));
835     assert(0 == cli_serv(cptr)->user);
836     cli_serv(cptr)->user = cli_user(by);
837     cli_user(by)->refcnt++;
838   }
839   else {
840     *(cli_serv(cptr))->by = '\0';
841     /* strcpy(cptr->serv->by, "Auto"); */
842   }
843   cli_serv(cptr)->up = &me;
844   SetConnecting(cptr);
845
846   if (cli_fd(cptr) > HighestFd)
847     HighestFd = cli_fd(cptr);
848
849   LocalClientArray[cli_fd(cptr)] = cptr;
850
851   Count_newunknown(UserStats);
852   /* Actually we lie, the connect hasn't succeeded yet, but we have a valid
853    * cptr, so we register it now.
854    * Maybe these two calls should be merged.
855    */
856   add_client_to_list(cptr);
857   hAddClient(cptr);
858 /*    nextping = CurrentTime; */
859
860   return (s_state(&cli_socket(cptr)) == SS_CONNECTED) ?
861     completed_connection(cptr) : 1;
862 }
863
864 /** Find the real hostname for the host running the server (or one which
865  * matches the server's name) and its primary IP#.  Hostname is stored
866  * in the client structure passed as a pointer.
867  */
868 void init_server_identity(void)
869 {
870   const struct LocalConf* conf = conf_get_local();
871   assert(0 != conf);
872
873   ircd_strncpy(cli_name(&me), conf->name, HOSTLEN);
874   SetYXXServerName(&me, conf->numeric);
875 }
876
877 /** Process events on a client socket.
878  * @param ev Socket event structure that has a struct Connection as
879  *   its associated data.
880  */
881 static void client_sock_callback(struct Event* ev)
882 {
883   struct Client* cptr;
884   struct Connection* con;
885   char *fmt = "%s";
886   char *fallback = 0;
887
888   assert(0 != ev_socket(ev));
889   assert(0 != s_data(ev_socket(ev)));
890
891   con = (struct Connection*) s_data(ev_socket(ev));
892
893   assert(0 != con_client(con) || ev_type(ev) == ET_DESTROY);
894
895   cptr = con_client(con);
896
897   assert(0 == cptr || con == cli_connect(cptr));
898
899   switch (ev_type(ev)) {
900   case ET_DESTROY:
901     con_freeflag(con) &= ~FREEFLAG_SOCKET;
902
903     if (!con_freeflag(con) && !cptr)
904       free_connection(con);
905     break;
906
907   case ET_CONNECT: /* socket connection completed */
908     if(cli_connect(cptr)->con_ssl) {
909       ssl_start_handshake_connect(cli_connect(cptr)->con_ssl);
910     }
911     else if (!completed_connection(cptr) || IsDead(cptr))
912       fallback = cli_info(cptr);
913     break;
914
915   case ET_ERROR: /* an error occurred */
916     fallback = cli_info(cptr);
917     cli_error(cptr) = ev_data(ev);
918     /* If the OS told us we have a bad file descriptor, we should
919      * record that for future reference.
920      */
921     if (cli_error(cptr) == EBADF)
922       cli_fd(cptr) = -1;
923     if (s_state(&(con_socket(con))) == SS_CONNECTING) {
924       completed_connection(cptr);
925       /* for some reason, the os_get_sockerr() in completed_connect()
926        * can return 0 even when ev_data(ev) indicates a real error, so
927        * re-assign the client error here.
928        */
929       cli_error(cptr) = ev_data(ev);
930       break;
931     }
932     /*FALLTHROUGH*/
933   case ET_EOF: /* end of file on socket */
934     Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d", cli_fd(cptr),
935            cli_error(cptr)));
936     SetFlag(cptr, FLAG_DEADSOCKET);
937     if ((IsServer(cptr) || IsHandshake(cptr)) && cli_error(cptr) == 0) {
938       exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
939                       cli_name(cptr), cli_serv(cptr)->last_error_msg);
940       return;
941     } else {
942       fmt = "Read error: %s";
943       fallback = "EOF from client";
944     }
945     break;
946
947   case ET_WRITE: /* socket is writable */
948     ClrFlag(cptr, FLAG_BLOCKED);
949     if (cli_listing(cptr) && MsgQLength(&(cli_sendQ(cptr))) < 2048)
950       list_next_channels(cptr);
951     Debug((DEBUG_SEND, "Sending queued data to %C", cptr));
952     send_queued(cptr);
953     break;
954
955   case ET_READ: /* socket is readable */
956     if (!IsDead(cptr)) {
957       Debug((DEBUG_DEBUG, "Reading data from %C", cptr));
958       if (read_packet(cptr, 1) == 0) /* error while reading packet */
959         fallback = "EOF from client";
960     }
961     break;
962
963   default:
964     assert(0 && "Unrecognized socket event in client_sock_callback()");
965     break;
966   }
967
968   assert(0 == cptr || 0 == cli_connect(cptr) || con == cli_connect(cptr));
969
970   if (fallback) {
971     const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : fallback;
972     if (!msg)
973       msg = "Unknown error";
974     exit_client_msg(cptr, cptr, &me, fmt, msg);
975   }
976 }
977
978 /** Process a timer on client socket.
979  * @param ev Timer event that has a struct Connection as its
980  * associated data.
981  */
982 static void client_timer_callback(struct Event* ev)
983 {
984   struct Client* cptr;
985   struct Connection* con;
986
987   assert(0 != ev_timer(ev));
988   assert(0 != t_data(ev_timer(ev)));
989   assert(ET_DESTROY == ev_type(ev) || ET_EXPIRE == ev_type(ev));
990
991   con = (struct Connection*) t_data(ev_timer(ev));
992
993   assert(0 != con_client(con) || ev_type(ev) == ET_DESTROY);
994
995   cptr = con_client(con);
996
997   assert(0 == cptr || con == cli_connect(cptr));
998
999   if (ev_type(ev)== ET_DESTROY) {
1000     con_freeflag(con) &= ~FREEFLAG_TIMER; /* timer has expired... */
1001
1002     if (!con_freeflag(con) && !cptr)
1003       free_connection(con); /* client is being destroyed */
1004   } else {
1005     Debug((DEBUG_LIST, "Client process timer for %C expired; processing",
1006            cptr));
1007     read_packet(cptr, 0); /* read_packet will re-add timer if needed */
1008   }
1009
1010   assert(0 == cptr || 0 == cli_connect(cptr) || con == cli_connect(cptr));
1011 }