socket.c 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  1. // Copyright (c) Athena Dev Teams - Licensed under GNU GPL
  2. // For more information, see LICENCE in the main folder
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <sys/types.h>
  6. #ifdef __WIN32
  7. #define __USE_W32_SOCKETS
  8. #include <windows.h>
  9. #include <winsock.h>
  10. #include <io.h>
  11. #else
  12. #include <errno.h>
  13. #include <sys/socket.h>
  14. #include <netinet/in.h>
  15. #include <netinet/tcp.h>
  16. #include <net/if.h>
  17. #include <unistd.h>
  18. #include <sys/time.h>
  19. #include <sys/ioctl.h>
  20. #include <netdb.h>
  21. #include <arpa/inet.h>
  22. #ifndef SIOCGIFCONF
  23. #include <sys/sockio.h> // SIOCGIFCONF on Solaris, maybe others? [Shinomori]
  24. #endif
  25. #endif
  26. // portability layer
  27. #ifdef _WIN32
  28. typedef int socklen_t;
  29. #define EBADF WSAENOTSOCK
  30. #define ECONNABORTED WSAECONNABORTED
  31. #define EAGAIN WSAEWOULDBLOCK
  32. #else
  33. #define SOCKET_ERROR -1
  34. #define INVALID_SOCKET -1
  35. #define ioctlsocket ioctl
  36. #define closesocket close
  37. #endif
  38. #include <fcntl.h>
  39. #include <string.h>
  40. #include "../common/socket.h"
  41. #include "../common/mmo.h"
  42. #include "../common/timer.h"
  43. #include "../common/malloc.h"
  44. #include "../common/showmsg.h"
  45. fd_set readfds;
  46. int fd_max;
  47. time_t last_tick;
  48. time_t stall_time = 60;
  49. int ip_rules = 1;
  50. // reuse port
  51. #ifndef SO_REUSEPORT
  52. #define SO_REUSEPORT 15
  53. #endif
  54. #ifndef TCP_FRAME_LEN
  55. #define TCP_FRAME_LEN 1024
  56. #endif
  57. static int mode_neg=1;
  58. static size_t frame_size=TCP_FRAME_LEN;
  59. #ifndef MINICORE
  60. enum {
  61. ACO_DENY_ALLOW=0,
  62. ACO_ALLOW_DENY,
  63. ACO_MUTUAL_FAILTURE,
  64. };
  65. static struct _access_control *access_allow;
  66. static struct _access_control *access_deny;
  67. static int access_order=ACO_DENY_ALLOW;
  68. static int access_allownum=0;
  69. static int access_denynum=0;
  70. static int access_debug=0;
  71. static int ddos_count = 10;
  72. static int ddos_interval = 3000;
  73. static int ddos_autoreset = 600*1000;
  74. #endif
  75. // values derived from freya
  76. // a player that send more than 2k is probably a hacker without be parsed
  77. // biggest known packet: S 0153 <len>.w <emblem data>.?B -> 24x24 256 color .bmp (0153 + len.w + 1618/1654/1756 bytes)
  78. size_t rfifo_size = (16*1024);
  79. size_t wfifo_size = (16*1024);
  80. #define CONVIP(ip) ip&0xFF,(ip>>8)&0xFF,(ip>>16)&0xFF,ip>>24
  81. struct socket_data *session[FD_SETSIZE];
  82. static int null_parse(int fd);
  83. static int (*default_func_parse)(int) = null_parse;
  84. static int null_console_parse(char *buf);
  85. static int (*default_console_parse)(char*) = null_console_parse;
  86. #ifndef MINICORE
  87. static int connect_check(unsigned int ip);
  88. #else
  89. #define connect_check(n) 1
  90. #endif
  91. /*======================================
  92. * CORE : Set function
  93. *--------------------------------------
  94. */
  95. void set_defaultparse(int (*defaultparse)(int))
  96. {
  97. default_func_parse = defaultparse;
  98. }
  99. void set_nonblocking(int fd, int yes)
  100. {
  101. // I don't think we need this
  102. // TCP_NODELAY BOOL Disables the Nagle algorithm for send coalescing.
  103. if(mode_neg)
  104. setsockopt(fd,IPPROTO_TCP,TCP_NODELAY,(char *)&yes,sizeof yes);
  105. // FIONBIO Use with a nonzero argp parameter to enable the nonblocking mode of socket s.
  106. // The argp parameter is zero if nonblocking is to be disabled.
  107. if (ioctlsocket(fd, FIONBIO, &yes) != 0)
  108. ShowError("Couldn't set the socket to non-blocking mode (code %d)!\n", h_errno);
  109. }
  110. static void setsocketopts(int fd)
  111. {
  112. int yes = 1; // reuse fix
  113. #ifndef WIN32
  114. // set SO_REAUSEADDR to true, unix only. on windows this option causes
  115. // the previous owner of the socket to give up, which is not desirable
  116. // in most cases, neither compatible with unix.
  117. setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,(char *)&yes,sizeof(yes));
  118. #ifdef SO_REUSEPORT
  119. setsockopt(fd,SOL_SOCKET,SO_REUSEPORT,(char *)&yes,sizeof(yes));
  120. #endif
  121. #endif
  122. setsockopt(fd,IPPROTO_TCP,TCP_NODELAY,(char *)&yes,sizeof(yes));
  123. // setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char *) &wfifo_size , sizeof(rfifo_size ));
  124. // setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char *) &rfifo_size , sizeof(rfifo_size ));
  125. #ifdef __WIN32
  126. { //set SO_LINGER option (from Freya)
  127. //(http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winsock/winsock/closesocket_2.asp)
  128. struct linger opt;
  129. opt.l_onoff = 1;
  130. opt.l_linger = 0;
  131. if (setsockopt(fd, SOL_SOCKET, SO_LINGER, (char*)&opt, sizeof(opt)))
  132. ShowWarning("setsocketopts: Unable to set SO_LINGER mode for connection %d!\n",fd);
  133. }
  134. #endif
  135. }
  136. /*======================================
  137. * CORE : Socket Sub Function
  138. *--------------------------------------
  139. */
  140. static void set_eof(int fd)
  141. { //Marks a connection eof and invokes the parse_function to disconnect it right away. [Skotlex]
  142. if (session_isActive(fd))
  143. session[fd]->eof=1;
  144. }
  145. static int recv_to_fifo(int fd)
  146. {
  147. int len;
  148. if( (fd < 0) || (fd >= FD_SETSIZE) || (NULL == session[fd]) || (session[fd]->eof) )
  149. return -1;
  150. len = recv(fd, (char *) session[fd]->rdata + session[fd]->rdata_size, RFIFOSPACE(fd), 0);
  151. if (len == SOCKET_ERROR) {
  152. if (h_errno == ECONNABORTED) {
  153. ShowWarning("recv_to_fifo: Software caused connection abort on session #%d\n", fd);
  154. FD_CLR(fd, &readfds); //Remove the socket so the select() won't hang on it.
  155. }
  156. if (h_errno != EAGAIN) {
  157. ShowDebug("recv_to_fifo: error %d, ending connection #%d\n", h_errno, fd);
  158. set_eof(fd);
  159. }
  160. return 0;
  161. }
  162. if (len <= 0) { //Normal connection end.
  163. set_eof(fd);
  164. return 0;
  165. }
  166. session[fd]->rdata_size += len;
  167. session[fd]->rdata_tick = last_tick;
  168. return 0;
  169. }
  170. static int send_from_fifo(int fd)
  171. {
  172. int len;
  173. if( !session_isValid(fd) )
  174. return -1;
  175. if (session[fd]->wdata_size == 0)
  176. return 0;
  177. len = send(fd, (const char *) session[fd]->wdata, session[fd]->wdata_size, 0);
  178. if (len == SOCKET_ERROR) {
  179. if (h_errno == ECONNABORTED) {
  180. ShowWarning("send_from_fifo: Software caused connection abort on session #%d\n", fd);
  181. session[fd]->wdata_size = 0; //Clear the send queue as we can't send anymore. [Skotlex]
  182. set_eof(fd);
  183. FD_CLR(fd, &readfds); //Remove the socket so the select() won't hang on it.
  184. }
  185. if (h_errno != EAGAIN) {
  186. ShowDebug("send_from_fifo: error %d, ending connection #%d\n", h_errno, fd);
  187. session[fd]->wdata_size = 0; //Clear the send queue as we can't send anymore. [Skotlex]
  188. set_eof(fd);
  189. }
  190. return 0;
  191. }
  192. //{ int i; ShowMessage("send %d : ",fd); for(i=0;i<len;i++){ ShowMessage("%02x ",session[fd]->wdata[i]); } ShowMessage("\n");}
  193. if(len > 0) {
  194. if((size_t)len < session[fd]->wdata_size)
  195. memmove(session[fd]->wdata, session[fd]->wdata + len, session[fd]->wdata_size - len);
  196. session[fd]->wdata_size -= len;
  197. }
  198. return 0;
  199. }
  200. /// Best effort
  201. /// There's no warranty that the data will be sent.
  202. void flush_fifo(int fd)
  203. {
  204. if(session[fd] != NULL && session[fd]->func_send == send_from_fifo)
  205. send_from_fifo(fd);
  206. }
  207. void flush_fifos(void)
  208. {
  209. int i;
  210. for(i=1;i<fd_max;i++)
  211. if(session[i] != NULL &&
  212. session[i]->func_send == send_from_fifo)
  213. send_from_fifo(i);
  214. }
  215. static int null_parse(int fd)
  216. {
  217. ShowMessage("null_parse : %d\n",fd);
  218. session[fd]->rdata_pos = session[fd]->rdata_size; //RFIFOSKIP(fd, RFIFOREST(fd)); simplify calculation
  219. return 0;
  220. }
  221. /*======================================
  222. * CORE : Socket Function
  223. *--------------------------------------
  224. */
  225. static int connect_client(int listen_fd)
  226. {
  227. int fd;
  228. struct sockaddr_in client_address;
  229. socklen_t len;
  230. //ShowMessage("connect_client : %d\n",listen_fd);
  231. len=sizeof(client_address);
  232. fd = accept(listen_fd,(struct sockaddr*)&client_address,&len);
  233. if ( fd == INVALID_SOCKET ) {
  234. ShowError("accept failed (code %i)!\n", h_errno);
  235. return -1;
  236. }
  237. if(fd_max<=fd) fd_max=fd+1;
  238. setsocketopts(fd);
  239. set_nonblocking(fd, 1);
  240. if (ip_rules && !connect_check(*(unsigned int*)(&client_address.sin_addr))) {
  241. do_close(fd);
  242. return -1;
  243. } else
  244. FD_SET(fd,&readfds);
  245. CREATE(session[fd], struct socket_data, 1);
  246. CREATE(session[fd]->rdata, unsigned char, rfifo_size);
  247. CREATE(session[fd]->wdata, unsigned char, wfifo_size);
  248. session[fd]->max_rdata = rfifo_size;
  249. session[fd]->max_wdata = wfifo_size;
  250. session[fd]->func_recv = recv_to_fifo;
  251. session[fd]->func_send = send_from_fifo;
  252. session[fd]->func_parse = (session[listen_fd]->func_parse) ? session[listen_fd]->func_parse : default_func_parse;
  253. session[fd]->client_addr = client_address;
  254. session[fd]->rdata_tick = last_tick;
  255. session[fd]->type = SESSION_UNKNOWN; // undefined type
  256. //ShowMessage("new_session : %d %d\n",fd,session[fd]->eof);
  257. return fd;
  258. }
  259. int make_listen_bind(long ip,int port)
  260. {
  261. struct sockaddr_in server_address;
  262. int fd;
  263. int result;
  264. fd = (int)socket( AF_INET, SOCK_STREAM, 0 );
  265. if (fd == INVALID_SOCKET) {
  266. ShowError("socket() creation failed (code %d)!\n", fd, h_errno);
  267. exit(1);
  268. }
  269. setsocketopts(fd);
  270. set_nonblocking(fd, 1);
  271. server_address.sin_family = AF_INET;
  272. server_address.sin_addr.s_addr = ip;
  273. server_address.sin_port = htons((unsigned short)port);
  274. result = bind(fd, (struct sockaddr*)&server_address, sizeof(server_address));
  275. if( result == SOCKET_ERROR ) {
  276. ShowError("bind failed (socket %d, code %d)!\n", fd, h_errno);
  277. exit(1);
  278. }
  279. result = listen( fd, 5 );
  280. if( result == SOCKET_ERROR ) {
  281. ShowError("listen failed (socket %d, code %d)!\n", fd, h_errno);
  282. exit(1);
  283. }
  284. if ( fd < 0 || fd > FD_SETSIZE )
  285. { //Crazy error that can happen in Windows? (info from Freya)
  286. ShowFatalError("listen() returned invalid fd %d!\n",fd);
  287. exit(1);
  288. }
  289. if(fd_max<=fd) fd_max=fd+1;
  290. FD_SET(fd, &readfds );
  291. CREATE(session[fd], struct socket_data, 1);
  292. session[fd]->func_recv = connect_client;
  293. return fd;
  294. }
  295. int make_listen_port(int port)
  296. {
  297. return make_listen_bind(INADDR_ANY,port);
  298. }
  299. // Console Reciever [Wizputer]
  300. int console_recieve(int i)
  301. {
  302. int n;
  303. char *buf;
  304. CREATE(buf, char, 64);
  305. n = read(0, buf , 64);
  306. if ( n < 0 )
  307. ShowError("Console input read error\n");
  308. else
  309. {
  310. ShowNotice ("Sorry, the console is currently non-functional.\n");
  311. // session[0]->func_console(buf);
  312. }
  313. aFree(buf);
  314. return 0;
  315. }
  316. void set_defaultconsoleparse(int (*defaultparse)(char*))
  317. {
  318. default_console_parse = defaultparse;
  319. }
  320. static int null_console_parse(char *buf)
  321. {
  322. ShowMessage("null_console_parse : %s\n",buf);
  323. return 0;
  324. }
  325. // function parse table
  326. // To-do: -- use dynamic arrays
  327. // -- add a register_parse_func();
  328. struct func_parse_table func_parse_table[SESSION_MAX];
  329. int default_func_check (struct socket_data *sd) { return 1; }
  330. void func_parse_check (struct socket_data *sd)
  331. {
  332. int i;
  333. for (i = SESSION_HTTP; i < SESSION_MAX; i++) {
  334. if (func_parse_table[i].func &&
  335. func_parse_table[i].check &&
  336. func_parse_table[i].check(sd) != 0)
  337. {
  338. sd->type = i;
  339. sd->func_parse = func_parse_table[i].func;
  340. return;
  341. }
  342. }
  343. // undefined -- treat as raw socket (using default parse)
  344. sd->type = SESSION_RAW;
  345. }
  346. // Console Input [Wizputer]
  347. int start_console(void) {
  348. //Until a better plan is came up with... can't be using session[0] anymore! [Skotlex]
  349. ShowNotice("The console is currently nonfunctional.\n");
  350. return 0;
  351. FD_SET(0,&readfds);
  352. if (!session[0]) { // dummy socket already uses fd 0
  353. CREATE(session[0], struct socket_data, 1);
  354. }
  355. malloc_set(session[0],0,sizeof(*session[0]));
  356. session[0]->func_recv = console_recieve;
  357. session[0]->func_console = default_console_parse;
  358. return 0;
  359. }
  360. int make_connection(long ip,int port)
  361. {
  362. struct sockaddr_in server_address;
  363. int fd;
  364. int result;
  365. fd = (int)socket( AF_INET, SOCK_STREAM, 0 );
  366. if (fd == INVALID_SOCKET) {
  367. ShowError("socket() creation failed (code %d)!\n", fd, h_errno);
  368. return -1;
  369. }
  370. setsocketopts(fd);
  371. server_address.sin_family = AF_INET;
  372. server_address.sin_addr.s_addr = ip;
  373. server_address.sin_port = htons((unsigned short)port);
  374. ShowStatus("Connecting to %d.%d.%d.%d:%i\n",
  375. (ip)&0xFF,(ip>>8)&0xFF,(ip>>16)&0xFF,(ip>>24)&0xFF,port);
  376. result = connect(fd, (struct sockaddr *)(&server_address), sizeof(struct sockaddr_in));
  377. if( result == SOCKET_ERROR ) {
  378. ShowError("connect failed (socket %d, code %d)!\n", fd, h_errno);
  379. do_close(fd);
  380. return -1;
  381. }
  382. //Now the socket can be made non-blocking. [Skotlex]
  383. set_nonblocking(fd, 1);
  384. if (fd_max <= fd)
  385. fd_max = fd + 1;
  386. FD_SET(fd,&readfds);
  387. CREATE(session[fd], struct socket_data, 1);
  388. CREATE(session[fd]->rdata, unsigned char, rfifo_size);
  389. CREATE(session[fd]->wdata, unsigned char, wfifo_size);
  390. session[fd]->max_rdata = rfifo_size;
  391. session[fd]->max_wdata = wfifo_size;
  392. session[fd]->func_recv = recv_to_fifo;
  393. session[fd]->func_send = send_from_fifo;
  394. session[fd]->func_parse = default_func_parse;
  395. session[fd]->rdata_tick = last_tick;
  396. return fd;
  397. }
  398. void free_session_mem(int fd)
  399. {
  400. if (session[fd]){
  401. if (session[fd]->rdata)
  402. aFree(session[fd]->rdata);
  403. if (session[fd]->wdata)
  404. aFree(session[fd]->wdata);
  405. if (session[fd]->session_data)
  406. aFree(session[fd]->session_data);
  407. aFree(session[fd]);
  408. session[fd] = NULL;
  409. }
  410. }
  411. int delete_session(int fd)
  412. {
  413. if (fd <= 0 || fd >= FD_SETSIZE)
  414. return -1;
  415. FD_CLR(fd, &readfds);
  416. free_session_mem(fd);
  417. //ShowMessage("delete_session:%d\n",fd);
  418. return 0;
  419. }
  420. int realloc_fifo(int fd,unsigned int rfifo_size,unsigned int wfifo_size)
  421. {
  422. if( !session_isValid(fd) )
  423. return 0;
  424. if( session[fd]->max_rdata != rfifo_size && session[fd]->rdata_size < rfifo_size){
  425. RECREATE(session[fd]->rdata, unsigned char, rfifo_size);
  426. session[fd]->max_rdata = rfifo_size;
  427. }
  428. if( session[fd]->max_wdata != wfifo_size && session[fd]->wdata_size < wfifo_size){
  429. RECREATE(session[fd]->wdata, unsigned char, wfifo_size);
  430. session[fd]->max_wdata = wfifo_size;
  431. }
  432. return 0;
  433. }
  434. int realloc_writefifo(int fd, size_t addition)
  435. {
  436. size_t newsize;
  437. if( !session_isValid(fd) ) // might not happen
  438. return 0;
  439. if( session[fd]->wdata_size + addition > session[fd]->max_wdata )
  440. { // grow rule; grow in multiples of wfifo_size
  441. newsize = wfifo_size;
  442. while( session[fd]->wdata_size + addition > newsize ) newsize += newsize;
  443. }
  444. else if( session[fd]->max_wdata>=FIFOSIZE_SERVERLINK) {
  445. //Inter-server adjust. [Skotlex]
  446. if ((session[fd]->wdata_size+addition)*4 < session[fd]->max_wdata)
  447. newsize = session[fd]->max_wdata/2;
  448. else
  449. return 0; //No change
  450. } else if( session[fd]->max_wdata>wfifo_size &&
  451. (session[fd]->wdata_size+addition)*4 < session[fd]->max_wdata )
  452. { // shrink rule, shrink by 2 when only a quater of the fifo is used, don't shrink below 4*addition
  453. newsize = session[fd]->max_wdata/2;
  454. }
  455. else // no change
  456. return 0;
  457. RECREATE(session[fd]->wdata, unsigned char, newsize);
  458. session[fd]->max_wdata = newsize;
  459. return 0;
  460. }
  461. int WFIFOSET(int fd,int len)
  462. {
  463. size_t newreserve;
  464. struct socket_data *s = session[fd];
  465. if( !session_isValid(fd) || s->wdata == NULL )
  466. return 0;
  467. // we have written len bytes to the buffer already before calling WFIFOSET
  468. if(s->wdata_size+len > s->max_wdata)
  469. { // actually there was a buffer overflow already
  470. unsigned char *sin_addr = (unsigned char *)&s->client_addr.sin_addr;
  471. ShowFatalError("socket: Buffer Overflow. Connection %d (%d.%d.%d.%d) has written %d byteson a %d/%d bytes buffer.\n", fd,
  472. sin_addr[0], sin_addr[1], sin_addr[2], sin_addr[3], len, s->wdata_size, s->max_wdata);
  473. ShowDebug("Likely command that caused it: 0x%x\n",
  474. (*(unsigned short*)(s->wdata+s->wdata_size)));
  475. // no other chance, make a better fifo model
  476. exit(1);
  477. }
  478. s->wdata_size += len;
  479. // always keep a wfifo_size reserve in the buffer
  480. // For inter-server connections, let the reserve be 1/4th of the link size.
  481. newreserve = s->wdata_size + (s->max_wdata>=FIFOSIZE_SERVERLINK?FIFOSIZE_SERVERLINK/4:wfifo_size);
  482. if(s->wdata_size >= frame_size)
  483. send_from_fifo(fd);
  484. // realloc after sending
  485. // readfifo does not need to be realloced at all
  486. // Even the inter-server buffer may need reallocating! [Skotlex]
  487. realloc_writefifo(fd, newreserve);
  488. return 0;
  489. }
  490. int do_sendrecv(int next)
  491. {
  492. fd_set rfd,efd; //Added the Error Set so that such sockets can be made eof. They are the same as the rfd for now. [Skotlex]
  493. struct sockaddr_in addr_check;
  494. struct timeval timeout;
  495. int ret,i,size;
  496. last_tick = time(0);
  497. //PRESEND Need to do this to ensure that the clients get something to do
  498. //which hopefully will cause them to send packets. [Meruru]
  499. for (i = 1; i < fd_max; i++)
  500. {
  501. if(!session[i])
  502. continue;
  503. if(session[i]->wdata_size && session[i]->func_send)
  504. session[i]->func_send(i);
  505. }
  506. timeout.tv_sec = next/1000;
  507. timeout.tv_usec = next%1000*1000;
  508. for(memcpy(&rfd, &readfds, sizeof(rfd)),
  509. memcpy(&efd, &readfds, sizeof(efd));
  510. (ret = select(fd_max, &rfd, NULL, &efd, &timeout))<0;
  511. memcpy(&rfd, &readfds, sizeof(rfd)),
  512. memcpy(&efd, &readfds, sizeof(efd)))
  513. {
  514. if(h_errno != EBADF)
  515. return 0;
  516. //Well then the error is due to a bad socket. Lets find and remove it
  517. //and try again
  518. for(i = 1; i < fd_max; i++)
  519. {
  520. if(!session[i])
  521. continue;
  522. //check the validity of the socket. Does what the last thing did
  523. //just alot faster [Meruru]
  524. size = sizeof(struct sockaddr);
  525. if(getsockname(i,(struct sockaddr*)&addr_check,&size)<0)
  526. if(h_errno == EBADF) //See the #defines at the top
  527. {
  528. free_session_mem(i); //free the bad session
  529. continue;
  530. }
  531. FD_SET(i,&readfds);
  532. ret = i;
  533. }
  534. fd_max = ret;
  535. }
  536. //ok under windows to use FD_ISSET is FUCKING stupid
  537. //because windows uses an array so lets do them part by part [Meruru]
  538. #ifdef _WIN32
  539. //Do the socket sets. Unlike linux which uses a bit mask windows uses
  540. //a array. So calls to FS_ISSET are SLOW AS SHIT. So we have to do
  541. //a special case for them which actually turns out ok [Meruru]
  542. for(i=0;i<(int)rfd.fd_count;i++)
  543. {
  544. if(session[rfd.fd_array[i]] &&
  545. session[rfd.fd_array[i]]->func_recv)
  546. session[rfd.fd_array[i]]->func_recv(rfd.fd_array[i]);
  547. }
  548. for(i=0;i<(int)efd.fd_count;i++)
  549. set_eof(efd.fd_array[i]);
  550. for (i = 1; i < fd_max; i++)
  551. {
  552. if(!session[i])
  553. continue;
  554. //POSTSEND: Does write EVER BLOCK? NO!! not unless WE ARE CURRENTLY SENDING SOMETHING
  555. //Or just have opened a connection and dont know if its ready
  556. //And since eA isn't multi threaded and all the sockets are non blocking THIS ISNT A PROBLEM! [Meruru]
  557. if(session[i]->wdata_size && session[i]->func_send)
  558. session[i]->func_send(i);
  559. if(session[i] && session[i]->eof) //The session check is for when the connection ended in func_parse
  560. { //Finally, even if there is no data to parse, connections signalled eof should be closed, so we call parse_func [Skotlex]
  561. if (session[i]->func_parse)
  562. session[i]->func_parse(i); //This should close the session inmediately.
  563. }
  564. }
  565. #else //where under linux its just a bit check so its smart [Meruru]
  566. for (i = 1; i < fd_max; i++){
  567. if(!session[i])
  568. continue;
  569. if(FD_ISSET(i,&efd)){
  570. //ShowMessage("error:%d\n",i);
  571. ShowDebug("do_sendrecv: Connection error on Session %d.\n", i);
  572. set_eof(i);
  573. continue;
  574. }
  575. if(FD_ISSET(i,&rfd)){
  576. //ShowMessage("read:%d\n",i);
  577. if(session[i]->func_recv)
  578. session[i]->func_recv(i);
  579. }
  580. //Does write EVER BLOCK. NO not unless WE ARE CURRENTALLY SENDING SOMETHING
  581. //And sence eA isnt multi threaded THIS ISNT A PROBLEM!
  582. if(session[i]->wdata_size && session[i]->func_send)
  583. session[i]->func_send(i);
  584. if(session[i] && session[i]->eof) //The session check is for when the connection ended in func_parse
  585. { //Finally, even if there is no data to parse, connections signalled eof should be closed, so we call parse_func [Skotlex]
  586. if (session[i]->func_parse)
  587. session[i]->func_parse(i); //This should close the session inmediately.
  588. }
  589. }
  590. #endif
  591. return 0;
  592. }
  593. int do_parsepacket(void)
  594. {
  595. int i;
  596. struct socket_data *sd;
  597. for(i = 1; i < fd_max; i++){
  598. sd = session[i];
  599. if(!sd)
  600. continue;
  601. if (sd->rdata_tick && DIFF_TICK(last_tick,sd->rdata_tick) > stall_time) {
  602. ShowInfo ("Session #%d timed out\n", i);
  603. sd->eof = 1;
  604. }
  605. if(sd->rdata_size == 0 && sd->eof == 0)
  606. continue;
  607. if(sd->func_parse){
  608. if(sd->type == SESSION_UNKNOWN)
  609. func_parse_check(sd);
  610. if(sd->type != SESSION_UNKNOWN)
  611. sd->func_parse(i);
  612. if(!session[i])
  613. continue;
  614. /* after parse, check client's RFIFO size to know if there is an invalid packet (too big and not parsed) */
  615. if (session[i]->rdata_size == rfifo_size && session[i]->max_rdata == rfifo_size) {
  616. session[i]->eof = 1;
  617. continue;
  618. }
  619. }
  620. RFIFOFLUSH(i);
  621. }
  622. return 0;
  623. }
  624. /* DDoS 攻撃対策 */
  625. #ifndef MINICORE
  626. struct _access_control {
  627. unsigned int ip;
  628. unsigned int mask;
  629. };
  630. struct _connect_history {
  631. struct _connect_history *next;
  632. struct _connect_history *prev;
  633. int status;
  634. int count;
  635. unsigned int ip;
  636. unsigned int tick;
  637. };
  638. static struct _connect_history *connect_history[0x10000];
  639. static int connect_check_(unsigned int ip);
  640. // 接続できるかどうかの確認
  641. // false : 接続OK
  642. // true : 接続NG
  643. static int connect_check(unsigned int ip) {
  644. int result = connect_check_(ip);
  645. if(access_debug) {
  646. ShowMessage("connect_check: Connection from %d.%d.%d.%d %s\n",
  647. CONVIP(ip),result ? "allowed." : "denied!");
  648. }
  649. return result;
  650. }
  651. static int connect_check_(unsigned int ip) {
  652. struct _connect_history *hist = connect_history[ip & 0xFFFF];
  653. struct _connect_history *hist_new;
  654. int i,is_allowip = 0,is_denyip = 0,connect_ok = 0;
  655. // allow , deny リストに入っているか確認
  656. for(i = 0;i < access_allownum; i++) {
  657. if((ip & access_allow[i].mask) == (access_allow[i].ip & access_allow[i].mask)) {
  658. if(access_debug) {
  659. ShowMessage("connect_check: Found match from allow list:%d.%d.%d.%d IP:%d.%d.%d.%d Mask:%d.%d.%d.%d\n",
  660. CONVIP(ip),
  661. CONVIP(access_allow[i].ip),
  662. CONVIP(access_allow[i].mask));
  663. }
  664. is_allowip = 1;
  665. break;
  666. }
  667. }
  668. for(i = 0;i < access_denynum; i++) {
  669. if((ip & access_deny[i].mask) == (access_deny[i].ip & access_deny[i].mask)) {
  670. if(access_debug) {
  671. ShowMessage("connect_check: Found match from deny list:%d.%d.%d.%d IP:%d.%d.%d.%d Mask:%d.%d.%d.%d\n",
  672. CONVIP(ip),
  673. CONVIP(access_deny[i].ip),
  674. CONVIP(access_deny[i].mask));
  675. }
  676. is_denyip = 1;
  677. break;
  678. }
  679. }
  680. // コネクト出来るかどうか確認
  681. // connect_ok
  682. // 0 : 無条件に拒否
  683. // 1 : 田代砲チェックの結果次第
  684. // 2 : 無条件に許可
  685. switch(access_order) {
  686. case ACO_DENY_ALLOW:
  687. default:
  688. if(is_allowip) {
  689. connect_ok = 2;
  690. } else if(is_denyip) {
  691. connect_ok = 0;
  692. } else {
  693. connect_ok = 1;
  694. }
  695. break;
  696. case ACO_ALLOW_DENY:
  697. if(is_denyip) {
  698. connect_ok = 0;
  699. } else if(is_allowip) {
  700. connect_ok = 2;
  701. } else {
  702. connect_ok = 1;
  703. }
  704. break;
  705. case ACO_MUTUAL_FAILTURE:
  706. if(is_allowip) {
  707. connect_ok = 2;
  708. } else {
  709. connect_ok = 0;
  710. }
  711. break;
  712. }
  713. // 接続履歴を調べる
  714. while(hist) {
  715. if(ip == hist->ip) {
  716. // 同じIP発見
  717. if(hist->status) {
  718. // ban フラグが立ってる
  719. return (connect_ok == 2 ? 1 : 0);
  720. } else if(DIFF_TICK(gettick(),hist->tick) < ddos_interval) {
  721. // ddos_interval秒以内にリクエスト有り
  722. hist->tick = gettick();
  723. if(hist->count++ >= ddos_count) {
  724. // ddos 攻撃を検出
  725. hist->status = 1;
  726. ShowWarning("connect_check: DDOS Attack detected from %d.%d.%d.%d!\n",
  727. CONVIP(ip));
  728. return (connect_ok == 2 ? 1 : 0);
  729. } else {
  730. return connect_ok;
  731. }
  732. } else {
  733. // ddos_interval秒以内にリクエスト無いのでタイマークリア
  734. hist->tick = gettick();
  735. hist->count = 0;
  736. return connect_ok;
  737. }
  738. }
  739. hist = hist->next;
  740. }
  741. // IPリストに無いので新規作成
  742. hist_new = (struct _connect_history *) aCalloc(1,sizeof(struct _connect_history));
  743. hist_new->ip = ip;
  744. hist_new->tick = gettick();
  745. if(connect_history[ip & 0xFFFF] != NULL) {
  746. hist = connect_history[ip & 0xFFFF];
  747. hist->prev = hist_new;
  748. hist_new->next = hist;
  749. }
  750. connect_history[ip & 0xFFFF] = hist_new;
  751. return connect_ok;
  752. }
  753. static int connect_check_clear(int tid,unsigned int tick,int id,int data) {
  754. int i;
  755. int clear = 0;
  756. int list = 0;
  757. struct _connect_history *hist , *hist2;
  758. for(i = 0;i < 0x10000 ; i++) {
  759. hist = connect_history[i];
  760. while(hist) {
  761. if ((DIFF_TICK(tick,hist->tick) > ddos_interval * 3 && !hist->status) ||
  762. (DIFF_TICK(tick,hist->tick) > ddos_autoreset && hist->status)) {
  763. // clear data
  764. hist2 = hist->next;
  765. if(hist->prev) {
  766. hist->prev->next = hist->next;
  767. } else {
  768. connect_history[i] = hist->next;
  769. }
  770. if(hist->next) {
  771. hist->next->prev = hist->prev;
  772. }
  773. aFree(hist);
  774. hist = hist2;
  775. clear++;
  776. } else {
  777. hist = hist->next;
  778. }
  779. list++;
  780. }
  781. }
  782. if(access_debug) {
  783. ShowMessage("connect_check_clear: Cleared %d of %d from IP list.\n", clear, list);
  784. }
  785. return list;
  786. }
  787. // IPマスクチェック
  788. int access_ipmask(const char *str,struct _access_control* acc)
  789. {
  790. unsigned int mask=0,i=0,m,ip, a0,a1,a2,a3;
  791. if( !strcmp(str,"all") ) {
  792. ip = 0;
  793. mask = 0;
  794. } else {
  795. if( sscanf(str,"%d.%d.%d.%d%n",&a0,&a1,&a2,&a3,&i)!=4 || i==0) {
  796. ShowError("access_ipmask: Unknown format %s!\n",str);
  797. return 0;
  798. }
  799. ip = (a3 << 24) | (a2 << 16) | (a1 << 8) | a0;
  800. if(sscanf(str+i,"/%d.%d.%d.%d",&a0,&a1,&a2,&a3)==4 ){
  801. mask = (a3 << 24) | (a2 << 16) | (a1 << 8) | a0;
  802. } else if(sscanf(str+i,"/%d",&m) == 1) {
  803. for(i=0;i<m;i++) {
  804. mask = (mask >> 1) | 0x80000000;
  805. }
  806. mask = ntohl(mask);
  807. } else {
  808. mask = 0xFFFFFFFF;
  809. }
  810. }
  811. if(access_debug) {
  812. ShowMessage("access_ipmask: Loaded IP:%d.%d.%d.%d mask:%d.%d.%d.%d\n",
  813. CONVIP(ip), CONVIP(mask));
  814. }
  815. acc->ip = ip;
  816. acc->mask = mask;
  817. return 1;
  818. }
  819. #endif
  820. int socket_config_read(const char *cfgName) {
  821. int i;
  822. char line[1024],w1[1024],w2[1024];
  823. FILE *fp;
  824. fp=fopen(cfgName, "r");
  825. if(fp==NULL){
  826. ShowError("File not found: %s\n", cfgName);
  827. return 1;
  828. }
  829. while(fgets(line,1020,fp)){
  830. if(line[0] == '/' && line[1] == '/')
  831. continue;
  832. i=sscanf(line,"%[^:]: %[^\r\n]",w1,w2);
  833. if(i!=2)
  834. continue;
  835. if(strcmpi(w1,"stall_time")==0){
  836. stall_time = atoi(w2);
  837. #ifndef MINICORE
  838. } else if(strcmpi(w1,"enable_ip_rules")==0){
  839. if(strcmpi(w2,"yes")==0)
  840. ip_rules = 1;
  841. else if(strcmpi(w2,"no")==0)
  842. ip_rules = 0;
  843. else ip_rules = atoi(w2);
  844. } else if(strcmpi(w1,"order")==0){
  845. access_order=atoi(w2);
  846. if(strcmpi(w2,"deny,allow")==0) access_order=ACO_DENY_ALLOW;
  847. if(strcmpi(w2,"allow,deny")==0) access_order=ACO_ALLOW_DENY;
  848. if(strcmpi(w2,"mutual-failure")==0) access_order=ACO_MUTUAL_FAILTURE;
  849. } else if(strcmpi(w1,"allow")==0){
  850. access_allow = (struct _access_control *) aRealloc(access_allow,(access_allownum+1)*sizeof(struct _access_control));
  851. if(access_ipmask(w2,&access_allow[access_allownum])) {
  852. access_allownum++;
  853. }
  854. } else if(strcmpi(w1,"deny")==0){
  855. access_deny = (struct _access_control *) aRealloc(access_deny,(access_denynum+1)*sizeof(struct _access_control));
  856. if(access_ipmask(w2,&access_deny[access_denynum])) {
  857. access_denynum++;
  858. }
  859. } else if(!strcmpi(w1,"ddos_interval")){
  860. ddos_interval = atoi(w2);
  861. } else if(!strcmpi(w1,"ddos_count")){
  862. ddos_count = atoi(w2);
  863. } else if(!strcmpi(w1,"ddos_autoreset")){
  864. ddos_autoreset = atoi(w2);
  865. } else if(!strcmpi(w1,"debug")){
  866. if(strcmpi(w2,"yes")==0)
  867. access_debug = 1;
  868. else if(strcmpi(w2,"no")==0)
  869. access_debug = 0;
  870. else access_debug = atoi(w2);
  871. #endif
  872. } else if (strcmpi(w1, "mode_neg") == 0)
  873. {
  874. if(strcmpi(w2,"yes")==0)
  875. mode_neg = 1;
  876. else if(strcmpi(w2,"no")==0)
  877. mode_neg = 0;
  878. else mode_neg = atoi(w2);
  879. } else if (strcmpi(w1, "frame_size") == 0)
  880. frame_size = (size_t)strtoul(w2, NULL, 10);
  881. else if (strcmpi(w1, "import") == 0)
  882. socket_config_read(w2);
  883. }
  884. fclose(fp);
  885. return 0;
  886. }
  887. int RFIFOSKIP(int fd,int len)
  888. {
  889. struct socket_data *s;
  890. if ( !session_isActive(fd) ) //Nullpo error here[Kevin]
  891. return 0;
  892. s = session[fd];
  893. if ( s->rdata_size - s->rdata_pos - len < 0 ) {
  894. //fprintf(stderr,"too many skip\n");
  895. //exit(1);
  896. //better than a COMPLETE program abort // TEST! :)
  897. ShowError("too many skip (%d) now skipped: %d (FD: %d)\n", len, RFIFOREST(fd), fd);
  898. len = RFIFOREST(fd);
  899. }
  900. s->rdata_pos = s->rdata_pos+len;
  901. return 0;
  902. }
  903. unsigned int addr_[16]; // ip addresses of local host (host byte order)
  904. unsigned int naddr_ = 0; // # of ip addresses
  905. void socket_final (void)
  906. {
  907. int i;
  908. #ifndef MINICORE
  909. struct _connect_history *hist , *hist2;
  910. for(i = 0; i < 0x10000; i++) {
  911. hist = connect_history[i];
  912. while(hist) {
  913. hist2 = hist->next;
  914. aFree(hist);
  915. hist = hist2;
  916. }
  917. }
  918. if (access_allow)
  919. aFree(access_allow);
  920. if (access_deny)
  921. aFree(access_deny);
  922. #endif
  923. for (i = 1; i < fd_max; i++) {
  924. if(session[i])
  925. delete_session(i);
  926. }
  927. // session[0] のダミーデータを削除
  928. aFree(session[0]->rdata);
  929. aFree(session[0]->wdata);
  930. aFree(session[0]);
  931. }
  932. //Closes a socket.
  933. //Needed to simplify shutdown code as well as manage the subtle differences in socket management from Windows and *nix.
  934. void do_close(int fd)
  935. {
  936. //We don't really care if these closing functions return an error, we are just shutting down and not reusing this socket.
  937. #ifdef __WIN32
  938. // shutdown(fd, SD_BOTH); //FIXME: Shutdown requires winsock2.h! What would be the proper shutting down method for winsock1?
  939. flush_fifo(fd); // try to send what's left (although it might not succeed since it's a nonblocking socket)
  940. #endif
  941. closesocket(fd);
  942. if (session[fd]) delete_session(fd);
  943. }
  944. void socket_init (void)
  945. {
  946. char *SOCKET_CONF_FILENAME = "conf/packet_athena.conf";
  947. #ifdef __WIN32
  948. char** a;
  949. unsigned int i;
  950. char fullhost[255];
  951. struct hostent* hent;
  952. /* Start up the windows networking */
  953. WORD version_wanted = MAKEWORD(1, 1); //Demand at least WinSocket version 1.1 (from Freya)
  954. WSADATA wsaData;
  955. if ( WSAStartup(version_wanted, &wsaData) != 0 ) {
  956. ShowFatalError("SYSERR: WinSock not available!\n");
  957. exit(1);
  958. }
  959. if(gethostname(fullhost, sizeof(fullhost)) == SOCKET_ERROR) {
  960. ShowError("Ugg.. no hostname defined!\n");
  961. return;
  962. }
  963. // XXX This should look up the local IP addresses in the registry
  964. // instead of calling gethostbyname. However, the way IP addresses
  965. // are stored in the registry is annoyingly complex, so I'll leave
  966. // this as T.B.D.
  967. hent = gethostbyname(fullhost);
  968. if (hent == NULL) {
  969. ShowError("Cannot resolve our own hostname to a IP address");
  970. return;
  971. }
  972. a = hent->h_addr_list;
  973. for(i = 0; a[i] != 0 && i < 16; ++i) {
  974. unsigned long addr1 = ntohl(*(unsigned long*) a[i]);
  975. addr_[i] = addr1;
  976. }
  977. naddr_ = i;
  978. #else
  979. int pos;
  980. int fdes = socket(AF_INET, SOCK_STREAM, 0);
  981. char buf[16 * sizeof(struct ifreq)];
  982. struct ifconf ic;
  983. // The ioctl call will fail with Invalid Argument if there are more
  984. // interfaces than will fit in the buffer
  985. ic.ifc_len = sizeof(buf);
  986. ic.ifc_buf = buf;
  987. if(ioctl(fdes, SIOCGIFCONF, &ic) == -1) {
  988. ShowError("SIOCGIFCONF failed!\n");
  989. return;
  990. }
  991. for(pos = 0; pos < ic.ifc_len;)
  992. {
  993. struct ifreq * ir = (struct ifreq *) (ic.ifc_buf + pos);
  994. struct sockaddr_in * a = (struct sockaddr_in *) &(ir->ifr_addr);
  995. if(a->sin_family == AF_INET) {
  996. u_long ad = ntohl(a->sin_addr.s_addr);
  997. if(ad != INADDR_LOOPBACK && ad != INADDR_ANY) {
  998. addr_[naddr_ ++] = ad;
  999. if(naddr_ == 16)
  1000. break;
  1001. }
  1002. }
  1003. #if defined(_AIX) || defined(__APPLE__)
  1004. pos += ir->ifr_addr.sa_len; // For when we port athena to run on Mac's :)
  1005. pos += sizeof(ir->ifr_name);
  1006. #else
  1007. pos += sizeof(struct ifreq);
  1008. #endif
  1009. }
  1010. #endif
  1011. FD_ZERO(&readfds);
  1012. socket_config_read(SOCKET_CONF_FILENAME);
  1013. // initialise last send-receive tick
  1014. last_tick = time(0);
  1015. // session[0] Was for the console (whatever that was?), but is now currently used for disconnected sessions of the map
  1016. // server, and as such, should hold enough buffer (it is a vacuum so to speak) as it is never flushed. [Skotlex]
  1017. CREATE(session[0], struct socket_data, 1);
  1018. CREATE(session[0]->rdata, unsigned char, 2*rfifo_size);
  1019. CREATE(session[0]->wdata, unsigned char, 2*wfifo_size);
  1020. session[0]->max_rdata = 2*rfifo_size;
  1021. session[0]->max_wdata = 2*wfifo_size;
  1022. malloc_set(func_parse_table, 0, sizeof(func_parse_table));
  1023. func_parse_table[SESSION_RAW].check = default_func_check;
  1024. func_parse_table[SESSION_RAW].func = default_func_parse;
  1025. #ifndef MINICORE
  1026. // とりあえず5分ごとに不要なデータを削除する
  1027. add_timer_func_list(connect_check_clear, "connect_check_clear");
  1028. add_timer_interval(gettick()+1000,connect_check_clear,0,0,300*1000);
  1029. #endif
  1030. }
  1031. bool session_isValid(int fd)
  1032. { //End of Exam has pointed out that fd==0 is actually an unconnected session! [Skotlex]
  1033. //But this is not so true, it is used... for... something. The console uses it, would this not cause problems? [Skotlex]
  1034. return ( (fd>0) && (fd<FD_SETSIZE) && (NULL!=session[fd]) );
  1035. }
  1036. bool session_isActive(int fd)
  1037. {
  1038. return ( session_isValid(fd) && !session[fd]->eof );
  1039. }
  1040. in_addr_t resolve_hostbyname(char* hostname, unsigned char *ip, char *ip_str) {
  1041. struct hostent *h = gethostbyname(hostname);
  1042. char ip_buf[16];
  1043. unsigned char ip2[4];
  1044. if (!h) return 0;
  1045. if (ip == NULL) ip = ip2;
  1046. ip[0] = (unsigned char) h->h_addr[0];
  1047. ip[1] = (unsigned char) h->h_addr[1];
  1048. ip[2] = (unsigned char) h->h_addr[2];
  1049. ip[3] = (unsigned char) h->h_addr[3];
  1050. if (ip_str == NULL) ip_str = ip_buf;
  1051. sprintf(ip_str, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
  1052. return inet_addr(ip_str);
  1053. }