Debian Codegraph @

socket/init.c

raw symbols SCIP
1 /*
2 * Crossfire -- cooperative multi-player graphical RPG and adventure game
3 *
4 * Copyright (c) 1999-2014 Mark Wedel and the Crossfire Development Team
5 * Copyright (c) 1992 Frank Tore Johansen
6 *
7 * Crossfire is free software and comes with ABSOLUTELY NO WARRANTY. You are
8 * welcome to redistribute it under certain conditions. For details, please
9 * see COPYING and LICENSE.
10 *
11 * The authors can be reached via e-mail at <[email protected]>.
12 */
13
14 /**
15 * \file
16 * Socket general functions
17 *
18 * \date 2003-12-02
19 *
20 * Mainly deals with initialization and higher level socket
21 * maintenance (checking for lost connections and if data has arrived.)
22 * The reading of data is handled in ericserver.c
23 */
24
25 #include "global.h"
26
27 #include <arpa/inet.h>
28 #include <assert.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <unistd.h>
34
35 #ifndef WIN32 /* ---win32 exclude include files */
36 #include <sys/types.h>
37 #include <sys/time.h>
38 #include <netinet/in.h>
39 #include <netdb.h>
40 #endif /* win32 */
41
42 #include "image.h"
43 #include "newserver.h"
44 #include "sproto.h"
45
46 /** Socket information. */
47 Socket_Info socket_info;
48
49 /**
50 * Established connections for clients not yet playing. See the page on
51 * @ref page_connection "the login process" for a description of its use.
52 * Socket at index 0 is the socket listening for connections, and must not
53 * be freed.
54 * If this socket becomes invalid, then the server will try to reopen it.
55 */
56 socket_struct *init_sockets;
57
58 static void set_output_sock_buf(socket_struct *ns, int bufsize) {
59 int oldbufsize;
60 socklen_t buflen = sizeof(oldbufsize);
61 if (getsockopt(ns->fd, SOL_SOCKET, SO_SNDBUF, (char *)&oldbufsize, &buflen) == -1)
62 oldbufsize = 0;
63 if (oldbufsize < bufsize) {
64 #ifdef ESRV_DEBUG
65 LOG(llevDebug, "Default buffer size was %d bytes, will reset it to %d\n", oldbufsize, bufsize);
66 #endif
67 if (setsockopt(ns->fd, SOL_SOCKET, SO_SNDBUF, (char *)&bufsize, sizeof(bufsize))) {
68 LOG(llevError, "init_connection: setsockopt unable to set output buf size to %d\n", bufsize);
69 }
70 }
71 buflen = sizeof(oldbufsize);
72 getsockopt(ns->fd, SOL_SOCKET, SO_SNDBUF, (char *)&oldbufsize, &buflen);
73 #ifdef ESRV_DEBUG
74 LOG(llevDebug, "Socket buffer size now %d bytes\n", oldbufsize);
75 #endif
76 }
77
78 /**
79 * Initializes a connection. Really, it just sets up the data structure,
80 * socket setup is handled elsewhere. We do send a version to the
81 * client.
82 */
83 void init_connection(socket_struct *ns, const char *from_ip) {
84 SockList sl;
85
86 #ifdef WIN32 /* ***WIN32 SOCKET: init win32 non blocking socket */
87 int temp = 1;
88
89 if (ioctlsocket(ns->fd, FIONBIO , &temp) == -1)
90 LOG(llevError, "init_connection: Error on ioctlsocket.\n");
91 #else
92 if (fcntl(ns->fd, F_SETFL, O_NONBLOCK) == -1) {
93 LOG(llevError, "init_connection: Error on fcntl.\n");
94 }
95 #endif /* end win32 */
96
97 set_output_sock_buf(ns, SOCKETBUFSIZE);
98
99 ns->faceset = 0;
100 ns->facecache = 0;
101 ns->sound = 0;
102 ns->sounds_this_tick = 0;
103 ns->monitor_spells = 0;
104 ns->darkness = 1;
105 ns->status = Ns_Add;
106 ns->mapx = 11;
107 ns->mapy = 11;
108 ns->look_position = 0;
109 ns->container_position = 0;
110 ns->update_look = 0;
111 ns->update_inventory = 0;
112 ns->tick = 0;
113 ns->is_bot = 0;
114 ns->num_look_objects = DEFAULT_NUM_LOOK_OBJECTS;
115 ns->want_pickup = 0;
116 ns->extended_stats = 0;
117 ns->account_name = NULL;
118 ns->account_chars = NULL;
119 ns->login_method = 0;
120 ns->notifications = 0;
121 ns->heartbeat = 0;
122
123 /* we should really do some checking here - if total clients overflows
124 * we need to do something more intelligent, because client id's will start
125 * duplicating (not likely in normal cases, but malicous attacks that
126 * just open and close connections could get this total up.
127 */
128 SockList_Init(&ns->inbuf);
129 SockList_ResetRead(&ns->inbuf);
130 /* Basic initialization. Needed because we do a check in
131 * handle_client for oldsocketmode without checking the
132 * length of data.
133 */
134 memset(ns->inbuf.buf, 0, sizeof(ns->inbuf.buf));
135 memset(&ns->lastmap, 0, sizeof(struct Map));
136 if (!ns->faces_sent)
137 ns->faces_sent = calloc(sizeof(*ns->faces_sent), get_faces_count());
138 ns->faces_sent_len = get_faces_count();
139
140 memset(&ns->anims_sent, 0, sizeof(ns->anims_sent));
141 memset(&ns->stats, 0, sizeof(struct statsinfo));
142 ns->map_scroll_x = 0;
143 ns->map_scroll_y = 0;
144 /* Do this so we don't send a face command for the client for
145 * this face. Face 0 is sent to the client to say clear
146 * face information.
147 */
148 ns->faces_sent[0] = NS_FACESENT_FACE;
149
150 ns->password_fails = 0;
151
152 ns->host = strdup_local(from_ip);
153 SockList_Init(&sl);
154 SockList_AddPrintf(&sl, "version %d %d %s\n", VERSION_CS, VERSION_SC, VERSION_INFO);
155 Send_With_Handling(ns, &sl);
156 SockList_Term(&sl);
157 #ifdef CS_LOGSTATS
158 if (socket_info.allocated_sockets > cst_tot.max_conn)
159 cst_tot.max_conn = socket_info.allocated_sockets;
160 if (socket_info.allocated_sockets > cst_lst.max_conn)
161 cst_lst.max_conn = socket_info.allocated_sockets;
162 #endif
163 }
164
165 /**
166 * This opens *ns for listening to connections.
167 * The structure must be allocated already and
168 * ns->listen must be initialized.
169 * No other variable is changed.
170 */
171 void init_listening_socket(socket_struct *ns) {
172 struct linger linger_opt;
173 char buf1[MAX_BUF], buf2[MAX_BUF];
174
175 if (ns == NULL || ns->listen == NULL) {
176 LOG(llevError, "init_listening_socket: missing listen info in socket_struct?!\n");
177 fatal(SEE_LAST_ERROR);
178 }
179
180 ns->status = Ns_Dead;
181
182 ns->fd = socket(ns->listen->family, ns->listen->socktype, ns->listen->protocol);
183 if (ns->fd == -1) {
184 LOG(llevError, "Cannot create socket: %s\n", strerror(errno));
185 return;
186 }
187
188 linger_opt.l_onoff = 0;
189 linger_opt.l_linger = 0;
190 if (setsockopt(ns->fd, SOL_SOCKET, SO_LINGER, (char *)&linger_opt, sizeof(struct linger))) {
191 LOG(llevError, "Cannot setsockopt(SO_LINGER): %s\n", strerror(errno));
192 }
193 /* Would be nice to have an autoconf check for this. It appears that
194 * these functions are both using the same calling syntax, just one
195 * of them needs extra valus passed.
196 */
197 #if defined(__osf__) || defined(hpux) || defined(sgi) || defined(NeXT) || \
198 defined(__sun__) || defined(__linux__) || defined(SVR4) || \
199 defined(__FreeBSD__) || defined(__OpenBSD__) || \
200 defined(WIN32) /* ---win32 add this here */ || \
201 defined(__GNU__) /* HURD */
202 {
203 #ifdef WIN32
204 char tmp = 1;
205 #else
206 int tmp = 1;
207 #endif
208
209 if (setsockopt(ns->fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp))) {
210 LOG(llevError, "Cannot setsockopt(SO_REUSEADDR): %s\n", strerror(errno));
211 }
212 #ifdef HAVE_GETADDRINFO
213 if ((ns->listen->family == AF_INET6) && setsockopt(ns->fd, IPPROTO_IPV6, IPV6_V6ONLY, &tmp, sizeof(tmp))) {
214 LOG(llevError, "Cannot setsockopt(IPV6_V6ONLY): %s\n", strerror(errno));
215 }
216 #endif
217 }
218 #else
219 if (setsockopt(ns->fd, SOL_SOCKET, SO_REUSEADDR, (char *)NULL, 0)) {
220 LOG(llevError, "Cannot setsockopt(SO_REUSEADDR): %s\n", strerror(errno));
221 }
222 #endif
223
224 if (bind(ns->fd, ns->listen->addr, ns->listen->addrlen) == (-1)) {
225 #ifdef HAVE_GETNAMEINFO
226 getnameinfo(ns->listen->addr, ns->listen->addrlen, buf1, sizeof(buf1), buf2, sizeof(buf2), NI_NUMERICHOST|NI_NUMERICSERV);
227 #else
228 short port;
229 long ip;
230
231 ip = ntohl(((struct sockaddr_in *)ns->listen->addr)->sin_addr.s_addr);
232 port = ntohs(((struct sockaddr_in *)ns->listen->addr)->sin_port);
233 snprintf(buf1, sizeof(buf1), "%ld.%ld.%ld.%ld", (ip>>24)&255, (ip>>16)&255, (ip>>8)&255, ip&255);
234 snprintf(buf2, sizeof(buf2), "%d", port&65535);
235 #endif
236 LOG(llevError, "Cannot bind socket to [%s]:%s: %s\n", buf1, buf2, strerror(errno));
237 #ifdef WIN32 /* ***win32: close() -> closesocket() */
238 shutdown(ns->fd, SD_BOTH);
239 closesocket(ns->fd);
240 #else
241 close(ns->fd);
242 #endif /* win32 */
243 ns->fd = -1;
244 return;
245 }
246 if (listen(ns->fd, 5) == (-1)) {
247 LOG(llevError, "Cannot listen on socket: %s\n", strerror(errno));
248 #ifdef WIN32 /* ***win32: close() -> closesocket() */
249 shutdown(ns->fd, SD_BOTH);
250 closesocket(ns->fd);
251 #else
252 close(ns->fd);
253 #endif /* win32 */
254 ns->fd = -1;
255 return;
256 }
257 ns->status = Ns_Add;
258 }
259
260 /** This sets up the socket and reads all the image information into memory.
261 * @todo fix socket_info.max_filedescriptor hack. */
262 void init_server(void) {
263 int i, e, listen_socket_count;
264 #ifdef HAVE_GETADDRINFO
265 struct addrinfo *ai, *ai_p;
266 struct addrinfo hints;
267 char buf[MAX_BUF];
268 #else
269 struct sockaddr_in *insock;
270 struct protoent *protox;
271 #endif
272
273 #ifdef WIN32 /* ***win32 - we init a windows socket */
274 WSADATA w;
275
276 socket_info.max_filedescriptor = 1; /* used in select, ignored in winsockets */
277 WSAStartup(0x0101, &w); /* this setup all socket stuff */
278 /* ill include no error tests here, winsocket 1.1 should always work */
279 /* except some old win95 versions without tcp/ip stack */
280 #else /* non windows */
281
282 #ifdef HAVE_SYSCONF
283 socket_info.max_filedescriptor = sysconf(_SC_OPEN_MAX);
284 #else
285 # ifdef HAVE_GETDTABLESIZE
286 socket_info.max_filedescriptor = getdtablesize();
287 # else
288 "Unable to find usable function to get max filedescriptors";
289 # endif
290 #endif
291 #endif /* win32 */
292
293 /*
294 * There is a bug on FreeBSD 9 in that the value we get here is over 1024,
295 * which is the limit FD_ZERO and friends will use.
296 * So later on file descriptors are not correctly cleared, and select() fails.
297 * Therefore here's a hack to prevent that, but the real solution would be
298 * to figure why this happens and how to fix it.
299 * Nicolas W, 2012 feb 07.
300 */
301 if (socket_info.max_filedescriptor > 1024) {
302 LOG(llevDebug, "warning, socket_info.max_filedescriptor is %d, setting to 1024.\n", socket_info.max_filedescriptor);
303 socket_info.max_filedescriptor = 1024;
304 }
305 /* end of hack */
306
307 socket_info.timeout.tv_sec = 0;
308 socket_info.timeout.tv_usec = 0;
309
310 #ifdef CS_LOGSTATS
311 memset(&cst_tot, 0, sizeof(CS_Stats));
312 memset(&cst_lst, 0, sizeof(CS_Stats));
313 cst_tot.time_start = time(NULL);
314 cst_lst.time_start = time(NULL);
315 #endif
316
317 #ifdef HAVE_GETADDRINFO
318 memset(&hints, '\0', sizeof(hints));
319 hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
320 hints.ai_socktype = SOCK_STREAM;
321 snprintf(buf, sizeof(buf), "%d", settings.csport);
322 e = getaddrinfo(NULL, buf, &hints, &ai);
323 if (e != 0) {
324 LOG(llevError, "init_server: getaddrinfo: %s\n", gai_strerror(e));
325 fatal(SEE_LAST_ERROR);
326 }
327
328 listen_socket_count = 0;
329 for (ai_p = ai; ai_p != NULL; ai_p = ai_p->ai_next) {
330 listen_socket_count++;
331 }
332
333 assert(listen_socket_count > 0);
334 #else
335 listen_socket_count = 1;
336 #endif
337
338 LOG(llevDebug, "Initialize new client/server data\n");
339 init_sockets = malloc(sizeof(socket_struct) * listen_socket_count);
340 socket_info.allocated_sockets = listen_socket_count;
341 for (i = 0; i < listen_socket_count; i++) {
342 init_sockets[i].listen = calloc(sizeof(struct listen_info), 1);
343 init_sockets[i].faces_sent = NULL; /* unused */
344 init_sockets[i].account_name = NULL; /* Must be set to avoid undef behaviour elsewhere. */
345 }
346
347 #ifdef HAVE_GETADDRINFO
348 for (i = 0, ai_p = ai; i < listen_socket_count && ai_p != NULL; i++, ai_p = ai_p->ai_next) {
349 init_sockets[i].listen->family = ai_p->ai_family;
350 init_sockets[i].listen->socktype = ai_p->ai_socktype;
351 init_sockets[i].listen->protocol = ai_p->ai_protocol;
352 init_sockets[i].listen->addrlen = ai_p->ai_addrlen;
353 init_sockets[i].listen->addr = malloc(ai_p->ai_addrlen);
354 memcpy(init_sockets[i].listen->addr, ai_p->ai_addr, ai_p->ai_addrlen);
355 }
356 freeaddrinfo(ai);
357 #else
358 protox = getprotobyname("tcp");
359 if (protox == NULL) {
360 LOG(llevError, "init_server: Error getting protox\n");
361 fatal(SEE_LAST_ERROR);
362 }
363 init_sockets[0].listen->family = PF_INET;
364 init_sockets[0].listen->socktype = SOCK_STREAM;
365 init_sockets[0].listen->protocol = protox->p_proto;
366 insock = calloc(sizeof(struct sockaddr_in), 1);
367 insock->sin_family = AF_INET;
368 insock->sin_port = htons(settings.csport);
369 insock->sin_addr.s_addr = htonl(INADDR_ANY);
370 init_sockets[0].listen->addr = (struct sockaddr *) insock;
371 init_sockets[0].listen->addrlen = sizeof(struct sockaddr_in);
372 #endif
373
374 e = 1;
375 for (i = 0; i < listen_socket_count; i++) {
376 init_listening_socket(&init_sockets[i]);
377 if (init_sockets[i].fd != -1)
378 e = 0;
379 }
380 if (e != 0) {
381 LOG(llevError, "init_server: can't open any listening socket\n");
382 fatal(SEE_LAST_ERROR);
383 }
384
385 read_client_images();
386 }
387
388 /*******************************************************************************
389 *
390 * Start of functions dealing with freeing of the data.
391 *
392 ******************************************************************************/
393
394 /** Free's all the memory that ericserver allocates. */
395 void free_all_newserver(void) {
396 int i;
397 LOG(llevDebug, "Freeing all new client/server information.\n");
398 free_socket_images();
399 for (i = 0; i < socket_info.allocated_sockets && init_sockets[i].listen; i++) {
400 free(init_sockets[i].listen->addr);
401 free(init_sockets[i].listen);
402 }
403 free(init_sockets);
404 }
405
406 /**
407 * Frees a socket.
408 * Basically, all we need to do here is free all data structures that
409 * might be associated with the socket. It is up to the caller to
410 * update the list
411 */
412
413 void free_newsocket(socket_struct *ns) {
414 #ifdef WIN32 /* ***win32: closesocket in windows style */
415 shutdown(ns->fd, SD_BOTH);
416 if (closesocket(ns->fd)) {
417 #else
418 if (close(ns->fd)) {
419 #endif /* win32 */
420
421 #ifdef ESRV_DEBUG
422 LOG(llevDebug, "Error closing socket %d\n", ns->fd);
423 #endif
424 }
425 ns->fd = -1;
426 if (ns->stats.range)
427 FREE_AND_CLEAR(ns->stats.range);
428 if (ns->stats.title)
429 FREE_AND_CLEAR(ns->stats.title);
430 if (ns->host)
431 FREE_AND_CLEAR(ns->host);
432 if (ns->account_name) {
433 account_char_save(ns->account_name, ns->account_chars);
434 FREE_AND_CLEAR(ns->account_name);
435 }
436 if (ns->account_chars) {
437 account_char_free(ns->account_chars);
438 ns->account_chars = NULL;
439 }
440 SockList_Term(&ns->inbuf);
441 }
442
443 /** Sends the 'goodbye' command to the player, and closes connection. */
444 void final_free_player(player *pl) {
445 SockList sl;
446
447 SockList_Init(&sl);
448 SockList_AddString(&sl, "goodbye");
449 Send_With_Handling(&pl->socket, &sl);
450 SockList_Term(&sl);
451 free_newsocket(&pl->socket);
452 free_player(pl);
453 }