ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/cvsroot/deliantra/server/socket/lowlevel.c
Revision: 1.4
Committed: Sat Jun 10 06:54:46 2006 UTC (20 years, 4 months ago) by root
Content type: text/plain
Branch: MAIN
Changes since 1.3: +8 -7 lines
Log Message:
tweaked connection timeout to be less sensitive, maybe this helps Ronwe

File Contents

# User Rev Content
1 root 1.1
2     /*
3     * static char *rcsid_sockets_c =
4 root 1.2 * "$Id$";
5 root 1.1 */
6    
7     /*
8     CrossFire, A Multiplayer game for X-windows
9    
10     Copyright (C) 1992 Frank Tore Johansen
11    
12     This program is free software; you can redistribute it and/or modify
13     it under the terms of the GNU General Public License as published by
14     the Free Software Foundation; either version 2 of the License, or
15     (at your option) any later version.
16    
17     This program is distributed in the hope that it will be useful,
18     but WITHOUT ANY WARRANTY; without even the implied warranty of
19     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20     GNU General Public License for more details.
21    
22     You should have received a copy of the GNU General Public License
23     along with this program; if not, write to the Free Software
24     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25    
26     The author can be reached via e-mail to mark@pyramid.com
27     */
28    
29     /**
30     * \file
31     * Low-level socket-related functions.
32     *
33     * \date 2003-12-02
34     *
35     * Contains some base functions that both the client and server
36     * can use. As such, depending what we are being compiled for will
37     * determine what we can include. the client is designed have
38     * CFCLIENT defined as part of its compile flags.
39     */
40    
41     #include <global.h>
42     #include <newclient.h>
43     #include <sproto.h>
44    
45 root 1.2 #ifdef __linux__
46     # include <sys/types.h>
47     # include <sys/socket.h>
48     # include <netinet/in.h>
49 root 1.3 # define TCP_HZ 1000 // sorry...
50 root 1.2 # include <netinet/tcp.h>
51     #endif
52    
53 root 1.3 // use a really low timeout, as it doesn't cost any bandwidth, and you can
54     // easily die in 20 seconds... (actually, 20s after the last data was sent
55     #define SOCKET_TIMEOUT 20
56    
57 root 1.2 void Socket_Flush (NewSocket *ns)
58     {
59     #ifdef __linux__
60 root 1.3 // check time of last ack, and, if too old, kill connection
61     struct tcp_info tcpi;
62     socklen_t len = sizeof (tcpi);
63 root 1.4
64 root 1.3 if (!getsockopt (ns->fd, IPPROTO_TCP, TCP_INFO, &tcpi, &len) && len == sizeof (tcpi))
65     {
66     unsigned int diff = tcpi.tcpi_last_ack_recv - tcpi.tcpi_last_data_sent;
67    
68 root 1.4 if (tcpi.tcpi_unacked && SOCKET_TIMEOUT * TCP_HZ < diff && diff < 0x80000000UL)
69 root 1.3 {
70 root 1.4 LOG (llevDebug, "Connection on fd %d closed due to ack timeout (%u/%u/%u)\n", ns->fd,
71     (unsigned)tcpi.tcpi_last_ack_recv, (unsigned)tcpi.tcpi_last_data_sent, (unsigned)tcpi.tcpi_unacked);
72 root 1.3 ns->status = Ns_Dead;
73     }
74     }
75 root 1.4
76     int val;
77     val = 0; setsockopt (ns->fd, IPPROTO_TCP, TCP_CORK, &val, sizeof (val));
78     val = 1; setsockopt (ns->fd, IPPROTO_TCP, TCP_CORK, &val, sizeof (val));
79 root 1.2 #endif
80     }
81    
82 root 1.1 /***********************************************************************
83     *
84     * SockList functions/utilities
85     *
86     **********************************************************************/
87    
88     void SockList_Init(SockList *sl)
89     {
90     sl->len=0;
91     sl->buf=NULL;
92     }
93    
94     void SockList_AddChar(SockList *sl, char c)
95     {
96     sl->buf[sl->len]=c;
97     sl->len++;
98     }
99    
100     void SockList_AddShort(SockList *sl, uint16 data)
101     {
102     sl->buf[sl->len++]= (data>>8)&0xff;
103     sl->buf[sl->len++] = data & 0xff;
104     }
105    
106    
107     void SockList_AddInt(SockList *sl, uint32 data)
108     {
109     sl->buf[sl->len++]= (data>>24)&0xff;
110     sl->buf[sl->len++]= (data>>16)&0xff;
111     sl->buf[sl->len++]= (data>>8)&0xff;
112     sl->buf[sl->len++] = data & 0xff;
113     }
114    
115     void SockList_AddInt64(SockList *sl, uint64 data)
116     {
117     sl->buf[sl->len++]= ( char )( (data>>56)&0xff );
118     sl->buf[sl->len++]= ( char )( (data>>48)&0xff );
119     sl->buf[sl->len++]= ( char )( (data>>40)&0xff );
120     sl->buf[sl->len++]= ( char )( (data>>32)&0xff );
121    
122     sl->buf[sl->len++]= ( char )( (data>>24)&0xff );
123     sl->buf[sl->len++]= ( char )( (data>>16)&0xff );
124     sl->buf[sl->len++]= ( char )( (data>>8)&0xff );
125     sl->buf[sl->len++] =( char )( data & 0xff );
126     }
127    
128     /* Basically does the reverse of SockList_AddInt, but on
129     * strings instead. Same for the GetShort, but for 16 bits.
130     */
131     int GetInt_String(unsigned char *data)
132     {
133     return ((data[0]<<24) + (data[1]<<16) + (data[2]<<8) + data[3]);
134     }
135    
136     short GetShort_String(unsigned char *data) {
137     return ((data[0]<<8)+data[1]);
138     }
139    
140     /******************************************************************************
141     *
142     * Start of read routines.
143     *
144     ******************************************************************************/
145    
146     /**
147     * This reads from fd and puts the data in sl. We return true if we think
148     * we have a full packet, 0 if we have a partial packet. The only processing
149     * we do is remove the intial size value. len (As passed) is the size of the
150     * buffer allocated in the socklist. We make the assumption the buffer is
151     * at least 2 bytes long.
152     */
153    
154     int SockList_ReadPacket(int fd, SockList *sl, int len)
155     {
156     int stat,toread;
157     extern int errno;
158    
159     /* Sanity check - shouldn't happen */
160     if (sl->len < 0) {
161     abort();
162     }
163     /* We already have a partial packet */
164     if (sl->len<2) {
165     #ifdef WIN32 /* ***WIN32 SockList_ReadPacket: change read() to recv() */
166    
167     stat=recv(fd, sl->buf + sl->len, 2-sl->len,0);
168    
169     #else
170     do {
171     stat=read(fd, sl->buf + sl->len, 2-sl->len);
172     } while ((stat==-1) && (errno==EINTR));
173     #endif
174     if (stat<0) {
175     /* In non blocking mode, EAGAIN is set when there is no
176     * data available.
177     */
178     #ifdef WIN32 /* ***WIN32 SockList_ReadPacket: error handling for win32 */
179     if ((stat==-1) && WSAGetLastError() !=WSAEWOULDBLOCK) {
180     if(WSAGetLastError() == WSAECONNRESET)
181     LOG(llevDebug,"Connection closed by client\n");
182     else
183     {
184     LOG(llevDebug,"ReadPacket got error %d, returning 0\n",WSAGetLastError());
185     }
186     return -1; /* kick this user! */
187     }
188     #else
189     if (errno != EAGAIN && errno !=EWOULDBLOCK) {
190     LOG(llevDebug, "ReadPacket got error %s, returning 0\n", strerror_local(errno));
191     }
192     #endif
193     return 0; /*Error */
194     }
195     if (stat==0) return -1;
196     sl->len += stat;
197     #ifdef CS_LOGSTATS
198     cst_tot.ibytes += stat;
199     cst_lst.ibytes += stat;
200     #endif
201     if (stat<2) return 0; /* Still don't have a full packet */
202     }
203     /* Figure out how much more data we need to read. Add 2 from the
204     * end of this - size header information is not included.
205     */
206     toread = 2+(sl->buf[0] << 8) + sl->buf[1] - sl->len;
207     if ((toread + sl->len) >= len) {
208     LOG(llevError,"SockList_ReadPacket: Want to read more bytes than will fit in buffer (%d>=%d).\n",
209     toread + sl->len, len);
210     /* Quick hack in case for 'oldsocketmode' input. If we are
211     * closing the socket anyways, then reading this extra 100 bytes
212     * shouldn't hurt.
213     */
214     #ifdef WIN32 /* ***win32 SockList_ReadPacket: change read() to recv() */
215     recv(fd, sl->buf+2, 100, 0);
216     #else
217     read(fd, sl->buf+2, 100);
218     #endif /* end win32 */
219    
220     /* return error so the socket is closed */
221     return -1;
222     }
223     do {
224     #ifdef WIN32 /* ***win32 SockList_ReadPacket: change read() to recv() */
225     stat = recv(fd, sl->buf+ sl->len, toread, 0);
226     #else
227     do {
228     stat = read(fd, sl->buf+ sl->len, toread);
229     } while ((stat<0) && (errno==EINTR));
230     #endif
231     if (stat<0) {
232    
233     #ifdef WIN32 /* ***win32 SockList_ReadPacket: change error handling for win32 */
234     if ((stat==-1) && WSAGetLastError() !=WSAEWOULDBLOCK) {
235     if(WSAGetLastError() == WSAECONNRESET)
236     LOG(llevDebug,"Connection closed by client\n");
237     else
238     {
239     LOG(llevDebug,"ReadPacket got error %d, returning 0\n",WSAGetLastError());
240     }
241     return -1; /* kick this user! */
242     }
243     #else
244     if (errno != EAGAIN && errno !=EWOULDBLOCK) {
245     LOG(llevDebug, "ReadPacket got error %s, returning 0\n", strerror_local(errno));
246     }
247     #endif
248     return 0; /*Error */
249     }
250     if (stat==0) return -1;
251     sl->len += stat;
252     #ifdef CS_LOGSTATS
253     cst_tot.ibytes += stat;
254     cst_lst.ibytes += stat;
255     #endif
256     toread -= stat;
257     if (toread==0) return 1;
258     if (toread < 0) {
259     LOG(llevError,"SockList_ReadPacket: Read more bytes than desired.\n");
260     return 1;
261     }
262     } while (toread>0);
263     return 0;
264     }
265    
266     /*******************************************************************************
267     *
268     * Start of write related routines.
269     *
270     ******************************************************************************/
271    
272     /**
273     * Adds data to a socket buffer for whatever reason.
274     *
275     * ns is the socket we are adding the data to, buf is the start of the
276     * data, and len is the number of bytes to add.
277     */
278    
279     static void add_to_buffer(NewSocket *ns, unsigned char *buf, int len)
280     {
281     int avail, end;
282    
283     if ((len+ns->outputbuffer.len)>SOCKETBUFSIZE) {
284     LOG(llevDebug,"Socket on fd %d has overrun internal buffer - marking as dead\n",
285     ns->fd);
286     ns->status = Ns_Dead;
287     return;
288     }
289    
290     /* data + end is where we start putting the new data. The last byte
291     * currently in use is actually data + end -1
292     */
293    
294     end=ns->outputbuffer.start + ns->outputbuffer.len;
295     /* The buffer is already in a wrapped state, so adjust end */
296     if (end>=SOCKETBUFSIZE) end-=SOCKETBUFSIZE;
297     avail=SOCKETBUFSIZE - end;
298    
299     /* We can all fit it behind the current data without wrapping */
300     if (avail >=len ) {
301     memcpy(ns->outputbuffer.data + end, buf, len);
302     }
303     else {
304     memcpy(ns->outputbuffer.data + end, buf, avail);
305     memcpy(ns->outputbuffer.data, buf+avail, len-avail);
306     }
307     ns->outputbuffer.len += len;
308     #if 0
309     LOG(llevDebug,"Added %d to output buffer, total length now %d, start=%d\n", len,
310     ns->outputbuffer.len, ns->outputbuffer.start);
311     #endif
312     }
313    
314     /**
315     * Writes data to socket.
316     *
317     * When the socket is clear to write, and we have backlogged data, this
318     * is called to write it out.
319     */
320     void write_socket_buffer(NewSocket *ns)
321     {
322     int amt, max;
323    
324     if (ns->outputbuffer.len==0) {
325     LOG(llevDebug,"write_socket_buffer called when there is no data, fd=%d\n",
326     ns->fd);
327     return;
328     }
329    
330     do {
331     max = SOCKETBUFSIZE - ns->outputbuffer.start;
332     if (ns->outputbuffer.len<max) max = ns->outputbuffer.len;
333    
334     #ifdef WIN32 /* ***win32 write_socket_buffer: change write() to send() */
335     amt=send(ns->fd, ns->outputbuffer.data + ns->outputbuffer.start, max,0);
336     #else
337     do {
338     amt=write(ns->fd, ns->outputbuffer.data + ns->outputbuffer.start, max);
339     } while ((amt<0) && (errno==EINTR));
340     #endif
341    
342     if (amt < 0) { /* We got an error */
343    
344     #ifdef WIN32 /* ***win32 write_socket_buffer: change error handling */
345     if (amt == -1 && WSAGetLastError() !=WSAEWOULDBLOCK) {
346     LOG(llevError,"New socket write failed (wsb) (%d).\n", WSAGetLastError());
347     #else
348     if (errno !=EWOULDBLOCK) {
349     LOG(llevError,"New socket write failed (wsb) (%d: %s).\n",
350     errno, strerror_local(errno));
351     #endif
352     ns->status=Ns_Dead;
353     return;
354     }
355     else { /* EWOULDBLOCK */
356     /* can't write it, so store it away. */
357     ns->can_write=0;
358     return;
359     }
360     }
361     ns->outputbuffer.start += amt;
362     /* wrap back to start of buffer */
363     if (ns->outputbuffer.start==SOCKETBUFSIZE) ns->outputbuffer.start=0;
364     ns->outputbuffer.len -= amt;
365     #ifdef CS_LOGSTATS
366     cst_tot.obytes += amt;
367     cst_lst.obytes += amt;
368     #endif
369     } while (ns->outputbuffer.len>0);
370     }
371    
372     /**
373     * This writes data to the socket. - It is very low level -
374     * all we try and do is write out the data to the socket
375     * provided (ns). buf is the data to write, len is the number
376     * of bytes to write. IT doesn't return anything - rather, it
377     * updates the ns structure if we get an error.
378     */
379     void Write_To_Socket(NewSocket *ns, unsigned char *buf, int len)
380     {
381     int amt=0;
382     unsigned char *pos=buf;
383    
384     if (ns->status == Ns_Dead || !buf) {
385     LOG(llevDebug,"Write_To_Socket called with dead socket\n");
386     return;
387     }
388    
389     #ifndef __GNU__ /* This caused problems on Hurd */
390     if (!ns->can_write) {
391     add_to_buffer(ns, buf, len);
392     return;
393     }
394     #endif
395     /* If we manage to write more than we wanted, take it as a bonus */
396     while (len>0) {
397    
398     #ifdef WIN32 /* ***win32 Write_To_Socket: change write() to send() */
399     amt=send(ns->fd, pos, len,0);
400     #else
401     do {
402     amt=write(ns->fd, pos, len);
403     } while ((amt<0) && (errno==EINTR));
404     #endif
405    
406     if (amt < 0) { /* We got an error */
407     #ifdef WIN32 /* ***win32 Write_To_Socket: change error handling */
408     if (amt == -1 && WSAGetLastError() !=WSAEWOULDBLOCK) {
409     LOG(llevError,"New socket write failed WTS (%d).\n",WSAGetLastError());
410     #else
411     if (errno !=EWOULDBLOCK) {
412     LOG(llevError,"New socket write failed WTS (%d: %s).\n", /* ---WIN32 */
413     errno, strerror_local(errno));
414     #endif
415     ns->status=Ns_Dead;
416     return;
417     }
418     else { /* EWOULDBLOCK */
419     /* can't write it, so store it away. */
420     add_to_buffer(ns, pos, len);
421     ns->can_write=0;
422     return;
423     }
424     }
425     /* amt gets set to 0 above in blocking code, so we do this as
426     * an else if to make sure we don't reprocess it.
427     */
428     else if (amt==0) {
429     LOG(llevError,"Write_To_Socket: No data written out.\n");
430     }
431     len -= amt;
432     pos += amt;
433     #ifdef CS_LOGSTATS
434     cst_tot.obytes += amt;
435     cst_lst.obytes += amt;
436     #endif
437     }
438     }
439    
440    
441     /**
442     * Takes a string of data, and writes it out to the socket. A very handy
443     * shortcut function.
444     */
445     void cs_write_string(NewSocket *ns, const char *buf, int len)
446     {
447     SockList sl;
448    
449     sl.len = len;
450     sl.buf = (unsigned char*)buf;
451     Send_With_Handling(ns, &sl);
452     }
453    
454    
455     /**
456     * Calls Write_To_Socket to send data to the client.
457     *
458     * The only difference in this function is that we take a SockList
459     *, and we prepend the length information.
460     */
461     void Send_With_Handling(NewSocket *ns,SockList *msg)
462     {
463     unsigned char sbuf[4];
464    
465     if (ns->status == Ns_Dead || !msg)
466     return;
467    
468     if (msg->len >= MAXSOCKBUF) {
469     LOG(llevError,"Trying to send a buffer beyond properly size, len =%d\n",
470     msg->len);
471     /* Almost certainly we've overflowed a buffer, so quite now to make
472     * it easier to debug.
473     */
474     abort();
475     }
476     sbuf[0] = ((uint32)(msg->len) >> 8) & 0xFF;
477     sbuf[1] = ((uint32)(msg->len)) & 0xFF;
478     if (ns->status != Ns_Old)
479     Write_To_Socket(ns, sbuf, 2);
480     Write_To_Socket(ns, msg->buf, msg->len);
481     }
482    
483     /**
484     * Takes a string of data, and writes it out to the socket. A very handy
485     * shortcut function.
486     */
487     void Write_String_To_Socket(NewSocket *ns, char *buf, int len)
488     {
489     SockList sl;
490    
491     sl.len = len;
492     sl.buf = (uint8*)buf;
493     Send_With_Handling(ns, &sl);
494     }
495    
496    
497     /******************************************************************************
498     *
499     * statistics logging functions.
500     *
501     ******************************************************************************/
502    
503     #ifdef CS_LOGSTATS
504     /* cst_tot is for the life of the server, cst_last is for the last series of
505     * stats
506     */
507     CS_Stats cst_tot, cst_lst;
508    
509     /**
510     * Writes out the gathered stats. We clear cst_lst.
511     */
512     void write_cs_stats(void)
513     {
514     time_t now=time(NULL);
515    
516     /* If no connections recently, don't both to log anything */
517     if (cst_lst.ibytes==0 && cst_lst.obytes==0) return;
518    
519     /* CSSTAT is put in so scripts can easily find the line */
520     LOG(llevInfo, "CSSTAT: %.16s tot %d %d %d %d inc %d %d %d %d\n",
521     ctime(&now), cst_tot.ibytes, cst_tot.obytes, cst_tot.max_conn,
522     now - cst_tot.time_start, cst_lst.ibytes, cst_lst.obytes,
523     cst_lst.max_conn, now - cst_lst.time_start);
524     cst_lst.ibytes=0;
525     cst_lst.obytes=0;
526     cst_lst.max_conn=socket_info.nconns;
527     cst_lst.time_start=now;
528     }
529     #endif