ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/server/socket/lowlevel.C
Revision: 1.53
Committed: Sat Jul 28 12:02:58 2007 UTC (16 years, 10 months ago) by root
Content type: text/plain
Branch: MAIN
Changes since 1.52: +6 -6 lines
Log Message:
- remote code was not making copies of strings it modified
- implemented two ew flags: NDI_REPLY and NDI_DEF.
- went over a lot of chat-related code and converted to send_msg,
  NDI_REPLY and NDI_DEF.

File Contents

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