--- deliantra/server/socket/loop.C 2006/09/09 21:48:29 1.5 +++ deliantra/server/socket/loop.C 2006/12/15 19:59:20 1.19 @@ -1,9 +1,3 @@ - -/* - * static char *rcsid_loop_c = - * "$Id: loop.C,v 1.5 2006/09/09 21:48:29 root Exp $"; - */ - /* CrossFire, A Multiplayer game for X-windows @@ -24,7 +18,7 @@ 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 crossfire-devel@real-time.com + The author can be reached via e-mail to */ /** @@ -40,29 +34,19 @@ #include -#ifndef __CEXTRACT__ #include #include -#endif -#ifndef WIN32 /* ---win32 exclude unix headers */ #include #include #include #include #include -#endif /* end win32 */ -#ifdef HAVE_UNISTD_H #include -#endif - -#ifdef HAVE_ARPA_INET_H #include -#endif #include -#include /***************************************************************************** * Start of command dispatch area. @@ -77,100 +61,69 @@ * we end up having 2 tables. */ -typedef void (*func_uint8_int_ns) (char*, int, NewSocket *); - -struct NsCmdMapping { - const char *cmdname; - func_uint8_int_ns cmdproc; +enum { + PF_PLAYER = 0x01, // must have valid player + PF_IMMEDIATE = 0x02, // TODO: hack, can be executed immediately + PF_PLAYING = 0x04, // must be in playing state }; -typedef void (*func_uint8_int_pl)(char*, int, player *); -struct PlCmdMapping { - const char *cmdname; - func_uint8_int_pl cmdproc; - uint8 flag; +struct pkt_type +{ + const char *name; + void *cb; + int flags; + + bool may_execute (client *ns) + { + return (!(flags & PF_PLAYER) || ns->pl) + && (!(flags & PF_PLAYING) || (ns->pl && ns->pl->state == ST_PLAYING)); + } + + void execute (client *ns, char *data, int datalen) + { + //TODO: only one format + if (flags & PF_PLAYER) + ((void (*)(char *, int, player * ))cb)((char *)data, datalen, ns->pl); + else + ((void (*)(char *, int, client *))cb)((char *)data, datalen, ns); + } }; +// SocketCommand, PlayingCommand, should not exist with those ugly casts +#define SC(cb) (void *)static_cast(cb), +#define PC(cb) (void *)static_cast(cb), PF_PLAYER | + /** * 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+ */ - { NULL, NULL, 0} /* terminator */ -}; - -/** Face-related commands */ -static struct NsCmdMapping nscommands[] = { - { "addme", AddMeCmd }, - { "askface", SendFaceCmd}, /* Added: phil */ - { "requestinfo", RequestInfo}, - { "setfacemode", SetFaceMode}, - { "setsound", SetSound}, - { "setup", SetUp}, - { "version", VersionCmd }, - { "toggleextendedinfos", ToggleExtendedInfos}, /*Added: tchize*/ - { "toggleextendedtext", ToggleExtendedText}, /*Added: tchize*/ - { "asksmooth", AskSmooth}, /*Added: tchize (smoothing technologies)*/ - { NULL, NULL} /* terminator (I, II & III)*/ +static struct pkt_type packets[] = { + {"ncom", PC(NewPlayerCmd) PF_PLAYING }, + {"command", PC(PlayerCmd) PF_PLAYING }, + + {"examine", PC(ExamineCmd) PF_PLAYING | PF_IMMEDIATE }, + {"apply", PC(ApplyCmd) PF_PLAYING | PF_IMMEDIATE }, + {"reply", PC(ReplyCmd) PF_IMMEDIATE }, + {"lookat", PC(LookAt) PF_PLAYING | PF_IMMEDIATE }, + {"lock", PC(LockItem) PF_PLAYING | PF_IMMEDIATE }, + {"mark", PC(MarkItem) PF_PLAYING | PF_IMMEDIATE }, + {"move", PC(MoveCmd) PF_PLAYING | PF_IMMEDIATE }, + {"ext", PC(ExtCmd) PF_IMMEDIATE }, /* CF+ */ + {"mapredraw", PC(MapRedrawCmd) PF_IMMEDIATE }, /* Added: phil */ + {"mapinfo", PC(MapInfoCmd) PF_IMMEDIATE }, /* CF+ */ + + {"addme", SC(AddMeCmd) PF_IMMEDIATE }, + {"askface", SC(SendFaceCmd) 0 }, /* Added: phil */ + {"requestinfo", SC(RequestInfo) 0 }, + {"setfacemode", SC(SetFaceMode) PF_IMMEDIATE }, + {"setsound", SC(SetSound) PF_IMMEDIATE }, + {"setup", SC(SetUp) PF_IMMEDIATE }, + {"version", SC(VersionCmd) PF_IMMEDIATE }, + {"toggleextendedinfos", SC(ToggleExtendedInfos) PF_IMMEDIATE }, /*Added: tchize */ + {"toggleextendedtext", SC(ToggleExtendedText) PF_IMMEDIATE }, /*Added: tchize */ + {"asksmooth", SC(AskSmooth) 0 }, /*Added: tchize (smoothing technologies) */ }; /** - * 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, NewSocket *ns) -{ - 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); - - /* 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); - else Write_String_To_Socket(ns, bigbuf, len); -} - -/** * Handle client input. * * HandleClient is actually not named really well - we only get here once @@ -179,345 +132,204 @@ * with this socket, null if no player (one of the init_sockets for just * starting a connection) */ - -void HandleClient(NewSocket *ns, player *pl) +void +HandleClient (client *ns, player *pl) { - int len=0,i,cnt; - char *data; + /* 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 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; - /* Loop through this - maybe we have several complete packets here. */ - // limit to a few commands only, though, as to not monopolise the server - for (cnt = 16; cnt--; ) { - /* 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 != NULL && pl->ob->speed_left < 0) { - return; - } - - i=SockList_ReadPacket(ns->fd, &ns->inbuf, MAXSOCKBUF-1); + int pkt_len = ns->read_packet (); - if (i<0) { -#ifdef ESRV_DEBUG - LOG(llevDebug,"HandleClient: Read error on connection player %s\n", (pl?pl->ob->name:"None")); -#endif - /* Caller will take care of cleaning this up */ - ns->status =Ns_Dead; - return; + 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 */ - if (i==0) return; - -// //D//TODO//temporarily log long commands -// if (ns->inbuf.len >= 40 && pl && pl->ob) -// LOG (llevDebug, "HandleClient: long comamnd from <%s,%s> %d<%s>\n", pl->ob->name, ns->host, ns->inbuf.len, ns->inbuf.buf + 2); - - /* 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. - */ - data = (char *)strchr((char*)ns->inbuf.buf +2, ' '); - if (data) { - *data='\0'; - data++; - len = ns->inbuf.len - (data - (char*)ns->inbuf.buf); - } - else len=0; + return; - ns->inbuf.buf[ns->inbuf.len]='\0'; /* Terminate buffer - useful for string data */ - for (i=0; nscommands[i].cmdname !=NULL; i++) { - if (strcmp((char*)ns->inbuf.buf+2,nscommands[i].cmdname)==0) { - nscommands[i].cmdproc((char*)data,len,ns); - ns->inbuf.len=0; - return;//D// not doing this causes random memory corruption - goto next_packet; - } - } - /* 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 (i=0; plcommands[i].cmdname !=NULL; i++) { - if (strcmp((char*)ns->inbuf.buf+2,plcommands[i].cmdname)==0) { - if (pl->state == ST_PLAYING || !(plcommands[i].flag & 1)) - plcommands[i].cmdproc((char*)data,len,pl); - ns->inbuf.len=0; - //D// not doing this causes random memory corruption - if (plcommands[i].flag & 2) + /* 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) + { + *data++ = 0; + datalen = pkt_len - (data - (char *)ns->inbuf); + } + 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 (pkt_type *pkt = packets; pkt < packets + (sizeof (packets) / sizeof (packets[0])); ++pkt) + if (!strcmp ((char *)ns->inbuf + 2, pkt->name)) + { + if (pkt->may_execute (ns)) + { + pkt->execute (ns, data, datalen); + ns->skip_packet (pkt_len); + //D//TODO not doing this causes random memory corruption + if (pkt->flags & PF_IMMEDIATE) goto next_packet; 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.buf+2); - next_packet: - ; - } -} - - -/***************************************************************************** - * - * Low level socket looping - select calls and watchdog udp packet - * sending. - * - ******************************************************************************/ - -#ifdef WATCHDOG -/** - * Tell watchdog that we are still alive - * - * I put the function here since we should hopefully already be getting - * all the needed include files for socket support - */ + } + } -void watchdog(void) -{ - static int fd=-1; - static struct sockaddr_in insock; - - if (fd==-1) - { - struct protoent *protoent; - - if ((protoent=getprotobyname("udp"))==NULL || - (fd=socket(PF_INET, SOCK_DGRAM, protoent->p_proto))==-1) - { - return; - } - insock.sin_family=AF_INET; - insock.sin_port=htons((unsigned short)13325); - insock.sin_addr.s_addr=inet_addr("127.0.0.1"); + /* 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: + ; } - sendto(fd,(void *)&fd,1,0,(struct sockaddr *)&insock,sizeof(insock)); } -#endif -void flush_sockets(void) +void +flush_sockets (void) { - player *pl; - - for (pl = first_player; pl != NULL; pl = pl->next) - if (pl->socket.status != Ns_Dead) - Socket_Flush (&pl->socket); + for (sockvec::iterator i = clients.begin (); i != clients.end (); ++i) + if ((*i)->status != Ns_Dead) + (*i)->flush (); } /** - * This checks the sockets for input and exceptions, does the right thing. + * This checks the sockets for input, does the right thing. * * A bit of this code is grabbed out of socket.c * There are 2 lists we need to look through - init_sockets is a list * */ -void doeric_server(void) +void +doeric_server (void) { - int i, pollret; - fd_set tmp_read, tmp_exceptions, tmp_write; - struct sockaddr_in addr; - socklen_t addrlen=sizeof(struct sockaddr); - player *pl, *next; + 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(); + if ((time (NULL) - cst_lst.time_start) >= CS_LOGTIME) + write_cs_stats (); #endif - FD_ZERO(&tmp_read); - FD_ZERO(&tmp_write); - FD_ZERO(&tmp_exceptions); - - for(i=0;inext; - /* Go through the players. Let the loop set the next pl value, - * since we may remove some - */ - for (pl=first_player; pl!=NULL; ) { - if (pl->socket.status == Ns_Dead) { - player *npl=pl->next; - - save_player(pl->ob, 0); - if(!QUERY_FLAG(pl->ob,FLAG_REMOVED)) { - terminate_all_pets(pl->ob); - remove_ob(pl->ob); + //TODO: must be handled cleanly elsewhere + if (pl->socket->status == Ns_Dead) + { + save_player (pl->ob, 0); + + if (!QUERY_FLAG (pl->ob, FLAG_REMOVED)) + { + terminate_all_pets (pl->ob); + pl->ob->remove (); } - leave(pl,1); - final_free_player(pl); - pl=npl; - } - else { - FD_SET((uint32)pl->socket.fd, &tmp_read); - FD_SET((uint32)pl->socket.fd, &tmp_write); - FD_SET((uint32)pl->socket.fd, &tmp_exceptions); - pl=pl->next; - } - } - - /* Reset timeout each time, since some OS's will change the values on - * the return from select. - */ - socket_info.timeout.tv_sec = 0; - socket_info.timeout.tv_usec = 0; - pollret= select(socket_info.max_filedescriptor, &tmp_read, &tmp_write, - &tmp_exceptions, &socket_info.timeout); + leave (pl, 1); + final_free_player (pl); + } - if (pollret==-1) { - LOG(llevError, "select failed: %s\n", strerror(errno)); - return; + pl = npl; } - /* We need to do some of the processing below regardless */ -/* if (!pollret) return;*/ + FD_ZERO (&tmp_read); - /* Following adds a new connection */ - if (pollret && FD_ISSET(init_sockets[0].fd, &tmp_read)) { - int newsocknum=0; + for (sockvec::iterator i = clients.begin (); i != clients.end (); ) + { + client *s = *i; -#ifdef ESRV_DEBUG - LOG(llevDebug,"doeric_server: New Connection\n"); -#endif - /* If this is the case, all sockets currently in used */ - if (socket_info.allocated_sockets <= socket_info.nconns) { - init_sockets = (NewSocket *) realloc(init_sockets,sizeof(NewSocket)*(socket_info.nconns+1)); - if (!init_sockets) fatal(OUT_OF_MEMORY); - newsocknum = socket_info.allocated_sockets; - socket_info.allocated_sockets++; - init_sockets[newsocknum].faces_sent_len = nrofpixmaps; - init_sockets[newsocknum].faces_sent = (uint8*) malloc(nrofpixmaps*sizeof(*init_sockets[newsocknum].faces_sent)); - if (!init_sockets[newsocknum].faces_sent) fatal(OUT_OF_MEMORY); - init_sockets[newsocknum].status = Ns_Avail; + if (s->status == Ns_Dead) + { + clients.erase (i); + delete s; } - else { - int j; + else + { + if (s->fd > maxfd) maxfd = s->fd; - for (j=1; j>24)&255, (ip>>16)&255, (ip>>8)&255, ip&255); - - if (checkbanned(NULL, buf)) { - LOG(llevInfo, "Banned host tried to connect: [%s]\n", buf); - close(init_sockets[newsocknum].fd); - init_sockets[newsocknum].fd = -1; - } - else { - InitConnection(ns, buf); - socket_info.nconns++; - } + FD_SET (s->fd, &tmp_read); + + ++i; } } - /* Check for any exceptions/input on the sockets */ - if (pollret) for(i=1;inext; - if (pl->socket.status==Ns_Dead) continue; + /* Check for any input on the sockets */ + for (sockvec::iterator i = clients.begin (); i != clients.end (); ++i) + { + client *s = *i; + player *pl = s->pl; - if (FD_ISSET(pl->socket.fd,&tmp_write)) { - if (!pl->socket.can_write) { -#if 0 - LOG(llevDebug,"Player %s socket now write enabled\n", pl->ob->name); -#endif - pl->socket.can_write=1; - write_socket_buffer(&pl->socket); + //TODO: disassociate handleclient from socket readin + if (s->inbuf_len || FD_ISSET (s->fd, &tmp_read)) + HandleClient (s, pl); + + //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)) + { + 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)); } - /* if we get an error on the write_socket buffer, no reason to - * continue on this socket. - */ - if (pl->socket.status==Ns_Dead) continue; - } - else pl->socket.can_write=0; - if (FD_ISSET(pl->socket.fd,&tmp_exceptions)) { - save_player(pl->ob, 0); - if(!QUERY_FLAG(pl->ob,FLAG_REMOVED)) { - terminate_all_pets(pl->ob); - remove_ob(pl->ob); - } - leave(pl,1); - final_free_player(pl); - } - else { - HandleClient(&pl->socket, pl); - /* If the player has left the game, then the socket status - * will be set to this be the leave function. We don't - * need to call leave again, as it has already been called - * once. - */ - if (pl->socket.status==Ns_Dead) { - save_player(pl->ob, 0); - if(!QUERY_FLAG(pl->ob,FLAG_REMOVED)) { - terminate_all_pets(pl->ob); - remove_ob(pl->ob); - } - leave(pl,1); - final_free_player(pl); - } else { - - /* 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)) { - 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)); - } - /* draw_client_map does sanity checking that map is - * valid, so don't do it here. - */ - draw_client_map(pl->ob); - if (pl->socket.update_look) esrv_draw_look(pl->ob); - } + /* 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); } } } +