Author: Kev <klmitch@mit.edu>
[ircu2.10.12-pk.git] / ircd / s_bsd.c
index d71037bfe5176fcb288fc34a3bd77733fd7d7574..459c9d399c929f2409eb7f158dcf6bd6bf9ad394 100644 (file)
@@ -19,6 +19,8 @@
  *
  * $Id$
  */
+#include "config.h"
+
 #include "s_bsd.h"
 #include "client.h"
 #include "IPcheck.h"
 #include "class.h"
 #include "hash.h"
 #include "ircd_log.h"
+#include "ircd_features.h"
 #include "ircd_osdep.h"
 #include "ircd_reply.h"
+#include "ircd_snprintf.h"
 #include "ircd_string.h"
 #include "ircd.h"
 #include "list.h"
 #include "listener.h"
 #include "msg.h"
+#include "msgq.h"
 #include "numeric.h"
 #include "numnicks.h"
 #include "packet.h"
@@ -45,7 +50,6 @@
 #include "s_misc.h"
 #include "s_user.h"
 #include "send.h"
-#include "sprintf_irc.h"
 #include "struct.h"
 #include "support.h"
 #include "sys.h"
@@ -92,20 +96,16 @@ const char* const LISTEN_ERROR_MSG    = "listen error for %s: %s";
 const char* const NONB_ERROR_MSG      = "error setting non-blocking for %s: %s";
 const char* const PEERNAME_ERROR_MSG  = "getpeername failed for %s: %s";
 const char* const POLL_ERROR_MSG      = "poll error for %s: %s";
+const char* const REGISTER_ERROR_MSG  = "registering %s: %s";
 const char* const REUSEADDR_ERROR_MSG = "error setting SO_REUSEADDR for %s: %s";
 const char* const SELECT_ERROR_MSG    = "select error for %s: %s";
 const char* const SETBUFS_ERROR_MSG   = "error setting buffer size for %s: %s";
 const char* const SOCKET_ERROR_MSG    = "error creating socket for %s: %s";
+const char* const TOS_ERROR_MSG              = "error setting TOS for %s: %s";
 
 
-#ifdef GODMODE
-#ifndef NODNS
-#define NODNS
-#endif
-#ifndef NOFLOODCONTROL
-#define NOFLOODCONTROL
-#endif
-#endif
+static void client_sock_callback(struct Event* ev);
+static void client_timer_callback(struct Event* ev);
 
 #if !defined(USE_POLL)
 #if FD_SETSIZE < (MAXCONNECTIONS + 4)
@@ -151,6 +151,7 @@ void report_error(const char* text, const char* who, int err)
   static time_t last_notice = 0;
   int           errtmp = errno;   /* debug may change 'errno' */
   const char*   errmsg = (err) ? strerror(err) : "";
+
   if (!errmsg)
     errmsg = "Unknown error"; 
 
@@ -164,7 +165,7 @@ void report_error(const char* text, const char* who, int err)
     sendto_opmask_butone(0, SNO_OLDSNO, text, who, errmsg);
     last_notice = CurrentTime;
   }
-  ircd_log(L_ERROR, text, who, errmsg);
+  log_write(LS_SOCKET, L_ERROR, 0, text, who, errmsg);
   errno = errtmp;
 }
 
@@ -185,7 +186,7 @@ static void connect_dns_callback(void* vptr, struct DNSReply* reply)
   }
   else
     sendto_opmask_butone(0, SNO_OLDSNO, "Connect to %s failed: host lookup",
-                        aconf->name);
+                         aconf->name);
 }
 
 /*
@@ -229,22 +230,23 @@ int init_connection_limits(void)
 static int connect_inet(struct ConfItem* aconf, struct Client* cptr)
 {
   static struct sockaddr_in sin;
+  IOResult result;
   assert(0 != aconf);
   assert(0 != cptr);
   /*
    * Might as well get sockhost from here, the connection is attempted
    * with it so if it fails its useless.
    */
-  cptr->fd = socket(AF_INET, SOCK_STREAM, 0);
-  if (-1 == cptr->fd) {
-    cptr->error = errno;
-    report_error(SOCKET_ERROR_MSG, cptr->name, errno);
+  cli_fd(cptr) = socket(AF_INET, SOCK_STREAM, 0);
+  if (-1 == cli_fd(cptr)) {
+    cli_error(cptr) = errno;
+    report_error(SOCKET_ERROR_MSG, cli_name(cptr), errno);
     return 0;
   }
-  if (cptr->fd >= MAXCLIENTS) {
-    report_error(CONNLIMIT_ERROR_MSG, cptr->name, 0);
-    close(cptr->fd);
-    cptr->fd = -1;
+  if (cli_fd(cptr) >= MAXCLIENTS) {
+    report_error(CONNLIMIT_ERROR_MSG, cli_name(cptr), 0);
+    close(cli_fd(cptr));
+    cli_fd(cptr) = -1;
     return 0;
   }
   /*
@@ -257,17 +259,20 @@ static int connect_inet(struct ConfItem* aconf, struct Client* cptr)
    * leading to a freezing select() on this side for some time.
    * I had this on my Linux 1.1.88 --Run
    */
-#ifdef VIRTUAL_HOST
+
   /*
    * No, we do bind it if we have virtual host support. If we don't
    * explicitly bind it, it will default to IN_ADDR_ANY and we lose
    * due to the other server not allowing our base IP --smg
    */
-  if (bind(cptr->fd, (struct sockaddr*) &VirtualHost, sizeof(VirtualHost))) {
-    report_error(BIND_ERROR_MSG, cptr->name, errno);
+  if (feature_bool(FEAT_VIRTUAL_HOST) &&
+      bind(cli_fd(cptr), (struct sockaddr*) &VirtualHost,
+          sizeof(VirtualHost))) {
+    report_error(BIND_ERROR_MSG, cli_name(cptr), errno);
+    close(cli_fd(cptr));
+    cli_fd(cptr) = -1;
     return 0;
   }
-#endif
 
   memset(&sin, 0, sizeof(sin));
   sin.sin_family      = AF_INET;
@@ -276,30 +281,47 @@ static int connect_inet(struct ConfItem* aconf, struct Client* cptr)
   /*
    * save connection info in client
    */
-  cptr->ip.s_addr = aconf->ipnum.s_addr;
-  cptr->port      = aconf->port;
-  ircd_ntoa_r(cptr->sock_ip, (const char*) &cptr->ip);
+  (cli_ip(cptr)).s_addr = aconf->ipnum.s_addr;
+  cli_port(cptr)        = aconf->port;
+  ircd_ntoa_r(cli_sock_ip(cptr), (const char*) &(cli_ip(cptr)));
   /*
    * we want a big buffer for server connections
    */
-  if (!os_set_sockbufs(cptr->fd, SERVER_TCP_WINDOW)) {
-    cptr->error = errno;
-    report_error(SETBUFS_ERROR_MSG, cptr->name, errno);
+  if (!os_set_sockbufs(cli_fd(cptr), SERVER_TCP_WINDOW)) {
+    cli_error(cptr) = errno;
+    report_error(SETBUFS_ERROR_MSG, cli_name(cptr), errno);
+    close(cli_fd(cptr));
+    cli_fd(cptr) = -1;
     return 0;
   }
   /*
    * ALWAYS set sockets non-blocking
    */
-  if (!os_set_nonblocking(cptr->fd)) {
-    cptr->error = errno;
-    report_error(NONB_ERROR_MSG, cptr->name, errno);
+  if (!os_set_nonblocking(cli_fd(cptr))) {
+    cli_error(cptr) = errno;
+    report_error(NONB_ERROR_MSG, cli_name(cptr), errno);
+    close(cli_fd(cptr));
+    cli_fd(cptr) = -1;
+    return 0;
+  }
+  if ((result = os_connect_nonb(cli_fd(cptr), &sin)) == IO_FAILURE) {
+    cli_error(cptr) = errno;
+    report_error(CONNECT_ERROR_MSG, cli_name(cptr), errno);
+    close(cli_fd(cptr));
+    cli_fd(cptr) = -1;
     return 0;
   }
-  if (!os_connect_nonb(cptr->fd, &sin)) {
-    cptr->error = errno;
-    report_error(CONNECT_ERROR_MSG, cptr->name, errno);
+  if (!socket_add(&(cli_socket(cptr)), client_sock_callback,
+                 (void*) cli_connect(cptr),
+                 (result == IO_SUCCESS) ? SS_CONNECTED : SS_CONNECTING,
+                 SOCK_EVENT_READABLE, cli_fd(cptr))) {
+    cli_error(cptr) = ENFILE;
+    report_error(REGISTER_ERROR_MSG, cli_name(cptr), ENFILE);
+    close(cli_fd(cptr));
+    cli_fd(cptr) = -1;
     return 0;
   }
+  cli_freeflag(cptr) |= FREEFLAG_SOCKET;
   return 1;
 }
 
@@ -326,34 +348,39 @@ static int connect_inet(struct ConfItem* aconf, struct Client* cptr)
  *      net.loads today anyway. Commented out the alarms to save cpu.
  *      --Run
  */
-unsigned int deliver_it(struct Client *cptr, const char *str, unsigned int len)
+unsigned int deliver_it(struct Client *cptr, struct MsgQ *buf)
 {
   unsigned int bytes_written = 0;
+  unsigned int bytes_count = 0;
   assert(0 != cptr);
 
-  switch (os_send_nonb(cptr->fd, str, len, &bytes_written)) {
+  switch (os_sendv_nonb(cli_fd(cptr), buf, &bytes_count, &bytes_written)) {
   case IO_SUCCESS:
-    cptr->flags &= ~FLAGS_BLOCKED;
+    cli_flags(cptr) &= ~FLAGS_BLOCKED;
 
-    cptr->sendB += bytes_written;
-    me.sendB    += bytes_written;
-    if (cptr->sendB > 1023) {
-      cptr->sendK += (cptr->sendB >> 10);
-      cptr->sendB &= 0x03ff;    /* 2^10 = 1024, 3ff = 1023 */
+    cli_sendB(cptr) += bytes_written;
+    cli_sendB(&me)  += bytes_written;
+    if (cli_sendB(cptr) > 1023) {
+      cli_sendK(cptr) += (cli_sendB(cptr) >> 10);
+      cli_sendB(cptr) &= 0x03ff;    /* 2^10 = 1024, 3ff = 1023 */
     }
-    if (me.sendB > 1023) {
-      me.sendK += (me.sendB >> 10);
-      me.sendB &= 0x03ff;
+    if (cli_sendB(&me) > 1023) {
+      cli_sendK(&me) += (cli_sendB(&me) >> 10);
+      cli_sendB(&me) &= 0x03ff;
     }
-    if (bytes_written < len)
-      cptr->flags |= FLAGS_BLOCKED;
+    /*
+     * XXX - hrmm.. set blocked here? the socket didn't
+     * say it was blocked
+     */
+    if (bytes_written < bytes_count)
+      cli_flags(cptr) |= FLAGS_BLOCKED;
     break;
   case IO_BLOCKED:
-    cptr->flags |= FLAGS_BLOCKED;
+    cli_flags(cptr) |= FLAGS_BLOCKED;
     break;
   case IO_FAILURE:
-    cptr->error = errno;
-    cptr->flags |= FLAGS_DEADSOCKET;
+    cli_error(cptr) = errno;
+    cli_flags(cptr) |= FLAGS_DEADSOCKET;
     break;
   }
   return bytes_written;
@@ -365,10 +392,10 @@ void release_dns_reply(struct Client* cptr)
   assert(0 != cptr);
   assert(MyConnect(cptr));
 
-  if (cptr->dns_reply) {
-    assert(0 < cptr->dns_reply->ref_count);
-    --cptr->dns_reply->ref_count;
-    cptr->dns_reply = 0;
+  if (cli_dns_reply(cptr)) {
+    assert(0 < cli_dns_reply(cptr)->ref_count);
+    --(cli_dns_reply(cptr))->ref_count;
+    cli_dns_reply(cptr) = 0;
   }
 }
 
@@ -394,26 +421,24 @@ static int completed_connection(struct Client* cptr)
    * get the socket status from the fd first to check if
    * connection actually succeeded
    */
-  if ((cptr->error = os_get_sockerr(cptr->fd))) {
-    const char* msg = strerror(cptr->error);
+  if ((cli_error(cptr) = os_get_sockerr(cli_fd(cptr)))) {
+    const char* msg = strerror(cli_error(cptr));
     if (!msg)
       msg = "Unknown error";
     sendto_opmask_butone(0, SNO_OLDSNO, "Connection failed to %s: %s",
-                        cptr->name, msg);
+                         cli_name(cptr), msg);
     return 0;
   }
-  if (!(aconf = find_conf_byname(cptr->confs, cptr->name, CONF_SERVER))) {
-    sendto_opmask_butone(0, SNO_OLDSNO, "Lost Server Line for %s", cptr->name);
+  if (!(aconf = find_conf_byname(cli_confs(cptr), cli_name(cptr), CONF_SERVER))) {
+    sendto_opmask_butone(0, SNO_OLDSNO, "Lost Server Line for %s", cli_name(cptr));
     return 0;
   }
+  if (s_state(&(cli_socket(cptr))) == SS_CONNECTING)
+    socket_state(&(cli_socket(cptr)), SS_CONNECTED);
 
   if (!EmptyString(aconf->passwd))
     sendrawto_one(cptr, MSG_PASS " :%s", aconf->passwd);
 
-#if 0 
-  /* dead code, already done in connect_server */
-  make_server(cptr);
-#endif
   /*
    * Create a unique timestamp
    */
@@ -421,23 +446,24 @@ static int completed_connection(struct Client* cptr)
   for (i = HighestFd; i > -1; --i) {
     if ((acptr = LocalClientArray[i]) && 
         (IsServer(acptr) || IsHandshake(acptr))) {
-      if (acptr->serv->timestamp >= newts)
-        newts = acptr->serv->timestamp + 1;
+      if (cli_serv(acptr)->timestamp >= newts)
+        newts = cli_serv(acptr)->timestamp + 1;
     }
   }
-  assert(0 != cptr->serv);
+  assert(0 != cli_serv(cptr));
 
-  cptr->serv->timestamp = newts;
+  cli_serv(cptr)->timestamp = newts;
   SetHandshake(cptr);
   /*
    * Make us timeout after twice the timeout for DNS look ups
    */
-  cptr->lasttime = CurrentTime;
-  cptr->flags |= FLAGS_PINGSENT;
+  cli_lasttime(cptr) = CurrentTime;
+  cli_flags(cptr) |= FLAGS_PINGSENT;
 
-  sendrawto_one(cptr, MSG_SERVER " %s 1 %Tu %Tu J%s %s%s :%s",
-               me.name, me.serv->timestamp, newts, MAJOR_PROTOCOL, 
-               NumServCap(&me), me.info);
+  sendrawto_one(cptr, MSG_SERVER " %s 1 %Tu %Tu J%s %s%s +%s :%s",
+                cli_name(&me), cli_serv(&me)->timestamp, newts,
+               MAJOR_PROTOCOL, NumServCap(&me),
+               feature_bool(FEAT_HUB) ? "h" : "", cli_info(&me));
 
   return (IsDead(cptr)) ? 0 : 1;
 }
@@ -454,11 +480,11 @@ void close_connection(struct Client *cptr)
 
   if (IsServer(cptr)) {
     ServerStats->is_sv++;
-    ServerStats->is_sbs += cptr->sendB;
-    ServerStats->is_sbr += cptr->receiveB;
-    ServerStats->is_sks += cptr->sendK;
-    ServerStats->is_skr += cptr->receiveK;
-    ServerStats->is_sti += CurrentTime - cptr->firsttime;
+    ServerStats->is_sbs += cli_sendB(cptr);
+    ServerStats->is_sbr += cli_receiveB(cptr);
+    ServerStats->is_sks += cli_sendK(cptr);
+    ServerStats->is_skr += cli_receiveK(cptr);
+    ServerStats->is_sti += CurrentTime - cli_firsttime(cptr);
     if (ServerStats->is_sbs > 1023) {
       ServerStats->is_sks += (ServerStats->is_sbs >> 10);
       ServerStats->is_sbs &= 0x3ff;
@@ -471,7 +497,7 @@ void close_connection(struct Client *cptr)
      * If the connection has been up for a long amount of time, schedule
      * a 'quick' reconnect, else reset the next-connect cycle.
      */
-    if ((aconf = find_conf_exact(cptr->name, 0, cptr->sockhost, CONF_SERVER))) {
+    if ((aconf = find_conf_exact(cli_name(cptr), 0, cli_sockhost(cptr), CONF_SERVER))) {
       /*
        * Reschedule a faster reconnect, if this was a automaticly
        * connected configuration entry. (Note that if we have had
@@ -479,19 +505,20 @@ void close_connection(struct Client *cptr)
        * CONF_ILLEGAL). But only do this if it was a "good" link.
        */
       aconf->hold = CurrentTime;
-      aconf->hold += (aconf->hold - cptr->since > HANGONGOODLINK) ?
-                     HANGONRETRYDELAY : ConfConFreq(aconf);
-      if (nextconnect > aconf->hold)
-        nextconnect = aconf->hold;
+      aconf->hold += ((aconf->hold - cli_since(cptr) >
+                      feature_int(FEAT_HANGONGOODLINK)) ?
+                     feature_int(FEAT_HANGONRETRYDELAY) : ConfConFreq(aconf));
+/*        if (nextconnect > aconf->hold) */
+/*          nextconnect = aconf->hold; */
     }
   }
   else if (IsUser(cptr)) {
     ServerStats->is_cl++;
-    ServerStats->is_cbs += cptr->sendB;
-    ServerStats->is_cbr += cptr->receiveB;
-    ServerStats->is_cks += cptr->sendK;
-    ServerStats->is_ckr += cptr->receiveK;
-    ServerStats->is_cti += CurrentTime - cptr->firsttime;
+    ServerStats->is_cbs += cli_sendB(cptr);
+    ServerStats->is_cbr += cli_receiveB(cptr);
+    ServerStats->is_cks += cli_sendK(cptr);
+    ServerStats->is_ckr += cli_receiveK(cptr);
+    ServerStats->is_cti += CurrentTime - cli_firsttime(cptr);
     if (ServerStats->is_cbs > 1023) {
       ServerStats->is_cks += (ServerStats->is_cbs >> 10);
       ServerStats->is_cbs &= 0x3ff;
@@ -504,24 +531,26 @@ void close_connection(struct Client *cptr)
   else
     ServerStats->is_ni++;
 
-  if (-1 < cptr->fd) {
+  if (-1 < cli_fd(cptr)) {
     flush_connections(cptr);
-    LocalClientArray[cptr->fd] = 0;
-    close(cptr->fd);
-    cptr->fd = -1;
+    LocalClientArray[cli_fd(cptr)] = 0;
+    close(cli_fd(cptr));
+    socket_del(&(cli_socket(cptr))); /* queue a socket delete */
+    cli_fd(cptr) = -1;
   }
-  cptr->flags |= FLAGS_DEADSOCKET;
+  cli_flags(cptr) |= FLAGS_DEADSOCKET;
 
-  DBufClear(&cptr->sendQ);
-  DBufClear(&cptr->recvQ);
-  memset(cptr->passwd, 0, sizeof(cptr->passwd));
+  MsgQClear(&(cli_sendQ(cptr)));
+  client_drop_sendq(cli_connect(cptr));
+  DBufClear(&(cli_recvQ(cptr)));
+  memset(cli_passwd(cptr), 0, sizeof(cli_passwd(cptr)));
   set_snomask(cptr, 0, SNO_SET);
 
   det_confs_butmask(cptr, 0);
 
-  if (cptr->listener) {
-    release_listener(cptr->listener);
-    cptr->listener = 0;
+  if (cli_listener(cptr)) {
+    release_listener(cli_listener(cptr));
+    cli_listener(cptr) = 0;
   }
 
   for ( ; HighestFd > 0; --HighestFd) {
@@ -547,86 +576,102 @@ int net_close_unregistered_connections(struct Client* source)
   return count;
 }
 
-/*
+/*----------------------------------------------------------------------------
+ * add_connection
+ *
  * Creates a client which has just connected to us on the given fd.
  * The sockhost field is initialized with the ip# of the host.
  * The client is not added to the linked list of clients, it is
  * passed off to the auth handler for dns and ident queries.
- */
-void add_connection(struct Listener* listener, int fd)
-{
+ *--------------------------------------------------------------------------*/
+void add_connection(struct Listener* listener, int fd) {
   struct sockaddr_in addr;
-  struct Client*     new_client;
+  struct Client      *new_client;
   time_t             next_target = 0;
+
   const char* const throttle_message =
-         "ERRORYour host is trying to (re)connect too fast -- throttled\r\n";
+         "ERROR :Your host is trying to (re)connect too fast -- throttled\r\n";
        /* 12345678901234567890123456789012345679012345678901234567890123456 */
+  const char* const register_message =
+         "ERROR :Unable to complete your registration\r\n";
   
   assert(0 != listener);
+
   /*
-   * Removed preliminary access check. Full check is performed in
-   * m_server and m_user instead. Also connection time out help to
-   * get rid of unwanted connections.
+   * Removed preliminary access check. Full check is performed in m_server and
+   * m_user instead. Also connection time out help to get rid of unwanted
+   * connections.  
    */
   if (!os_get_peername(fd, &addr) || !os_set_nonblocking(fd)) {
     ++ServerStats->is_ref;
     close(fd);
     return;
   }
+
   /*
    * Add this local client to the IPcheck registry.
-   * If it is a connection to a user port and if the site has been throttled,
-   * reject the user.
+   *
+   * If they're throttled, murder them, but tell them why first.
    */
   if (!IPcheck_local_connect(addr.sin_addr, &next_target) && !listener->server) {
-#ifdef IPCHECKDEBUG     
-   char buff[512];
-   snprintf(buff,"\n%s [%i connections active]\n",
-       throttle_message,
-       IPcheck_nr(addr.sin_addr));
-   buff[511]=0;
-   send(fd,buff,strlen(buff));
-#else
-    /*
-     * strlen(throttle_message) == 66
-     *
-     * strlen is slow, so we use the constant here.
-     */
-    send(fd, throttle_message, 66, 0);
-#endif
-    close(fd);
     ++ServerStats->is_ref;
-    return;
+     write(fd, throttle_message, strlen(throttle_message));
+     close(fd);
+     return;
   }
 
-  new_client = make_client(0,
-      (listener->server) ? STAT_UNKNOWN_SERVER : STAT_UNKNOWN_USER);
+  new_client = make_client(0, ((listener->server) ? 
+                               STAT_UNKNOWN_SERVER : STAT_UNKNOWN_USER));
+
   /*
-   * Copy ascii address to 'sockhost' just in case. Then we
-   * have something valid to put into error messages...
+   * Copy ascii address to 'sockhost' just in case. Then we have something
+   * valid to put into error messages...  
    */
-  ircd_ntoa_r(new_client->sock_ip, (const char*) &addr.sin_addr);   
-  strcpy(new_client->sockhost, new_client->sock_ip);
-  new_client->ip.s_addr = addr.sin_addr.s_addr;
-  new_client->port      = ntohs(addr.sin_port);
+  ircd_ntoa_r(cli_sock_ip(new_client), (const char*) &addr.sin_addr);   
+  strcpy(cli_sockhost(new_client), cli_sock_ip(new_client));
+  (cli_ip(new_client)).s_addr = addr.sin_addr.s_addr;
+  cli_port(new_client)        = ntohs(addr.sin_port);
 
   if (next_target)
-    new_client->nexttarget = next_target;
-
-  new_client->fd = fd;
+    cli_nexttarget(new_client) = next_target;
 
-  if (!listener->server)
-    SetIPChecked(new_client);
-  new_client->listener = listener;
+  cli_fd(new_client) = fd;
+  if (!socket_add(&(cli_socket(new_client)), client_sock_callback,
+                 (void*) cli_connect(new_client), SS_CONNECTED, 0, fd)) {
+    ++ServerStats->is_ref;
+    write(fd, register_message, strlen(register_message));
+    close(fd);
+    cli_fd(new_client) = -1;
+    return;
+  }
+  cli_freeflag(new_client) |= FREEFLAG_SOCKET;
+  cli_listener(new_client) = listener;
   ++listener->ref_count;
 
   Count_newunknown(UserStats);
-  /*
-   * if we've made it this far we can put the client on the auth query pile
-   */
+  /* if we've made it this far we can put the client on the auth query pile */
   start_auth(new_client);
 }
 
+/*
+ * update_write
+ *
+ * Determines whether to tell the events engine we're interested in
+ * writable events
+ */
+void update_write(struct Client* cptr)
+{
+  /* If there are messages that need to be sent along, or if the client
+   * is in the middle of a /list, then we need to tell the engine that
+   * we're interested in writable events--otherwise, we need to drop
+   * that interest.
+   */
+  socket_events(&(cli_socket(cptr)),
+               ((MsgQLength(&cli_sendQ(cptr)) || cli_listing(cptr)) ?
+                SOCK_ACTION_ADD : SOCK_ACTION_DEL) | SOCK_EVENT_WRITABLE);
+}
+
 /*
  * read_packet
  *
@@ -640,20 +685,22 @@ static int read_packet(struct Client *cptr, int socket_ready)
   unsigned int dolen = 0;
   unsigned int length = 0;
 
-  if (socket_ready && !(IsUser(cptr) && DBufLength(&cptr->recvQ) > CLIENT_FLOOD)) {
-    switch (os_recv_nonb(cptr->fd, readbuf, sizeof(readbuf), &length)) {
+  if (socket_ready &&
+      !(IsUser(cptr) &&
+       DBufLength(&(cli_recvQ(cptr))) > feature_int(FEAT_CLIENT_FLOOD))) {
+    switch (os_recv_nonb(cli_fd(cptr), readbuf, sizeof(readbuf), &length)) {
     case IO_SUCCESS:
       if (length) {
-        cptr->lasttime = CurrentTime;
-        if (cptr->lasttime > cptr->since)
-          cptr->since = cptr->lasttime;
-        cptr->flags &= ~(FLAGS_PINGSENT | FLAGS_NONL);
+        cli_lasttime(cptr) = CurrentTime;
+        if (cli_lasttime(cptr) > cli_since(cptr))
+          cli_since(cptr) = cli_lasttime(cptr);
+        cli_flags(cptr) &= ~(FLAGS_PINGSENT | FLAGS_NONL);
       }
       break;
     case IO_BLOCKED:
       break;
     case IO_FAILURE:
-      cptr->error = errno;
+      cli_error(cptr) = errno;
       /* cptr->flags |= FLAGS_DEADSOCKET; */
       return 0;
     }
@@ -672,31 +719,29 @@ static int read_packet(struct Client *cptr, int socket_ready)
      * it on the end of the receive queue and do it when its
      * turn comes around.
      */
-    if (length > 0 && 0 == dbuf_put(&cptr->recvQ, readbuf, length)) {
+    if (length > 0 && 0 == dbuf_put(&(cli_recvQ(cptr)), readbuf, length)) {
       return exit_client(cptr, cptr, &me, "dbuf_put fail");
     }
-#ifndef NOFLOODCONTROL
+
     /*
      * XXX - cptr will always be a user or unregistered
      */
-    if (IsUser(cptr) && DBufLength(&cptr->recvQ) > CLIENT_FLOOD)
+    if (IsUser(cptr) &&
+       DBufLength(&(cli_recvQ(cptr))) > feature_int(FEAT_CLIENT_FLOOD))
       return exit_client(cptr, cptr, &me, "Excess Flood");
 
-    while (DBufLength(&cptr->recvQ) && !NoNewLine(cptr) && 
-           (IsTrusted(cptr) || cptr->since - CurrentTime < 10))
-#else
-    while (DBufLength(&cptr->recvQ) && !NoNewLine(cptr))
-#endif
+    while (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) && 
+           (IsTrusted(cptr) || cli_since(cptr) - CurrentTime < 10))
     {
       /*
        * If it has become registered as a Server
        * then skip the per-message parsing below.
        */
       if (IsServer(cptr)) {
-        dolen = dbuf_get(&cptr->recvQ, readbuf, sizeof(readbuf));
+        dolen = dbuf_get(&(cli_recvQ(cptr)), readbuf, sizeof(readbuf));
         return (dolen) ? server_dopacket(cptr, readbuf, dolen) : 1;
       }
-      dolen = dbuf_getmsg(&cptr->recvQ, cptr->buffer, BUFSIZE);
+      dolen = dbuf_getmsg(&(cli_recvQ(cptr)), cli_buffer(cptr), BUFSIZE);
       /*
        * Devious looking...whats it do ? well..if a client
        * sends a *long* message without any CR or LF, then
@@ -706,596 +751,27 @@ static int read_packet(struct Client *cptr, int socket_ready)
        * -avalon
        */
       if (0 == dolen) {
-        if (DBufLength(&cptr->recvQ) < 510)
-          cptr->flags |= FLAGS_NONL;
+        if (DBufLength(&(cli_recvQ(cptr))) < 510)
+          cli_flags(cptr) |= FLAGS_NONL;
         else
-          DBufClear(&cptr->recvQ);
+          DBufClear(&(cli_recvQ(cptr)));
       }
       else if (CPTR_KILLED == client_dopacket(cptr, dolen))
         return CPTR_KILLED;
     }
-  }
-  return 1;
-}
-
-static int on_write_unblocked(struct Client* cptr)
-{
-  /*
-   *  ...room for writing, empty some queue then...
-   */
-  cptr->flags &= ~FLAGS_BLOCKED;
-  if (IsConnecting(cptr)) {
-    if (!completed_connection(cptr))
-      return 0;
-  }
-  else if (cptr->listing && DBufLength(&cptr->sendQ) < 2048)
-    list_next_channels(cptr, 64);
-  send_queued(cptr);
-  return 1;
-}
-
-/*
- * Select / Poll Read Algorithm for ircd
- *
- * We need to check the file descriptors for all the different types
- * of things that use them, so check for reads on everything but connects
- * and writes on connects and descriptors that are blocked
- *
- * for each (client in local) {
- *   if (not connecting)
- *     check for read;
- *   if (connecting or blocked)
- *     check for write;
- * }
- * wait for activity;
- *
- * for each (client in local) {
- *   if (there are descriptors to check) {
- *     if (write activity)
- *       send data;
- *     if (read activity)
- *       read data;
- *   }
- *   process data read;
- * }
- * Note we must always process data read whether or not there has been
- * read activity or file descriptors set, since data is buffered by the client.
- */
-
-
-#ifdef USE_POLL
-
-/*
- * poll macros
- */
-#if defined(POLLMSG) && defined(POLLIN) && defined(POLLRDNORM)
-#  define POLLREADFLAGS (POLLMSG|POLLIN|POLLRDNORM)
-#else
-#  if defined(POLLIN) && defined(POLLRDNORM)
-#    define POLLREADFLAGS (POLLIN|POLLRDNORM)
-#  else
-#    if defined(POLLIN)
-#      define POLLREADFLAGS POLLIN
-#    else
-#      if defined(POLLRDNORM)
-#        define POLLREADFLAGS POLLRDNORM
-#      endif
-#    endif
-#  endif
-#endif
-
-#if defined(POLLOUT) && defined(POLLWRNORM)
-#define POLLWRITEFLAGS (POLLOUT|POLLWRNORM)
-#else
-#  if defined(POLLOUT)
-#    define POLLWRITEFLAGS POLLOUT
-#  else
-#    if defined(POLLWRNORM)
-#      define POLLWRITEFLAGS POLLWRNORM
-#    endif
-#  endif
-#endif
-
-#ifdef POLLHUP
-#define POLLERRORS (POLLHUP|POLLERR)
-#else
-#define POLLERRORS POLLERR
-#endif
-
-/*
- * NOTE: pfd and pfd_count are local variable names in read_message
- */
-#define PFD_SETR(xfd) \
-  do { CHECK_ADD_PFD(xfd) pfd->events |= POLLREADFLAGS; } while(0)
-#define PFD_SETW(xfd) \
-  do { CHECK_ADD_PFD(xfd) pfd->events |= POLLWRITEFLAGS; } while(0)
-
-#define CHECK_ADD_PFD(xfd) \
-  if (pfd->fd != xfd) { \
-    pfd = &poll_fds[pfd_count++]; \
-    poll_fds[pfd_count].fd = -1; \
-    pfd->fd = xfd; \
-    pfd->events = 0; \
-  }
-
-/*
- * Check all connections for new connections and input data that is to be
- * processed. Also check for connections with data queued and whether we can
- * write it out.
- *
- * Don't ever use ZERO for `delay', unless you mean to poll and then
- * you have to have sleep/wait somewhere else in the code.--msa
- */
-int read_message(time_t delay)
-{
-  struct pollfd poll_fds[MAXCONNECTIONS + 1];
-  struct Client*      cptr;
-  struct Listener*    listener   = 0;
-  struct AuthRequest* auth       = 0;
-  struct AuthRequest* auth_next  = 0;
-  struct UPing*       uping      = 0;
-  struct UPing*       uping_next = 0;
-  time_t delay2 = delay;
-  int nfds;
-  int length;
-  int i;
-  int res = 0;
-  int pfd_count;
-  struct pollfd* pfd;
-  struct pollfd* res_pfd;
-  struct pollfd* uping_pfd;
-  int read_ready;
-  int write_ready;
-
-  unsigned int timeout;
-
-  for ( ; ; ) {
-    pfd_count = 0;
-    pfd = poll_fds;
-    res_pfd = 0;
-    uping_pfd = 0;
-    pfd->fd = -1;
-
-    if (-1 < ResolverFileDescriptor) {
-      PFD_SETR(ResolverFileDescriptor);
-      res_pfd = pfd;
-    }
-    if (-1 < UPingFileDescriptor) {
-      PFD_SETR(UPingFileDescriptor);
-      uping_pfd = pfd;
-    }
-    /*
-     * add uping descriptors
-     */
-    for (uping = uping_begin(); uping; uping = uping_next) {
-      uping_next = uping->next;
-      if (uping->active) {
-        delay2 = 1;
-       if (uping->lastsent && CurrentTime > uping->timeout) {
-          uping_end(uping);
-          continue;
-        }
-        uping->index = pfd_count;
-        PFD_SETR(uping->fd);
-      }
-    }
-    /*
-     * add auth file descriptors
-     */
-    for (auth = AuthPollList; auth; auth = auth->next) {
-      assert(-1 < auth->fd);
-      auth->index = pfd_count;
-      if (IsAuthConnect(auth))
-        PFD_SETW(auth->fd);
-      else
-        PFD_SETR(auth->fd);
-    }
-    /*
-     * add listener file descriptors
-     */    
-    for (listener = ListenerPollList; listener; listener = listener->next) {
-      assert(-1 < listener->fd);
-      /*
-       * pfd_count is incremented by PFD_SETR so we need to save the 
-       * index first 
-       */
-      listener->index = pfd_count;
-      PFD_SETR(listener->fd);
-    }
-
-    for (i = HighestFd; -1 < i; --i) {
-      if ((cptr = LocalClientArray[i])) {
-
-        if (DBufLength(&cptr->recvQ))
-          delay2 = 1;
-        if (DBufLength(&cptr->recvQ) < 4088 || IsServer(cptr)) {
-          PFD_SETR(i);
-        }
-        if (DBufLength(&cptr->sendQ) || IsConnecting(cptr) ||
-            (cptr->listing && DBufLength(&cptr->sendQ) < 2048)) {
-          PFD_SETW(i);
-        }
-      }
-    }
-
-    Debug((DEBUG_INFO, "poll: %d %d", delay, delay2));
-
-    timeout = (IRCD_MIN(delay2, delay)) * 1000;
-
-    nfds = poll(poll_fds, pfd_count, timeout);
-
-    CurrentTime = time(0);
-    if (-1 < nfds)
-      break;
-
-    if (EINTR == errno)
-      return -1;
-    report_error(POLL_ERROR_MSG, me.name, errno);
-    ++res;
-    if (res > 5)
-      server_restart("too many poll errors");
-    sleep(1);
-    CurrentTime = time(0);
-  }
-
-  if (uping_pfd && (uping_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
-    uping_echo();
-    --nfds;
-  }
-  /*
-   * check uping replies
-   */
-  for (uping = uping_begin(); uping; uping = uping_next) {
-    uping_next = uping->next;
-    if (uping->active) {
-      assert(-1 < uping->index);
-      if (poll_fds[uping->index].revents) {
-        uping_read(uping);
-        if (0 == --nfds)
-          break;
-      }
-      else if (CurrentTime > uping->lastsent) {
-        uping->lastsent = CurrentTime;
-        uping_send(uping);
-      }
-    }
-  }
-
-  if (res_pfd && (res_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
-    resolver_read();
-    --nfds;
-  }
-  /*
-   * check auth queries
-   */
-  for (auth = AuthPollList; auth; auth = auth_next) {
-    auth_next = auth->next;
-    i = auth->index;
-    /*
-     * check for any event, we only ask for one at a time
-     */
-    if (poll_fds[i].revents) {
-      if (IsAuthConnect(auth))
-        send_auth_query(auth);
-      else
-        read_auth_reply(auth);
-      if (0 == --nfds)
-        break;
-    }
-  }
-  /*
-   * check listeners
-   */
-  for (listener = ListenerPollList; listener; listener = listener->next) {
-    i = listener->index;
-    if (poll_fds[i].revents) {
-      accept_connection(listener);
-      if (0 == --nfds)
-        break;
-    }
-  }
-  /*
-   * i contains the next non-auth/non-listener index, since we put the
-   * resolver, auth and listener, file descriptors in poll_fds first,
-   * the very next one should be the start of the clients
-   */
-  pfd = &poll_fds[++i];
-
-  for ( ; (i < pfd_count); ++i, ++pfd) {
-    if (!(cptr = LocalClientArray[pfd->fd]))
-      continue;
-    read_ready = write_ready = 0;
-
-    if (0 < nfds && pfd->revents) {
-      --nfds;
-    
-      read_ready  = pfd->revents & POLLREADFLAGS;
-      write_ready = pfd->revents & POLLWRITEFLAGS;
-
-      if (pfd->revents & POLLERRORS) {
-        if (pfd->events & POLLREADFLAGS)
-          ++read_ready;
-        if (pfd->events & POLLWRITEFLAGS)
-          ++write_ready;
-      }
-    }
-    if (write_ready) {
-      if (!on_write_unblocked(cptr) || IsDead(cptr)) {
-        const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
-        if (!msg)
-          msg = "Unknown error";
-        exit_client(cptr, cptr, &me, msg);
-        continue;
-      }
-    }
-    length = 1;                 /* for fall through case */
-    if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
-      if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
-        continue;
-    }
-#if 0
-    /* Bullshit, why would we want to flush sockets while using non-blocking?
-     * This uses > 4% cpu! --Run */
-    if (length > 0)
-      flush_connections(poll_cptr[i]);
-#endif
-    if (IsDead(cptr)) {
-      const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
-      if (!msg)
-        msg = "Unknown error";
-      exit_client(cptr, cptr, &me, (char*) msg);
-      continue;
-    }
-    if (length > 0)
-      continue;
-    cptr->flags |= FLAGS_DEADSOCKET;
-    /*
-     * ...hmm, with non-blocking sockets we might get
-     * here from quite valid reasons, although.. why
-     * would select report "data available" when there
-     * wasn't... So, this must be an error anyway...  --msa
-     * actually, EOF occurs when read() returns 0 and
-     * in due course, select() returns that fd as ready
-     * for reading even though it ends up being an EOF. -avalon
-     */
-    Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", pfd->fd, errno, length));
-
-    if ((IsServer(cptr) || IsHandshake(cptr)) && cptr->error == 0 && length == 0)
-      exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
-                      cptr->name, cptr->serv->last_error_msg);
-    else {
-      const char* msg = (cptr->error) ? strerror(cptr->error) : "EOF from client";
-      if (!msg)
-        msg = "Unknown error";
-      exit_client_msg(cptr, cptr, &me, "Read error: %s",
-                      msg);
-    }
-  }
-  return 0;
-}
-#else /* USE_SELECT */
-
-/*
- * Check all connections for new connections and input data that is to be
- * processed. Also check for connections with data queued and whether we can
- * write it out.
- *
- * Don't ever use ZERO for `delay', unless you mean to poll and then
- * you have to have sleep/wait somewhere else in the code.--msa
- */
-int read_message(time_t delay)
-{
-  struct Client*   cptr;
-  struct Listener* listener;
-  struct AuthRequest* auth = 0;
-  struct AuthRequest* auth_next = 0;
-  struct UPing*       uping;
-  struct UPing*       uping_next;
-  int              nfds;
-  struct timeval   wait;
-  time_t           delay2 = delay;
-  unsigned int     usec = 0;
-  int              res = 0;
-  int              length;
-  int              i;
-  int              read_ready;
-  fd_set           read_set;
-  fd_set           write_set;
-
-  for ( ; ; )
-  {
-    FD_ZERO(&read_set);
-    FD_ZERO(&write_set);
-
-    if (-1 < ResolverFileDescriptor)
-      FD_SET(ResolverFileDescriptor, &read_set);
-    if (-1 < UPingFileDescriptor)
-      FD_SET(UPingFileDescriptor, &read_set);
-    /*
-     * set up uping file descriptors
-     */
-    for (uping = uping_begin(); uping; uping = uping_next) {
-      uping_next = uping->next;
-      if (uping->active) {
-        delay2 = 1;
-        if (uping->lastsent && CurrentTime > uping->timeout) {
-          uping_end(uping);
-          continue;
-        }
-        assert(-1 < uping->fd);
-        FD_SET(uping->fd, &read_set);
-      }
-    }
-    /*
-     * set auth file descriptors
-     */
-    for (auth = AuthPollList; auth; auth = auth->next) {
-      assert(-1 < auth->fd);
-      if (IsAuthConnect(auth))
-        FD_SET(auth->fd, &write_set);
-      else /* if (IsAuthPending(auth)) */
-        FD_SET(auth->fd, &read_set);
-    }
-    /*
-     * set listener file descriptors
-     */
-    for (listener = ListenerPollList; listener; listener = listener->next) {
-      assert(-1 < listener->fd);
-      FD_SET(listener->fd, &read_set);
-    }
-
-    for (i = HighestFd; i > -1; --i) {
-      if ((cptr = LocalClientArray[i])) {
-        if (DBufLength(&cptr->recvQ))
-          delay2 = 1;
-        if (DBufLength(&cptr->recvQ) < 4088 || IsServer(cptr))
-          FD_SET(i, &read_set);
-        if (DBufLength(&cptr->sendQ) || IsConnecting(cptr) ||
-            (cptr->listing && DBufLength(&cptr->sendQ) < 2048))
-          FD_SET(i, &write_set);
-      }
-    }
-
-    wait.tv_sec = IRCD_MIN(delay2, delay);
-    wait.tv_usec = usec;
-
-    Debug((DEBUG_INFO, "select: %d %d", delay, delay2));
-
-    nfds = select(FD_SETSIZE, &read_set, &write_set, 0, &wait);
-
-    CurrentTime = time(0);
-
-    if (-1 < nfds)
-      break;
-
-    if (errno == EINTR)
-      return -1;
-    report_error(SELECT_ERROR_MSG, me.name, errno);
-    if (++res > 5)
-      server_restart("too many select errors");
-    sleep(1);
-    CurrentTime = time(0);
-  }
-
-  if (-1 < UPingFileDescriptor && FD_ISSET(UPingFileDescriptor, &read_set)) {
-    uping_echo();
-    --nfds;
-  }
-  for (uping = uping_begin(); uping; uping = uping_next) {
-    uping_next = uping->next;
-    if (uping->active) {
-      assert(-1 < uping->fd);
-      if (FD_ISSET(uping->fd, &read_set)) {
-        uping_read(uping);
-        if (0 == --nfds)
-          break;
-      }
-      else if (CurrentTime > uping->lastsent) {
-        uping->lastsent = CurrentTime;
-        uping_send(uping);
-      }
-    }
-  }
-  if (-1 < ResolverFileDescriptor && FD_ISSET(ResolverFileDescriptor, &read_set)) {
-    resolver_read();
-    --nfds;
-  }
-  /*
-   * Check fd sets for the auth fd's (if set and valid!) first
-   * because these can not be processed using the normal loops below.
-   * -avalon
-   */
-  for (auth = AuthPollList; auth; auth = auth_next) {
-    auth_next = auth->next;
-    assert(-1 < auth->fd);
-    if (IsAuthConnect(auth) && FD_ISSET(auth->fd, &write_set)) {
-      send_auth_query(auth);
-      if (0 == --nfds)
-        break;
-    }
-    else if (FD_ISSET(auth->fd, &read_set)) {
-      read_auth_reply(auth);
-      if (0 == --nfds)
-        break;
-    }
-  }
-  /*
-   * next accept connections from active listeners
-   */
-  for (listener = ListenerPollList; listener; listener = listener->next) {
-    assert(-1 < listener->fd);
-    if (0 < nfds && FD_ISSET(listener->fd, &read_set))
-      accept_connection(listener);
-  } 
-
-  for (i = HighestFd; -1 < i; --i) {
-    if (!(cptr = LocalClientArray[i]))
-      continue;
-    read_ready = 0;
-    if (0 < nfds) {
-      if (FD_ISSET(i, &write_set)) {
-        --nfds;
-        if (!on_write_unblocked(cptr) || IsDead(cptr)) {
-          const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
-          if (!msg)
-            msg = "Unknown error";
-          if (FD_ISSET(i, &read_set))
-            --nfds;
-          exit_client(cptr, cptr, &me, msg);
-          continue;
-        }
-      }
-      if ((read_ready = FD_ISSET(i, &read_set)))
-        --nfds;
-    }
-    length = 1;                 /* for fall through case */
-    if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
-      if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
-        continue;
-    }
-#if 0
-    /* Bullshit, why would we want to flush sockets while using non-blocking?
-     * This uses > 4% cpu! --Run */
-    if (length > 0)
-      flush_connections(LocalClientArray[i]);
-#endif
-    if (IsDead(cptr)) {
-      const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
-      if (!msg)
-        msg = "Unknown error";
-      exit_client(cptr, cptr, &me, msg);
-      continue;
-    }
-    if (length > 0)
-      continue;
-
-    /*
-     * ...hmm, with non-blocking sockets we might get
-     * here from quite valid reasons, although.. why
-     * would select report "data available" when there
-     * wasn't... So, this must be an error anyway...  --msa
-     * actually, EOF occurs when read() returns 0 and
-     * in due course, select() returns that fd as ready
-     * for reading even though it ends up being an EOF. -avalon
-     */
-    Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", i, cptr->error, length));
 
-    if ((IsServer(cptr) || IsHandshake(cptr)) && cptr->error == 0 && length == 0)
-      exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
-                      cptr->name, cptr->serv->last_error_msg);
-    else {
-      const char* msg = (cptr->error) ? strerror(cptr->error) : "EOF from client";
-      if (!msg)
-        msg = "Unknown error";
-      exit_client_msg(cptr, cptr, &me, "Read error: %s",
-                      msg);
+    /* If there's still data to process, wait 2 seconds first */
+    if (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) &&
+       !(cli_freeflag(cptr) & FREEFLAG_TIMER)) {
+      Debug((DEBUG_LIST, "Adding client process timer for %C", cptr));
+      cli_freeflag(cptr) |= FREEFLAG_TIMER;
+      timer_add(&(cli_proc(cptr)), client_timer_callback, cli_connect(cptr),
+               TT_RELATIVE, 2);
     }
   }
-  return 0;
+  return 1;
 }
 
-#endif /* USE_SELECT */
-
 /*
  * connect_server - start or complete a connection to another server
  * returns true (1) if successful, false (0) otherwise
@@ -1317,7 +793,7 @@ int connect_server(struct ConfItem* aconf, struct Client* by,
 
   if (aconf->dns_pending) {
     sendto_opmask_butone(0, SNO_OLDSNO, "Server %s connect DNS pending",
-                        aconf->name);
+                         aconf->name);
     return 0;
   }
   Debug((DEBUG_NOTICE, "Connect to %s[@%s]", aconf->name,
@@ -1326,17 +802,17 @@ int connect_server(struct ConfItem* aconf, struct Client* by,
   if ((cptr = FindClient(aconf->name))) {
     if (IsServer(cptr) || IsMe(cptr)) {
       sendto_opmask_butone(0, SNO_OLDSNO, "Server %s already present from %s", 
-                          aconf->name, cptr->from->name);
+                           aconf->name, cli_name(cli_from(cptr)));
       if (by && IsUser(by) && !MyUser(by)) {
-       sendcmdto_one(&me, CMD_NOTICE, by, "%C :Server %s already present "
-                     "from %s", by, aconf->name, cptr->from->name);
+        sendcmdto_one(&me, CMD_NOTICE, by, "%C :Server %s already present "
+                      "from %s", by, aconf->name, cli_name(cli_from(cptr)));
       }
       return 0;
     }
     else if (IsHandshake(cptr) || IsConnecting(cptr)) {
       if (by && IsUser(by)) {
-       sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connection to %s already in "
-                     "progress", by, cptr->name);
+        sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connection to %s already in "
+                      "progress", by, cli_name(cptr));
       }
       return 0;
     }
@@ -1368,13 +844,13 @@ int connect_server(struct ConfItem* aconf, struct Client* by,
   cptr = make_client(NULL, STAT_UNKNOWN_SERVER);
   if (reply)
     ++reply->ref_count;
-  cptr->dns_reply = reply;
+  cli_dns_reply(cptr) = reply;
 
   /*
    * Copy these in so we have something for error detection.
    */
-  ircd_strncpy(cptr->name, aconf->name, HOSTLEN);
-  ircd_strncpy(cptr->sockhost, aconf->host, HOSTLEN);
+  ircd_strncpy(cli_name(cptr), aconf->name, HOSTLEN);
+  ircd_strncpy(cli_sockhost(cptr), aconf->host, HOSTLEN);
 
   /*
    * Attach config entries to client here rather than in
@@ -1382,12 +858,12 @@ int connect_server(struct ConfItem* aconf, struct Client* by,
    */
   attach_confs_byhost(cptr, aconf->host, CONF_SERVER);
 
-  if (!find_conf_byhost(cptr->confs, aconf->host, CONF_SERVER)) {
+  if (!find_conf_byhost(cli_confs(cptr), aconf->host, CONF_SERVER)) {
     sendto_opmask_butone(0, SNO_OLDSNO, "Host %s is not enabled for "
-                        "connecting: no C-line", aconf->name);
+                         "connecting: no C-line", aconf->name);
     if (by && IsUser(by) && !MyUser(by)) {
       sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connect to host %s failed: no "
-                   "C-line", by, aconf->name);
+                    "C-line", by, aconf->name);
     }
     det_confs_butmask(cptr, 0);
     free_client(cptr);
@@ -1399,7 +875,7 @@ int connect_server(struct ConfItem* aconf, struct Client* by,
   if (!connect_inet(aconf, cptr)) {
     if (by && IsUser(by) && !MyUser(by)) {
       sendcmdto_one(&me, CMD_NOTICE, by, "%C :Couldn't connect to %s", by,
-                   cptr->name);
+                    cli_name(cptr));
     }
     det_confs_butmask(cptr, 0);
     free_client(cptr);
@@ -1414,47 +890,46 @@ int connect_server(struct ConfItem* aconf, struct Client* by,
    */
   make_server(cptr);
   if (by && IsUser(by)) {
-    sprintf_irc(cptr->serv->by, "%s%s", NumNick(by));
-    assert(0 == cptr->serv->user);
-    cptr->serv->user = by->user;
-    by->user->refcnt++;
+    ircd_snprintf(0, cli_serv(cptr)->by, sizeof(cli_serv(cptr)->by), "%s%s",
+                 NumNick(by));
+    assert(0 == cli_serv(cptr)->user);
+    cli_serv(cptr)->user = cli_user(by);
+    cli_user(by)->refcnt++;
   }
   else {
-    *cptr->serv->by = '\0';
+    *(cli_serv(cptr))->by = '\0';
     /* strcpy(cptr->serv->by, "Auto"); */
   }
-  cptr->serv->up = &me;
+  cli_serv(cptr)->up = &me;
   SetConnecting(cptr);
 
-  if (cptr->fd > HighestFd)
-    HighestFd = cptr->fd;
-  LocalClientArray[cptr->fd] = cptr;
+  if (cli_fd(cptr) > HighestFd)
+    HighestFd = cli_fd(cptr);
+
+  
+  LocalClientArray[cli_fd(cptr)] = cptr;
 
   Count_newunknown(UserStats);
+  /* Actually we lie, the connect hasn't succeeded yet, but we have a valid
+   * cptr, so we register it now.
+   * Maybe these two calls should be merged.
+   */
   add_client_to_list(cptr);
   hAddClient(cptr);
-  nextping = CurrentTime;
+/*    nextping = CurrentTime; */
 
-  return 1;
+  return (s_state(&cli_socket(cptr)) == SS_CONNECTED) ?
+    completed_connection(cptr) : 1;
 }
 
 /*
  * Setup local socket structure to use for binding to.
  */
-void init_virtual_host(const struct ConfItem* conf)
+void set_virtual_host(struct in_addr addr)
 {
-  assert(0 != conf);
-
   memset(&VirtualHost, 0, sizeof(VirtualHost));
   VirtualHost.sin_family = AF_INET;
-  VirtualHost.sin_addr.s_addr = INADDR_ANY;
-
-  if (EmptyString(conf->passwd) || 0 == strcmp(conf->passwd, "*"))
-    return;
-  VirtualHost.sin_addr.s_addr = inet_addr(conf->passwd);
-
-  if (INADDR_NONE == VirtualHost.sin_addr.s_addr)
-    VirtualHost.sin_addr.s_addr = INADDR_ANY;
+  VirtualHost.sin_addr.s_addr = addr.s_addr;
 }  
 
 /*
@@ -1462,17 +937,134 @@ void init_virtual_host(const struct ConfItem* conf)
  * matches the server's name) and its primary IP#.  Hostname is stored
  * in the client structure passed as a pointer.
  */
-int init_server_identity()
+void init_server_identity(void)
 {
-  struct ConfItem* conf = find_me();
+  const struct LocalConf* conf = conf_get_local();
+  assert(0 != conf);
 
-  if (!conf || EmptyString(conf->host))
-    return 0;
+  ircd_strncpy(cli_name(&me), conf->name, HOSTLEN);
+  SetYXXServerName(&me, conf->numeric);
+}
 
-  ircd_strncpy(me.name, conf->host, HOSTLEN);
+/*
+ * Process events on a client socket
+ */
+static void client_sock_callback(struct Event* ev)
+{
+  struct Client* cptr;
+  struct Connection* con;
+  char *fmt = "%s";
+  char *fallback = 0;
 
-  init_virtual_host(conf);
-  return 1;
+  assert(0 != ev_socket(ev));
+  assert(0 != s_data(ev_socket(ev)));
+
+  con = s_data(ev_socket(ev));
+
+  assert(0 != con_client(con) || ev_type(ev) == ET_DESTROY);
+
+  cptr = con_client(con);
+
+  assert(0 == cptr || con == cli_connect(cptr));
+
+  switch (ev_type(ev)) {
+  case ET_DESTROY:
+    con_freeflag(con) &= ~FREEFLAG_SOCKET;
+
+    if (!con_freeflag(con) && !cptr)
+      free_connection(con);
+    break;
+
+  case ET_CONNECT: /* socket connection completed */
+    if (!completed_connection(cptr) || IsDead(cptr))
+      fallback = cli_info(cptr);
+    break;
+
+  case ET_ERROR: /* an error occurred */
+    fallback = cli_info(cptr);
+    cli_error(cptr) = ev_data(ev);
+    if (s_state(&(con_socket(con))) == SS_CONNECTING) {
+      completed_connection(cptr);
+      break;
+    }
+    /*FALLTHROUGH*/
+  case ET_EOF: /* end of file on socket */
+    Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d", cli_fd(cptr),
+          cli_error(cptr)));
+    cli_flags(cptr) |= FLAGS_DEADSOCKET;
+    if ((IsServer(cptr) || IsHandshake(cptr)) && cli_error(cptr) == 0) {
+      exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
+                     cli_name(cptr), cli_serv(cptr)->last_error_msg);
+      return;
+    } else {
+      fmt = "Read error: %s";
+      fallback = "EOF from client";
+    }
+    break;
+
+  case ET_WRITE: /* socket is writable */
+    cli_flags(cptr) &= ~FLAGS_BLOCKED;
+    if (cli_listing(cptr) && MsgQLength(&(cli_sendQ(cptr))) < 2048)
+      list_next_channels(cptr, 64);
+    Debug((DEBUG_SEND, "Sending queued data to %C", cptr));
+    send_queued(cptr);
+    break;
+
+  case ET_READ: /* socket is readable */
+    if (!IsDead(cptr)) {
+      Debug((DEBUG_DEBUG, "Reading data from %C", cptr));
+      if (read_packet(cptr, 1) == 0) /* error while reading packet */
+       fallback = "EOF from client";
+    }
+    break;
+
+  default:
+#ifndef NDEBUG
+    abort(); /* unrecognized event */
+#endif
+    break;
+  }
+
+  assert(0 == cptr || 0 == cli_connect(cptr) || con == cli_connect(cptr));
+
+  if (fallback) {
+    const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : fallback;
+    if (!msg)
+      msg = "Unknown error";
+    exit_client_msg(cptr, cptr, &me, fmt, msg);
+  }
 }
 
+/*
+ * Process a timer on client socket
+ */
+static void client_timer_callback(struct Event* ev)
+{
+  struct Client* cptr;
+  struct Connection* con;
+
+  assert(0 != ev_timer(ev));
+  assert(0 != t_data(ev_timer(ev)));
+  assert(ET_DESTROY == ev_type(ev) || ET_EXPIRE == ev_type(ev));
+
+  con = t_data(ev_timer(ev));
 
+  assert(0 != con_client(con) || ev_type(ev) == ET_DESTROY);
+
+  cptr = con_client(con);
+
+  assert(0 == cptr || con == cli_connect(cptr));
+
+  con_freeflag(con) &= ~FREEFLAG_TIMER; /* timer has expired... */
+
+  if (ev_type(ev)== ET_DESTROY) {
+    if (!con_freeflag(con) && !cptr)
+      free_connection(con); /* client is being destroyed */
+  } else {
+    Debug((DEBUG_LIST, "Client process timer for %C expired; processing",
+          cptr));
+    read_packet(cptr, 0); /* read_packet will re-add timer if needed */
+  }
+
+  assert(0 == cptr || 0 == cli_connect(cptr) || con == cli_connect(cptr));
+}