socket.cpp 43 KB

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