ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/server/socket/lowlevel.C
Revision: 1.45
Committed: Sun Jun 10 02:51:46 2007 UTC (17 years ago) by root
Content type: text/plain
Branch: MAIN
Changes since 1.44: +2 -14 lines
Log Message:
use configure to check for tcp_info

File Contents

# User Rev Content
1 elmex 1.1 /*
2 root 1.42 * This file is part of Crossfire TRT, the Multiplayer Online Role Playing Game.
3 pippijn 1.32 *
4 root 1.42 * Copyright (©) 2005,2006,2007 Marc Alexander Lehmann / Robin Redeker / the Crossfire TRT team
5     * Copyright (©) 1992,2007 Frank Tore Johansen
6     *
7     * Crossfire TRT is free software; you can redistribute it and/or modify it
8     * under the terms of the GNU General Public License as published by the Free
9     * Software Foundation; either version 2 of the License, or (at your option)
10     * any later version.
11     *
12     * This program is distributed in the hope that it will be useful, but
13     * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14     * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15     * for more details.
16     *
17     * You should have received a copy of the GNU General Public License along
18     * with Crossfire TRT; if not, write to the Free Software Foundation, Inc. 51
19     * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 pippijn 1.32 *
21 root 1.42 * The authors can be reached via e-mail to <crossfire@schmorp.de>
22 pippijn 1.32 */
23 root 1.42
24 elmex 1.1 using namespace std;
25    
26     #include <global.h>
27     #include <sproto.h>
28 root 1.11 #include <cstdarg>
29 elmex 1.1
30 root 1.45 #if HAVE_TCP_INFO
31 elmex 1.1 # include <sys/types.h>
32     # include <sys/socket.h>
33     # include <netinet/in.h>
34     # include <netinet/tcp.h>
35     #endif
36    
37 root 1.43 // disconnect a socket after this many seconds without an ack
38     #define SOCKET_TIMEOUT 8.
39    
40     // force a packet when idle for more than this many seconds,
41     // forcing an ack regularly.
42     #define IDLE_PING 2.
43 elmex 1.1
44 root 1.5 void
45 root 1.22 client::flush ()
46 elmex 1.1 {
47 root 1.29 if (destroyed ())
48     return;
49    
50 root 1.45 #if HAVE_TCP_INFO
51 root 1.43 // check about once per second, spread evenly over all clients
52     if (!((pticks + fd) & 7))
53     {
54     // check time of last ack, and, if too old, kill connection
55     struct tcp_info tcpi;
56     socklen_t len = sizeof (tcpi);
57 elmex 1.1
58 root 1.43 if (!getsockopt (fd, IPPROTO_TCP, TCP_INFO, &tcpi, &len) && len == sizeof (tcpi))
59     {
60     rtt = tcpi.tcpi_rtt;
61     rttvar = tcpi.tcpi_rttvar;
62 elmex 1.1
63 root 1.43 if (tcpi.tcpi_last_ack_recv > int (SOCKET_TIMEOUT * 1000))
64     {
65     send_msg (NDI_RED, "connection-timeout", "safety disconnect due to tcp/ip timeout (no packets received)");
66     write_outputbuffer ();
67 root 1.21
68 root 1.43 LOG (llevDebug, "connection on fd %d closed due to ack timeout (%u/%u/%u)\n", fd,
69     (unsigned)tcpi.tcpi_last_ack_recv, (unsigned)tcpi.tcpi_last_data_sent, (unsigned)tcpi.tcpi_unacked);
70     destroy ();
71     }
72 elmex 1.1 }
73     }
74 root 1.20 #endif
75    
76     /**
77     * Writes data to socket.
78     *
79     * When the socket is clear to write, and we have backlogged data, this
80     * is called to write it out.
81     */
82    
83 root 1.43 // write a nop to the socket at least every IDLE_NOP seconds.
84     if (!outputbuffer.len)
85     {
86     if (last_send + IDLE_PING <= NOW)
87     {
88     // this is a bit ugly, but map1/map1a seem to be the only
89     // nop'able commands and they are quite small.
90     packet sl (mapmode == Map1Cmd ? "map1" : "map1a");
91     send_packet (sl);
92     }
93     else
94     return;
95     }
96    
97     if (socket_ev.poll () & PE_W)
98 root 1.20 return;
99    
100 root 1.43 last_send = NOW;
101 root 1.20 write_outputbuffer ();
102     }
103 elmex 1.1
104 root 1.20 void
105 root 1.22 client::write_outputbuffer ()
106 root 1.20 {
107     while (outputbuffer.len)
108     {
109     int res = write (fd, outputbuffer.data + outputbuffer.start,
110     min (outputbuffer.len, SOCKETBUFSIZE - outputbuffer.start));
111 root 1.5
112 root 1.20 if (res > 0)
113     {
114     outputbuffer.start += res;
115     /* wrap back to start of buffer */
116     if (outputbuffer.start == SOCKETBUFSIZE)
117     outputbuffer.start = 0;
118    
119     outputbuffer.len -= res;
120     }
121     else if (res == 0)
122     {
123     LOG (llevError, "socket write failed, connection closed.\n");
124 root 1.23 destroy ();
125 root 1.20 return;
126     }
127     else if (errno == EINTR)
128     {
129     // just retry
130     }
131     else if (errno == EAGAIN)
132     {
133     // delay till ready
134     socket_ev.poll (socket_ev.poll () | PE_W);
135     socket_ev.start ();
136     return;
137     }
138     else
139     {
140     LOG (llevError, "socket write failed: %s\n", strerror (errno));
141 root 1.23 destroy ();
142 root 1.20 return;
143     }
144     }
145    
146     socket_ev.poll (socket_ev.poll () & ~PE_W);
147 elmex 1.1 }
148    
149 root 1.23 /******************************************************************************
150 elmex 1.1 *
151 root 1.23 * Start of read routines.
152 elmex 1.1 *
153 root 1.23 ******************************************************************************/
154 elmex 1.1
155 root 1.23 int
156     client::next_packet ()
157 elmex 1.1 {
158 root 1.23 if (inbuf_len >= 2)
159 root 1.11 {
160 root 1.23 int pkt_len = (inbuf [0] << 8) | inbuf [1];
161    
162     if (inbuf_len >= 2 + pkt_len)
163     return 2 + pkt_len;
164    
165     if (inbuf_len == sizeof (inbuf))
166 root 1.15 {
167 root 1.23 send_packet_printf ("drawinfo %d input buffer overflow - closing connection.", NDI_RED);
168     destroy ();
169     return -1;
170 root 1.15 }
171 root 1.11 }
172 root 1.9
173 root 1.23 return 0;
174 root 1.11 }
175 root 1.9
176 root 1.23 void
177     client::skip_packet (int len)
178 root 1.11 {
179 root 1.23 inbuf_len -= len;
180     memmove (inbuf, inbuf + len, inbuf_len);
181 elmex 1.1 }
182    
183 root 1.23 /*****************************************************************************
184     * Start of command dispatch area.
185     * The commands here are protocol commands.
186     ****************************************************************************/
187    
188     // SocketCommand, PlayingCommand, should not exist with those ugly casts
189     #define SC(cb) (void *)static_cast<void (*)(char *, int, client *)>(cb),
190     #define PC(cb) (void *)static_cast<void (*)(char *, int, player *)>(cb), PF_PLAYER |
191    
192     /**
193     * Dispatch table for the server.
194     */
195     static struct packet_type packets[] = {
196 root 1.33 {"ncom", PC(NewPlayerCmd) PF_PLAYING | PF_COMMAND6 },
197     {"command", PC(PlayerCmd) PF_PLAYING | PF_COMMAND0 },
198 root 1.23
199     {"examine", PC(ExamineCmd) PF_PLAYING },
200 root 1.39 {"ex", PC(ExCmd) PF_PLAYING },
201 root 1.23 {"apply", PC(ApplyCmd) PF_PLAYING },
202     {"lookat", PC(LookAt) PF_PLAYING },
203     {"lock", PC(LockItem) PF_PLAYING },
204     {"mark", PC(MarkItem) PF_PLAYING },
205     {"move", PC(MoveCmd) PF_PLAYING },
206 root 1.39 {"ext", PC(ExtCmd) 0 }, // CF+
207     {"mapredraw", PC(MapRedrawCmd) 0 },
208     {"mapinfo", PC(MapInfoCmd) 0 }, // CF+
209 root 1.23
210 root 1.28 {"reply", SC(ReplyCmd) 0 },
211 root 1.39 {"exti", SC(ExtiCmd) 0 }, // CF+
212 root 1.26 {"addme", SC(AddMeCmd) 0 },
213 root 1.36 {"askface", SC(AskFaceCmd) 0 },
214 root 1.26 {"requestinfo", SC(RequestInfo) 0 },
215     {"setfacemode", SC(SetFaceMode) 0 },
216     {"setsound", SC(SetSound) 0 },
217     {"setup", SC(SetUp) 0 },
218     {"version", SC(VersionCmd) 0 },
219     {"toggleextendedinfos", SC(ToggleExtendedInfos) 0 }, /*Added: tchize */
220     {"toggleextendedtext", SC(ToggleExtendedText) 0 }, /*Added: tchize */
221     {"asksmooth", SC(AskSmooth) 0 }, /*Added: tchize (smoothing technologies) */
222 root 1.23 };
223    
224     bool
225     client::may_execute (const packet_type *pkt) const
226 elmex 1.1 {
227 root 1.23 return (!(pkt->flags & PF_PLAYER) || pl)
228 root 1.29 && (!(pkt->flags & PF_PLAYING) || state == ST_PLAYING);
229 root 1.11 }
230 root 1.9
231 root 1.33 // HACK: some commands currently should be executed
232     // even when the player is frozen. this hack detects
233     // those commands. it should be folded into may_execute,
234     // but kept seperate to emphasise the hack aspect, i.e.
235     // do it better, then remove.
236     static bool
237     always_immediate (const client *ns, const packet_type *pkt, const char *data, int len)
238     {
239     if (!(pkt->flags & (PF_COMMAND0 | PF_COMMAND6)))
240     return false;
241    
242     if (!ns->pl || !ns->pl->ob || !ns->pl->ob->map)
243     return false;
244    
245     if (pkt->flags & PF_COMMAND6)
246     {
247     data += 6;
248     len -= 6;
249     }
250    
251     if (len > 4 && !strncmp (data, "say " , 4))
252     return true;
253     if (len > 5 && !strncmp (data, "chat ", 5))
254     return true;
255    
256     return false;
257     }
258    
259 root 1.23 void
260     client::execute (const packet_type *pkt, char *data, int datalen)
261 root 1.11 {
262 root 1.33 if (may_execute (pkt) || always_immediate (this, pkt, data, datalen))
263 root 1.23 {
264     //TODO: only one format
265     if (pkt->flags & PF_PLAYER)
266     ((void (*)(char *, int, player *))pkt->cb)((char *)data, datalen, pl);
267     else
268     ((void (*)(char *, int, client *))pkt->cb)((char *)data, datalen, this);
269     }
270     else
271     send_packet_printf ("drawinfo %d ERROR: you cannot execute '%s' now.", NDI_RED, pkt->name);
272 elmex 1.1 }
273    
274 root 1.23 bool
275     client::handle_packet ()
276 root 1.10 {
277 root 1.23 int pkt_len = next_packet ();
278    
279     if (!pkt_len)
280     return false;
281     else if (pkt_len < 0)
282     {
283     LOG (llevError, "read error on player %s\n",
284     pl && pl->ob ? &pl->ob->name : "[anonymous]");
285     destroy ();
286     return false;
287     }
288    
289     inbuf [pkt_len] = 0; /* Terminate buffer - useful for string data */
290    
291     /* First, break out beginning word. There are at least
292     * a few commands that do not have any paremeters. If
293     * we get such a command, don't worry about trying
294     * to break it up.
295     */
296     int datalen;
297     char *data = strchr ((char *)inbuf + 2, ' ');
298    
299     if (data)
300     {
301     *data++ = 0;
302     datalen = pkt_len - (data - (char *)inbuf);
303     }
304     else
305     {
306     data = (char *)inbuf + 2; // better read garbage than segfault
307     datalen = 0;
308     }
309 root 1.15
310 root 1.23 for (packet_type *pkt = packets; pkt < packets + (sizeof (packets) / sizeof (packets[0])); ++pkt)
311     if (!strcmp ((char *)inbuf + 2, pkt->name))
312     {
313 root 1.33 if (pkt->flags & PF_PLAYER && !always_immediate (this, pkt, data, datalen))
314 root 1.26 queue_command (pkt, data, datalen);
315     else
316 root 1.23 execute (pkt, data, datalen);
317    
318     goto next_packet;
319     }
320    
321 root 1.26 // If we get here, we didn't find a valid command.
322 root 1.23 send_packet_printf ("drawinfo %d ERROR: command '%s' not supported.", NDI_RED, (char *)inbuf + 2);
323     next_packet:
324     skip_packet (pkt_len);
325 root 1.11
326 root 1.23 // input buffer has space again
327     socket_ev.poll (socket_ev.poll () | PE_R);
328 root 1.10
329 root 1.23 return true;
330 root 1.10 }
331    
332 root 1.23 // callback called when socket is either readable or writable
333     void
334     client::socket_cb (iow &w, int got)
335     {
336     //TODO remove when we have better socket cleanup logic
337 root 1.29 if (destroyed ())
338 root 1.23 {
339     socket_ev.poll (0);
340     return;
341     }
342 elmex 1.1
343 root 1.23 if (got & PE_W)
344 root 1.5 {
345 root 1.23 write_outputbuffer ();
346    
347     if (!outputbuffer.len)
348     socket_ev.poll (socket_ev.poll () & ~PE_W);
349     }
350 root 1.12
351 root 1.23 if (got & PE_R)
352     {
353     //TODO: rate-limit tcp connection in better ways, important
354 pippijn 1.8
355 root 1.12 int amount = sizeof (inbuf) - inbuf_len;
356    
357 root 1.23 if (!amount)
358 root 1.5 {
359 root 1.23 // input buffer full
360     socket_ev.poll (socket_ev.poll () & ~PE_R);
361     return;
362 root 1.3 }
363 elmex 1.1
364 root 1.12 amount = read (fd, inbuf + inbuf_len, amount);
365    
366     if (!amount)
367 root 1.5 {
368 root 1.23 destroy ();
369     return;
370 root 1.5 }
371 root 1.12 else if (amount < 0)
372 root 1.5 {
373 root 1.12 if (errno != EAGAIN && errno != EINTR)
374 root 1.5 {
375 root 1.20 LOG (llevError, "read error: %s\n", strerror (errno));
376 root 1.23 destroy ();
377     return;
378 root 1.3 }
379 root 1.12
380 root 1.23 // should not be here, normally
381 root 1.3 }
382 root 1.23 else
383     {
384     inbuf_len += amount;
385 root 1.12
386 root 1.23 cmd_ev.start ();
387     }
388 root 1.5 }
389 root 1.12 }
390    
391 root 1.23 // called whenever we have additional commands to process
392 root 1.12 void
393 root 1.23 client::cmd_cb (iw &w)
394 root 1.12 {
395 root 1.26 if (handle_packet ())
396 root 1.23 w.start ();
397     else
398     flush ();
399 elmex 1.1 }
400    
401     /*******************************************************************************
402     *
403     * Start of write related routines.
404     *
405     ******************************************************************************/
406    
407     /**
408     * Adds data to a socket buffer for whatever reason.
409     *
410     * ns is the socket we are adding the data to, buf is the start of the
411     * data, and len is the number of bytes to add.
412     */
413 root 1.20 void
414 root 1.22 client::send (void *buf_, int len)
415 root 1.20 {
416     char *buf = (char *)buf_;
417 elmex 1.1
418 root 1.29 if (destroyed () || !buf)
419 root 1.23 return;
420 elmex 1.1
421 root 1.31 if (len + outputbuffer.len > SOCKETBUFSIZE)
422 root 1.5 {
423 root 1.23 LOG (llevDebug, "socket on fd %d has overrun internal buffer - marking as dead\n", fd);
424 root 1.36 // shutdown the socket, this is safer than destroying it immediately
425     // as lots of code in the callchain might still access the map etc.
426     shutdown (fd, SHUT_RDWR);
427 root 1.5 return;
428     }
429    
430 root 1.20 int avail, end;
431    
432 root 1.5 /* data + end is where we start putting the new data. The last byte
433     * currently in use is actually data + end -1
434     */
435 root 1.20 end = outputbuffer.start + outputbuffer.len;
436 root 1.5 /* The buffer is already in a wrapped state, so adjust end */
437     if (end >= SOCKETBUFSIZE)
438     end -= SOCKETBUFSIZE;
439 root 1.7
440 root 1.5 avail = SOCKETBUFSIZE - end;
441 elmex 1.1
442 root 1.5 /* We can all fit it behind the current data without wrapping */
443     if (avail >= len)
444 root 1.20 memcpy (outputbuffer.data + end, buf, len);
445 root 1.5 else
446     {
447 root 1.20 memcpy (outputbuffer.data + end, buf, avail);
448     memcpy (outputbuffer.data, buf + avail, len - avail);
449 elmex 1.1 }
450 root 1.7
451 root 1.20 outputbuffer.len += len;
452 elmex 1.1 }
453    
454     /**
455     * Takes a string of data, and writes it out to the socket. A very handy
456     * shortcut function.
457     */
458 root 1.13 void
459 root 1.22 client::send_packet (packet &sl)
460 root 1.13 {
461 root 1.29 if (destroyed ())
462 root 1.19 return;
463    
464     if (sl.length () >= MAXSOCKBUF)
465     {
466     LOG (llevError, "Trying to send a buffer beyond properly size, len =%d\n", sl.length ());
467     /* Almost certainly we've overflowed a buffer, so quit now to make
468     * it easier to debug.
469     */
470     abort ();
471     }
472    
473     if (!sl.length ())
474     return;
475    
476     assert (sl.hdrlen == 2);
477    
478     sl.buf_ [0] = sl.length () >> 8;
479     sl.buf_ [1] = sl.length () ;
480    
481     send (sl.buf_, sl.length () + sl.hdrlen);
482 root 1.13 }
483    
484 root 1.5 void
485 root 1.22 client::send_packet (const char *buf, int len)
486 elmex 1.1 {
487 root 1.14 packet sl;
488 elmex 1.1
489 root 1.13 sl << data (buf, len);
490     send_packet (sl);
491 elmex 1.1 }
492    
493 root 1.13 void
494 root 1.22 client::send_packet (const char *buf)
495 root 1.13 {
496     send_packet (buf, strlen (buf));
497     }
498 elmex 1.1
499 root 1.23 void
500     client::send_packet_printf (const char *format, ...)
501     {
502     packet sl;
503    
504     va_list ap;
505     va_start (ap, format);
506     sl.vprintf (format, ap);
507     va_end (ap);
508    
509     send_packet (sl);
510     }
511    
512 root 1.35 void
513     client::send_drawinfo (const char *msg, int flags)
514     {
515     send_packet_printf ("drawinfo %d %s", flags, msg);
516     }
517    
518 root 1.40 void
519     client::send_msg (int color, const char *type, const char *msg)
520     {
521     if (can_msg)
522     send_packet_printf ("msg %d %s %s", color, type, msg);
523     else if (color < 0)
524     return; // client cannot handle this
525     else if (strchr (msg, '<') || strchr (msg, '&'))
526     {
527     //TODO: should escape/modify to old syntax
528     send_packet_printf ("drawinfo %d %s", color, msg);
529     }
530     else
531     send_packet_printf ("drawinfo %d %s", color, msg);
532     }
533    
534 root 1.23 /***********************************************************************
535     *
536     * packet functions/utilities
537     *
538     **********************************************************************/
539    
540 root 1.27 packet::packet (const char *name)
541     {
542     reset ();
543    
544     int len = strlen (name);
545     memcpy (cur, name, len); cur += len;
546     *cur++ = ' ';
547     }
548    
549 root 1.37 packet &packet::operator <<(const ber32 v)
550     {
551     enum { maxlen = 32 / 7 + 1};
552     uint8 buf[maxlen];
553     uint8 *p = buf + maxlen;
554     uint32 val = v.val;
555    
556 root 1.38 *--p = val & 0x7F;
557    
558 root 1.37 while (val > 0x7F)
559     {
560 root 1.38 val >>= 7;
561 root 1.37 *--p = (val & 0x7F) | 0x80;
562     }
563    
564     return *this << data (p, buf + maxlen - p);
565     }
566    
567 root 1.23 packet &packet::operator <<(const data &v)
568     {
569     if (room () < v.len)
570     reset ();
571     else
572     {
573     if (v.len)
574     {
575     memcpy (cur, v.ptr, v.len);
576     cur += v.len;
577     }
578     }
579    
580     return *this;
581     }
582    
583     packet &packet::operator <<(const data8 &v)
584     {
585     unsigned int len = min (v.len, 0x00FF);
586     return *this << uint8 (len) << data (v.ptr, len);
587     }
588    
589     packet &packet::operator <<(const data16 &v)
590     {
591     unsigned int len = min (v.len, 0xFFFF);
592     return *this << uint16 (len) << data (v.ptr, len);
593     }
594    
595     packet &packet::operator <<(const char *v)
596     {
597     return *this << data (v, strlen (v ? v : 0));
598     }
599    
600     void
601     packet::vprintf (const char *format, va_list ap)
602     {
603     int size = room ();
604    
605     int len = vsnprintf ((char *)cur, size, format, ap);
606    
607     if (len >= size)
608     return reset ();
609    
610     cur += len;
611     }
612