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