socket.c 39 KB

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