socket.c 38 KB

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