EQStreamFactory.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. /*
  2. EQ2Emulator: Everquest II Server Emulator
  3. Copyright (C) 2007 EQ2EMulator Development Team (http://www.eq2emulator.net)
  4. This file is part of EQ2Emulator.
  5. EQ2Emulator is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. EQ2Emulator is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with EQ2Emulator. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. #include "EQStreamFactory.h"
  17. #include "Log.h"
  18. #ifdef WIN32
  19. #include <WinSock2.h>
  20. #include <windows.h>
  21. #include <process.h>
  22. #include <io.h>
  23. #include <stdio.h>
  24. #else
  25. #include <sys/socket.h>
  26. #include <netinet/in.h>
  27. #include <sys/select.h>
  28. #include <arpa/inet.h>
  29. #include <netdb.h>
  30. #include <pthread.h>
  31. #endif
  32. #include <fcntl.h>
  33. #include <fstream>
  34. #include <iostream>
  35. #include "op_codes.h"
  36. #include "EQStream.h"
  37. #include "packet_dump.h"
  38. #ifdef WORLD
  39. #include "../WorldServer/client.h"
  40. #endif
  41. using namespace std;
  42. #ifdef WORLD
  43. extern ClientList client_list;
  44. #endif
  45. ThreadReturnType EQStreamFactoryReaderLoop(void *eqfs)
  46. {
  47. if(eqfs){
  48. EQStreamFactory *fs=(EQStreamFactory *)eqfs;
  49. fs->ReaderLoop();
  50. }
  51. THREAD_RETURN(NULL);
  52. }
  53. ThreadReturnType EQStreamFactoryWriterLoop(void *eqfs)
  54. {
  55. if(eqfs){
  56. EQStreamFactory *fs=(EQStreamFactory *)eqfs;
  57. fs->WriterLoop();
  58. }
  59. THREAD_RETURN(NULL);
  60. }
  61. ThreadReturnType EQStreamFactoryCombinePacketLoop(void *eqfs)
  62. {
  63. if(eqfs){
  64. EQStreamFactory *fs=(EQStreamFactory *)eqfs;
  65. fs->CombinePacketLoop();
  66. }
  67. THREAD_RETURN(NULL);
  68. }
  69. EQStreamFactory::EQStreamFactory(EQStreamType type, int port)
  70. {
  71. StreamType=type;
  72. Port=port;
  73. listen_ip_address = 0;
  74. }
  75. void EQStreamFactory::Close()
  76. {
  77. CheckTimeout(true);
  78. Stop();
  79. #ifdef WIN32
  80. closesocket(sock);
  81. #else
  82. close(sock);
  83. #endif
  84. sock=-1;
  85. }
  86. bool EQStreamFactory::Open()
  87. {
  88. struct sockaddr_in address;
  89. #ifndef WIN32
  90. pthread_t t1, t2, t3;
  91. #endif
  92. /* Setup internet address information.
  93. This is used with the bind() call */
  94. memset((char *) &address, 0, sizeof(address));
  95. address.sin_family = AF_INET;
  96. address.sin_port = htons(Port);
  97. #if defined(LOGIN) || defined(MINILOGIN)
  98. if(listen_ip_address)
  99. address.sin_addr.s_addr = inet_addr(listen_ip_address);
  100. else
  101. address.sin_addr.s_addr = htonl(INADDR_ANY);
  102. #else
  103. address.sin_addr.s_addr = htonl(INADDR_ANY);
  104. #endif
  105. /* Setting up UDP port for new clients */
  106. sock = socket(AF_INET, SOCK_DGRAM, 0);
  107. if (sock < 0) {
  108. return false;
  109. }
  110. if (bind(sock, (struct sockaddr *) &address, sizeof(address)) < 0) {
  111. close(sock);
  112. sock=-1;
  113. return false;
  114. }
  115. #ifdef WIN32
  116. unsigned long nonblock = 1;
  117. ioctlsocket(sock, FIONBIO, &nonblock);
  118. #else
  119. fcntl(sock, F_SETFL, O_NONBLOCK);
  120. #endif
  121. //moved these because on windows the output was delayed and causing the console window to look bad
  122. LogWrite(WORLD__DEBUG, 0, "World", "Starting factory Reader");
  123. LogWrite(WORLD__DEBUG, 0, "World", "Starting factory Writer");
  124. #ifdef WIN32
  125. _beginthread(EQStreamFactoryReaderLoop,0, this);
  126. _beginthread(EQStreamFactoryWriterLoop,0, this);
  127. _beginthread(EQStreamFactoryCombinePacketLoop,0, this);
  128. #else
  129. pthread_create(&t1,NULL,EQStreamFactoryReaderLoop,this);
  130. pthread_create(&t2,NULL,EQStreamFactoryWriterLoop,this);
  131. pthread_create(&t3,NULL,EQStreamFactoryCombinePacketLoop,this);
  132. pthread_detach(t1);
  133. pthread_detach(t2);
  134. pthread_detach(t3);
  135. #endif
  136. return true;
  137. }
  138. EQStream *EQStreamFactory::Pop()
  139. {
  140. if (!NewStreams.size())
  141. return NULL;
  142. EQStream *s=NULL;
  143. //cout << "Pop():Locking MNewStreams" << endl;
  144. MNewStreams.lock();
  145. if (NewStreams.size()) {
  146. s=NewStreams.front();
  147. NewStreams.pop();
  148. s->PutInUse();
  149. }
  150. MNewStreams.unlock();
  151. //cout << "Pop(): Unlocking MNewStreams" << endl;
  152. return s;
  153. }
  154. void EQStreamFactory::Push(EQStream *s)
  155. {
  156. //cout << "Push():Locking MNewStreams" << endl;
  157. MNewStreams.lock();
  158. NewStreams.push(s);
  159. MNewStreams.unlock();
  160. //cout << "Push(): Unlocking MNewStreams" << endl;
  161. }
  162. void EQStreamFactory::ReaderLoop()
  163. {
  164. fd_set readset;
  165. map<string,EQStream *>::iterator stream_itr;
  166. int num;
  167. int length;
  168. unsigned char buffer[2048];
  169. sockaddr_in from;
  170. int socklen=sizeof(sockaddr_in);
  171. timeval sleep_time;
  172. ReaderRunning=true;
  173. while(sock!=-1) {
  174. MReaderRunning.lock();
  175. if (!ReaderRunning)
  176. break;
  177. MReaderRunning.unlock();
  178. FD_ZERO(&readset);
  179. FD_SET(sock,&readset);
  180. sleep_time.tv_sec=30;
  181. sleep_time.tv_usec=0;
  182. if ((num=select(sock+1,&readset,NULL,NULL,&sleep_time))<0) {
  183. // What do we wanna do?
  184. } else if (num==0)
  185. continue;
  186. if (FD_ISSET(sock,&readset)) {
  187. #ifdef WIN32
  188. if ((length=recvfrom(sock,(char*)buffer,sizeof(buffer),0,(struct sockaddr*)&from,(int *)&socklen))<0)
  189. #else
  190. if ((length=recvfrom(sock,buffer,2048,0,(struct sockaddr *)&from,(socklen_t *)&socklen))<0)
  191. #endif
  192. {
  193. // What do we wanna do?
  194. } else {
  195. char temp[25];
  196. sprintf(temp,"%u.%d",ntohl(from.sin_addr.s_addr),ntohs(from.sin_port));
  197. MStreams.lock();
  198. if ((stream_itr=Streams.find(temp))==Streams.end() || buffer[1]==OP_SessionRequest) {
  199. MStreams.unlock();
  200. if (buffer[1]==OP_SessionRequest) {
  201. if(stream_itr != Streams.end() && stream_itr->second)
  202. stream_itr->second->SetState(CLOSED);
  203. EQStream *s=new EQStream(from);
  204. s->SetFactory(this);
  205. s->SetStreamType(StreamType);
  206. Streams[temp]=s;
  207. WriterWork.Signal();
  208. Push(s);
  209. s->Process(buffer,length);
  210. s->SetLastPacketTime(Timer::GetCurrentTime2());
  211. }
  212. } else {
  213. EQStream *curstream = stream_itr->second;
  214. //dont bother processing incoming packets for closed connections
  215. if(curstream->CheckClosed())
  216. curstream = NULL;
  217. else
  218. curstream->PutInUse();
  219. MStreams.unlock();
  220. if(curstream) {
  221. curstream->Process(buffer,length);
  222. curstream->SetLastPacketTime(Timer::GetCurrentTime2());
  223. curstream->ReleaseFromUse();
  224. }
  225. }
  226. }
  227. }
  228. }
  229. }
  230. void EQStreamFactory::CheckTimeout(bool remove_all)
  231. {
  232. //lock streams the entire time were checking timeouts, it should be fast.
  233. MStreams.lock();
  234. unsigned long now=Timer::GetCurrentTime2();
  235. map<string,EQStream *>::iterator stream_itr;
  236. for(stream_itr=Streams.begin();stream_itr!=Streams.end();) {
  237. EQStream *s = stream_itr->second;
  238. EQStreamState state = s->GetState();
  239. if (state==CLOSING && !s->HasOutgoingData()) {
  240. stream_itr->second->SetState(CLOSED);
  241. state = CLOSED;
  242. } else if (s->CheckTimeout(now, STREAM_TIMEOUT)) {
  243. const char* stateString;
  244. switch (state){
  245. case ESTABLISHED:
  246. stateString = "Established";
  247. break;
  248. case CLOSING:
  249. stateString = "Closing";
  250. break;
  251. case CLOSED:
  252. stateString = "Closed";
  253. break;
  254. default:
  255. stateString = "Unknown";
  256. break;
  257. }
  258. LogWrite(WORLD__DEBUG, 0, "World", "Timeout up!, state=%s", stateString);
  259. if (state==ESTABLISHED) {
  260. s->Close();
  261. } else if (state == CLOSING) {
  262. //if we time out in the closing state, just give up
  263. s->SetState(CLOSED);
  264. state = CLOSED;
  265. }
  266. }
  267. //not part of the else so we check it right away on state change
  268. if (remove_all || state==CLOSED) {
  269. if (!remove_all && s->getTimeoutDelays()<2) {
  270. s->addTimeoutDelay();
  271. //give it a little time for everybody to finish with it
  272. } else {
  273. //everybody is done, we can delete it now
  274. LogWrite(WORLD__DEBUG, 0, "World", "Removing connection...");
  275. map<string,EQStream *>::iterator temp=stream_itr;
  276. stream_itr++;
  277. //let whoever has the stream outside delete it
  278. #ifdef WORLD
  279. client_list.RemoveConnection(temp->second);
  280. #endif
  281. delete temp->second;
  282. Streams.erase(temp);
  283. continue;
  284. }
  285. }
  286. stream_itr++;
  287. }
  288. MStreams.unlock();
  289. }
  290. void EQStreamFactory::CombinePacketLoop(){
  291. deque<EQStream*> combine_que;
  292. CombinePacketRunning = true;
  293. bool packets_waiting = false;
  294. while(sock!=-1) {
  295. if (!CombinePacketRunning)
  296. break;
  297. MStreams.lock();
  298. map<string,EQStream *>::iterator stream_itr;
  299. for(stream_itr=Streams.begin();stream_itr!=Streams.end();stream_itr++) {
  300. if(!stream_itr->second){
  301. continue;
  302. }
  303. if(stream_itr->second->combine_timer && stream_itr->second->combine_timer->Check())
  304. combine_que.push_back(stream_itr->second);
  305. }
  306. EQStream* stream = 0;
  307. packets_waiting = false;
  308. while(combine_que.size()){
  309. stream = combine_que.front();
  310. if(stream->CheckActive()){
  311. if(!stream->CheckCombineQueue())
  312. packets_waiting = true;
  313. }
  314. combine_que.pop_front();
  315. }
  316. MStreams.unlock();
  317. if(!packets_waiting)
  318. Sleep(25);
  319. Sleep(1);
  320. }
  321. }
  322. void EQStreamFactory::WriterLoop()
  323. {
  324. map<string,EQStream *>::iterator stream_itr;
  325. vector<EQStream *> wants_write;
  326. vector<EQStream *>::iterator cur,end;
  327. deque<EQStream*> resend_que;
  328. bool decay=false;
  329. uint32 stream_count;
  330. Timer DecayTimer(20);
  331. WriterRunning=true;
  332. DecayTimer.Enable();
  333. while(sock!=-1) {
  334. Timer::SetCurrentTime();
  335. //if (!havework) {
  336. //WriterWork.Wait();
  337. //}
  338. MWriterRunning.lock();
  339. if (!WriterRunning)
  340. break;
  341. MWriterRunning.unlock();
  342. wants_write.clear();
  343. decay=DecayTimer.Check();
  344. //copy streams into a seperate list so we dont have to keep
  345. //MStreams locked while we are writting
  346. MStreams.lock();
  347. for(stream_itr=Streams.begin();stream_itr!=Streams.end();stream_itr++) {
  348. // If it's time to decay the bytes sent, then let's do it before we try to write
  349. if(!stream_itr->second){
  350. Streams.erase(stream_itr);
  351. break;
  352. }
  353. if (decay)
  354. stream_itr->second->Decay();
  355. if (stream_itr->second->HasOutgoingData()) {
  356. stream_itr->second->PutInUse();
  357. wants_write.push_back(stream_itr->second);
  358. }
  359. if(stream_itr->second->resend_que_timer->Check())
  360. resend_que.push_back(stream_itr->second);
  361. }
  362. MStreams.unlock();
  363. //do the actual writes
  364. cur = wants_write.begin();
  365. end = wants_write.end();
  366. for(; cur != end; cur++) {
  367. (*cur)->Write(sock);
  368. (*cur)->ReleaseFromUse();
  369. }
  370. while(resend_que.size()){
  371. resend_que.front()->CheckResend(sock);
  372. resend_que.pop_front();
  373. }
  374. Sleep(10);
  375. MStreams.lock();
  376. stream_count=Streams.size();
  377. MStreams.unlock();
  378. if (!stream_count) {
  379. //cout << "No streams, waiting on condition" << endl;
  380. WriterWork.Wait();
  381. //cout << "Awake from condition, must have a stream now" << endl;
  382. }
  383. }
  384. }