/* CrossFire, A Multiplayer game for X-windows Copyright (C) 1992 Frank Tore Johansen This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. The author can be reached via e-mail to mark@pyramid.com */ /** * \file * Low-level socket-related functions. * * \date 2003-12-02 * * Contains some base functions that both the client and server * can use. As such, depending what we are being compiled for will * determine what we can include. the client is designed have * CFCLIENT defined as part of its compile flags. */ using namespace std; #include #include #include #include #ifdef __linux__ # include # include # include # define TCP_HZ 1000 // sorry... # include #endif // use a really low timeout, as it doesn't cost any bandwidth, and you can // easily die in 20 seconds... #define SOCKET_TIMEOUT1 10 #define SOCKET_TIMEOUT2 20 void Socket_Flush (client_socket * ns) { #ifdef __linux__ // check time of last ack, and, if too old, kill connection struct tcp_info tcpi; socklen_t len = sizeof (tcpi); if (!getsockopt (ns->fd, IPPROTO_TCP, TCP_INFO, &tcpi, &len) && len == sizeof (tcpi)) { unsigned int diff = tcpi.tcpi_last_ack_recv - tcpi.tcpi_last_data_sent; if (tcpi.tcpi_unacked && SOCKET_TIMEOUT1 * TCP_HZ < diff && diff < 0x80000000UL // ack delayed for 20s && SOCKET_TIMEOUT2 * TCP_HZ < tcpi.tcpi_last_data_sent) // no data sent for 10s { LOG (llevDebug, "Connection on fd %d closed due to ack timeout (%u/%u/%u)\n", ns->fd, (unsigned) tcpi.tcpi_last_ack_recv, (unsigned) tcpi.tcpi_last_data_sent, (unsigned) tcpi.tcpi_unacked); ns->status = Ns_Dead; } } int val; val = 0; setsockopt (ns->fd, IPPROTO_TCP, TCP_CORK, &val, sizeof (val)); val = 1; setsockopt (ns->fd, IPPROTO_TCP, TCP_CORK, &val, sizeof (val)); #endif } /*********************************************************************** * * packet functions/utilities * **********************************************************************/ packet &packet::operator <<(const data &v) { if (room () < v.len) reset (); else { if (v.len) { memcpy (cur, v.ptr, v.len); cur += v.len; } } return *this; } packet &packet::operator <<(const data8 &v) { unsigned int len = min (v.len, 0x00FF); return *this << uint8 (len) << data (v.ptr, len); } packet &packet::operator <<(const data16 &v) { unsigned int len = min (v.len, 0xFFFF); return *this << uint16 (len) << data (v.ptr, len); } packet &packet::operator <<(const char *v) { return *this << data (v, strlen (v ? v : 0)); } void packet::printf (const char *format, ...) { int size = room (); va_list ap; va_start (ap, format); int len = vsnprintf ((char *)cur, size, format, ap); va_end (ap); if (len >= size) return reset (); cur += len; } /****************************************************************************** * * Start of read routines. * ******************************************************************************/ int client_socket::read_packet () { for (;;) { if (inbuf_len >= 2) { unsigned int pkt_len = (inbuf [0] << 8) | inbuf [1]; if (inbuf_len >= 2 + pkt_len) return pkt_len + 2; } int amount = sizeof (inbuf) - inbuf_len; if (amount <= 0) { LOG (llevError, "packet too large");//TODO return -1; } amount = read (fd, inbuf + inbuf_len, amount); if (!amount) { status = Ns_Dead; return -1; } else if (amount < 0) { if (errno != EAGAIN && errno != EINTR) { LOG (llevError, "read error: %s", strerror (errno)); return -1; } return 0; } inbuf_len += amount; cst_tot.ibytes += amount; cst_lst.ibytes += amount; } } void client_socket::skip_packet (int len) { inbuf_len -= len; memmove (inbuf, inbuf + len, inbuf_len); } /******************************************************************************* * * Start of write related routines. * ******************************************************************************/ /** * Adds data to a socket buffer for whatever reason. * * ns is the socket we are adding the data to, buf is the start of the * data, and len is the number of bytes to add. */ static void add_to_buffer (client_socket *ns, char *buf, int len) { int avail, end; if ((len + ns->outputbuffer.len) > SOCKETBUFSIZE) { LOG (llevDebug, "Socket on fd %d has overrun internal buffer - marking as dead\n", ns->fd); ns->status = Ns_Dead; return; } /* data + end is where we start putting the new data. The last byte * currently in use is actually data + end -1 */ end = ns->outputbuffer.start + ns->outputbuffer.len; /* The buffer is already in a wrapped state, so adjust end */ if (end >= SOCKETBUFSIZE) end -= SOCKETBUFSIZE; avail = SOCKETBUFSIZE - end; /* We can all fit it behind the current data without wrapping */ if (avail >= len) memcpy (ns->outputbuffer.data + end, buf, len); else { memcpy (ns->outputbuffer.data + end, buf, avail); memcpy (ns->outputbuffer.data, buf + avail, len - avail); } ns->outputbuffer.len += len; #if 0 LOG (llevDebug, "Added %d to output buffer, total length now %d, start=%d\n", len, ns->outputbuffer.len, ns->outputbuffer.start); #endif } /** * Writes data to socket. * * When the socket is clear to write, and we have backlogged data, this * is called to write it out. */ void write_socket_buffer (client_socket * ns) { int amt, max; if (ns->outputbuffer.len == 0) { LOG (llevDebug, "write_socket_buffer called when there is no data, fd=%d\n", ns->fd); return; } do { max = SOCKETBUFSIZE - ns->outputbuffer.start; if (ns->outputbuffer.len < max) max = ns->outputbuffer.len; do { amt = write (ns->fd, ns->outputbuffer.data + ns->outputbuffer.start, max); } while ((amt < 0) && (errno == EINTR)); if (amt < 0) { /* We got an error */ if (errno != EWOULDBLOCK) { LOG (llevError, "New socket write failed (wsb) (%d: %s).\n", errno, strerror (errno)); ns->status = Ns_Dead; return; } else { /* EWOULDBLOCK */ /* can't write it, so store it away. */ ns->can_write = 0; return; } } ns->outputbuffer.start += amt; /* wrap back to start of buffer */ if (ns->outputbuffer.start == SOCKETBUFSIZE) ns->outputbuffer.start = 0; ns->outputbuffer.len -= amt; #ifdef CS_LOGSTATS cst_tot.obytes += amt; cst_lst.obytes += amt; #endif } while (ns->outputbuffer.len > 0); } /** * This writes data to the socket. - It is very low level - * all we try and do is write out the data to the socket * provided (ns). buf is the data to write, len is the number * of bytes to write. IT doesn't return anything - rather, it * updates the ns structure if we get an error. */ void client_socket::send (void *buf_, int len) { char *buf = (char *)buf_; char *pos = buf; int amt = 0; if (status == Ns_Dead || !buf) { LOG (llevDebug, "Write_To_Socket called with dead socket\n"); return; } #ifndef __GNU__ /* This caused problems on Hurd */ if (!can_write) { add_to_buffer (this, buf, len); return; } #endif /* If we manage to write more than we wanted, take it as a bonus */ while (len > 0) { do { amt = write (fd, pos, len); } while ((amt < 0) && (errno == EINTR)); if (amt < 0) { /* We got an error */ if (errno != EWOULDBLOCK) { LOG (llevError, "New socket write failed WTS (%d: %s).\n", /* ---WIN32 */ errno, strerror (errno)); status = Ns_Dead; return; } else { /* EWOULDBLOCK */ /* can't write it, so store it away. */ add_to_buffer (this, pos, len); can_write = 0; return; } } /* amt gets set to 0 above in blocking code, so we do this as * an else if to make sure we don't reprocess it. */ else if (amt == 0) LOG (llevError, "Write_To_Socket: No data written out.\n"); len -= amt; pos += amt; #ifdef CS_LOGSTATS cst_tot.obytes += amt; cst_lst.obytes += amt; #endif } } /** * Takes a string of data, and writes it out to the socket. A very handy * shortcut function. */ void client_socket::send_packet (packet &sl) { Send_With_Handling (this, &sl); } void client_socket::send_packet (const char *buf, int len) { packet sl; sl << data (buf, len); send_packet (sl); } void client_socket::send_packet (const char *buf) { send_packet (buf, strlen (buf)); } /** * Calls Write_To_Socket to send data to the client. * * The only difference in this function is that we take a packet *, and we prepend the length information. */ void Send_With_Handling (client_socket *ns, packet *msg) { unsigned char sbuf[4]; if (ns->status == Ns_Dead || !msg) return; if (msg->length () >= MAXSOCKBUF) { LOG (llevError, "Trying to send a buffer beyond properly size, len =%d\n", msg->length ()); /* Almost certainly we've overflowed a buffer, so quite now to make * it easier to debug. */ abort (); } sbuf[0] = ((uint32) (msg->length ()) >> 8); sbuf[1] = ((uint32) (msg->length ()) ); //TODO: single write, or writev ns->send (sbuf, 2); ns->send (msg->buf, msg->length ()); } /****************************************************************************** * * statistics logging functions. * ******************************************************************************/ #ifdef CS_LOGSTATS /* cst_tot is for the life of the server, cst_last is for the last series of * stats */ CS_Stats cst_tot, cst_lst; /** * Writes out the gathered stats. We clear cst_lst. */ void write_cs_stats (void) { time_t now = time (NULL); /* If no connections recently, don't both to log anything */ if (cst_lst.ibytes == 0 && cst_lst.obytes == 0) return; /* CSSTAT is put in so scripts can easily find the line */ LOG (llevInfo, "CSSTAT: %.16s tot %d %d %d %d inc %d %d %d %d\n", ctime (&now), cst_tot.ibytes, cst_tot.obytes, cst_tot.max_conn, now - cst_tot.time_start, cst_lst.ibytes, cst_lst.obytes, cst_lst.max_conn, now - cst_lst.time_start); cst_lst.ibytes = 0; cst_lst.obytes = 0; cst_lst.time_start = now; } #endif