summaryrefslogtreecommitdiff
path: root/src/net/server.c
blob: a37c17cc72a2edfc5fe79e1b8c96eb0b32c137d6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
/**************************************************************************
 *                          ___ __  __ ___ _ __                           *
 *                         / _ \\ \/ // _ \ '_ \                          *
 *                        | (_) |>  <|  __/ | | |                         *
 *                         \___//_/\_\\___|_| |_|                         *
 *                                                                        *
 *                             The card game                              *
 *                                                                        *
 *  Copyright (C) 2011, Reiner Herrmann <reiner@reiner-h.de>              *
 *                      Mario Kilies <MarioKilies@GMX.net>                *
 *                                                                        *
 *  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 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 <http://www.gnu.org/licenses/>.  *
 *                                                                        *
 **************************************************************************/

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include "server.h"
#include "../data_store.h"


/**
 * Return socket with connection to player with specified player id
 * @param[in] client_socks Pointer to socket_list with connection to clients
 * @param[in] pid Player ID to search in socket list
 * @return Socket corresponding to specified player id
 */
int socket_for_player_id(const socket_list_t *client_socks, const player_id_t pid)
{
	for(int i=0; i<client_socks->count; i++)
	{
		if(client_socks->player_ids[i] == pid)
			return client_socks->sockets[i];
	}
	assert(false);
	return 0;
}

/**
 * Starts the server. The server will listen on a specified port.
 * @param[in] addr Bind socket to specified address
 * @param[in] port Port on which server should listen
 * @return Listening socket
 */
int server_start(const char* addr, const char* port)
{
	assert(port != NULL);

	int status;
	int serversock;
	struct addrinfo hints, *result, *tmp;

	memset(&hints, 0, sizeof(struct addrinfo));
	hints.ai_family = AF_UNSPEC;		// IPv4 or IPv6
	hints.ai_socktype = SOCK_STREAM;	// TCP socket
	hints.ai_flags = AI_PASSIVE;		// wildcard IP
	hints.ai_protocol = 0;			// any protocol

	status = getaddrinfo(addr, port, &hints, &result);
	if(status != 0)
	{
		printf("getaddrinfo: %s\n", gai_strerror(status));
		exit(EXIT_FAILURE);
	}

	// iterate over linked addrinfo list and use first useable entry
	for(tmp = result; tmp != NULL; tmp = tmp->ai_next)
	{
		int yes=1;

		// create socket
		serversock = socket(tmp->ai_family, tmp->ai_socktype, tmp->ai_protocol);
		if(serversock == -1)
			continue;

		// try to reuse still open sockets in TIME_WAIT state
		setsockopt(serversock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));

		// try to bind to address/port
		if(bind(serversock, tmp->ai_addr, tmp->ai_addrlen) == 0)
			break; // Success!

		close(serversock);
	}

	if(tmp == NULL)
	{
		printf("failed to bind\n");
		exit(EXIT_FAILURE);
	}
	freeaddrinfo(result);

	// start listening
	status = listen(serversock, 1);
	if(status == -1)
	{
		printf("listen: %s\n", strerror(status));
		exit(EXIT_FAILURE);
	}

	return serversock;
}

/**
 * Waits for and accepts connections from clients. Each client connection is represented by a socket that will be stored in a list for further communication.
 * @param[in] serversock Socket on which server is listening
 * @param[out] client_socks Socket list in which to store open client connections
 * @param[in] count Number of clients that should connect
 */
void server_get_players(int serversock, socket_list_t* client_socks, const uint8_t count)
{
	int i;

	assert(count <= MAX_PLAYERS && count > 0);

	printf("Waiting for %d players to connect ...\n", count);

	// accept connections
	for(i=0; i<count; i++)
	{
		struct sockaddr_storage addr;
		socklen_t addrlen = sizeof(addr);
		client_socks->sockets[i] = accept(serversock, (struct sockaddr*) &addr, &addrlen);
		if(client_socks->sockets[i] == -1)
		{
			printf("accept: %s\n", strerror(client_socks->sockets[i]));
			exit(EXIT_FAILURE);
		}
		//printf("new client connected: %s\n", inet_ntop(sock.ss_family, get_in_addr((struct sockaddr*)&sock), INET6_ADDRSTRLEN));
	}
	client_socks->count = count;

	printf("All players connected. Starting game!\n");
}

/**
  * Parses hello message from client and store username in the global data store.
  * @param[in] m The message to parse
  * @return true
  */
bool server_parse_hello(const msg_t *m)
{
	assert(m != NULL);
	assert(m->hdr.payload_length > 0);
	assert(m->hdr.payload_length < MAX_PLAYER_NAME_LENGTH);

	data_store_t *ds = data_store();

	for(int i=0; i<ds->player_list.count; i++)
	{
		if(ds->player_list.players[i].player_id != 0) // search for first empty (not yet assigned) slot
			continue;
		memcpy(ds->player_list.players[i].player_name, m->payload, m->hdr.payload_length);
		ds->player_list.players[i].player_name[m->hdr.payload_length] = '\0';
		break;
	}

	return true;
}

/**
  * Parses open card message from client and stores the selected card in the global data store.
  * @param[in] m The message to parse
  * @return true
  */
bool server_parse_selected_card(const msg_t *m)
{
	assert(m != NULL);
	assert(m->hdr.payload_length == 1);

	data_store_t *ds = data_store();
	ds->selected_card = m->payload[0];

	return true;
}

/**
  * Parses selected stack message from client and stores the stack index in the global data store.
  * @param[in] m The message to parse
  * @return true
  */
bool server_parse_selected_stack(const msg_t *m)
{
	assert(m != NULL);
	assert(m->hdr.payload_length == 1);

	data_store_t *ds = data_store();
	ds->stack_index = m->payload[0];

	assert(ds->stack_index <= NUM_TABLE_STACKS);

	return true;
}

/**
 * Prepares start game message. All player IDs, player names and name lengths will be saved in the message payload.\n
 * Payload format:\n
 * [ count:1 | pid1:1 | namelen1:1 | name1:namelen1 | ... | pidN:1 | namelenN:1 | nameN:namelenN ]
 * @param[out] m A preallocated message object to store header and payload information
 */
void server_prep_start_game(msg_t *m)
{
	uint16_t pos = 0;
	data_store_t *ds = data_store();
	player_list_t *player_list = &ds->player_list;

	m->hdr.type = msg_type_start_game;
	m->payload[pos++] = player_list->count;

	// copy player_ids, length and nicknames to message payload
	for(int i = 0; i < player_list->count; i++)
	{
		player_list_entry_t *ple = &player_list->players[i];
		m->payload[pos++] = ple->player_id;
		uint8_t len = strlen(ple->player_name);
		m->payload[pos++] = len;
		memcpy(m->payload+pos, ple->player_name, len);
		pos += len;
	}

	m->hdr.payload_length = pos;
}

/**
 * Prepares hello message to notify client of its assigned id\n
 * Payload format:\n
 * [ playerid:1 ]
 * @param[out] m A preallocated message object to store header and payload information
 * @param[in] player The player_list_entry_t belonging to the destined client
 */
void server_prep_hello(msg_t *m, const player_list_entry_t* player)
{
	m->hdr.type = msg_type_hello_s;
	m->payload[0] = player->player_id;
	m->hdr.payload_length = 1;
}

/**
 * Send selected stack by current player to client\n
 * Payload format:\n
 * [ stack_index:1 ]
 * @param[out] m A preallocated message object to store header and payload information
 */
void server_prep_selected_stack(msg_t *m)
{
	data_store_t *ds = data_store();
	
	m->hdr.type = msg_type_selected_stack_s;
	m->payload[0] = ds->stack_index;
	m->hdr.payload_length = 1;
}

/**
 * Send a hand to a client\n
 * Payload format:\n
 * [ card1:1 | ... | cardN:1 ]
 * @param[out] m A preallocated message object to store header and payload information
 * @param[in] h The hand for the client
 */
void server_prep_deal_hand(msg_t *m, const hand_t *h)
{
	assert(h != NULL);

	m->hdr.type = msg_type_deal_hand;

	for(int i=0; i<MAX_HAND_CARDS; i++)
		m->payload[i] = h->cards[i];

	m->hdr.payload_length = MAX_HAND_CARDS;
}

/**
 * Send cards of initial stacks to client at beginning of game.\n
 * Payload format:\n
 * [ stack_card1:1 | ... stack_cardN:1 ]
 * @param[out] m A preallocated message object to store header and payload information
 */
void server_prep_initial_stacks(msg_t *m)
{
	data_store_t *ds = data_store();

	m->hdr.type = msg_type_initial_stacks;

	for(int i=0; i<NUM_TABLE_STACKS; i++)
		m->payload[i] = ds->table_stacks.stacks[i].cards[0];

	m->hdr.payload_length = NUM_TABLE_STACKS;
}

/**
 * Send all open cards to client\n
 * Payload format:\n
 * [ player_id1:1 | open_card1:1 | ... | player_idN:1 | open_cardN:1 ]
 * @param[out] m A preallocated message object to store header and payload information
 */
void server_prep_selected_card_all(msg_t *m)
{
	uint8_t pos = 0;
	data_store_t *ds = data_store();

	m->hdr.type = msg_type_selected_card_all;

	for(int i = 0; i < ds->player_list.count; i++)
	{
		player_list_entry_t *ple = &ds->player_list.players[i];
		if(ple->player_id == 0) // invalid player
			continue;
		m->payload[pos++] = ple->player_id;
		m->payload[pos++] = ple->open_card;
	}

	m->hdr.payload_length = pos;
}

/**
 * Notify client whether the game will continue or end\n
 * Payload format:\n
 * [ next_action:1 ]
 * @param[out] m A preallocated message object to store header and payload information
 */
void server_prep_next_action(msg_t *m)
{
	data_store_t *ds = data_store();

	m->hdr.type = msg_type_next_action;
	m->payload[0] = ds->game_finished;
	m->hdr.payload_length = 1;
}