socket.c 31 KB

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