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