Debian Codegraph @

socket/lowlevel.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 * Low-level socket-related functions.
17 *
18 * \date 2003-12-02
19 *
20 * Contains some base functions that both the client and server
21 * can use. As such, depending what we are being compiled for will
22 * determine what we can include. the client is designed have
23 * CFCLIENT defined as part of its compile flags.
24 */
25
26 #include "global.h"
27
28 #include <assert.h>
29 #include <errno.h>
30 #include <stdarg.h>
31 #include <stdlib.h>
32 #include <string.h>
33
34 #include "shared/newclient.h"
35 #include "sproto.h"
36
37 /***********************************************************************
38 *
39 * SockList functions/utilities
40 *
41 **********************************************************************/
42
43 /**
44 * Initializes the SockList instance. Must be called before other socklist
45 * functions are called.
46 * @param sl the SockList instance to initialize
47 */
48 void SockList_Init(SockList *sl) {
49 SockList_Reset(sl);
50 }
51
52 /**
53 * Frees all resources allocated by a SockList instance. Must be called when
54 * the instance is not needed anymore. Afterwards no socklist functions except
55 * SockList_Init may be called.
56 * @param sl the SockList instance to free
57 */
58 void SockList_Term(SockList *sl) {
59 }
60
61 /**
62 * Resets the length of the stored data for writing. Does not free or
63 * re-allocate resources.
64 * @param sl the SockList instance to reset
65 */
66 void SockList_Reset(SockList *sl) {
67 sl->len = 2;
68 }
69
70 /**
71 * Resets the length of the stored data for reading. Does not free or
72 * re-allocate resources.
73 * @param sl the SockList instance to reset
74 */
75 void SockList_ResetRead(SockList *sl) {
76 sl->len = 0;
77 }
78
79 /**
80 * Checks that at least a given number of bytes is available in a SockList
81 * instance. Returns normal if the space is available. Otherwise calls
82 * fatal(OUT_OF_MEMORY);
83 *
84 * @param sl the SockList instance to check
85 * @param size the number of bytes to ensure
86 */
87 static void SockList_Ensure(const SockList *sl, size_t size) {
88 if (sl->len+size > sizeof(sl->buf)) {
89 fatal(OUT_OF_MEMORY);
90 }
91 }
92
93 /**
94 * Adds an 8 bit value.
95 * @param sl the SockList instance to add to
96 * @param data the value to add
97 */
98 void SockList_AddChar(SockList *sl, unsigned char data) {
99 SockList_Ensure(sl, 1);
100 sl->buf[sl->len++] = data;
101 }
102
103 /**
104 * Adds a 16 bit value.
105 * @param sl the SockList instance to add to
106 * @param data the value to add
107 */
108 void SockList_AddShort(SockList *sl, uint16_t data) {
109 SockList_Ensure(sl, 2);
110 sl->buf[sl->len++] = (data>>8)&0xff;
111 sl->buf[sl->len++] = data&0xff;
112 }
113
114 /**
115 * Adds a 32 bit value.
116 * @param sl the SockList instance to add to
117 * @param data the value to add
118 */
119 void SockList_AddInt(SockList *sl, uint32_t data) {
120 SockList_Ensure(sl, 4);
121 sl->buf[sl->len++] = (data>>24)&0xff;
122 sl->buf[sl->len++] = (data>>16)&0xff;
123 sl->buf[sl->len++] = (data>>8)&0xff;
124 sl->buf[sl->len++] = data&0xff;
125 }
126
127 /**
128 * Adds a 64 bit value.
129 * @param sl the SockList instance to add to
130 * @param data the value to add
131 */
132 void SockList_AddInt64(SockList *sl, uint64_t data) {
133 SockList_Ensure(sl, 8);
134 sl->buf[sl->len++] = (char)((data>>56)&0xff);
135 sl->buf[sl->len++] = (char)((data>>48)&0xff);
136 sl->buf[sl->len++] = (char)((data>>40)&0xff);
137 sl->buf[sl->len++] = (char)((data>>32)&0xff);
138 sl->buf[sl->len++] = (char)((data>>24)&0xff);
139 sl->buf[sl->len++] = (char)((data>>16)&0xff);
140 sl->buf[sl->len++] = (char)((data>>8)&0xff);
141 sl->buf[sl->len++] = (char)(data&0xff);
142 }
143
144 /**
145 * Adds a string without length.
146 * @param sl the SockList instance to add to
147 * @param data the value to add
148 */
149 void SockList_AddString(SockList *sl, const char *data) {
150 SockList_AddData(sl, data, strlen(data));
151 }
152
153 /**
154 * Adds a data block.
155 * @param sl the SockList instance to add to
156 * @param data the value to add
157 * @param len the length in byte
158 */
159 void SockList_AddData(SockList *sl, const void *data, size_t len) {
160 SockList_Ensure(sl, len);
161 memcpy(sl->buf+sl->len, data, len);
162 sl->len += len;
163 }
164
165 /**
166 * Adds a data block prepended with an 8 bit length field.
167 * @param sl the SockList instance to add to
168 * @param data the value to add
169 * @param len the length in byte; must not exceed 255
170 */
171 void SockList_AddLen8Data(SockList *sl, const void *data, size_t len) {
172 assert(len <= 255);
173 SockList_AddChar(sl, len);
174 SockList_AddData(sl, data, len);
175 }
176
177 /**
178 * Adds a data block prepended with an 16 bit length field.
179 * @param sl the SockList instance to add to
180 * @param data the value to add
181 * @param len the length in byte; must not exceed 65535
182 */
183 void SockList_AddLen16Data(SockList *sl, const void *data, size_t len) {
184 assert(len <= 65535);
185 SockList_AddShort(sl, len);
186 SockList_AddData(sl, data, len);
187 }
188
189 /**
190 * Adds a printf like formatted string.
191 * @param sl the SockList instance to add to
192 * @param format the format specifier
193 */
194 void SockList_AddPrintf(SockList *sl, const char *format, ...) {
195 size_t size;
196 int n;
197 va_list arg;
198
199 size = sizeof(sl->buf)-sl->len;
200
201 va_start(arg, format);
202 n = vsnprintf((char *)sl->buf+sl->len, size, format, arg);
203 va_end(arg);
204
205 if (n <= -1 || (size_t)n >= size) {
206 fatal(OUT_OF_MEMORY);
207 }
208 sl->len += (size_t)n;
209 }
210
211 /**
212 * Deallocates string buffer instance and appends its contents. The passed
213 * StringBuffer must not be accessed afterwards.
214 * @param sl the SockList instance to add to
215 * @param sb the StringBuffer to deallocate
216 */
217 void SockList_AddStringBuffer(SockList *sl, StringBuffer *sb) {
218 char *p;
219
220 p = stringbuffer_finish(sb);
221 SockList_AddString(sl, p);
222 free(p);
223 }
224
225 /**
226 * Adds a NUL byte without changing the length.
227 * @param sl the SockList instance to add to
228 */
229 void SockList_NullTerminate(SockList *sl) {
230 SockList_Ensure(sl, 1);
231 sl->buf[sl->len] = '\0';
232 }
233
234 /**
235 * Returns the available bytes in a SockList instance.
236 * @return the available bytes
237 */
238 size_t SockList_Avail(const SockList *sl) {
239 return sizeof(sl->buf)-sl->len;
240 }
241
242 /**
243 * Basically does the reverse of SockList_AddInt, but on
244 * strings instead. Same for the GetShort, but for 16 bits.
245 */
246 int GetInt_String(const unsigned char *data) {
247 return ((data[0]<<24)+(data[1]<<16)+(data[2]<<8)+data[3]);
248 }
249
250 short GetShort_String(const unsigned char *data) {
251 return ((data[0]<<8)+data[1]);
252 }
253
254 /******************************************************************************
255 *
256 * Start of read routines.
257 *
258 ******************************************************************************/
259
260 /**
261 * This reads from fd and puts the data in sl. We return true if we think
262 * we have a full packet, 0 if we have a partial packet, or -1 if an error
263 * occurred. The only processing we do is remove the initial size value. len
264 * (As passed) is the size of the buffer allocated in the socklist. We make
265 * the assumption the buffer is at least 2 bytes long.
266 */
267 int SockList_ReadPacket(int fd, SockList *sl, int len) {
268 int stat, toread;
269
270 /* We already have a partial packet */
271 if (sl->len < 2) {
272 #ifdef WIN32 /* ***WIN32 SockList_ReadPacket: change read() to recv() */
273
274 stat = recv(fd, sl->buf+sl->len, 2-sl->len, 0);
275
276 #else
277 do {
278 stat = read(fd, sl->buf+sl->len, 2-sl->len);
279 } while ((stat == -1) && (errno == EINTR));
280 #endif
281 if (stat < 0) {
282 /* In non blocking mode, EAGAIN is set when there is no
283 * data available.
284 */
285 #ifdef WIN32 /* ***WIN32 SockList_ReadPacket: error handling for win32 */
286 if ((stat == -1) && WSAGetLastError() != WSAEWOULDBLOCK) {
287 if (WSAGetLastError() == WSAECONNRESET)
288 LOG(llevDebug, "Connection closed by client\n");
289 else {
290 LOG(llevDebug, "ReadPacket got error %d, returning -1\n", WSAGetLastError());
291 }
292 return -1; /* kick this user! */
293 }
294 #else
295 if (errno == ECONNRESET) {
296 LOG(llevDebug, "ReadPacket got error %s, returning -1\n", strerror(errno));
297 return -1;
298 }
299 if (errno != EAGAIN && errno != EWOULDBLOCK) {
300 LOG(llevDebug, "ReadPacket got error %s, returning 0\n", strerror(errno));
301 }
302 #endif
303 return 0; /*Error */
304 }
305 if (stat == 0)
306 return -1;
307 sl->len += stat;
308 #ifdef CS_LOGSTATS
309 cst_tot.ibytes += stat;
310 cst_lst.ibytes += stat;
311 #endif
312 if (stat < 2)
313 return 0; /* Still don't have a full packet */
314 }
315 /* Figure out how much more data we need to read. Add 2 from the
316 * end of this - size header information is not included.
317 */
318 toread = 2+(sl->buf[0]<<8)+sl->buf[1]-sl->len;
319 if ((toread+(int)sl->len) >= len) {
320 LOG(llevError, "SockList_ReadPacket: Want to read more bytes than will fit in buffer (%lu>=%lu).\n", (unsigned long)toread+sl->len, (unsigned long)len);
321 /* Quick hack in case for 'oldsocketmode' input. If we are
322 * closing the socket anyways, then reading this extra 100 bytes
323 * shouldn't hurt.
324 */
325 #ifdef WIN32 /* ***win32 SockList_ReadPacket: change read() to recv() */
326 stat = recv(fd, sl->buf+2, 100, 0);
327 #else
328 stat = read(fd, sl->buf+2, 100);
329 #endif /* end win32 */
330 (void) stat; // Don't care how much we read; avoid complier warnings
331
332 /* return error so the socket is closed */
333 return -1;
334 }
335 do {
336 #ifdef WIN32 /* ***win32 SockList_ReadPacket: change read() to recv() */
337 stat = recv(fd, sl->buf+sl->len, toread, 0);
338 #else
339 do {
340 stat = read(fd, sl->buf+sl->len, toread);
341 } while ((stat < 0) && (errno == EINTR));
342 #endif
343 if (stat < 0) {
344 #ifdef WIN32 /* ***win32 SockList_ReadPacket: change error handling for win32 */
345 if ((stat == -1) && WSAGetLastError() != WSAEWOULDBLOCK) {
346 if (WSAGetLastError() == WSAECONNRESET)
347 LOG(llevDebug, "Connection closed by client\n");
348 else {
349 LOG(llevDebug, "ReadPacket got error %d, returning -1\n", WSAGetLastError());
350 }
351 return -1; /* kick this user! */
352 }
353 #else
354 if (errno != EAGAIN && errno != EWOULDBLOCK) {
355 LOG(llevDebug, "ReadPacket got error %s, returning 0\n", strerror(errno));
356 }
357 #endif
358 return 0; /*Error */
359 }
360 if (stat == 0)
361 return -1;
362 sl->len += stat;
363 #ifdef CS_LOGSTATS
364 cst_tot.ibytes += stat;
365 cst_lst.ibytes += stat;
366 #endif
367 toread -= stat;
368 if (toread == 0)
369 return 1;
370 if (toread < 0) {
371 LOG(llevError, "SockList_ReadPacket: Read more bytes than desired.\n");
372 return 1;
373 }
374 } while (toread > 0);
375 return 0;
376 }
377
378 /*******************************************************************************
379 *
380 * Start of write related routines.
381 *
382 ******************************************************************************/
383
384 /**
385 * This writes data to the socket. - It is very low level -
386 * all we try and do is write out the data to the socket
387 * provided (ns). buf is the data to write, len is the number
388 * of bytes to write. IT doesn't return anything - rather, it
389 * updates the ns structure if we get an error.
390 */
391 static void Write_To_Socket(socket_struct* ns, const unsigned char* buf, const int len) {
392 if (ns->status == Ns_Dead || !buf) {
393 LOG(llevDebug, "Write_To_Socket called with dead socket\n");
394 return;
395 }
396
397 const int amt = send(ns->fd, buf, len, 0);
398 if (amt < 0) { /* We got an error */
399 #ifdef WIN32 /* ***win32 Write_To_Socket: change error handling */
400 if (amt == -1 && WSAGetLastError() != WSAEWOULDBLOCK) {
401 LOG(llevInfo, "New socket write failed WTS (%d).\n",
402 WSAGetLastError());
403 #else
404 if (errno != EWOULDBLOCK) {
405 LOG(llevInfo, "New socket write failed WTS: %s\n",
406 strerror(errno));
407 #endif
408 ns->status = Ns_Dead;
409 return;
410 } else { /* EWOULDBLOCK */
411 LOG(llevError,
412 "Write_To_Socket: write would block; disconnecting. Try "
413 "increasing SOCKETBUFSIZE.\n");
414 ns->status = Ns_Dead;
415 return;
416 }
417 } else if (amt != len) {
418 LOG(llevError, "Write_To_Socket: write wrote less than requested; "
419 "disconnecting. Try increasing SOCKETBUFSIZE.\n");
420 ns->status = Ns_Dead;
421 return;
422 }
423 #ifdef CS_LOGSTATS
424 cst_tot.obytes += amt;
425 cst_lst.obytes += amt;
426 #endif
427 }
428
429 /**
430 * Calls Write_To_Socket to send data to the client.
431 *
432 * The only difference in this function is that we take a SockList
433 *, and we prepend the length information.
434 */
435 void Send_With_Handling(socket_struct *ns, SockList *sl) {
436 if (ns->status == Ns_Dead || sl == NULL)
437 return;
438
439 sl->buf[0] = ((sl->len-2)>>8)&0xFF;
440 sl->buf[1] = (sl->len-2)&0xFF;
441 Write_To_Socket(ns, sl->buf, sl->len);
442 }
443
444 /******************************************************************************
445 *
446 * statistics logging functions.
447 *
448 ******************************************************************************/
449
450 #ifdef CS_LOGSTATS
451 /* cst_tot is for the life of the server, cst_last is for the last series of
452 * stats
453 */
454 CS_Stats cst_tot, cst_lst;
455
456 /**
457 * Writes out the gathered stats. We clear cst_lst.
458 */
459 void write_cs_stats(void) {
460 time_t now = time(NULL);
461
462 /* If no connections recently, don't bother to log anything */
463 if (cst_lst.ibytes == 0 && cst_lst.obytes == 0)
464 return;
465
466 /* CSSTAT is put in so scripts can easily find the line */
467 LOG(llevInfo, "CSSTAT: %.16s tot %d %d %d %ld inc %d %d %d %ld\n",
468 ctime(&now), cst_tot.ibytes, cst_tot.obytes, cst_tot.max_conn,
469 (long)(now-cst_tot.time_start), cst_lst.ibytes, cst_lst.obytes,
470 cst_lst.max_conn, (long)(now-cst_lst.time_start));
471 cst_lst.ibytes = 0;
472 cst_lst.obytes = 0;
473 cst_lst.max_conn = socket_info.allocated_sockets;
474 cst_lst.time_start = now;
475 }
476 #endif
477