socket.cpp 47 KB

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