--- deliantra/server/socket/loop.C 2006/12/14 21:46:34 1.15 +++ deliantra/server/socket/loop.C 2007/07/01 06:07:03 1.57 @@ -1,25 +1,25 @@ /* - CrossFire, A Multiplayer game for X-windows - - Copyright (C) 2002-2003 Mark Wedel & The Crossfire Development Team - 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 -*/ + * This file is part of Crossfire TRT, the Roguelike Realtime MORPG. + * + * Copyright (©) 2005,2006,2007 Marc Alexander Lehmann / Robin Redeker / the Crossfire TRT team + * Copyright (©) 2002-2003,2007 Mark Wedel & The Crossfire Development Team + * Copyright (©) 1992,2007 Frank Tore Johansen + * + * Crossfire TRT 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 3 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, see . + * + * The authors can be reached via e-mail to + */ /** * \file @@ -28,11 +28,9 @@ * \date 2003-12-02 * * loop.c mainly deals with initialization and higher level socket - * maintenance (checking for lost connections and if data has arrived.) - * The reading of data is handled in ericserver.c + * maintanance (checking for lost connections and if data has arrived.) */ - #include #include #include @@ -43,246 +41,77 @@ #include #include -#ifdef HAVE_UNISTD_H -# include -#endif - -#ifdef HAVE_ARPA_INET_H -# include -#endif +#include +#include #include -#include - -/***************************************************************************** - * Start of command dispatch area. - * The commands here are protocol commands. - ****************************************************************************/ - -/* Either keep this near the start or end of the file so it is - * at least reasonablye easy to find. - * There are really 2 commands - those which are sent/received - * before player joins, and those happen after the player has joined. - * As such, we have function types that might be called, so - * we end up having 2 tables. - */ -typedef void (*func_uint8_int_ns) (char *, int, client_socket *); +#define BG_SCRUB_RATE 4 // how often to send a face in the background -struct NsCmdMapping -{ - const char *cmdname; - func_uint8_int_ns cmdproc; - uint8 flag; -}; +#define MAX_QUEUE_DEPTH 500 +#define MAX_QUEUE_BACKLOG 3. -typedef void (*func_uint8_int_pl) (char *, int, player *); -struct PlCmdMapping +void +client::reset_state () { - const char *cmdname; - func_uint8_int_pl cmdproc; - uint8 flag; -}; + if (!pl) + return; -/** - * Dispatch table for the server. - * - * CmdMapping is the dispatch table for the server, used in HandleClient, - * which gets called when the client has input. All commands called here - * use the same parameter form (char* data, int len, int clientnum. - * We do implicit casts, because the data that is being passed is - * unsigned (pretty much needs to be for binary data), however, most - * of these treat it only as strings, so it makes things easier - * to cast it here instead of a bunch of times in the function itself. - * flag is 1 if the player must be in the playing state to issue the - * command, 0 if they can issue it at any time. - */ -static struct PlCmdMapping plcommands[] = { - {"examine", ExamineCmd, 1}, - {"apply", ApplyCmd, 1}, - {"move", MoveCmd, 1}, - {"reply", ReplyCmd, 0}, - {"command", PlayerCmd, 1}, - {"ncom", (func_uint8_int_pl) NewPlayerCmd, 1}, - {"lookat", LookAt, 1}, - {"lock", (func_uint8_int_pl) LockItem, 1}, - {"mark", (func_uint8_int_pl) MarkItem, 1}, - {"mapredraw", MapRedrawCmd, 0}, /* Added: phil */ - {"mapinfo", MapInfoCmd, 2}, /* CF+ */ - {"ext", ExtCmd, 2}, /* CF+ */ - { 0 } /* terminator */ -}; - -/** Face-related commands */ -static struct NsCmdMapping nscommands[] = { - {"addme", AddMeCmd, 2}, - {"askface", SendFaceCmd}, /* Added: phil */ - {"requestinfo", RequestInfo}, - {"setfacemode", SetFaceMode, 2}, - {"setsound", SetSound, 2}, - {"setup", SetUp, 2}, - {"version", VersionCmd, 2}, - {"toggleextendedinfos", ToggleExtendedInfos, 2}, /*Added: tchize */ - {"toggleextendedtext", ToggleExtendedText, 2}, /*Added: tchize */ - {"asksmooth", AskSmooth}, /*Added: tchize (smoothing technologies) */ - { 0 } /* terminator (I, II & III) */ -}; + pl->run_on = 0; + pl->fire_on = 0; +} -/** - * RequestInfo is sort of a meta command. There is some specific - * request of information, but we call other functions to provide - * that information. - */ void -RequestInfo (char *buf, int len, client_socket * ns) +client::queue_command (packet_type *handler, char *data, int datalen) { - char *params = NULL, *cp; - - /* No match */ - char bigbuf[MAX_BUF]; - int slen; - - /* Set up replyinfo before we modify any of the buffers - this is used - * if we don't find a match. - */ - strcpy (bigbuf, "replyinfo "); - slen = strlen (bigbuf); - safe_strcat (bigbuf, buf, &slen, MAX_BUF); + tstamp stamp = NOW; - /* find the first space, make it null, and update the - * params pointer. - */ - for (cp = buf; *cp != '\0'; cp++) - if (*cp == ' ') - { - *cp = '\0'; - params = cp + 1; - break; - } - - if (!strcmp (buf, "image_info")) - send_image_info (ns, params); - else if (!strcmp (buf, "image_sums")) - send_image_sums (ns, params); - else if (!strcmp (buf, "skill_info")) - send_skill_info (ns, params); - else if (!strcmp (buf, "spell_paths")) - send_spell_paths (ns, params); + if (cmd_queue.size () >= MAX_QUEUE_DEPTH) + { + //TODO: just disconnect here? + reset_state (); + send_packet_printf ("drawinfo %d command queue overflow, ignoring.", NDI_RED); + } else - ns->send_packet (bigbuf, len); + { + cmd_queue.push_back (command ()); + command &cmd = cmd_queue.back (); + cmd.stamp = stamp; + cmd.handler = handler; + cmd.data = salloc (datalen + 1, data); + cmd.datalen = datalen; + } } -/** - * Handle client input. - * - * HandleClient is actually not named really well - we only get here once - * there is input, so we don't do exception or other stuff here. - * sock is the output socket information. pl is the player associated - * with this socket, null if no player (one of the init_sockets for just - * starting a connection) - */ - -void -HandleClient (client_socket *ns, player *pl) +bool +client::handle_command () { - /* Loop through this - maybe we have several complete packets here. */ - // limit to a few commands only, though, as to not monopolise the server - for (int repeat = 16; repeat--;) + if (!cmd_queue.empty () + && state == ST_PLAYING + && pl->ob->speed_left > 0.f) { - /* If it is a player, and they don't have any speed left, we - * return, and will read in the data when they do have time. - */ - if (pl && pl->state == ST_PLAYING && pl->ob && pl->ob->speed_left < 0) - return; + command &cmd = cmd_queue.front (); - int pkt_len = ns->read_packet (); - - if (pkt_len < 0) - { - LOG (llevError, "read error on player %s\n", &pl->ob->name); - /* Caller will take care of cleaning this up */ - ns->status = Ns_Dead; - return; - } - else if (pkt_len == 0) - /* Still dont have a full packet */ - return; - - /* First, break out beginning word. There are at least - * a few commands that do not have any paremeters. If - * we get such a command, don't worry about trying - * to break it up. - */ - int datalen; - char *data = strchr ((char *)ns->inbuf + 2, ' '); - - if (data) + if (cmd.stamp + MAX_QUEUE_BACKLOG < NOW) { - *data++ = 0; - datalen = pkt_len - (data - (char *)ns->inbuf); + reset_state (); + send_packet_printf ("drawinfo %d ignoring delayed commands.", NDI_RED); } else - { - data = (char *)ns->inbuf + 2; // better read garbage than segfault - datalen = 0; - } - - ns->inbuf [pkt_len] = 0; /* Terminate buffer - useful for string data */ - - for (int i = 0; nscommands[i].cmdname; i++) - { - if (!strcmp ((char *)ns->inbuf + 2, nscommands[i].cmdname)) - { - nscommands[i].cmdproc (data, datalen, ns); - ns->skip_packet (pkt_len); - //D// not doing this causes random memory corruption - if (nscommands[i].flag & 2) - goto next_packet; - return; - } - } - - /* Player must be in the playing state or the flag on the - * the command must be zero for the user to use the command - - * otherwise, a player cam save, be in the play_again state, and - * the map they were on gets swapped out, yet things that try to look - * at the map causes a crash. If the command is valid, but - * one they can't use, we still swallow it up. - */ - if (pl) - for (int i = 0; plcommands[i].cmdname; i++) - { - if (!strcmp ((char *)ns->inbuf + 2, plcommands[i].cmdname)) - { - if (pl->state == ST_PLAYING || !(plcommands[i].flag & 1)) - plcommands[i].cmdproc ((char *) data, datalen, pl); - - ns->skip_packet (pkt_len); - //D// not doing this causes random memory corruption - if (plcommands[i].flag & 2) - goto next_packet; + execute (cmd.handler, cmd.data, cmd.datalen); - return; - } - } - - /* If we get here, we didn't find a valid command. Logging - * this might be questionable, because a broken client/malicious - * user could certainly send a whole bunch of invalid commands. - */ - LOG (llevDebug, "Bad command from client (%s)\n", ns->inbuf + 2); - ns->skip_packet (pkt_len); - next_packet: - ; + cmd_queue.pop_front (); + return true; } + else + return false; } void flush_sockets (void) { - for (sockvec::iterator i = client_sockets.begin (); i != client_sockets.end (); ++i) - if ((*i)->status != Ns_Dead) - (*i)->flush (); + for (sockvec::iterator i = clients.begin (); i != clients.end (); ++i) + (*i)->flush (); } /** @@ -295,113 +124,122 @@ void doeric_server (void) { - int i, pollret; - fd_set tmp_read; - struct sockaddr_in addr; - socklen_t addrlen = sizeof (struct sockaddr); - player *pl, *next; - int maxfd = 0; - -#ifdef CS_LOGSTATS - if ((time (NULL) - cst_lst.time_start) >= CS_LOGTIME) - write_cs_stats (); -#endif - - /* Go through the players. Let the loop set the next pl value, - * since we may remove some - */ - //TODO: must be handled cleanly elsewhere - for (pl = first_player; pl; ) + //TODO: should not be done here, either + for (unsigned i = 0; i < clients.size (); ++i) { - player *npl = pl->next; + client *ns = clients [i]; - //TODO: must be handled cleanly elsewhere - if (pl->socket->status == Ns_Dead) - { - save_player (pl->ob, 0); + ns->tick (); + ns->refcnt_chk (); + } +} - if (!QUERY_FLAG (pl->ob, FLAG_REMOVED)) - { - terminate_all_pets (pl->ob); - pl->ob->remove (); - } +void +client::tick () +{ + if (!pl || destroyed ()) + return; - leave (pl, 1); - final_free_player (pl); - } + /* Update the players stats once per tick. More efficient than + * sending them whenever they change, and probably just as useful + */ + esrv_update_stats (pl); - pl = npl; + if (last_weight != -1 && last_weight != WEIGHT (pl->ob)) + { + esrv_update_item (UPD_WEIGHT, pl->ob, pl->ob); + if (last_weight != WEIGHT (pl->ob)) + LOG (llevError, "esrv_update_item(UPD_WEIGHT) did not set player weight: is %lu, should be %lu\n", + (unsigned long) last_weight, WEIGHT (pl->ob)); } - FD_ZERO (&tmp_read); + draw_client_map (pl); + + if (update_look) + esrv_draw_look (pl); - for (sockvec::iterator i = client_sockets.begin (); i != client_sockets.end (); ) + if (ixface.empty ()) { - client_socket *s = *i; + // regularly send a new face when queue is empty + if (bg_scrub && !--bg_scrub && enable_bg_scrub) + while (scrub_idx < faces.size () - 1) + { + ++scrub_idx; - if (s->status == Ns_Dead) - { - client_sockets.erase (i); - delete s; - } - else - { - if (s->fd > maxfd) maxfd = s->fd; + if (!faces_sent [scrub_idx]) + { + send_face (scrub_idx); + flush_fx (); - FD_SET (s->fd, &tmp_read); + bg_scrub = 1; // send up to one face per tick, unless an image was requested + break; + } + } - ++i; - } + rate_avail = max_rate - outputbuffer_len (); } + else + { + int ol = outputbuffer_len (); - struct timeval timeout; + rate_avail = min (max_rate, rate_avail + max_rate); + rate_avail -= ol; - timeout.tv_sec = 0; - timeout.tv_usec = 0; + int avail = rate_avail; - pollret = select (maxfd + 1, - &tmp_read, 0, 0, - &timeout); + // if we can split images, transfer up to mss-sized packets if possible + // but never 768 bytes more. + if (fxix) avail += min (768, mss - (ol % mss)); - if (pollret == -1) - { - LOG (llevError, "select failed: %s\n", strerror (errno)); - return; - } + bg_scrub = BG_SCRUB_RATE; - /* We need to do some of the processing below regardless */ + while (avail > 0) + { + ixsend &ix = ixface.back (); - /* Check for any input on the sockets */ - for (sockvec::iterator i = client_sockets.begin (); i != client_sockets.end (); ++i) - { - client_socket *s = *i; - player *pl = s->pl; + if (facedata *d = face_data (ix.idx, faceset)) + { + if (fxix) + { + // 9 bytes is enough for fx_FFFOOO, 240 leaves some room for image data + int chunk = min (min (avail - 240, MAXSOCKBUF - 9), ix.ofs); + + if (chunk <= 0) + break; + + ix.ofs -= chunk; + + packet sl ("ix"); + + sl << ber32 (ix.idx) + << ber32 (ix.ofs) + << data (d->data.data () + ix.ofs, chunk); + + send_packet (sl); + } + else + { + send_image (ix.idx); + ix.ofs = 0; + } + } + else + ix.ofs = 0; - //TODO: disassociate handleclient from socket readin - if (s->inbuf_len || FD_ISSET (s->fd, &tmp_read)) - HandleClient (s, pl); + int consumed = outputbuffer_len () - ol; - //TODO: should not be done here, either - if (s->status != Ns_Dead && pl) - { - /* Update the players stats once per tick. More efficient than - * sending them whenever they change, and probably just as useful - */ - esrv_update_stats (pl); - if (pl->last_weight != -1 && pl->last_weight != WEIGHT (pl->ob)) + avail -= consumed; + rate_avail -= consumed; + + ol = outputbuffer_len (); + + if (!ix.ofs) { - esrv_update_item (UPD_WEIGHT, pl->ob, pl->ob); - if (pl->last_weight != WEIGHT (pl->ob)) - LOG (llevError, "esrv_update_item(UPD_WEIGHT) did not set player weight: is %lu, should be %lu\n", - (unsigned long) pl->last_weight, WEIGHT (pl->ob)); - } + ixface.pop_back (); - /* draw_client_map does sanity checking that map is - * valid, so don't do it here. - */ - draw_client_map (pl->ob); - if (s->update_look) - esrv_draw_look (pl->ob); + if (ixface.empty ()) + break; + } } } }