socket.c 36 KB

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