PageRenderTime 74ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/src/common/socket.c

https://gitlab.com/evol/hercules
C | 1811 lines | 1335 code | 231 blank | 245 comment | 335 complexity | a625539ce5340c1d4a65b80c4de6a247 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. /**
  2. * This file is part of Hercules.
  3. * http://herc.ws - http://github.com/HerculesWS/Hercules
  4. *
  5. * Copyright (C) 2012-2015 Hercules Dev Team
  6. * Copyright (C) Athena Dev Teams
  7. *
  8. * Hercules is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. */
  21. #define HERCULES_CORE
  22. #include "config/core.h" // SHOW_SERVER_STATS
  23. #include "socket.h"
  24. #include "common/HPM.h"
  25. #include "common/cbasetypes.h"
  26. #include "common/db.h"
  27. #include "common/memmgr.h"
  28. #include "common/mmo.h"
  29. #include "common/nullpo.h"
  30. #include "common/showmsg.h"
  31. #include "common/strlib.h"
  32. #include "common/timer.h"
  33. #include <stdio.h>
  34. #include <stdlib.h>
  35. #include <sys/types.h>
  36. #ifdef WIN32
  37. # include "common/winapi.h"
  38. #else
  39. # include <arpa/inet.h>
  40. # include <errno.h>
  41. # include <net/if.h>
  42. # include <netdb.h>
  43. #if defined __linux__ || defined __linux
  44. # include <linux/tcp.h>
  45. #else
  46. # include <netinet/in.h>
  47. # include <netinet/tcp.h>
  48. #endif
  49. # include <sys/ioctl.h>
  50. # include <sys/socket.h>
  51. # include <sys/time.h>
  52. # include <unistd.h>
  53. # ifndef SIOCGIFCONF
  54. # include <sys/sockio.h> // SIOCGIFCONF on Solaris, maybe others? [Shinomori]
  55. # endif
  56. # ifndef FIONBIO
  57. # include <sys/filio.h> // FIONBIO on Solaris [FlavioJS]
  58. # endif
  59. # ifdef HAVE_SETRLIMIT
  60. # include <sys/resource.h>
  61. # endif
  62. #endif
  63. /**
  64. * Socket Interface Source
  65. **/
  66. struct socket_interface sockt_s;
  67. struct socket_interface *sockt;
  68. struct socket_data **session;
  69. #ifdef SEND_SHORTLIST
  70. // Add a fd to the shortlist so that it'll be recognized as a fd that needs
  71. // sending done on it.
  72. void send_shortlist_add_fd(int fd);
  73. // Do pending network sends (and eof handling) from the shortlist.
  74. void send_shortlist_do_sends(void);
  75. #endif
  76. /////////////////////////////////////////////////////////////////////
  77. #if defined(WIN32)
  78. /////////////////////////////////////////////////////////////////////
  79. // windows portability layer
  80. typedef int socklen_t;
  81. #define sErrno WSAGetLastError()
  82. #define S_ENOTSOCK WSAENOTSOCK
  83. #define S_EWOULDBLOCK WSAEWOULDBLOCK
  84. #define S_EINTR WSAEINTR
  85. #define S_ECONNABORTED WSAECONNABORTED
  86. #define SHUT_RD SD_RECEIVE
  87. #define SHUT_WR SD_SEND
  88. #define SHUT_RDWR SD_BOTH
  89. // global array of sockets (emulating linux)
  90. // fd is the position in the array
  91. static SOCKET sock_arr[FD_SETSIZE];
  92. static int sock_arr_len = 0;
  93. /// Returns the socket associated with the target fd.
  94. ///
  95. /// @param fd Target fd.
  96. /// @return Socket
  97. #define fd2sock(fd) sock_arr[fd]
  98. /// Returns the first fd associated with the socket.
  99. /// Returns -1 if the socket is not found.
  100. ///
  101. /// @param s Socket
  102. /// @return Fd or -1
  103. int sock2fd(SOCKET s)
  104. {
  105. int fd;
  106. // search for the socket
  107. for( fd = 1; fd < sock_arr_len; ++fd )
  108. if( sock_arr[fd] == s )
  109. break;// found the socket
  110. if( fd == sock_arr_len )
  111. return -1;// not found
  112. return fd;
  113. }
  114. /// Inserts the socket into the global array of sockets.
  115. /// Returns a new fd associated with the socket.
  116. /// If there are too many sockets it closes the socket, sets an error and
  117. // returns -1 instead.
  118. /// Since fd 0 is reserved, it returns values in the range [1,FD_SETSIZE[.
  119. ///
  120. /// @param s Socket
  121. /// @return New fd or -1
  122. int sock2newfd(SOCKET s)
  123. {
  124. int fd;
  125. // find an empty position
  126. for( fd = 1; fd < sock_arr_len; ++fd )
  127. if( sock_arr[fd] == INVALID_SOCKET )
  128. break;// empty position
  129. if( fd == ARRAYLENGTH(sock_arr) )
  130. {// too many sockets
  131. closesocket(s);
  132. WSASetLastError(WSAEMFILE);
  133. return -1;
  134. }
  135. sock_arr[fd] = s;
  136. if( sock_arr_len <= fd )
  137. sock_arr_len = fd+1;
  138. return fd;
  139. }
  140. int sAccept(int fd, struct sockaddr* addr, int* addrlen)
  141. {
  142. SOCKET s;
  143. // accept connection
  144. s = accept(fd2sock(fd), addr, addrlen);
  145. if( s == INVALID_SOCKET )
  146. return -1;// error
  147. return sock2newfd(s);
  148. }
  149. int sClose(int fd)
  150. {
  151. int ret = closesocket(fd2sock(fd));
  152. fd2sock(fd) = INVALID_SOCKET;
  153. return ret;
  154. }
  155. int sSocket(int af, int type, int protocol)
  156. {
  157. SOCKET s;
  158. // create socket
  159. s = socket(af,type,protocol);
  160. if( s == INVALID_SOCKET )
  161. return -1;// error
  162. return sock2newfd(s);
  163. }
  164. char* sErr(int code)
  165. {
  166. static char sbuf[512];
  167. // strerror does not handle socket codes
  168. if( FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
  169. code, MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT), (LPTSTR)&sbuf, sizeof(sbuf), NULL) == 0 )
  170. snprintf(sbuf, sizeof(sbuf), "unknown error");
  171. return sbuf;
  172. }
  173. #define sBind(fd,name,namelen) bind(fd2sock(fd),(name),(namelen))
  174. #define sConnect(fd,name,namelen) connect(fd2sock(fd),(name),(namelen))
  175. #define sIoctl(fd,cmd,argp) ioctlsocket(fd2sock(fd),(cmd),(argp))
  176. #define sListen(fd,backlog) listen(fd2sock(fd),(backlog))
  177. #define sRecv(fd,buf,len,flags) recv(fd2sock(fd),(buf),(len),(flags))
  178. #define sSelect select
  179. #define sSend(fd,buf,len,flags) send(fd2sock(fd),(buf),(len),(flags))
  180. #define sSetsockopt(fd,level,optname,optval,optlen) setsockopt(fd2sock(fd),(level),(optname),(optval),(optlen))
  181. #define sShutdown(fd,how) shutdown(fd2sock(fd),(how))
  182. #define sFD_SET(fd,set) FD_SET(fd2sock(fd),(set))
  183. #define sFD_CLR(fd,set) FD_CLR(fd2sock(fd),(set))
  184. #define sFD_ISSET(fd,set) FD_ISSET(fd2sock(fd),(set))
  185. #define sFD_ZERO FD_ZERO
  186. /////////////////////////////////////////////////////////////////////
  187. #else
  188. /////////////////////////////////////////////////////////////////////
  189. // nix portability layer
  190. #define SOCKET_ERROR (-1)
  191. #define sErrno errno
  192. #define S_ENOTSOCK EBADF
  193. #define S_EWOULDBLOCK EAGAIN
  194. #define S_EINTR EINTR
  195. #define S_ECONNABORTED ECONNABORTED
  196. #define sAccept accept
  197. #define sClose close
  198. #define sSocket socket
  199. #define sErr strerror
  200. #define sBind bind
  201. #define sConnect connect
  202. #define sIoctl ioctl
  203. #define sListen listen
  204. #define sRecv recv
  205. #define sSelect select
  206. #define sSend send
  207. #define sSetsockopt setsockopt
  208. #define sShutdown shutdown
  209. #define sFD_SET FD_SET
  210. #define sFD_CLR FD_CLR
  211. #define sFD_ISSET FD_ISSET
  212. #define sFD_ZERO FD_ZERO
  213. /////////////////////////////////////////////////////////////////////
  214. #endif
  215. /////////////////////////////////////////////////////////////////////
  216. #ifndef MSG_NOSIGNAL
  217. #define MSG_NOSIGNAL 0
  218. #endif
  219. fd_set readfds;
  220. // Maximum packet size in bytes, which the client is able to handle.
  221. // Larger packets cause a buffer overflow and stack corruption.
  222. #if PACKETVER >= 20131223
  223. static size_t socket_max_client_packet = 0xFFFF;
  224. #else
  225. static size_t socket_max_client_packet = 0x6000;
  226. #endif
  227. #ifdef SHOW_SERVER_STATS
  228. // Data I/O statistics
  229. static size_t socket_data_i = 0, socket_data_ci = 0, socket_data_qi = 0;
  230. static size_t socket_data_o = 0, socket_data_co = 0, socket_data_qo = 0;
  231. static time_t socket_data_last_tick = 0;
  232. #endif
  233. // initial recv buffer size (this will also be the max. size)
  234. // biggest known packet: S 0153 <len>.w <emblem data>.?B -> 24x24 256 color .bmp (0153 + len.w + 1618/1654/1756 bytes)
  235. #define RFIFO_SIZE (2*1024)
  236. // initial send buffer size (will be resized as needed)
  237. #define WFIFO_SIZE (16*1024)
  238. // Maximum size of pending data in the write fifo. (for non-server connections)
  239. // The connection is closed if it goes over the limit.
  240. #define WFIFO_MAX (1*1024*1024)
  241. #ifdef SEND_SHORTLIST
  242. int send_shortlist_array[FD_SETSIZE];// we only support FD_SETSIZE sockets, limit the array to that
  243. int send_shortlist_count = 0;// how many fd's are in the shortlist
  244. uint32 send_shortlist_set[(FD_SETSIZE+31)/32];// to know if specific fd's are already in the shortlist
  245. #endif
  246. static int create_session(int fd, RecvFunc func_recv, SendFunc func_send, ParseFunc func_parse);
  247. #ifndef MINICORE
  248. int ip_rules = 1;
  249. static int connect_check(uint32 ip);
  250. #endif
  251. const char* error_msg(void)
  252. {
  253. static char buf[512];
  254. int code = sErrno;
  255. snprintf(buf, sizeof(buf), "error %d: %s", code, sErr(code));
  256. return buf;
  257. }
  258. /*======================================
  259. * CORE : Default processing functions
  260. *--------------------------------------*/
  261. int null_recv(int fd) { return 0; }
  262. int null_send(int fd) { return 0; }
  263. int null_parse(int fd) { return 0; }
  264. ParseFunc default_func_parse = null_parse;
  265. void set_defaultparse(ParseFunc defaultparse)
  266. {
  267. default_func_parse = defaultparse;
  268. }
  269. /*======================================
  270. * CORE : Socket options
  271. *--------------------------------------*/
  272. void set_nonblocking(int fd, unsigned long yes)
  273. {
  274. // FIONBIO Use with a nonzero argp parameter to enable the nonblocking mode of socket s.
  275. // The argp parameter is zero if nonblocking is to be disabled.
  276. if( sIoctl(fd, FIONBIO, &yes) != 0 )
  277. ShowError("set_nonblocking: Failed to set socket #%d to non-blocking mode (%s) - Please report this!!!\n", fd, error_msg());
  278. }
  279. /**
  280. * Sets the options for a socket.
  281. *
  282. * @param fd The socket descriptor
  283. * @param opt Optional, additional options to set (Can be NULL).
  284. */
  285. void setsocketopts(int fd, struct hSockOpt *opt)
  286. {
  287. #if defined(WIN32)
  288. BOOL yes = TRUE;
  289. #else // not WIN32
  290. int yes = 1;
  291. #endif // WIN32
  292. struct linger lopt = { 0 };
  293. // Note: We cast the fourth argument to (char *) because, while in UNIX
  294. // it takes a const void *, in Windows it takes a const char *.
  295. #if !defined(WIN32)
  296. // set SO_REAUSEADDR to true, unix only. on windows this option causes
  297. // the previous owner of the socket to give up, which is not desirable
  298. // in most cases, neither compatible with unix.
  299. if (sSetsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&yes, sizeof(yes)))
  300. ShowWarning("setsocketopts: Unable to set SO_REUSEADDR mode for connection #%d!\n", fd);
  301. #ifdef SO_REUSEPORT
  302. if (sSetsockopt(fd, SOL_SOCKET, SO_REUSEPORT, (char *)&yes, sizeof(yes)))
  303. ShowWarning("setsocketopts: Unable to set SO_REUSEPORT mode for connection #%d!\n", fd);
  304. #endif // SO_REUSEPORT
  305. #endif // WIN32
  306. // Set the socket into no-delay mode; otherwise packets get delayed for up to 200ms, likely creating server-side lag.
  307. // The RO protocol is mainly single-packet request/response, plus the FIFO model already does packet grouping anyway.
  308. if (sSetsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&yes, sizeof(yes)))
  309. ShowWarning("setsocketopts: Unable to set TCP_NODELAY mode for connection #%d!\n", fd);
  310. if (opt && opt->setTimeo) {
  311. #if defined(WIN32)
  312. DWORD timeout = 5000; // https://msdn.microsoft.com/en-us/library/windows/desktop/ms740476(v=vs.85).aspx
  313. #else // not WIN32
  314. struct timeval timeout = { 0 };
  315. timeout.tv_sec = 5;
  316. #endif // WIN32
  317. if (sSetsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)))
  318. ShowWarning("setsocketopts: Unable to set SO_RCVTIMEO for connection #%d!\n", fd);
  319. if (sSetsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout)))
  320. ShowWarning("setsocketopts: Unable to set SO_SNDTIMEO for connection #%d!\n", fd);
  321. }
  322. // force the socket into no-wait, graceful-close mode (should be the default, but better make sure)
  323. //(http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winsock/winsock/closesocket_2.asp)
  324. lopt.l_onoff = 0; // SO_DONTLINGER
  325. lopt.l_linger = 0; // Do not care
  326. if (sSetsockopt(fd, SOL_SOCKET, SO_LINGER, (char *)&lopt, sizeof(lopt)))
  327. ShowWarning("setsocketopts: Unable to set SO_LINGER mode for connection #%d!\n", fd);
  328. #ifdef TCP_THIN_LINEAR_TIMEOUTS
  329. if (sSetsockopt(fd, IPPROTO_TCP, TCP_THIN_LINEAR_TIMEOUTS, (char *)&yes, sizeof(yes)))
  330. ShowWarning("setsocketopts: Unable to set TCP_THIN_LINEAR_TIMEOUTS mode for connection #%d!\n", fd);
  331. #endif
  332. #ifdef TCP_THIN_DUPACK
  333. if (sSetsockopt(fd, IPPROTO_TCP, TCP_THIN_DUPACK, (char *)&yes, sizeof(yes)))
  334. ShowWarning("setsocketopts: Unable to set TCP_THIN_DUPACK mode for connection #%d!\n", fd);
  335. #endif
  336. }
  337. /*======================================
  338. * CORE : Socket Sub Function
  339. *--------------------------------------*/
  340. void set_eof(int fd)
  341. {
  342. if (sockt->session_is_active(fd)) {
  343. #ifdef SEND_SHORTLIST
  344. // Add this socket to the shortlist for eof handling.
  345. send_shortlist_add_fd(fd);
  346. #endif
  347. sockt->session[fd]->flag.eof = 1;
  348. }
  349. }
  350. int recv_to_fifo(int fd)
  351. {
  352. ssize_t len;
  353. if (!sockt->session_is_active(fd))
  354. return -1;
  355. len = sRecv(fd, (char *) sockt->session[fd]->rdata + sockt->session[fd]->rdata_size, (int)RFIFOSPACE(fd), 0);
  356. if( len == SOCKET_ERROR )
  357. {//An exception has occurred
  358. if( sErrno != S_EWOULDBLOCK ) {
  359. //ShowDebug("recv_to_fifo: %s, closing connection #%d\n", error_msg(), fd);
  360. sockt->eof(fd);
  361. }
  362. return 0;
  363. }
  364. if( len == 0 )
  365. {//Normal connection end.
  366. sockt->eof(fd);
  367. return 0;
  368. }
  369. sockt->session[fd]->rdata_size += len;
  370. sockt->session[fd]->rdata_tick = sockt->last_tick;
  371. #ifdef SHOW_SERVER_STATS
  372. socket_data_i += len;
  373. socket_data_qi += len;
  374. if (!sockt->session[fd]->flag.server)
  375. {
  376. socket_data_ci += len;
  377. }
  378. #endif
  379. return 0;
  380. }
  381. int send_from_fifo(int fd)
  382. {
  383. ssize_t len;
  384. if (!sockt->session_is_valid(fd))
  385. return -1;
  386. if( sockt->session[fd]->wdata_size == 0 )
  387. return 0; // nothing to send
  388. len = sSend(fd, (const char *) sockt->session[fd]->wdata, (int)sockt->session[fd]->wdata_size, MSG_NOSIGNAL);
  389. if( len == SOCKET_ERROR )
  390. {//An exception has occurred
  391. if( sErrno != S_EWOULDBLOCK ) {
  392. //ShowDebug("send_from_fifo: %s, ending connection #%d\n", error_msg(), fd);
  393. #ifdef SHOW_SERVER_STATS
  394. socket_data_qo -= sockt->session[fd]->wdata_size;
  395. #endif
  396. sockt->session[fd]->wdata_size = 0; //Clear the send queue as we can't send anymore. [Skotlex]
  397. sockt->eof(fd);
  398. }
  399. return 0;
  400. }
  401. if( len > 0 )
  402. {
  403. // some data could not be transferred?
  404. // shift unsent data to the beginning of the queue
  405. if( (size_t)len < sockt->session[fd]->wdata_size )
  406. memmove(sockt->session[fd]->wdata, sockt->session[fd]->wdata + len, sockt->session[fd]->wdata_size - len);
  407. sockt->session[fd]->wdata_size -= len;
  408. #ifdef SHOW_SERVER_STATS
  409. socket_data_o += len;
  410. socket_data_qo -= len;
  411. if (!sockt->session[fd]->flag.server)
  412. {
  413. socket_data_co += len;
  414. }
  415. #endif
  416. }
  417. return 0;
  418. }
  419. /// Best effort - there's no warranty that the data will be sent.
  420. void flush_fifo(int fd)
  421. {
  422. if(sockt->session[fd] != NULL)
  423. sockt->session[fd]->func_send(fd);
  424. }
  425. void flush_fifos(void)
  426. {
  427. int i;
  428. for(i = 1; i < sockt->fd_max; i++)
  429. sockt->flush(i);
  430. }
  431. /*======================================
  432. * CORE : Connection functions
  433. *--------------------------------------*/
  434. int connect_client(int listen_fd) {
  435. int fd;
  436. struct sockaddr_in client_address;
  437. socklen_t len;
  438. len = sizeof(client_address);
  439. fd = sAccept(listen_fd, (struct sockaddr*)&client_address, &len);
  440. if ( fd == -1 ) {
  441. ShowError("connect_client: accept failed (%s)!\n", error_msg());
  442. return -1;
  443. }
  444. if( fd == 0 ) { // reserved
  445. ShowError("connect_client: Socket #0 is reserved - Please report this!!!\n");
  446. sClose(fd);
  447. return -1;
  448. }
  449. if( fd >= FD_SETSIZE ) { // socket number too big
  450. ShowError("connect_client: New socket #%d is greater than can we handle! Increase the value of FD_SETSIZE (currently %d) for your OS to fix this!\n", fd, FD_SETSIZE);
  451. sClose(fd);
  452. return -1;
  453. }
  454. setsocketopts(fd,NULL);
  455. sockt->set_nonblocking(fd, 1);
  456. #ifndef MINICORE
  457. if( ip_rules && !connect_check(ntohl(client_address.sin_addr.s_addr)) ) {
  458. sockt->close(fd);
  459. return -1;
  460. }
  461. #endif
  462. if( sockt->fd_max <= fd ) sockt->fd_max = fd + 1;
  463. sFD_SET(fd,&readfds);
  464. create_session(fd, recv_to_fifo, send_from_fifo, default_func_parse);
  465. sockt->session[fd]->client_addr = ntohl(client_address.sin_addr.s_addr);
  466. return fd;
  467. }
  468. int make_listen_bind(uint32 ip, uint16 port)
  469. {
  470. struct sockaddr_in server_address = { 0 };
  471. int fd;
  472. int result;
  473. fd = sSocket(AF_INET, SOCK_STREAM, 0);
  474. if( fd == -1 ) {
  475. ShowError("make_listen_bind: socket creation failed (%s)!\n", error_msg());
  476. exit(EXIT_FAILURE);
  477. }
  478. if( fd == 0 ) { // reserved
  479. ShowError("make_listen_bind: Socket #0 is reserved - Please report this!!!\n");
  480. sClose(fd);
  481. return -1;
  482. }
  483. if( fd >= FD_SETSIZE ) { // socket number too big
  484. ShowError("make_listen_bind: New socket #%d is greater than can we handle! Increase the value of FD_SETSIZE (currently %d) for your OS to fix this!\n", fd, FD_SETSIZE);
  485. sClose(fd);
  486. return -1;
  487. }
  488. setsocketopts(fd,NULL);
  489. sockt->set_nonblocking(fd, 1);
  490. server_address.sin_family = AF_INET;
  491. server_address.sin_addr.s_addr = htonl(ip);
  492. server_address.sin_port = htons(port);
  493. result = sBind(fd, (struct sockaddr*)&server_address, sizeof(server_address));
  494. if( result == SOCKET_ERROR ) {
  495. ShowError("make_listen_bind: bind failed (socket #%d, %s)!\n", fd, error_msg());
  496. exit(EXIT_FAILURE);
  497. }
  498. result = sListen(fd,5);
  499. if( result == SOCKET_ERROR ) {
  500. ShowError("make_listen_bind: listen failed (socket #%d, %s)!\n", fd, error_msg());
  501. exit(EXIT_FAILURE);
  502. }
  503. if(sockt->fd_max <= fd) sockt->fd_max = fd + 1;
  504. sFD_SET(fd, &readfds);
  505. create_session(fd, connect_client, null_send, null_parse);
  506. sockt->session[fd]->client_addr = 0; // just listens
  507. sockt->session[fd]->rdata_tick = 0; // disable timeouts on this socket
  508. return fd;
  509. }
  510. int make_connection(uint32 ip, uint16 port, struct hSockOpt *opt) {
  511. struct sockaddr_in remote_address = { 0 };
  512. int fd;
  513. int result;
  514. fd = sSocket(AF_INET, SOCK_STREAM, 0);
  515. if (fd == -1) {
  516. ShowError("make_connection: socket creation failed (%s)!\n", error_msg());
  517. return -1;
  518. }
  519. if( fd == 0 ) {// reserved
  520. ShowError("make_connection: Socket #0 is reserved - Please report this!!!\n");
  521. sClose(fd);
  522. return -1;
  523. }
  524. if( fd >= FD_SETSIZE ) {// socket number too big
  525. ShowError("make_connection: New socket #%d is greater than can we handle! Increase the value of FD_SETSIZE (currently %d) for your OS to fix this!\n", fd, FD_SETSIZE);
  526. sClose(fd);
  527. return -1;
  528. }
  529. setsocketopts(fd,opt);
  530. remote_address.sin_family = AF_INET;
  531. remote_address.sin_addr.s_addr = htonl(ip);
  532. remote_address.sin_port = htons(port);
  533. if( !( opt && opt->silent ) )
  534. ShowStatus("Connecting to %d.%d.%d.%d:%i\n", CONVIP(ip), port);
  535. result = sConnect(fd, (struct sockaddr *)(&remote_address), sizeof(struct sockaddr_in));
  536. if( result == SOCKET_ERROR ) {
  537. if( !( opt && opt->silent ) )
  538. ShowError("make_connection: connect failed (socket #%d, %s)!\n", fd, error_msg());
  539. sockt->close(fd);
  540. return -1;
  541. }
  542. //Now the socket can be made non-blocking. [Skotlex]
  543. sockt->set_nonblocking(fd, 1);
  544. if (sockt->fd_max <= fd) sockt->fd_max = fd + 1;
  545. sFD_SET(fd,&readfds);
  546. create_session(fd, recv_to_fifo, send_from_fifo, default_func_parse);
  547. sockt->session[fd]->client_addr = ntohl(remote_address.sin_addr.s_addr);
  548. return fd;
  549. }
  550. static int create_session(int fd, RecvFunc func_recv, SendFunc func_send, ParseFunc func_parse)
  551. {
  552. CREATE(sockt->session[fd], struct socket_data, 1);
  553. CREATE(sockt->session[fd]->rdata, unsigned char, RFIFO_SIZE);
  554. CREATE(sockt->session[fd]->wdata, unsigned char, WFIFO_SIZE);
  555. sockt->session[fd]->max_rdata = RFIFO_SIZE;
  556. sockt->session[fd]->max_wdata = WFIFO_SIZE;
  557. sockt->session[fd]->func_recv = func_recv;
  558. sockt->session[fd]->func_send = func_send;
  559. sockt->session[fd]->func_parse = func_parse;
  560. sockt->session[fd]->rdata_tick = sockt->last_tick;
  561. sockt->session[fd]->session_data = NULL;
  562. sockt->session[fd]->hdata = NULL;
  563. return 0;
  564. }
  565. static void delete_session(int fd)
  566. {
  567. if (sockt->session_is_valid(fd)) {
  568. #ifdef SHOW_SERVER_STATS
  569. socket_data_qi -= sockt->session[fd]->rdata_size - sockt->session[fd]->rdata_pos;
  570. socket_data_qo -= sockt->session[fd]->wdata_size;
  571. #endif
  572. aFree(sockt->session[fd]->rdata);
  573. aFree(sockt->session[fd]->wdata);
  574. if( sockt->session[fd]->session_data )
  575. aFree(sockt->session[fd]->session_data);
  576. HPM->data_store_destroy(&sockt->session[fd]->hdata);
  577. aFree(sockt->session[fd]);
  578. sockt->session[fd] = NULL;
  579. }
  580. }
  581. int realloc_fifo(int fd, unsigned int rfifo_size, unsigned int wfifo_size)
  582. {
  583. if (!sockt->session_is_valid(fd))
  584. return 0;
  585. if( sockt->session[fd]->max_rdata != rfifo_size && sockt->session[fd]->rdata_size < rfifo_size) {
  586. RECREATE(sockt->session[fd]->rdata, unsigned char, rfifo_size);
  587. sockt->session[fd]->max_rdata = rfifo_size;
  588. }
  589. if( sockt->session[fd]->max_wdata != wfifo_size && sockt->session[fd]->wdata_size < wfifo_size) {
  590. RECREATE(sockt->session[fd]->wdata, unsigned char, wfifo_size);
  591. sockt->session[fd]->max_wdata = wfifo_size;
  592. }
  593. return 0;
  594. }
  595. int realloc_writefifo(int fd, size_t addition)
  596. {
  597. size_t newsize;
  598. if (!sockt->session_is_valid(fd)) // might not happen
  599. return 0;
  600. if (sockt->session[fd]->wdata_size + addition > sockt->session[fd]->max_wdata) {
  601. // grow rule; grow in multiples of WFIFO_SIZE
  602. newsize = WFIFO_SIZE;
  603. while( sockt->session[fd]->wdata_size + addition > newsize ) newsize += WFIFO_SIZE;
  604. } else if (sockt->session[fd]->max_wdata >= (size_t)2*(sockt->session[fd]->flag.server?FIFOSIZE_SERVERLINK:WFIFO_SIZE)
  605. && (sockt->session[fd]->wdata_size+addition)*4 < sockt->session[fd]->max_wdata
  606. ) {
  607. // shrink rule, shrink by 2 when only a quarter of the fifo is used, don't shrink below nominal size.
  608. newsize = sockt->session[fd]->max_wdata / 2;
  609. } else {
  610. // no change
  611. return 0;
  612. }
  613. RECREATE(sockt->session[fd]->wdata, unsigned char, newsize);
  614. sockt->session[fd]->max_wdata = newsize;
  615. return 0;
  616. }
  617. /// advance the RFIFO cursor (marking 'len' bytes as processed)
  618. int rfifoskip(int fd, size_t len)
  619. {
  620. struct socket_data *s;
  621. if (!sockt->session_is_active(fd))
  622. return 0;
  623. s = sockt->session[fd];
  624. if (s->rdata_size < s->rdata_pos + len) {
  625. ShowError("RFIFOSKIP: skipped past end of read buffer! Adjusting from %"PRIuS" to %"PRIuS" (session #%d)\n", len, RFIFOREST(fd), fd);
  626. len = RFIFOREST(fd);
  627. }
  628. s->rdata_pos = s->rdata_pos + len;
  629. #ifdef SHOW_SERVER_STATS
  630. socket_data_qi -= len;
  631. #endif
  632. return 0;
  633. }
  634. /// advance the WFIFO cursor (marking 'len' bytes for sending)
  635. int wfifoset(int fd, size_t len)
  636. {
  637. size_t newreserve;
  638. struct socket_data* s = sockt->session[fd];
  639. if (!sockt->session_is_valid(fd) || s->wdata == NULL)
  640. return 0;
  641. // we have written len bytes to the buffer already before calling WFIFOSET
  642. if (s->wdata_size+len > s->max_wdata) {
  643. // actually there was a buffer overflow already
  644. uint32 ip = s->client_addr;
  645. ShowFatalError("WFIFOSET: Write Buffer Overflow. Connection %d (%d.%d.%d.%d) has written %u bytes on a %u/%u bytes buffer.\n", fd, CONVIP(ip), (unsigned int)len, (unsigned int)s->wdata_size, (unsigned int)s->max_wdata);
  646. ShowDebug("Likely command that caused it: 0x%x\n", (*(uint16*)(s->wdata + s->wdata_size)));
  647. // no other chance, make a better fifo model
  648. exit(EXIT_FAILURE);
  649. }
  650. if( len > 0xFFFF )
  651. {
  652. // dynamic packets allow up to UINT16_MAX bytes (<packet_id>.W <packet_len>.W ...)
  653. // all known fixed-size packets are within this limit, so use the same limit
  654. ShowFatalError("WFIFOSET: Packet 0x%x is too big. (len=%u, max=%u)\n", (*(uint16*)(s->wdata + s->wdata_size)), (unsigned int)len, 0xFFFF);
  655. exit(EXIT_FAILURE);
  656. }
  657. else if( len == 0 )
  658. {
  659. // abuses the fact, that the code that did WFIFOHEAD(fd,0), already wrote
  660. // the packet type into memory, even if it could have overwritten vital data
  661. // this can happen when a new packet was added on map-server, but packet len table was not updated
  662. ShowWarning("WFIFOSET: Attempted to send zero-length packet, most likely 0x%04x (please report this).\n", WFIFOW(fd,0));
  663. return 0;
  664. }
  665. if( !s->flag.server ) {
  666. if (len > socket_max_client_packet) { // see declaration of socket_max_client_packet for details
  667. ShowError("WFIFOSET: Dropped too large client packet 0x%04x (length=%"PRIuS", max=%"PRIuS").\n",
  668. WFIFOW(fd,0), len, socket_max_client_packet);
  669. return 0;
  670. }
  671. }
  672. s->wdata_size += len;
  673. #ifdef SHOW_SERVER_STATS
  674. socket_data_qo += len;
  675. #endif
  676. //If the interserver has 200% of its normal size full, flush the data.
  677. if( s->flag.server && s->wdata_size >= 2*FIFOSIZE_SERVERLINK )
  678. sockt->flush(fd);
  679. // always keep a WFIFO_SIZE reserve in the buffer
  680. // For inter-server connections, let the reserve be 1/4th of the link size.
  681. newreserve = s->flag.server ? FIFOSIZE_SERVERLINK / 4 : WFIFO_SIZE;
  682. // readjust the buffer to include the chosen reserve
  683. sockt->realloc_writefifo(fd, newreserve);
  684. #ifdef SEND_SHORTLIST
  685. send_shortlist_add_fd(fd);
  686. #endif
  687. return 0;
  688. }
  689. int do_sockets(int next)
  690. {
  691. fd_set rfd;
  692. struct timeval timeout;
  693. int ret,i;
  694. // PRESEND Timers are executed before do_sendrecv and can send packets and/or set sessions to eof.
  695. // Send remaining data and process client-side disconnects here.
  696. #ifdef SEND_SHORTLIST
  697. send_shortlist_do_sends();
  698. #else
  699. for (i = 1; i < sockt->fd_max; i++)
  700. {
  701. if(!sockt->session[fd]
  702. continue;
  703. if(sockt->session[fd]>wdata_size)
  704. sockt->session[fd]>func_send(i);
  705. }
  706. #endif
  707. // can timeout until the next tick
  708. timeout.tv_sec = next/1000;
  709. timeout.tv_usec = next%1000*1000;
  710. memcpy(&rfd, &readfds, sizeof(rfd));
  711. ret = sSelect(sockt->fd_max, &rfd, NULL, NULL, &timeout);
  712. if( ret == SOCKET_ERROR )
  713. {
  714. if( sErrno != S_EINTR )
  715. {
  716. ShowFatalError("do_sockets: select() failed, %s!\n", error_msg());
  717. exit(EXIT_FAILURE);
  718. }
  719. return 0; // interrupted by a signal, just loop and try again
  720. }
  721. sockt->last_tick = time(NULL);
  722. #if defined(WIN32)
  723. // on windows, enumerating all members of the fd_set is way faster if we access the internals
  724. for( i = 0; i < (int)rfd.fd_count; ++i )
  725. {
  726. int fd = sock2fd(rfd.fd_array[i]);
  727. if( sockt->session[fd] )
  728. sockt->session[fd]->func_recv(fd);
  729. }
  730. #else
  731. // otherwise assume that the fd_set is a bit-array and enumerate it in a standard way
  732. for( i = 1; ret && i < sockt->fd_max; ++i )
  733. {
  734. if(sFD_ISSET(i,&rfd) && sockt->session[i])
  735. {
  736. sockt->session[i]->func_recv(i);
  737. --ret;
  738. }
  739. }
  740. #endif
  741. // POSTSEND Send remaining data and handle eof sessions.
  742. #ifdef SEND_SHORTLIST
  743. send_shortlist_do_sends();
  744. #else
  745. for (i = 1; i < sockt->fd_max; i++)
  746. {
  747. if(!sockt->session[i])
  748. continue;
  749. if(sockt->session[i]->wdata_size)
  750. sockt->session[i]->func_send(i);
  751. if (sockt->session[i]->flag.eof) { //func_send can't free a session, this is safe.
  752. //Finally, even if there is no data to parse, connections signaled eof should be closed, so we call parse_func [Skotlex]
  753. sockt->session[i]->func_parse(i); //This should close the session immediately.
  754. }
  755. }
  756. #endif
  757. // parse input data on each socket
  758. for(i = 1; i < sockt->fd_max; i++)
  759. {
  760. if(!sockt->session[i])
  761. continue;
  762. if (sockt->session[i]->rdata_tick && DIFF_TICK(sockt->last_tick, sockt->session[i]->rdata_tick) > sockt->stall_time) {
  763. if( sockt->session[i]->flag.server ) {/* server is special */
  764. if( sockt->session[i]->flag.ping != 2 )/* only update if necessary otherwise it'd resend the ping unnecessarily */
  765. sockt->session[i]->flag.ping = 1;
  766. } else {
  767. ShowInfo("Session #%d timed out\n", i);
  768. sockt->eof(i);
  769. }
  770. }
  771. #ifdef __clang_analyzer__
  772. // Let Clang's static analyzer know this never happens (it thinks it might because of a NULL check in session_is_valid)
  773. if (!sockt->session[i]) continue;
  774. #endif // __clang_analyzer__
  775. sockt->session[i]->func_parse(i);
  776. if(!sockt->session[i])
  777. continue;
  778. RFIFOFLUSH(i);
  779. // after parse, check client's RFIFO size to know if there is an invalid packet (too big and not parsed)
  780. if (sockt->session[i]->rdata_size == sockt->session[i]->max_rdata) {
  781. sockt->eof(i);
  782. continue;
  783. }
  784. }
  785. #ifdef SHOW_SERVER_STATS
  786. if (sockt->last_tick != socket_data_last_tick)
  787. {
  788. char buf[1024];
  789. sprintf(buf, "In: %.03f kB/s (%.03f kB/s, Q: %.03f kB) | Out: %.03f kB/s (%.03f kB/s, Q: %.03f kB) | RAM: %.03f MB", socket_data_i/1024., socket_data_ci/1024., socket_data_qi/1024., socket_data_o/1024., socket_data_co/1024., socket_data_qo/1024., iMalloc->usage()/1024.);
  790. #ifdef _WIN32
  791. SetConsoleTitle(buf);
  792. #else
  793. ShowMessage("\033[s\033[1;1H\033[2K%s\033[u", buf);
  794. #endif
  795. socket_data_last_tick = sockt->last_tick;
  796. socket_data_i = socket_data_ci = 0;
  797. socket_data_o = socket_data_co = 0;
  798. }
  799. #endif
  800. return 0;
  801. }
  802. //////////////////////////////
  803. #ifndef MINICORE
  804. //////////////////////////////
  805. // IP rules and DDoS protection
  806. typedef struct connect_history {
  807. uint32 ip;
  808. int64 tick;
  809. int count;
  810. unsigned ddos : 1;
  811. } ConnectHistory;
  812. typedef struct access_control {
  813. uint32 ip;
  814. uint32 mask;
  815. } AccessControl;
  816. enum aco {
  817. ACO_DENY_ALLOW,
  818. ACO_ALLOW_DENY,
  819. ACO_MUTUAL_FAILURE
  820. };
  821. static AccessControl* access_allow = NULL;
  822. static AccessControl* access_deny = NULL;
  823. static int access_order = ACO_DENY_ALLOW;
  824. static int access_allownum = 0;
  825. static int access_denynum = 0;
  826. static int access_debug = 0;
  827. static int ddos_count = 10;
  828. static int ddos_interval = 3*1000;
  829. static int ddos_autoreset = 10*60*1000;
  830. DBMap *connect_history = NULL;
  831. static int connect_check_(uint32 ip);
  832. /// Verifies if the IP can connect. (with debug info)
  833. /// @see connect_check_()
  834. static int connect_check(uint32 ip)
  835. {
  836. int result = connect_check_(ip);
  837. if( access_debug ) {
  838. ShowInfo("connect_check: Connection from %d.%d.%d.%d %s\n", CONVIP(ip),result ? "allowed." : "denied!");
  839. }
  840. return result;
  841. }
  842. /// Verifies if the IP can connect.
  843. /// 0 : Connection Rejected
  844. /// 1 or 2 : Connection Accepted
  845. static int connect_check_(uint32 ip)
  846. {
  847. ConnectHistory* hist = NULL;
  848. int i;
  849. int is_allowip = 0;
  850. int is_denyip = 0;
  851. int connect_ok = 0;
  852. // Search the allow list
  853. for( i=0; i < access_allownum; ++i ){
  854. if (SUBNET_MATCH(ip, access_allow[i].ip, access_allow[i].mask)) {
  855. if( access_debug ){
  856. ShowInfo("connect_check: Found match from allow list:%d.%d.%d.%d IP:%d.%d.%d.%d Mask:%d.%d.%d.%d\n",
  857. CONVIP(ip),
  858. CONVIP(access_allow[i].ip),
  859. CONVIP(access_allow[i].mask));
  860. }
  861. is_allowip = 1;
  862. break;
  863. }
  864. }
  865. // Search the deny list
  866. for( i=0; i < access_denynum; ++i ){
  867. if (SUBNET_MATCH(ip, access_deny[i].ip, access_deny[i].mask)) {
  868. if( access_debug ){
  869. ShowInfo("connect_check: Found match from deny list:%d.%d.%d.%d IP:%d.%d.%d.%d Mask:%d.%d.%d.%d\n",
  870. CONVIP(ip),
  871. CONVIP(access_deny[i].ip),
  872. CONVIP(access_deny[i].mask));
  873. }
  874. is_denyip = 1;
  875. break;
  876. }
  877. }
  878. // Decide connection status
  879. // 0 : Reject
  880. // 1 : Accept
  881. // 2 : Unconditional Accept (accepts even if flagged as DDoS)
  882. switch(access_order) {
  883. case ACO_DENY_ALLOW:
  884. default:
  885. if( is_denyip )
  886. connect_ok = 0; // Reject
  887. else if( is_allowip )
  888. connect_ok = 2; // Unconditional Accept
  889. else
  890. connect_ok = 1; // Accept
  891. break;
  892. case ACO_ALLOW_DENY:
  893. if( is_allowip )
  894. connect_ok = 2; // Unconditional Accept
  895. else if( is_denyip )
  896. connect_ok = 0; // Reject
  897. else
  898. connect_ok = 1; // Accept
  899. break;
  900. case ACO_MUTUAL_FAILURE:
  901. if( is_allowip && !is_denyip )
  902. connect_ok = 2; // Unconditional Accept
  903. else
  904. connect_ok = 0; // Reject
  905. break;
  906. }
  907. // Inspect connection history
  908. if( ( hist = uidb_get(connect_history, ip)) ) { //IP found
  909. if( hist->ddos ) {// flagged as DDoS
  910. return (connect_ok == 2 ? 1 : 0);
  911. } else if( DIFF_TICK(timer->gettick(),hist->tick) < ddos_interval ) {// connection within ddos_interval
  912. hist->tick = timer->gettick();
  913. if( ++hist->count >= ddos_count ) {// DDoS attack detected
  914. hist->ddos = 1;
  915. ShowWarning("connect_check: DDoS Attack detected from %d.%d.%d.%d!\n", CONVIP(ip));
  916. return (connect_ok == 2 ? 1 : 0);
  917. }
  918. return connect_ok;
  919. } else {// not within ddos_interval, clear data
  920. hist->tick = timer->gettick();
  921. hist->count = 0;
  922. return connect_ok;
  923. }
  924. }
  925. // IP not found, add to history
  926. CREATE(hist, ConnectHistory, 1);
  927. hist->ip = ip;
  928. hist->tick = timer->gettick();
  929. uidb_put(connect_history, ip, hist);
  930. return connect_ok;
  931. }
  932. /// Timer function.
  933. /// Deletes old connection history records.
  934. static int connect_check_clear(int tid, int64 tick, int id, intptr_t data) {
  935. int clear = 0;
  936. int list = 0;
  937. ConnectHistory *hist = NULL;
  938. DBIterator *iter;
  939. if( !db_size(connect_history) )
  940. return 0;
  941. iter = db_iterator(connect_history);
  942. for( hist = dbi_first(iter); dbi_exists(iter); hist = dbi_next(iter) ){
  943. if( (!hist->ddos && DIFF_TICK(tick,hist->tick) > ddos_interval*3) ||
  944. (hist->ddos && DIFF_TICK(tick,hist->tick) > ddos_autoreset) )
  945. {// Remove connection history
  946. uidb_remove(connect_history, hist->ip);
  947. clear++;
  948. }
  949. list++;
  950. }
  951. dbi_destroy(iter);
  952. if( access_debug ){
  953. ShowInfo("connect_check_clear: Cleared %d of %d from IP list.\n", clear, list);
  954. }
  955. return list;
  956. }
  957. /// Parses the ip address and mask and puts it into acc.
  958. /// Returns 1 is successful, 0 otherwise.
  959. int access_ipmask(const char* str, AccessControl* acc)
  960. {
  961. uint32 ip;
  962. uint32 mask;
  963. if( strcmp(str,"all") == 0 ) {
  964. ip = 0;
  965. mask = 0;
  966. } else {
  967. unsigned int a[4];
  968. unsigned int m[4];
  969. int n;
  970. if( ((n=sscanf(str,"%u.%u.%u.%u/%u.%u.%u.%u",a,a+1,a+2,a+3,m,m+1,m+2,m+3)) != 8 && // not an ip + standard mask
  971. (n=sscanf(str,"%u.%u.%u.%u/%u",a,a+1,a+2,a+3,m)) != 5 && // not an ip + bit mask
  972. (n=sscanf(str,"%u.%u.%u.%u",a,a+1,a+2,a+3)) != 4 ) || // not an ip
  973. a[0] > 255 || a[1] > 255 || a[2] > 255 || a[3] > 255 || // invalid ip
  974. (n == 8 && (m[0] > 255 || m[1] > 255 || m[2] > 255 || m[3] > 255)) || // invalid standard mask
  975. (n == 5 && m[0] > 32) ){ // invalid bit mask
  976. return 0;
  977. }
  978. ip = MAKEIP(a[0],a[1],a[2],a[3]);
  979. if( n == 8 )
  980. {// standard mask
  981. mask = MAKEIP(m[0],m[1],m[2],m[3]);
  982. } else if( n == 5 )
  983. {// bit mask
  984. mask = 0;
  985. while( m[0] ){
  986. mask = (mask >> 1) | 0x80000000;
  987. --m[0];
  988. }
  989. } else
  990. {// just this ip
  991. mask = 0xFFFFFFFF;
  992. }
  993. }
  994. if( access_debug ){
  995. ShowInfo("access_ipmask: Loaded IP:%d.%d.%d.%d mask:%d.%d.%d.%d\n", CONVIP(ip), CONVIP(mask));
  996. }
  997. acc->ip = ip;
  998. acc->mask = mask;
  999. return 1;
  1000. }
  1001. //////////////////////////////
  1002. #endif
  1003. //////////////////////////////
  1004. int socket_config_read(const char* cfgName)
  1005. {
  1006. char line[1024],w1[1024],w2[1024];
  1007. FILE *fp;
  1008. fp = fopen(cfgName, "r");
  1009. if(fp == NULL) {
  1010. ShowError("File not found: %s\n", cfgName);
  1011. return 1;
  1012. }
  1013. while (fgets(line, sizeof(line), fp)) {
  1014. if(line[0] == '/' && line[1] == '/')
  1015. continue;
  1016. if (sscanf(line, "%1023[^:]: %1023[^\r\n]", w1, w2) != 2)
  1017. continue;
  1018. if (!strcmpi(w1, "stall_time")) {
  1019. sockt->stall_time = atoi(w2);
  1020. if( sockt->stall_time < 3 )
  1021. sockt->stall_time = 3;/* a minimum is required to refrain it from killing itself */
  1022. }
  1023. #ifndef MINICORE
  1024. else if (!strcmpi(w1, "enable_ip_rules")) {
  1025. ip_rules = config_switch(w2);
  1026. } else if (!strcmpi(w1, "order")) {
  1027. if (!strcmpi(w2, "deny,allow"))
  1028. access_order = ACO_DENY_ALLOW;
  1029. else if (!strcmpi(w2, "allow,deny"))
  1030. access_order = ACO_ALLOW_DENY;
  1031. else if (!strcmpi(w2, "mutual-failure"))
  1032. access_order = ACO_MUTUAL_FAILURE;
  1033. } else if (!strcmpi(w1, "allow")) {
  1034. RECREATE(access_allow, AccessControl, access_allownum+1);
  1035. if (access_ipmask(w2, &access_allow[access_allownum]))
  1036. ++access_allownum;
  1037. else
  1038. ShowError("socket_config_read: Invalid ip or ip range '%s'!\n", line);
  1039. } else if (!strcmpi(w1, "deny")) {
  1040. RECREATE(access_deny, AccessControl, access_denynum+1);
  1041. if (access_ipmask(w2, &access_deny[access_denynum]))
  1042. ++access_denynum;
  1043. else
  1044. ShowError("socket_config_read: Invalid ip or ip range '%s'!\n", line);
  1045. }
  1046. else if (!strcmpi(w1,"ddos_interval"))
  1047. ddos_interval = atoi(w2);
  1048. else if (!strcmpi(w1,"ddos_count"))
  1049. ddos_count = atoi(w2);
  1050. else if (!strcmpi(w1,"ddos_autoreset"))
  1051. ddos_autoreset = atoi(w2);
  1052. else if (!strcmpi(w1,"debug"))
  1053. access_debug = config_switch(w2);
  1054. else if (!strcmpi(w1,"socket_max_client_packet"))
  1055. socket_max_client_packet = strtoul(w2, NULL, 0);
  1056. #endif
  1057. else if (!strcmpi(w1, "import"))
  1058. socket_config_read(w2);
  1059. else
  1060. ShowWarning("Unknown setting '%s' in file %s\n", w1, cfgName);
  1061. }
  1062. fclose(fp);
  1063. return 0;
  1064. }
  1065. void socket_final(void)
  1066. {
  1067. int i;
  1068. #ifndef MINICORE
  1069. if( connect_history )
  1070. db_destroy(connect_history);
  1071. if( access_allow )
  1072. aFree(access_allow);
  1073. if( access_deny )
  1074. aFree(access_deny);
  1075. #endif
  1076. for( i = 1; i < sockt->fd_max; i++ )
  1077. if(sockt->session[i])
  1078. sockt->close(i);
  1079. // sockt->session[0]
  1080. aFree(sockt->session[0]->rdata);
  1081. aFree(sockt->session[0]->wdata);
  1082. aFree(sockt->session[0]);
  1083. aFree(sockt->session);
  1084. VECTOR_CLEAR(sockt->lan_subnets);
  1085. VECTOR_CLEAR(sockt->allowed_ips);
  1086. VECTOR_CLEAR(sockt->trusted_ips);
  1087. }
  1088. /// Closes a socket.
  1089. void socket_close(int fd)
  1090. {
  1091. if( fd <= 0 ||fd >= FD_SETSIZE )
  1092. return;// invalid
  1093. sockt->flush(fd); // Try to send what's left (although it might not succeed since it's a nonblocking socket)
  1094. sFD_CLR(fd, &readfds);// this needs to be done before closing the socket
  1095. sShutdown(fd, SHUT_RDWR); // Disallow further reads/writes
  1096. sClose(fd); // We don't really care if these closing functions return an error, we are just shutting down and not reusing this socket.
  1097. if (sockt->session[fd]) delete_session(fd);
  1098. }
  1099. /// Retrieve local ips in host byte order.
  1100. /// Uses loopback is no address is found.
  1101. int socket_getips(uint32* ips, int max)
  1102. {
  1103. int num = 0;
  1104. if( ips == NULL || max <= 0 )
  1105. return 0;
  1106. #ifdef WIN32
  1107. {
  1108. char fullhost[255];
  1109. // XXX This should look up the local IP addresses in the registry
  1110. // instead of calling gethostbyname. However, the way IP addresses
  1111. // are stored in the registry is annoyingly complex, so I'll leave
  1112. // this as T.B.D. [Meruru]
  1113. if (gethostname(fullhost, sizeof(fullhost)) == SOCKET_ERROR) {
  1114. ShowError("socket_getips: No hostname defined!\n");
  1115. return 0;
  1116. } else {
  1117. u_long** a;
  1118. struct hostent *hent =gethostbyname(fullhost);
  1119. if( hent == NULL ){
  1120. ShowError("socket_getips: Cannot resolve our own hostname to an IP address\n");
  1121. return 0;
  1122. }
  1123. a = (u_long**)hent->h_addr_list;
  1124. for (; num < max && a[num] != NULL; ++num)
  1125. ips[num] = (uint32)ntohl(*a[num]);
  1126. }
  1127. }
  1128. #else // not WIN32
  1129. {
  1130. int fd;
  1131. char buf[2*16*sizeof(struct ifreq)];
  1132. struct ifconf ic;
  1133. u_long ad;
  1134. fd = sSocket(AF_INET, SOCK_STREAM, 0);
  1135. if (fd == -1) {
  1136. ShowError("socket_getips: Unable to create a socket!\n");
  1137. return 0;
  1138. }
  1139. memset(buf, 0x00, sizeof(buf));
  1140. // The ioctl call will fail with Invalid Argument if there are more
  1141. // interfaces than will fit in the buffer
  1142. ic.ifc_len = sizeof(buf);
  1143. ic.ifc_buf = buf;
  1144. if (sIoctl(fd, SIOCGIFCONF, &ic) == -1) {
  1145. ShowError("socket_getips: SIOCGIFCONF failed!\n");
  1146. sClose(fd);
  1147. return 0;
  1148. } else {
  1149. int pos;
  1150. for (pos = 0; pos < ic.ifc_len && num < max; ) {
  1151. struct ifreq *ir = (struct ifreq*)(buf+pos);
  1152. struct sockaddr_in *a = (struct sockaddr_in*) &(ir->ifr_addr);
  1153. if (a->sin_family == AF_INET) {
  1154. ad = ntohl(a->sin_addr.s_addr);
  1155. if (ad != INADDR_LOOPBACK && ad != INADDR_ANY)
  1156. ips[num++] = (uint32)ad;
  1157. }
  1158. #if (defined(BSD) && BSD >= 199103) || defined(_AIX) || defined(__APPLE__)
  1159. pos += ir->ifr_addr.sa_len + sizeof(ir->ifr_name);
  1160. #else// not AIX or APPLE
  1161. pos += sizeof(struct ifreq);
  1162. #endif//not AIX or APPLE
  1163. }
  1164. }
  1165. sClose(fd);
  1166. }
  1167. #endif // not W32
  1168. // Use loopback if no ips are found
  1169. if( num == 0 )
  1170. ips[num++] = (uint32)INADDR_LOOPBACK;
  1171. return num;
  1172. }
  1173. void socket_init(void)
  1174. {
  1175. char *SOCKET_CONF_FILENAME = "conf/packet.conf";
  1176. uint64 rlim_cur = FD_SETSIZE;
  1177. #ifdef WIN32
  1178. {// Start up windows networking
  1179. WSADATA wsaData;
  1180. WORD wVersionRequested = MAKEWORD(2, 0);
  1181. if( WSAStartup(wVersionRequested, &wsaData) != 0 )
  1182. {
  1183. ShowError("socket_init: WinSock not available!\n");
  1184. return;
  1185. }
  1186. if( LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 0 )
  1187. {
  1188. ShowError("socket_init: WinSock version mismatch (2.0 or compatible required)!\n");
  1189. return;
  1190. }
  1191. }
  1192. #elif defined(HAVE_SETRLIMIT) && !defined(CYGWIN)
  1193. // NOTE: getrlimit and setrlimit have bogus behavior in cygwin.
  1194. // "Number of fds is virtually unlimited in cygwin" (sys/param.h)
  1195. {// set socket limit to FD_SETSIZE
  1196. struct rlimit rlp;
  1197. if( 0 == getrlimit(RLIMIT_NOFILE, &rlp) )
  1198. {
  1199. rlp.rlim_cur = FD_SETSIZE;
  1200. if( 0 != setrlimit(RLIMIT_NOFILE, &rlp) )
  1201. {// failed, try setting the maximum too (permission to change system limits is required)
  1202. rlp.rlim_max = FD_SETSIZE;
  1203. if( 0 != setrlimit(RLIMIT_NOFILE, &rlp) )
  1204. {// failed
  1205. const char *errmsg = error_msg();
  1206. int rlim_ori;
  1207. // set to maximum allowed
  1208. getrlimit(RLIMIT_NOFILE, &rlp);
  1209. rlim_ori = (int)rlp.rlim_cur;
  1210. rlp.rlim_cur = rlp.rlim_max;
  1211. setrlimit(RLIMIT_NOFILE, &rlp);
  1212. // report limit
  1213. getrlimit(RLIMIT_NOFILE, &rlp);
  1214. rlim_cur = rlp.rlim_cur;
  1215. ShowWarning("socket_init: failed to set socket limit to %d, setting to maximum allowed (original limit=%d, current limit=%d, maximum allowed=%d, %s).\n", FD_SETSIZE, rlim_ori, (int)rlp.rlim_cur, (int)rlp.rlim_max, errmsg);
  1216. }
  1217. }
  1218. }
  1219. }
  1220. #endif
  1221. // Get initial local ips
  1222. sockt->naddr_ = sockt->getips(sockt->addr_,16);
  1223. sFD_ZERO(&readfds);
  1224. #if defined(SEND_SHORTLIST)
  1225. memset(send_shortlist_set, 0, sizeof(send_shortlist_set));
  1226. #endif
  1227. CREATE(sockt->session, struct socket_data *, FD_SETSIZE);
  1228. socket_config_read(SOCKET_CONF_FILENAME);
  1229. // initialize last send-receive tick
  1230. sockt->last_tick = time(NULL);
  1231. // sockt->session[0] is now currently used for disconnected sessions of the map server, and as such,
  1232. // should hold enough buffer (it is a vacuum so to speak) as it is never flushed. [Skotlex]
  1233. create_session(0, null_recv, null_send, null_parse);
  1234. #ifndef MINICORE
  1235. // Delete old connection history every 5 minutes
  1236. connect_history = uidb_alloc(DB_OPT_RELEASE_DATA);
  1237. timer->add_func_list(connect_check_clear, "connect_check_clear");
  1238. timer->add_interval(timer->gettick()+1000, connect_check_clear, 0, 0, 5*60*1000);
  1239. #endif
  1240. ShowInfo("Server supports up to '"CL_WHITE"%"PRId64""CL_RESET"' concurrent connections.\n", rlim_cur);
  1241. }
  1242. bool session_is_valid(int fd)
  1243. {
  1244. return ( fd > 0 && fd < FD_SETSIZE && sockt->session[fd] != NULL );
  1245. }
  1246. bool session_is_active(int fd)
  1247. {
  1248. return ( sockt->session_is_valid(fd) && !sockt->session[fd]->flag.eof );
  1249. }
  1250. // Resolves hostname into a numeric ip.
  1251. uint32 host2ip(const char* hostname)
  1252. {
  1253. struct hostent* h = gethostbyname(hostname);
  1254. return (h != NULL) ? ntohl(*(uint32*)h->h_addr) : 0;
  1255. }
  1256. /**
  1257. * Converts a numeric ip into a dot-formatted string.
  1258. *
  1259. * @param ip Numeric IP to convert.
  1260. * @param ip_str Output buffer, optional (if provided, must have size greater or equal to 16).
  1261. *
  1262. * @return A pointer to the output string.
  1263. */
  1264. const char *ip2str(uint32 ip, char *ip_str)
  1265. {
  1266. struct in_addr addr;
  1267. addr.s_addr = htonl(ip);
  1268. return (ip_str == NULL) ? inet_ntoa(addr) : strncpy(ip_str, inet_ntoa(addr), 16);
  1269. }
  1270. // Converts a dot-formatted ip string into a numeric ip.
  1271. uint32 str2ip(const char* ip_str)
  1272. {
  1273. return ntohl(inet_addr(ip_str));
  1274. }
  1275. // Reorders bytes from network to little endian (Windows).
  1276. // Necessary for sending port numbers to the RO client until Gravity notices that they forgot ntohs() calls.
  1277. uint16 ntows(uint16 netshort)
  1278. {
  1279. return ((netshort & 0xFF) << 8) | ((netshort & 0xFF00) >> 8);
  1280. }
  1281. /* [Ind/Hercules] - socket_datasync */
  1282. void socket_datasync(int fd, bool send) {
  1283. struct {
  1284. unsigned int length;/* short is not enough for some */
  1285. } data_list[] = {
  1286. { sizeof(struct mmo_charstatus) },
  1287. { sizeof(struct quest) },
  1288. { sizeof(struct item) },
  1289. { sizeof(struct point) },
  1290. { sizeof(struct s_skill) },
  1291. { sizeof(struct status_change_data) },
  1292. { sizeof(struct storage_data) },
  1293. { sizeof(struct guild_storage) },
  1294. { sizeof(struct s_pet) },
  1295. { sizeof(struct s_mercenary) },
  1296. { sizeof(struct s_homunculus) },
  1297. { sizeof(struct s_elemental) },
  1298. { sizeof(struct s_friend) },
  1299. { sizeof(struct mail_message) },
  1300. { sizeof(struct mail_data) },
  1301. { sizeof(struct party_member) },
  1302. { sizeof(struct party) },
  1303. { sizeof(struct guild_member) },
  1304. { sizeof(struct guild_position) },
  1305. { sizeof(struct guild_alliance) },
  1306. { sizeof(struct guild_expulsion) },
  1307. { sizeof(struct guild_skill) },
  1308. { sizeof(struct guild) },
  1309. { sizeof(struct guild_castle) },
  1310. { sizeof(struct fame_list) },
  1311. { PACKETVER },
  1312. };
  1313. unsigned short i;
  1314. unsigned int alen = ARRAYLENGTH(data_list);
  1315. if( send ) {
  1316. unsigned short p_len = ( alen * 4 ) + 4;
  1317. WFIFOHEAD(fd, p_len);
  1318. WFIFOW(fd, 0) = 0x2b0a;
  1319. WFIFOW(fd, 2) = p_len;
  1320. for( i = 0; i < alen; i++ ) {
  1321. WFIFOL(fd, 4 + ( i * 4 ) ) = data_list[i].length;
  1322. }
  1323. WFIFOSET(fd, p_len);
  1324. } else {
  1325. for( i = 0; i < alen; i++ ) {
  1326. if( RFIFOL(fd, 4 + (i * 4) ) != data_list[i].length ) {
  1327. /* force the other to go wrong too so both are taken down */
  1328. WFIFOHEAD(fd, 8);
  1329. WFIFOW(fd, 0) = 0x2b0a;
  1330. WFIFOW(fd, 2) = 8;
  1331. WFIFOL(fd, 4) = 0;
  1332. WFIFOSET(fd, 8);
  1333. sockt->flush(fd);
  1334. /* shut down */
  1335. ShowFatalError("Servers are out of sync! recompile from scratch (%d)\n",i);
  1336. exit(EXIT_FAILURE);
  1337. }
  1338. }
  1339. }
  1340. }
  1341. #ifdef SEND_SHORTLIST
  1342. // Add a fd to the shortlist so that it'll be recognized as a fd that needs
  1343. // sending or eof handling.
  1344. void send_shortlist_add_fd(int fd)
  1345. {
  1346. int i;
  1347. int bit;
  1348. if (!sockt->session_is_valid(fd))
  1349. return;// out of range
  1350. i = fd/32;
  1351. bit = fd%32;
  1352. if( (send_shortlist_set[i]>>bit)&1 )
  1353. return;// already in the list
  1354. if (send_shortlist_count >= ARRAYLENGTH(send_shortlist_array)) {
  1355. ShowDebug("send_shortlist_add_fd: shortlist is full, ignoring... (fd=%d shortlist.count=%d shortlist.length=%d)\n",
  1356. fd, send_shortlist_count, ARRAYLENGTH(send_shortlist_array));
  1357. return;
  1358. }
  1359. // set the bit
  1360. send_shortlist_set[i] |= 1<<bit;
  1361. // Add to the end of the shortlist array.
  1362. send_shortlist_array[send_shortlist_count++] = fd;
  1363. }
  1364. // Do pending network sends and eof handling from the shortlist.
  1365. void send_shortlist_do_sends(void)
  1366. {
  1367. int i;
  1368. for( i = send_shortlist_count-1; i >= 0; --i )
  1369. {
  1370. int fd = send_shortlist_array[i];
  1371. int idx = fd/32;
  1372. int bit = fd%32;
  1373. // Remove fd from shortlist, move the last fd to the current position
  1374. --send_shortlist_count;
  1375. send_shortlist_array[i] = send_shortlist_array[send_shortlist_count];
  1376. send_shortlist_array[send_shortlist_count] = 0;
  1377. if( fd <= 0 || fd >= FD_SETSIZE )
  1378. {
  1379. ShowDebug("send_shortlist_do_sends: fd is out of range, corrupted memory? (fd=%d)\n", fd);
  1380. continue;
  1381. }
  1382. if( ((send_shortlist_set[idx]>>bit)&1) == 0 )
  1383. {
  1384. ShowDebug("send_shortlist_do_sends: fd is not set, why is it in the shortlist? (fd=%d)\n", fd);
  1385. continue;
  1386. }
  1387. send_shortlist_set[idx]&=~(1<<bit);// unset fd
  1388. // If this session still exists, perform send operations on it and
  1389. // check for the eof state.
  1390. if( sockt->session[fd] )
  1391. {
  1392. // Send data
  1393. if( sockt->session[fd]->wdata_size )
  1394. sockt->session[fd]->func_send(fd);
  1395. // If it's been marked as eof, call the parse func on it so that
  1396. // the socket will be immediately closed.
  1397. if( sockt->session[fd]->flag.eof )
  1398. sockt->session[fd]->func_parse(fd);
  1399. // If the session still exists, is not eof and has things left to
  1400. // be sent from it we'll re-add it to the shortlist.
  1401. if( sockt->session[fd] && !sockt->session[fd]->flag.eof && sockt->session[fd]->wdata_size )
  1402. send_shortlist_add_fd(fd);
  1403. }
  1404. }
  1405. }
  1406. #endif
  1407. /**
  1408. * Checks whether the given IP comes from LAN or WAN.
  1409. *
  1410. * @param[in] ip IP address to check.
  1411. * @param[out] info Verbose output, if requested. Filled with the matching entry. Ignored if NULL.
  1412. * @retval 0 if it is a WAN IP.
  1413. * @return the appropriate LAN server address to send, if it is a LAN IP.
  1414. */
  1415. uint32 socket_lan_subnet_check(uint32 ip, struct s_subnet *info)
  1416. {
  1417. int i;
  1418. ARR_FIND(0, VECTOR_LENGTH(sockt->lan_subnets), i, SUBNET_MATCH(ip, VECTOR_INDEX(sockt->lan_subnets, i).ip, VECTOR_INDEX(sockt->lan_subnets, i).mask));
  1419. if (i != VECTOR_LENGTH(sockt->lan_subnets)) {
  1420. if (info) {
  1421. info->ip = VECTOR_INDEX(sockt->lan_subnets, i).ip;
  1422. info->mask = VECTOR_INDEX(sockt->lan_subnets, i).mask;
  1423. }
  1424. return VECTOR_INDEX(sockt->lan_subnets, i).ip;
  1425. }
  1426. if (info) {
  1427. info->ip = info->mask = 0;
  1428. }
  1429. return 0;
  1430. }
  1431. /**
  1432. * Checks whether the given IP is allowed to connect as a server.
  1433. *
  1434. * @param ip IP address to check.
  1435. * @retval true if we allow server connections from the given IP.
  1436. * @retval false otherwise.
  1437. */
  1438. bool socket_allowed_ip_check(uint32 ip)
  1439. {
  1440. int i;
  1441. ARR_FIND(0, VECTOR_LENGTH(sockt->allowed_ips), i, SUBNET_MATCH(ip, VECTOR_INDEX(sockt->allowed_ips, i).ip, VECTOR_INDEX(sockt->allowed_ips, i).mask));
  1442. if (i != VECTOR_LENGTH(sockt->allowed_ips))
  1443. return true;
  1444. return sockt->trusted_ip_check(ip); // If an address is trusted, it's automatically also allowed.
  1445. }
  1446. /**
  1447. * Checks whether the given IP is trusted and can skip ipban checks.
  1448. *
  1449. * @param ip IP address to check.
  1450. * @retval true if we trust the given IP.
  1451. * @retval false otherwise.
  1452. */
  1453. bool socket_trusted_ip_check(uint32 ip)
  1454. {
  1455. int i;
  1456. ARR_FIND(0, VECTOR_LENGTH(sockt->trusted_ips), i, SUBNET_MATCH(ip, VECTOR_INDEX(sockt->trusted_ips, i).ip, VECTOR_INDEX(sockt->trusted_ips, i).mask));
  1457. if (i != VECTOR_LENGTH(sockt->trusted_ips))
  1458. return true;
  1459. return false;
  1460. }
  1461. /**
  1462. * Helper function to read a list of network.conf values.
  1463. *
  1464. * Entries will be appended to the variable-size array pointed to by list/count.
  1465. *
  1466. * @param[in] t The list to parse.
  1467. * @param[in,out] list Vector to append to. Must not be NULL (but the vector may be empty).
  1468. * @param[in] filename Current filename, for output/logging reasons.
  1469. * @param[in] groupname Current group name, for output/logging reasons.
  1470. * @return The amount of entries read, zero in case of errors.
  1471. */
  1472. int socket_net_config_read_sub(config_setting_t *t, struct s_subnet_vector *list, const char *filename, const char *groupname)
  1473. {
  1474. int i, len;
  1475. char ipbuf[64], maskbuf[64];
  1476. nullpo_retr(0, list);
  1477. if (t == NULL)
  1478. return 0;
  1479. len = libconfig->setting_length(t);
  1480. VECTOR_ENS

Large files files are truncated, but you can click here to view the full file