socket.c 33 KB

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