fb842764a4152c36de12749765db47110bcb908e
[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: s_bsd.c 1863 2008-03-15 05:24:14Z entrope $
23  */
24 #include "config.h"
25
26 #include "s_bsd.h"
27 #include "client.h"
28 #include "IPcheck.h"
29 #include "channel.h"
30 #include "class.h"
31 #include "hash.h"
32 #include "ircd_alloc.h"
33 #include "ircd_log.h"
34 #include "ircd_features.h"
35 #include "ircd_osdep.h"
36 #include "ircd_reply.h"
37 #include "ircd_snprintf.h"
38 #include "ircd_string.h"
39 #include "ircd.h"
40 #include "list.h"
41 #include "listener.h"
42 #include "msg.h"
43 #include "msgq.h"
44 #include "numeric.h"
45 #include "numnicks.h"
46 #include "packet.h"
47 #include "parse.h"
48 #include "querycmds.h"
49 #include "res.h"
50 #include "s_auth.h"
51 #include "s_conf.h"
52 #include "s_debug.h"
53 #include "s_misc.h"
54 #include "s_user.h"
55 #include "send.h"
56 #include "struct.h"
57 #include "sys.h"
58 #include "uping.h"
59 #include "version.h"
60
61 /* #include <assert.h> -- Now using assert in ircd_log.h */
62 #include <errno.h>
63 #include <fcntl.h>
64 #include <netdb.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <sys/ioctl.h>
69 #include <sys/socket.h>
70 #include <sys/time.h>
71 #include <sys/utsname.h>
72 #include <unistd.h>
73
74 /** Array of my own clients, indexed by file descriptor. */
75 struct Client*            LocalClientArray[MAXCONNECTIONS];
76 /** Maximum file descriptor in current use. */
77 int                       HighestFd = -1;
78 /** Default local address for outbound IPv4 connections. */
79 struct irc_sockaddr       VirtualHost_v4;
80 /** Default local address for outbound IPv6 connections. */
81 struct irc_sockaddr       VirtualHost_v6;
82 /** Temporary buffer for reading data from a peer. */
83 static char               readbuf[SERVER_TCP_WINDOW];
84
85 /*
86  * report_error text constants
87  */
88 const char* const ACCEPT_ERROR_MSG    = "error accepting connection for %s: %s";
89 const char* const BIND_ERROR_MSG      = "bind error for %s: %s";
90 const char* const CONNECT_ERROR_MSG   = "connect to host %s failed: %s";
91 const char* const CONNLIMIT_ERROR_MSG = "connect limit exceeded for %s: %s";
92 const char* const LISTEN_ERROR_MSG    = "listen error for %s: %s";
93 const char* const NONB_ERROR_MSG      = "error setting non-blocking for %s: %s";
94 const char* const PEERNAME_ERROR_MSG  = "getpeername failed for %s: %s";
95 const char* const POLL_ERROR_MSG      = "poll error for %s: %s";
96 const char* const REGISTER_ERROR_MSG  = "registering %s: %s";
97 const char* const REUSEADDR_ERROR_MSG = "error setting SO_REUSEADDR for %s: %s";
98 const char* const SELECT_ERROR_MSG    = "select error for %s: %s";
99 const char* const SETBUFS_ERROR_MSG   = "error setting buffer size for %s: %s";
100 const char* const SOCKET_ERROR_MSG    = "error creating socket for %s: %s";
101 const char* const TOS_ERROR_MSG       = "error setting TOS for %s: %s";
102
103
104 static void client_timer_callback(struct Event* ev);
105
106
107 /*
108  * Cannot use perror() within daemon. stderr is closed in
109  * ircd and cannot be used. And, worse yet, it might have
110  * been reassigned to a normal connection...
111  */
112
113 /** Replacement for perror(). Record error to log.  Send a copy to all
114  * *LOCAL* opers, but only if no errors were sent to them in the last
115  * 20 seconds.
116  * @param text A *format* string for outputting error. It must contain
117  * only two '%s', the first will be replaced by the sockhost from the
118  * cptr, and the latter will be taken from sys_errlist[errno].
119  * @param who The client associated with the error.
120  * @param err The errno value to display.
121  */
122 void report_error(const char* text, const char* who, int err)
123 {
124   static time_t last_notice = 0;
125   int           errtmp = errno;   /* debug may change 'errno' */
126   const char*   errmsg = (err) ? strerror(err) : "";
127
128   if (!errmsg)
129     errmsg = "Unknown error"; 
130
131   if (EmptyString(who))
132     who = "unknown";
133
134   sendto_opmask_butone_ratelimited(0, SNO_OLDSNO, &last_notice, text, who, errmsg);
135   log_write(LS_SOCKET, L_ERROR, 0, text, who, errmsg);
136   errno = errtmp;
137 }
138
139
140 /** Called when resolver query finishes.  If the DNS lookup was
141  * successful, start the connection; otherwise notify opers of the
142  * failure.
143  * @param vptr The struct ConfItem representing the Connect block.
144  * @param hp A pointer to the DNS lookup results (NULL on failure).
145  */
146 static void connect_dns_callback(void* vptr, const struct irc_in_addr *addr, const char *h_name)
147 {
148   struct ConfItem* aconf = (struct ConfItem*) vptr;
149   assert(aconf);
150   aconf->dns_pending = 0;
151   if (addr) {
152     memcpy(&aconf->address, addr, sizeof(aconf->address));
153     connect_server(aconf, 0);
154   }
155   else
156     sendto_opmask_butone(0, SNO_OLDSNO, "Connect to %s failed: host lookup",
157                          aconf->name);
158 }
159
160 /* Helper routines */
161 static IOResult client_recv(struct Client *cptr, char *buf, unsigned int length, unsigned int *count_out)
162 {
163   if (cli_socket(cptr).ssl)
164     return ssl_recv(cli_fd(cptr), cli_socket(cptr).ssl, buf, length, count_out);
165   else
166     return os_recv_nonb(cli_fd(cptr), buf, length, count_out);
167 }
168
169 static IOResult client_sendv(struct Client *cptr, struct MsgQ *buf, unsigned int *count_in, unsigned int *count_out)
170 {
171   if (cli_socket(cptr).ssl)
172     return ssl_sendv(cli_fd(cptr), cli_socket(cptr).ssl, buf, count_in, count_out);
173   else
174     return os_sendv_nonb(cli_fd(cptr), buf, count_in, count_out);
175 }
176
177 /** Closes all file descriptors.
178  * @param close_stderr If non-zero, also close stderr.
179  */
180 void close_connections(int close_stderr)
181 {
182   int i;
183   if (close_stderr)
184   {
185     close(0);
186     close(1);
187     close(2);
188   }
189   for (i = 3; i < MAXCONNECTIONS; ++i)
190     close(i);
191 }
192
193 /** Initialize process fd limit to MAXCONNECTIONS.
194  */
195 int init_connection_limits(void)
196 {
197   int limit = os_set_fdlimit(MAXCONNECTIONS);
198   if (0 == limit)
199     return 1;
200   if (limit < 0) {
201     fprintf(stderr, "error setting max fds to %d: %s\n", limit, strerror(errno));
202   }
203   else if (limit > 0) {
204     fprintf(stderr, "ircd fd table too big\nHard Limit: %d IRC max: %d\n",
205             limit, MAXCONNECTIONS);
206     fprintf(stderr, "set MAXCONNECTIONS to a smaller value");
207   }
208   return 0;
209 }
210
211 /** Set up address and port and make a connection.
212  * @param aconf Provides the connection information.
213  * @param cptr Client structure for the peer.
214  * @return Non-zero on success; zero on failure.
215  */
216 static int connect_inet(struct ConfItem* aconf, struct Client* cptr)
217 {
218   const struct irc_sockaddr *local;
219   IOResult result;
220   int family = 0;
221
222   assert(0 != aconf);
223   assert(0 != cptr);
224   /*
225    * Might as well get sockhost from here, the connection is attempted
226    * with it so if it fails its useless.
227    */
228   if (irc_in_addr_valid(&aconf->origin.addr))
229     local = &aconf->origin;
230   else if (irc_in_addr_is_ipv4(&aconf->address.addr)) {
231     local = &VirtualHost_v4;
232     family = AF_INET;
233   } else
234     local = &VirtualHost_v6;
235   cli_fd(cptr) = os_socket(local, SOCK_STREAM, cli_name(cptr), family);
236   if (cli_fd(cptr) < 0)
237     return 0;
238
239   /*
240    * save connection info in client
241    */
242   memcpy(&cli_ip(cptr), &aconf->address.addr, sizeof(cli_ip(cptr)));
243   ircd_ntoa_r(cli_sock_ip(cptr), &cli_ip(cptr));
244   /*
245    * we want a big buffer for server connections
246    */
247   if (!os_set_sockbufs(cli_fd(cptr), feature_int(FEAT_SOCKSENDBUF), feature_int(FEAT_SOCKRECVBUF))) {
248     cli_error(cptr) = errno;
249     report_error(SETBUFS_ERROR_MSG, cli_name(cptr), errno);
250     close(cli_fd(cptr));
251     cli_fd(cptr) = -1;
252     return 0;
253   }
254   /*
255    * Set the TOS bits - this is nonfatal if it doesn't stick.
256    */
257   if (!os_set_tos(cli_fd(cptr), FEAT_TOS_SERVER)) {
258     report_error(TOS_ERROR_MSG, cli_name(cptr), errno);
259   }
260   if ((result = os_connect_nonb(cli_fd(cptr), &aconf->address)) == IO_FAILURE) {
261     cli_error(cptr) = errno;
262     report_error(CONNECT_ERROR_MSG, cli_name(cptr), errno);
263     close(cli_fd(cptr));
264     cli_fd(cptr) = -1;
265     return 0;
266   }
267   if (!socket_add(&(cli_socket(cptr)), client_sock_callback,
268                   (void*) cli_connect(cptr),
269                   (result == IO_SUCCESS) ? SS_CONNECTED : SS_CONNECTING,
270                   SOCK_EVENT_READABLE, cli_fd(cptr))) {
271     cli_error(cptr) = ENFILE;
272     report_error(REGISTER_ERROR_MSG, cli_name(cptr), ENFILE);
273     close(cli_fd(cptr));
274     cli_fd(cptr) = -1;
275     return 0;
276   }
277   cli_freeflag(cptr) |= FREEFLAG_SOCKET;
278   return 1;
279 }
280
281 /** Attempt to send a sequence of bytes to the connection.
282  * As a side effect, updates \a cptr's FLAG_BLOCKED setting
283  * and sendB/sendK fields.
284  * @param cptr Client that should receive data.
285  * @param buf Message buffer to send to client.
286  * @return Negative on connection-fatal error; otherwise
287  *  number of bytes sent.
288  */
289 unsigned int deliver_it(struct Client *cptr, struct MsgQ *buf)
290 {
291   unsigned int bytes_written = 0;
292   unsigned int bytes_count = 0;
293   assert(0 != cptr);
294
295   switch (client_sendv(cptr, buf, &bytes_count, &bytes_written)) {
296   case IO_SUCCESS:
297     ClrFlag(cptr, FLAG_BLOCKED);
298
299     cli_sendB(cptr) += bytes_written;
300     cli_sendB(&me)  += bytes_written;
301     /* A partial write implies that future writes will block. */
302     if (bytes_written < bytes_count)
303       SetFlag(cptr, FLAG_BLOCKED);
304     break;
305   case IO_BLOCKED:
306     SetFlag(cptr, FLAG_BLOCKED);
307     break;
308   case IO_FAILURE:
309     cli_error(cptr) = errno;
310     SetFlag(cptr, FLAG_DEADSOCKET);
311     break;
312   }
313   return bytes_written;
314 }
315
316 /** Complete non-blocking connect()-sequence. Check access and
317  * terminate connection, if trouble detected.
318  * @param cptr Client to which we have connected, with all ConfItem structs attached.
319  * @return Zero on failure (caller should exit_client()), non-zero on success.
320  */
321 int completed_connection(struct Client* cptr)
322 {
323   struct ConfItem *aconf;
324   time_t newts;
325   struct Client *acptr;
326   int i;
327
328   assert(0 != cptr);
329
330   /*
331    * get the socket status from the fd first to check if
332    * connection actually succeeded
333    */
334   if ((cli_error(cptr) = os_get_sockerr(cli_fd(cptr)))) {
335     const char* msg = strerror(cli_error(cptr));
336     if (!msg)
337       msg = "Unknown error";
338     sendto_opmask_butone(0, SNO_OLDSNO, "Connection failed to %s: %s",
339                          cli_name(cptr), msg);
340     return 0;
341   }
342   if (!(aconf = find_conf_byname(cli_confs(cptr), cli_name(cptr), CONF_SERVER))) {
343     sendto_opmask_butone(0, SNO_OLDSNO, "Lost Server Line for %s", cli_name(cptr));
344     return 0;
345   }
346   if (s_state(&(cli_socket(cptr))) == SS_CONNECTING)
347     socket_state(&(cli_socket(cptr)), SS_CONNECTED);
348
349   /* Check whether we have to secure the connection.
350    * Server<->Server encryption requires us to pass the FD to the SSL module
351    * now which performs the handshake and later calls this function again.
352    *
353    * When this function is called again, there is either an error, which occurred,
354    * or the handshake completed and we continue without passing it to the SSL
355    * module again.
356    */
357   if(!cli_socket(cptr).ssl && (aconf->flags & CONF_SECURE)) {
358     return ssl_connect(cptr);
359   }
360
361   if (!EmptyString(aconf->passwd))
362     sendrawto_one(cptr, MSG_PASS " :%s", aconf->passwd);
363
364   /*
365    * Create a unique timestamp
366    */
367   newts = TStime();
368   for (i = HighestFd; i > -1; --i) {
369     if ((acptr = LocalClientArray[i]) && 
370         (IsServer(acptr) || IsHandshake(acptr))) {
371       if (cli_serv(acptr)->timestamp >= newts)
372         newts = cli_serv(acptr)->timestamp + 1;
373     }
374   }
375   assert(0 != cli_serv(cptr));
376
377   cli_serv(cptr)->timestamp = newts;
378   SetHandshake(cptr);
379   /*
380    * Make us timeout after twice the timeout for DNS look ups
381    */
382   cli_lasttime(cptr) = CurrentTime;
383   ClearPingSent(cptr);
384
385   sendrawto_one(cptr, MSG_SERVER " %s 1 %Tu %Tu J%s %s%s +%s6 :%s",
386                 cli_name(&me), cli_serv(&me)->timestamp, newts,
387                 MAJOR_PROTOCOL, NumServCap(&me),
388                 feature_bool(FEAT_HUB) ? "h" : "", cli_info(&me));
389
390   return (IsDead(cptr)) ? 0 : 1;
391 }
392
393 /** Close the physical connection.  Side effects: MyConnect(cptr)
394  * becomes false and cptr->from becomes NULL.
395  * @param cptr Client to disconnect.
396  */
397 void close_connection(struct Client *cptr)
398 {
399   struct ConfItem* aconf;
400
401   if (IsServer(cptr)) {
402     ServerStats->is_sv++;
403     ServerStats->is_sbs += cli_sendB(cptr);
404     ServerStats->is_sbr += cli_receiveB(cptr);
405     ServerStats->is_sti += CurrentTime - cli_firsttime(cptr);
406     /*
407      * If the connection has been up for a long amount of time, schedule
408      * a 'quick' reconnect, else reset the next-connect cycle.
409      */
410     if ((aconf = find_conf_exact(cli_name(cptr), cptr, CONF_SERVER))) {
411       /*
412        * Reschedule a faster reconnect, if this was a automatically
413        * connected configuration entry. (Note that if we have had
414        * a rehash in between, the status has been changed to
415        * CONF_ILLEGAL). But only do this if it was a "good" link.
416        */
417       aconf->hold = CurrentTime;
418       aconf->hold += ((aconf->hold - cli_since(cptr) >
419                        feature_int(FEAT_HANGONGOODLINK)) ?
420                       feature_int(FEAT_HANGONRETRYDELAY) : ConfConFreq(aconf));
421 /*        if (nextconnect > aconf->hold) */
422 /*          nextconnect = aconf->hold; */
423     }
424   }
425   else if (IsUser(cptr)) {
426     ServerStats->is_cl++;
427     ServerStats->is_cbs += cli_sendB(cptr);
428     ServerStats->is_cbr += cli_receiveB(cptr);
429     ServerStats->is_cti += CurrentTime - cli_firsttime(cptr);
430   }
431   else
432     ServerStats->is_ni++;
433
434   if (-1 < cli_fd(cptr)) {
435     flush_connections(cptr);
436     LocalClientArray[cli_fd(cptr)] = 0;
437     close(cli_fd(cptr));
438     socket_del(&(cli_socket(cptr))); /* queue a socket delete */
439     cli_fd(cptr) = -1;
440   }
441   SetFlag(cptr, FLAG_DEADSOCKET);
442
443   MsgQClear(&(cli_sendQ(cptr)));
444   client_drop_sendq(cli_connect(cptr));
445   DBufClear(&(cli_recvQ(cptr)));
446   memset(cli_passwd(cptr), 0, sizeof(cli_passwd(cptr)));
447   set_snomask(cptr, 0, SNO_SET);
448
449   det_confs_butmask(cptr, 0);
450
451   if (cli_listener(cptr)) {
452     release_listener(cli_listener(cptr));
453     cli_listener(cptr) = 0;
454   }
455
456   for ( ; HighestFd > 0; --HighestFd) {
457     if (LocalClientArray[HighestFd])
458       break;
459   }
460 }
461
462 /**
463  * Switches a client's connection over to a different, zombied client.
464  *
465  * @param source client to attach to zombied client
466  * @param target zombied client
467  */
468 void connection_switch_to_client(struct Client *source, struct Client *target)
469 {
470   assert(IsNotConn(target));
471   assert(MyConnect(source));
472   assert(-1 < cli_fd(source));
473   cli_connect(target) = cli_connect(source);
474   /* conveniently, this makes it much easier to get rid of source later on */
475   cli_from(target) = target;
476   LocalClientArray[cli_fd(source)] = target;
477
478   /* make main loop remove source soonish */
479   SetFlag(source, FLAG_DEADSOCKET);
480
481   /* need to copy over data from old client */
482   cli_user(target)->server = cli_user(source)->server;
483   strcpy(cli_yxx(target), cli_yxx(source));
484   cli_hopcount(target) = cli_hopcount(source);
485   cli_ip(target) = cli_ip(source);
486   strcpy(cli_username(target), cli_username(source));
487   strcpy(cli_user(target)->realhost, cli_user(source)->realhost);
488 }
489
490 /** Close all unregistered connections.
491  * @param source Oper who requested the close.
492  * @return Number of closed connections.
493  */
494 int net_close_unregistered_connections(struct Client* source)
495 {
496   int            i;
497   struct Client* cptr;
498   int            count = 0;
499   assert(0 != source);
500
501   for (i = HighestFd; i > 0; --i) {
502     if ((cptr = LocalClientArray[i]) && !IsRegistered(cptr)) {
503       send_reply(source, RPL_CLOSING, get_client_name(source, HIDE_IP));
504       exit_client(source, cptr, &me, "Oper Closing");
505       ++count;
506     }
507   }
508   return count;
509 }
510
511 /** Creates a client which has just connected to us on the given fd.
512  * The sockhost field is initialized with the ip# of the host.
513  * The client is not added to the linked list of clients, it is
514  * passed off to the auth handler for dns and ident queries.
515  * @param listener Listening socket that received the connection.
516  * @param fd File descriptor of new connection.
517  */
518 void add_connection(struct Listener* listener, int fd, ssl_session_t *ssl) {
519   struct irc_sockaddr addr;
520   struct Client      *new_client;
521   time_t             next_target = 0;
522
523   const char* const throttle_message =
524          "ERROR :Your host is trying to (re)connect too fast -- throttled\r\n";
525        /* 12345678901234567890123456789012345679012345678901234567890123456 */
526   const char* const register_message =
527          "ERROR :Unable to complete your registration\r\n";
528
529   assert(0 != listener);
530
531   /*
532    * Removed preliminary access check. Full check is performed in m_server and
533    * m_user instead. Also connection time out help to get rid of unwanted
534    * connections.
535    */
536   if (!os_get_peername(fd, &addr) || !os_set_nonblocking(fd)) {
537     ++ServerStats->is_ref;
538     ssl_close(fd, ssl, NULL, 0);
539     return;
540   }
541   /*
542    * Disable IP (*not* TCP) options.  In particular, this makes it impossible
543    * to use source routing to connect to the server.  If we didn't do this
544    * (and if intermediate networks didn't drop source-routed packets), an
545    * attacker could successfully IP spoof us...and even return the anti-spoof
546    * ping, because the options would cause the packet to be routed back to
547    * the spoofer's machine.  When we disable the IP options, we delete the
548    * source route, and the normal routing takes over.
549    */
550   os_disable_options(fd);
551
552   if (listener_server(listener))
553   {
554     new_client = make_client(0, STAT_UNKNOWN_SERVER);
555   }
556   else
557   {
558     /*
559      * Add this local client to the IPcheck registry.
560      *
561      * If they're throttled, murder them, but tell them why first.
562      */
563     if (!IPcheck_local_connect(&addr.addr, &next_target))
564     {
565       ++ServerStats->is_ref;
566       ssl_close(fd, ssl, throttle_message, strlen(throttle_message));
567       return;
568     }
569     new_client = make_client(0, STAT_UNKNOWN_USER);
570     SetIPChecked(new_client);
571   }
572
573   /*
574    * Copy ascii address to 'sockhost' just in case. Then we have something
575    * valid to put into error messages...
576    */
577   ircd_ntoa_r(cli_sock_ip(new_client), &addr.addr);
578   strcpy(cli_sockhost(new_client), cli_sock_ip(new_client));
579   memcpy(&cli_ip(new_client), &addr.addr, sizeof(cli_ip(new_client)));
580
581   if (next_target)
582     cli_nexttarget(new_client) = next_target;
583
584   cli_fd(new_client) = fd;
585   if (!socket_add(&(cli_socket(new_client)), client_sock_callback,
586                   (void*) cli_connect(new_client), SS_CONNECTED, 0, fd)) {
587     ++ServerStats->is_ref;
588     ssl_close(fd, ssl, register_message, strlen(register_message));
589     cli_fd(new_client) = -1;
590     return;
591   }
592   cli_socket(new_client).ssl = ssl;
593   cli_freeflag(new_client) |= FREEFLAG_SOCKET;
594   cli_listener(new_client) = listener;
595   ++listener->ref_count;
596
597   Count_newunknown(UserStats);
598   /* if we've made it this far we can put the client on the auth query pile */
599   start_auth(new_client);
600 }
601
602 /** Determines whether to tell the events engine we're interested in
603  * writable events.
604  * @param cptr Client for which to decide this.
605  */
606 void update_write(struct Client* cptr)
607 {
608   /* If there are messages that need to be sent along, or if the client
609    * is in the middle of a /list, then we need to tell the engine that
610    * we're interested in writable events--otherwise, we need to drop
611    * that interest.
612    */
613   socket_events(&(cli_socket(cptr)),
614                 ((MsgQLength(&cli_sendQ(cptr)) || cli_listing(cptr)) ?
615                  SOCK_ACTION_ADD : SOCK_ACTION_DEL) | SOCK_EVENT_WRITABLE);
616 }
617
618 /** Read a 'packet' of data from a connection and process it.  Read in
619  * 8k chunks to give a better performance rating (for server
620  * connections).  Do some tricky stuff for client connections to make
621  * sure they don't do any flooding >:-) -avalon
622  * @param cptr Client from which to read data.
623  * @param socket_ready If non-zero, more data can be read from the client's socket.
624  * @return Positive number on success, zero on connection-fatal failure, negative
625  *   if user is killed.
626  */
627 static int read_packet(struct Client *cptr, int socket_ready)
628 {
629   unsigned int dolen = 0;
630   unsigned int length = 0;
631   unsigned int client_flood = feature_int(FEAT_CLIENT_FLOOD) * (HasPriv(cptr, PRIV_HALFFLOOD) ? 4 : 1);
632
633   if (socket_ready &&
634       !(IsUser(cptr) && !HasPriv(cptr, PRIV_FLOOD) &&
635         DBufLength(&(cli_recvQ(cptr))) > client_flood)) {
636     switch (client_recv(cptr, readbuf, sizeof(readbuf), &length)) {
637     case IO_SUCCESS:
638       if (length)
639       {
640         cli_lasttime(cptr) = CurrentTime;
641         ClearPingSent(cptr);
642         ClrFlag(cptr, FLAG_NONL);
643         if (cli_lasttime(cptr) > cli_since(cptr))
644           cli_since(cptr) = cli_lasttime(cptr);
645       }
646       break;
647     case IO_BLOCKED:
648       break;
649     case IO_FAILURE:
650       cli_error(cptr) = errno;
651       /* SetFlag(cptr, FLAG_DEADSOCKET); */
652       return 0;
653     }
654   }
655
656   /*
657    * For server connections, we process as many as we can without
658    * worrying about the time of day or anything :)
659    */
660   if (length > 0 && IsServer(cptr))
661     return server_dopacket(cptr, readbuf, length);
662   else if (length > 0 && (IsHandshake(cptr) || IsConnecting(cptr) || HasPriv(cptr, PRIV_FLOOD)))
663     return connect_dopacket(cptr, readbuf, length);
664   else
665   {
666     /*
667      * Before we even think of parsing what we just read, stick
668      * it on the end of the receive queue and do it when its
669      * turn comes around.
670      */
671     if (length > 0 && dbuf_put(&(cli_recvQ(cptr)), readbuf, length) == 0)
672       return exit_client(cptr, cptr, &me, "dbuf_put fail");
673
674     if (!HasPriv(cptr, PRIV_FLOOD) && DBufLength(&(cli_recvQ(cptr))) > client_flood)
675       return exit_client(cptr, cptr, &me, "Excess Flood");
676
677     while (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) && 
678            (IsTrusted(cptr) || cli_since(cptr) - CurrentTime < 10))
679     {
680       dolen = dbuf_getmsg(&(cli_recvQ(cptr)), cli_buffer(cptr), BUFSIZE);
681       /*
682        * Devious looking...whats it do ? well..if a client
683        * sends a *long* message without any CR or LF, then
684        * dbuf_getmsg fails and we pull it out using this
685        * loop which just gets the next 512 bytes and then
686        * deletes the rest of the buffer contents.
687        * -avalon
688        */
689       if (dolen == 0)
690       {
691         if (DBufLength(&(cli_recvQ(cptr))) < 510)
692           SetFlag(cptr, FLAG_NONL);
693         else
694         {
695           /* More than 512 bytes in the line - drop the input and yell
696            * at the client.
697            */
698           DBufClear(&(cli_recvQ(cptr)));
699           send_reply(cptr, ERR_INPUTTOOLONG);
700         }
701       }
702       else if (client_dopacket(cptr, dolen) == CPTR_KILLED)
703         return CPTR_KILLED;
704       /*
705        * If it has become registered as a Server
706        * then skip the per-message parsing below.
707        */
708       if (IsHandshake(cptr) || IsServer(cptr))
709       {
710         while (-1)
711         {
712           dolen = dbuf_get(&(cli_recvQ(cptr)), readbuf, sizeof(readbuf));
713           if (dolen <= 0)
714             return 1;
715           else if (dolen == 0)
716           {
717             if (DBufLength(&(cli_recvQ(cptr))) < 510)
718               SetFlag(cptr, FLAG_NONL);
719             else
720               DBufClear(&(cli_recvQ(cptr)));
721           }
722           else if ((IsServer(cptr) &&
723                     server_dopacket(cptr, readbuf, dolen) == CPTR_KILLED) ||
724                    (!IsServer(cptr) &&
725                     connect_dopacket(cptr, readbuf, dolen) == CPTR_KILLED))
726             return CPTR_KILLED;
727         }
728       }
729     }
730
731     /* If there's still data to process, wait 2 seconds first */
732     if (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) &&
733         !t_onqueue(&(cli_proc(cptr))))
734     {
735       Debug((DEBUG_LIST, "Adding client process timer for %C", cptr));
736       cli_freeflag(cptr) |= FREEFLAG_TIMER;
737       timer_add(&(cli_proc(cptr)), client_timer_callback, cli_connect(cptr),
738                 TT_RELATIVE, 2);
739     }
740   }
741   return 1;
742 }
743
744 /** Start a connection to another server.
745  * @param aconf Connect block data for target server.
746  * @param by Client who requested the connection (if any).
747  * @return Non-zero on success; zero on failure.
748  */
749 int connect_server(struct ConfItem* aconf, struct Client* by)
750 {
751   struct Client*   cptr = 0;
752   assert(0 != aconf);
753
754   if (aconf->dns_pending) {
755     sendto_opmask_butone(0, SNO_OLDSNO, "Server %s connect DNS pending",
756                          aconf->name);
757     return 0;
758   }
759   Debug((DEBUG_NOTICE, "Connect to %s[@%s]", aconf->name,
760          ircd_ntoa(&aconf->address.addr)));
761
762   if ((cptr = FindClient(aconf->name))) {
763     if (IsServer(cptr) || IsMe(cptr)) {
764       sendto_opmask_butone(0, SNO_OLDSNO, "Server %s already present from %s", 
765                            aconf->name, cli_name(cli_from(cptr)));
766       if (by && IsUser(by) && !MyUser(by)) {
767         sendcmdto_one(&me, CMD_NOTICE, by, "%C :Server %s already present "
768                       "from %s", by, aconf->name, cli_name(cli_from(cptr)));
769       }
770       return 0;
771     }
772     else if (IsHandshake(cptr) || IsConnecting(cptr)) {
773       if (by && IsUser(by)) {
774         sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connection to %s already in "
775                       "progress", by, cli_name(cptr));
776       }
777       return 0;
778     }
779   }
780   /*
781    * If we don't know the IP# for this host and it is a hostname and
782    * not a ip# string, then try and find the appropriate host record.
783    */
784   if (!irc_in_addr_valid(&aconf->address.addr)
785       && !ircd_aton(&aconf->address.addr, aconf->host)) {
786     char buf[HOSTLEN + 1];
787
788     host_from_uh(buf, aconf->host, HOSTLEN);
789     gethost_byname(buf, connect_dns_callback, aconf);
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 Connect block", aconf->name);
810     if (by && IsUser(by) && !MyUser(by)) {
811       sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connect to host %s failed: no "
812                     "Connect block", 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 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
912     if(ev_socket(ev)->ssl) ssl_session_free(ev_socket(ev)->ssl);
913     break;
914
915   case ET_CONNECT: /* socket connection completed */
916     if (!completed_connection(cptr) || IsDead(cptr))
917       fallback = cli_info(cptr);
918     break;
919
920   case ET_ERROR: /* an error occurred */
921     fallback = cli_info(cptr);
922     cli_error(cptr) = ev_data(ev);
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 }