File: client.c

package info (click to toggle)
gtkatlantic 0.6.2-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 2,288 kB
  • ctags: 896
  • sloc: ansic: 7,805; sh: 4,154; xml: 188; makefile: 92
file content (426 lines) | stat: -rw-r--r-- 11,581 bytes parent folder | download
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
/*
 *     gtkatlantic - the gtk+ monopd client, enjoy network monopoly games
 *
 *
 *  Copyright © 2002-2015 Sylvain Rochet
 *
 *  gtkatlantic 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; see the file COPYING. If not, see
 *  <http://www.gnu.org/licenses/>.
 */

/* ** functions for connect/disconnect server, receive/send data to/from server */

#include "config.h"

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

#ifndef WIN32

#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <fcntl.h>
#define closesocket close
#define my_io_channel_socket_new g_io_channel_unix_new

#if defined(__linux__) || defined(__OpenBSD__) || defined(__GLIBC__)
#define _XOPEN_SOURCE 700
#endif /* defined(__linux__) || defined(__OpenBSD__) || defined(__GLIBC__) */

#else /* WIN32 */

#undef _WIN32_WINNT
#define _WIN32_WINNT _WIN32_WINNT_WINXP  /* getaddrinfo() is only supported since WinXP */
#include <winsock2.h>
#include <ws2tcpip.h>
#include <mstcpip.h>
#define my_io_channel_socket_new g_io_channel_win32_new_socket
#ifndef SHUT_RDWR
#define SHUT_RDWR SD_BOTH
#endif /* SHUT_RDWR */

#endif /* WIN32 */

#include <sys/time.h>
#include <sys/types.h>
#include <time.h>

#include "xmlparse.h"
#include "global.h"
#include "client.h"
#include "game.h"
#include "interface.h"

static void client_connect_async(connection *c);
static gboolean client_connect_finish(connection *c);
static gboolean client_connect_failed(gchar *msg);
static void client_connect_free(connection *c);

/* -- connect to server
     >
     > return false if:
     >   - max number of connection reached
     >   - can't resolve host
     >   - can't open port or socket
*/
#if DEBUG
static guint32 nextid;
#endif /* DEBUG */
void client_connect(guint8 type, gchar* host, gint32 port, gchar *cmd) {
	connection *c;
	GThread *t;
	gchar *msg;

	switch (type) {
		case CONNECT_TYPE_MONOPD_GETGAME:
			client_disconnect(global->customserver_connect);
			break;
		case CONNECT_TYPE_MONOPD_GAME:
			client_disconnect(global->game_connect);
			break;
		case CONNECT_TYPE_METASERVER:
			client_disconnect(global->metaserver_connect);
			break;
	}

	c = g_malloc0(sizeof(connection));
#if DEBUG
	c->id = nextid++;
#endif /* DEBUG */
	c->type = type;
	c->host = g_strdup(host);
	c->port = port;
	c->buffer_out = cmd;

	msg = g_strdup_printf("Connecting to %s:%d…", c->host, c->port);
	interface_set_infolabel(msg, "008000", true);
	g_free(msg);

	t = g_thread_new("connect", (GThreadFunc)client_connect_async, c);
	g_thread_unref(t);
}

static void client_connect_async(connection *c) {
	struct addrinfo hints;
	struct addrinfo *result, *addrinfo;
	char port_str[6];
	int r;
	char ip_str[INET6_ADDRSTRLEN];
	int sock;

	memset(&hints, 0, sizeof(struct addrinfo));
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	snprintf(port_str, sizeof(port_str), "%d", c->port);

	r = getaddrinfo(c->host, port_str, &hints, &result);
	if (r != 0) {
		gchar *msg = g_strdup_printf("Can't resolve host %s:%d: %s", c->host, c->port, gai_strerror(r));
		g_idle_add((GSourceFunc)client_connect_failed, msg);
		goto failed;
	}

	for (addrinfo = result; addrinfo != NULL; addrinfo = addrinfo->ai_next) {
		sock = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
		if (sock < 0) {
			gchar *msg = g_strdup_printf("Socket failed %s:%d: %s", c->host, c->port, strerror(errno));
			g_idle_add((GSourceFunc)client_connect_failed, msg);
			continue;
		}

		ip_str[0] = '\0';
#ifndef WIN32
		if (addrinfo->ai_family == AF_INET) {
			inet_ntop(addrinfo->ai_family, &(((struct sockaddr_in *)addrinfo->ai_addr)->sin_addr), ip_str, INET6_ADDRSTRLEN);
		} else if (addrinfo->ai_family == AF_INET6) {
			inet_ntop(addrinfo->ai_family, &(((struct sockaddr_in6 *)addrinfo->ai_addr)->sin6_addr), ip_str, INET6_ADDRSTRLEN);
		}
#else /* WIN32 */
		if (addrinfo->ai_family == AF_INET) {
			DWORD len = INET6_ADDRSTRLEN;
			WSAAddressToString(addrinfo->ai_addr, (DWORD)sizeof(struct sockaddr_in), NULL, ip_str, &len);
		} else if (addrinfo->ai_family == AF_INET6) {
			DWORD len = INET6_ADDRSTRLEN;
			WSAAddressToString(addrinfo->ai_addr, (DWORD)sizeof(struct sockaddr_in6), NULL, ip_str, &len);
		}
#endif /* WIN32 */

		r = connect(sock, addrinfo->ai_addr, addrinfo->ai_addrlen);
		if (r < 0) {
			gchar *msg = g_strdup_printf("Connect failed to %s:%d, %s: %s", c->host, c->port, ip_str, strerror(errno));
			g_idle_add((GSourceFunc)client_connect_failed, msg);
			close(sock);
			continue;
		}
		break;
	}

	freeaddrinfo(result);

	if (addrinfo == NULL) {
		goto failed;
	}

#ifndef WIN32
	/* set socket to non-blocking */
	int flags = fcntl(sock, F_GETFL);
	if (flags >= 0) {
		flags |= O_NONBLOCK;
		fcntl(sock, F_SETFL, flags);
	}
#else /* WIN32 */
	u_long on = 1;
	ioctlsocket(sock, FIONBIO, &on);
#endif /* WIN32 */

	/* Disable Nagle's algorithm */
	int opt = 1;
	setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char*)&opt, sizeof(opt));

	/*
	 * Player can stay for a while in the get game window or game lobby without receiving or sending
	 * any packet. Some end user broken network equipment forget about idle TCP sessions more sooner
	 * than acceptable. Enable TCP keepalive to prevent that.
	 */
#ifndef WIN32
	opt = 1;
	if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char*)&opt, sizeof(opt))) {
		fprintf(stderr, "setsockopt() SO_KEEPALIVE failed on socket %d: %s\n", sock, strerror(errno));
	}
	/* 10s idle before keepalive probe */
	opt = 10;
	if (setsockopt(sock, SOL_TCP, TCP_KEEPIDLE, (char*)&opt, sizeof(opt)))  {
		fprintf(stderr, "setsockopt() TCP_KEEPIDLE failed on socket %d: %s\n", sock, strerror(errno));
	}
	/* 10s probe interval */
	opt = 10;
	if (setsockopt(sock, SOL_TCP, TCP_KEEPINTVL, (char*)&opt, sizeof(opt)))  {
		fprintf(stderr, "setsockopt() TCP_KEEPINTVL failed on socket %d: %s\n", sock, strerror(errno));
	}
	/* consider session down after 10 missed probes */
	opt = 10;
	if (setsockopt(sock, SOL_TCP, TCP_KEEPCNT, (char*)&opt, sizeof(opt)))  {
		fprintf(stderr, "setsockopt() TCP_KEEPCNT failed on socket %d: %s\n", sock, strerror(errno));
	}
#else /* WIN32 */
	DWORD bytesret = 0;
	struct tcp_keepalive keepalive;
	keepalive.onoff = TRUE;
	keepalive.keepalivetime = 10000; /* ms */
	keepalive.keepaliveinterval = 10000; /* ms */

	if (WSAIoctl(sock, SIO_KEEPALIVE_VALS, &keepalive, sizeof(keepalive), NULL, 0, &bytesret, NULL, NULL)) {
		fprintf(stderr, "WSAIotcl(SIO_KEEPALIVE_VALS) failed on socket %d: %d\n", sock, WSAGetLastError());
	}
#endif /* WIN32 */

	c->ip = g_strdup(ip_str);
	c->socket = sock;
	g_idle_add((GSourceFunc)client_connect_finish, c);
	return;

failed:
	g_free(c->host);
	if (c->buffer_out) {
		g_free(c->buffer_out);
	}
	g_free(c);
}

static gboolean client_connect_finish(connection *c) {
	GIOChannel *channel;
	gchar *msg;

	/* we are a bit too late */
	if ( (c->type == CONNECT_TYPE_MONOPD_GETGAME && global->customserver_connect)
	  || (c->type == CONNECT_TYPE_MONOPD_GETGAME && global->phase != PHASE_GETGAMES)
	  || (c->type == CONNECT_TYPE_METASERVER && global->metaserver_connect)
	  || (c->type == CONNECT_TYPE_METASERVER && global->phase != PHASE_GETGAMES)
	  || (c->type == CONNECT_TYPE_MONOPD_GAME && global->game_connect)
	  ) {
		client_connect_free(c);
		return G_SOURCE_REMOVE;
	}

	channel = my_io_channel_socket_new(c->socket);
	g_io_channel_set_encoding(channel, NULL, NULL);
	c->channel = channel;
	c->event_source_id = g_io_add_watch(channel, G_IO_IN|G_IO_ERR|G_IO_HUP, (GIOFunc)client_event, c);

	msg = g_strdup_printf("Connected to %s:%d, using %s", c->host, c->port, c->ip);
	interface_set_infolabel(msg, "008000", false);
	g_free(msg);

	if (c->buffer_out) {
		client_send(c, c->buffer_out);
		g_free(c->buffer_out);
		c->buffer_out = NULL;
	}

	switch (c->type) {
		case CONNECT_TYPE_MONOPD_GETGAME:
			global->customserver_connect = c;
			break;
		case CONNECT_TYPE_MONOPD_GAME:
			global->game_connect = c;
			break;
		case CONNECT_TYPE_METASERVER:
			global->metaserver_connect = c;
			break;
	}

	return G_SOURCE_REMOVE;
}

static gboolean client_connect_failed(gchar *msg) {
	interface_set_infolabel(msg, "b00000", true);
	g_free(msg);
	return G_SOURCE_REMOVE;
}

/* -- close the connection */
void client_disconnect(connection *c) {
	if (!c) return;

	switch (c->type) {
		case CONNECT_TYPE_MONOPD_GETGAME:
			global->customserver_connect = NULL;
			break;
		case CONNECT_TYPE_MONOPD_GAME:
			global->game_connect = NULL;
			break;
		case CONNECT_TYPE_METASERVER:
			global->metaserver_connect = NULL;
			break;
	}

	client_connect_free(c);
}

static void client_connect_free(connection *c) {
	if (c->event_source_id) g_source_remove(c->event_source_id);
	if (c->channel) g_io_channel_unref(c->channel);
	shutdown(c->socket, SHUT_RDWR);
	closesocket(c->socket);
	if (c->buffer_in) {
		g_free(c->buffer_in);
	}
	g_free(c->host);
	g_free(c->ip);
	g_free(c->server_version);
	g_free(c);
}

gboolean client_event(GIOChannel *channel, GIOCondition condition, connection *c) {

	if (condition == G_IO_IN) {
		GIOStatus status;
		gchar chunk[1024 +1];
		gsize bytes_read;
		GError *err = NULL;
		gchar *buffer, *beg, *cur;

		status = g_io_channel_read_chars(channel, chunk, 1024, &bytes_read, &err);
		switch (status) {
			case G_IO_STATUS_NORMAL:
				break;

			case G_IO_STATUS_AGAIN:
				return TRUE;

			case G_IO_STATUS_ERROR:
			case G_IO_STATUS_EOF:
				client_disconnect(c);
				interface_set_infolabel("Connection to server lost.", "b00000", true);
				return TRUE;
		}

		chunk[bytes_read] = '\0';

		if(c->buffer_in == NULL) {
			buffer = g_strdup(chunk);
		} else {
			buffer = g_strconcat(c->buffer_in, chunk, NULL);
			g_free(c->buffer_in);
			c->buffer_in = NULL;
		}

		/* parse data */
		for(beg = cur = buffer; *cur; cur++)  {
			if( *cur == '\n') {
				*cur = '\0';
#if DEBUG
				fprintf(stdout, "\033[32mID(%.2d): RECV(%.4d): [%s]\033[m\n", c->id, (int)strlen(beg), beg);
#endif /* DEBUG */
				switch(c->type)  {

					case CONNECT_TYPE_MONOPD_GETGAME:
						xmlparse_getgamelist_plugger(c, beg);
						break;
					case CONNECT_TYPE_MONOPD_GAME:
						xmlparse_game_plugger(c, beg);
						break;

					case CONNECT_TYPE_METASERVER:
						xmlparse_metaserver(c, beg);
						break;
				}

				beg = cur+1;
			}
		}

		/* bufferise remaining data */
		if (beg != cur) {
			c->buffer_in = g_strdup(beg);
		}

		g_free(buffer);
	}

	else /* if (condition == G_IO_ERR || condition == G_IO_HUP) */ {
		client_disconnect(c);
		interface_set_infolabel("Connection to server lost.", "b00000", true);
		return TRUE;
	}

	return TRUE;
}


/* -- send data to server
      >> get from send_tmp buffer
      >> flush send_tmp buffer */
void client_send(connection *c, gchar *data)  {
	size_t len;
	ssize_t s;

	if (!c) return;

	len = strlen(data);
	s = send(c->socket, data, len, 0);
	if (s < 0 || (size_t)s != len) {
		return;
	}

#if DEBUG
	fprintf(stdout, "\033[31mID(%.2d): SEND(%.4d): [%s]\033[m\n", c->id, (int)len, data);
#endif /* DEBUG */
}