socket.c 31 KB

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