source: network-game/server/server.cpp@ 7d91bbe

Last change on this file since 7d91bbe was d211210, checked in by dportnoy <dmp1488@…>, 12 years ago

Add server-side checking of player movement

  • Property mode set to 100644
File size: 13.1 KB
Line 
1#include <cstdlib>
2#include <cstdio>
3#include <unistd.h>
4#include <string>
5#include <iostream>
6#include <sstream>
7#include <cstring>
8#include <cmath>
9
10#include <vector>
11#include <map>
12
13#include <sys/time.h>
14
15#include <sys/socket.h>
16#include <netdb.h>
17#include <netinet/in.h>
18#include <arpa/inet.h>
19
20#include <crypt.h>
21
22/*
23#include <openssl/bio.h>
24#include <openssl/ssl.h>
25#include <openssl/err.h>
26*/
27
28#include "../common/Compiler.h"
29#include "../common/Common.h"
30#include "../common/Message.h"
31#include "../common/WorldMap.h"
32#include "../common/Player.h"
33
34#include "DataAccess.h"
35
36using namespace std;
37
38// from used to be const. Removed that so I could take a reference
39// and use it to send messages
40bool processMessage(const NETWORK_MSG &clientMsg, struct sockaddr_in &from, map<unsigned int, Player>& mapPlayers, WorldMap* gameMap, unsigned int& unusedId, NETWORK_MSG &serverMsg, int sock);
41
42void updateUnusedId(unsigned int& id, map<unsigned int, Player>& mapPlayers);
43
44// this should probably go somewhere in the common folder
45void error(const char *msg)
46{
47 perror(msg);
48 exit(0);
49}
50
51Player *findPlayerByName(map<unsigned int, Player> &m, string name)
52{
53 map<unsigned int, Player>::iterator it;
54
55 for (it = m.begin(); it != m.end(); it++)
56 {
57 if ( it->second.name.compare(name) == 0 )
58 return &(it->second);
59 }
60
61 return NULL;
62}
63
64Player *findPlayerByAddr(map<unsigned int, Player> &m, const sockaddr_in &addr)
65{
66 map<unsigned int, Player>::iterator it;
67
68 for (it = m.begin(); it != m.end(); it++)
69 {
70 if ( it->second.addr.sin_addr.s_addr == addr.sin_addr.s_addr &&
71 it->second.addr.sin_port == addr.sin_port )
72 return &(it->second);
73 }
74
75 return NULL;
76}
77
78void broadcastPlayerPositions(map<unsigned int, Player> &m, int sock)
79{
80 map<unsigned int, Player>::iterator it, it2;
81 NETWORK_MSG serverMsg;
82
83 serverMsg.type = MSG_TYPE_PLAYER;
84
85 for (it = m.begin(); it != m.end(); it++)
86 {
87 it->second.serialize(serverMsg.buffer);
88
89 for (it2 = m.begin(); it2 != m.end(); it2++)
90 {
91 if ( sendMessage(&serverMsg, sock, &(it2->second.addr)) < 0 )
92 error("sendMessage");
93 }
94 }
95}
96
97int main(int argc, char *argv[])
98{
99 int sock, length, n;
100 struct sockaddr_in server;
101 struct sockaddr_in from; // info of client sending the message
102 NETWORK_MSG clientMsg, serverMsg;
103 map<unsigned int, Player> mapPlayers;
104 unsigned int unusedId = 1;
105
106 //SSL_load_error_strings();
107 //ERR_load_BIO_strings();
108 //OpenSSL_add_all_algorithms();
109
110 if (argc < 2) {
111 cerr << "ERROR, no port provided" << endl;
112 exit(1);
113 }
114
115 WorldMap* gameMap = WorldMap::loadMapFromFile("../data/map.txt");
116
117 sock = socket(AF_INET, SOCK_DGRAM, 0);
118 if (sock < 0) error("Opening socket");
119 length = sizeof(server);
120 bzero(&server,length);
121 server.sin_family=AF_INET;
122 server.sin_port=htons(atoi(argv[1]));
123 server.sin_addr.s_addr=INADDR_ANY;
124 if ( bind(sock, (struct sockaddr *)&server, length) < 0 )
125 error("binding");
126
127 set_nonblock(sock);
128
129 bool broadcastResponse;
130 timespec ts;
131 long timeLastUpdated = 0, curTime = 0;
132 while (true) {
133
134 usleep(5000);
135
136 clock_gettime(CLOCK_REALTIME, &ts);
137 curTime = ts.tv_sec + ts.tv_nsec*1000000000;
138
139 if (timeLastUpdated == 0 || (curTime-timeLastUpdated) >= 50000) {
140 timeLastUpdated = curTime;
141
142 // maybe put this in a separate method
143 map<unsigned int, Player>::iterator it, it2;
144 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++) {
145 if (!it->second.move(gameMap)) {
146 cout << "Cenceling move" << endl;
147 //serverMsg.type = MSG_TYPE_PLAYER;
148 //it->second.serialize(serverMsg.buffer);
149
150 cout << "about to send move cencellation" << endl;
151 for (it2 = mapPlayers.begin(); it2 != mapPlayers.end(); it2++)
152 {
153 //if ( sendMessage(&serverMsg, sock, &(it2->second.addr)) < 0 )
154 // error("sendMessage");
155 }
156 }
157 }
158 }
159
160 n = receiveMessage(&clientMsg, sock, &from);
161
162 if (n >= 0) {
163 cout << "Got a message" << endl;
164
165 broadcastResponse = processMessage(clientMsg, from, mapPlayers, gameMap, unusedId, serverMsg, sock);
166
167 // probably replace this with a function that prints based on the
168 // message type
169 cout << "msg: " << serverMsg.buffer << endl;
170 cout << "broadcastResponse: " << broadcastResponse << endl;
171 if (broadcastResponse)
172 {
173 cout << "Should be broadcasting the message" << endl;
174
175 map<unsigned int, Player>::iterator it;
176 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
177 {
178 cout << "Sent message back to " << it->second.name << endl;
179 if ( sendMessage(&serverMsg, sock, &(it->second.addr)) < 0 )
180 error("sendMessage");
181 }
182 }
183 else
184 {
185 cout << "Should be sending back the message" << endl;
186
187 if ( sendMessage(&serverMsg, sock, &from) < 0 )
188 error("sendMessage");
189 }
190 }
191
192 // we don't want to update and broadcast player positions here
193 // when a player sends a position update, we want to check if
194 // it's reasonable and send it out to all other players
195
196 // update player positions
197 /*
198 map<unsigned int, Player>::iterator it;
199 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
200 {
201 it->second.move();
202 }
203
204 broadcastPlayerPositions(mapPlayers, sock);
205 */
206 }
207
208 return 0;
209}
210
211bool processMessage(const NETWORK_MSG& clientMsg, struct sockaddr_in& from, map<unsigned int, Player>& mapPlayers, WorldMap* gameMap, unsigned int& unusedId, NETWORK_MSG& serverMsg, int sock)
212{
213 DataAccess da;
214
215 cout << "MSG: type: " << clientMsg.type << endl;
216 cout << "MSG contents: " << clientMsg.buffer << endl;
217
218 // maybe we should make a message class and have this be a member
219 bool broadcastResponse = false;
220
221 // Check that if an invalid message is sent, the client will correctly
222 // receive and display the response. Maybe make a special error msg type
223 switch(clientMsg.type)
224 {
225 case MSG_TYPE_REGISTER:
226 {
227 string username(clientMsg.buffer);
228 string password(strchr(clientMsg.buffer, '\0')+1);
229
230 cout << "username: " << username << endl;
231 cout << "password: " << password << endl;
232
233 int error = da.insertPlayer(username, password);
234
235 if (!error)
236 strcpy(serverMsg.buffer, "Registration successful.");
237 else
238 strcpy(serverMsg.buffer, "Registration failed. Please try again.");
239
240 serverMsg.type = MSG_TYPE_REGISTER;
241
242 break;
243 }
244 case MSG_TYPE_LOGIN:
245 {
246 cout << "Got login message" << endl;
247
248 serverMsg.type = MSG_TYPE_LOGIN;
249
250 string username(clientMsg.buffer);
251 string password(strchr(clientMsg.buffer, '\0')+1);
252
253 Player* p = da.getPlayer(username);
254
255 if (p == NULL || !da.verifyPassword(password, p->password))
256 {
257 strcpy(serverMsg.buffer, "Incorrect username or password");
258 }
259 else if(findPlayerByName(mapPlayers, username) != NULL)
260 {
261 strcpy(serverMsg.buffer, "Player has already logged in.");
262 }
263 else
264 {
265 serverMsg.type = MSG_TYPE_PLAYER;
266
267 p->setAddr(from);
268 updateUnusedId(unusedId, mapPlayers);
269 p->id = unusedId;
270 cout << "new player id: " << p->id << endl;
271
272 // tell the new player about all the existing players
273 cout << "Sending other players to new player" << endl;
274
275 map<unsigned int, Player>::iterator it;
276 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
277 {
278 it->second.serialize(serverMsg.buffer);
279
280 cout << "sending info about " << it->second.name << endl;
281 cout << "sending ind " << it->second.id << endl;
282 if ( sendMessage(&serverMsg, sock, &from) < 0 )
283 error("sendMessage");
284 }
285
286 p->serialize(serverMsg.buffer);
287 cout << "Should be broadcasting the message" << endl;
288
289 for (it = mapPlayers.begin(); it != mapPlayers.end(); it++)
290 {
291 cout << "Sent message back to " << it->second.name << endl;
292 if ( sendMessage(&serverMsg, sock, &(it->second.addr)) < 0 )
293 error("sendMessage");
294 }
295
296 serverMsg.type = MSG_TYPE_LOGIN;
297 mapPlayers[unusedId] = *p;
298 }
299
300 delete(p);
301
302 break;
303 }
304 case MSG_TYPE_LOGOUT:
305 {
306 string name(clientMsg.buffer);
307 cout << "Player logging out: " << name << endl;
308
309 Player *p = findPlayerByName(mapPlayers, name);
310
311 if (p == NULL)
312 {
313 strcpy(serverMsg.buffer, "That player is not logged in. This is either a bug, or you're trying to hack the server.");
314 cout << "Player not logged in" << endl;
315 }
316 else if ( p->addr.sin_addr.s_addr != from.sin_addr.s_addr ||
317 p->addr.sin_port != from.sin_port )
318 {
319 strcpy(serverMsg.buffer, "That player is logged in using a differemt connection. This is either a bug, or you're trying to hack the server.");
320 cout << "Player logged in using a different connection" << endl;
321 }
322 else
323 {
324 if (p->id < unusedId)
325 unusedId = p->id;
326 mapPlayers.erase(p->id);
327 strcpy(serverMsg.buffer, "You have successfully logged out.");
328 cout << "Player logged out successfuly" << endl;
329 }
330
331 serverMsg.type = MSG_TYPE_LOGOUT;
332
333 break;
334 }
335 case MSG_TYPE_CHAT:
336 {
337 cout << "Got a chat message" << endl;
338
339 Player *p = findPlayerByAddr(mapPlayers, from);
340
341 if (p == NULL)
342 {
343 strcpy(serverMsg.buffer, "No player is logged in using this connection. This is either a bug, or you're trying to hack the server.");
344 }
345 else
346 {
347 broadcastResponse = true;
348
349 ostringstream oss;
350 oss << p->name << ": " << clientMsg.buffer;
351
352 strcpy(serverMsg.buffer, oss.str().c_str());
353 }
354
355 serverMsg.type = MSG_TYPE_CHAT;
356
357 break;
358 }
359 case MSG_TYPE_PLAYER_MOVE:
360 {
361 istringstream iss;
362 iss.str(clientMsg.buffer);
363
364 cout << "PLAYER_MOVE" << endl;
365
366 int id, x, y;
367
368 memcpy(&id, clientMsg.buffer, 4);
369 memcpy(&x, clientMsg.buffer+4, 4);
370 memcpy(&y, clientMsg.buffer+8, 4);
371
372 cout << "x: " << x << endl;
373 cout << "y: " << y << endl;
374 cout << "id: " << id << endl;
375
376 if ( mapPlayers[id].addr.sin_addr.s_addr == from.sin_addr.s_addr &&
377 mapPlayers[id].addr.sin_port == from.sin_port )
378 {
379 // we need to make sure the player can move here
380 if (0 <= x && x < 300 && 0 <= y && y < 300 &&
381 gameMap->getElement(x/25, y/25) == WorldMap::TERRAIN_GRASS)
382 {
383 cout << "valid terrain" << endl;
384
385 //cout << "orig x: " << mapPlayers[id].pos.x << endl;
386 //cout << "orig y: " << mapPlayers[id].pos.y << endl;
387 // first we get the correct vector
388 mapPlayers[id].target.x = x;
389 mapPlayers[id].target.y = y;
390 int xDiff = mapPlayers[id].target.x - mapPlayers[id].pos.x;
391 int yDiff = mapPlayers[id].target.y - mapPlayers[id].pos.y;
392 //cout << "xDiff: " << xDiff << endl;
393 //cout << "yDiff: " << yDiff << endl;
394
395 // then we get the correct angle
396 double angle = atan2(yDiff, xDiff);
397 cout << "angle: " << angle << endl;
398
399 // finally we use the angle to determine
400 // how much the player moves
401 // the player will move 50 pixels in the correct direction
402 //mapPlayers[id].pos.x += cos(angle)*50;
403 //mapPlayers[id].pos.y += sin(angle)*50;
404
405 serverMsg.type = MSG_TYPE_PLAYER_MOVE;
406
407 memcpy(serverMsg.buffer, &id, 4);
408 memcpy(serverMsg.buffer+4, &mapPlayers[id].target.x, 4);
409 memcpy(serverMsg.buffer+8, &mapPlayers[id].target.y, 4);
410 //memcpy(serverMsg.buffer, clientMsg.buffer, 12);
411
412 broadcastResponse = true;
413 }
414 else
415 cout << "Bad terrain detected" << endl;
416 }
417 else // nned to send back a message indicating failure
418 cout << "Player id (" << id << ") doesn't match sender" << endl;
419
420 break;
421 }
422 default:
423 {
424 strcpy(serverMsg.buffer, "Server error occured. Report this please.");
425
426 serverMsg.type = MSG_TYPE_CHAT;
427
428 break;
429 }
430 }
431
432 cout << "Got to the end of the switch" << endl;
433
434 return broadcastResponse;
435}
436
437void updateUnusedId(unsigned int& id, map<unsigned int, Player>& mapPlayers)
438{
439 while (mapPlayers.find(id) != mapPlayers.end())
440 id++;
441}
Note: See TracBrowser for help on using the repository browser.