1
0

sio_packet.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. //
  2. // sio_packet.cpp
  3. //
  4. // Created by Melo Yao on 3/22/15.
  5. //
  6. #include "sio_packet.h"
  7. #include <rapidjson/document.h>
  8. #include <rapidjson/encodedstream.h>
  9. #include <rapidjson/writer.h>
  10. #include <cassert>
  11. #include <boost/lexical_cast.hpp>
  12. #define kBIN_PLACE_HOLDER "_placeholder"
  13. namespace sio
  14. {
  15. using namespace rapidjson;
  16. using namespace std;
  17. void accept_message(message const& msg,Value& val, Document& doc,vector<shared_ptr<const string> >& buffers);
  18. void accept_bool_message(bool_message const& msg, Value& val)
  19. {
  20. val.SetBool(msg.get_bool());
  21. }
  22. void accept_null_message(Value& val)
  23. {
  24. val.SetNull();
  25. }
  26. void accept_int_message(int_message const& msg, Value& val)
  27. {
  28. val.SetInt64(msg.get_int());
  29. }
  30. void accept_double_message(double_message const& msg, Value& val)
  31. {
  32. val.SetDouble(msg.get_double());
  33. }
  34. void accept_string_message(string_message const& msg, Value& val)
  35. {
  36. val.SetString(msg.get_string().data(),(SizeType) msg.get_string().length());
  37. }
  38. void accept_binary_message(binary_message const& msg,Value& val,Document& doc,vector<shared_ptr<const string> >& buffers)
  39. {
  40. val.SetObject();
  41. Value boolVal;
  42. boolVal.SetBool(true);
  43. val.AddMember(kBIN_PLACE_HOLDER, boolVal, doc.GetAllocator());
  44. Value numVal;
  45. numVal.SetInt((int)buffers.size());
  46. val.AddMember("num", numVal, doc.GetAllocator());
  47. //FIXME can not avoid binary copy here.
  48. shared_ptr<string> write_buffer = make_shared<string>();
  49. write_buffer->reserve(msg.get_binary()->size()+1);
  50. char frame_char = packet::frame_message;
  51. write_buffer->append(&frame_char,1);
  52. write_buffer->append(*(msg.get_binary()));
  53. buffers.push_back(write_buffer);
  54. }
  55. void accept_array_message(array_message const& msg,Value& val,Document& doc,vector<shared_ptr<const string> >& buffers)
  56. {
  57. val.SetArray();
  58. for (vector<message::ptr>::const_iterator it = msg.get_vector().begin(); it!=msg.get_vector().end(); ++it) {
  59. Value child;
  60. accept_message(*(*it), child, doc,buffers);
  61. val.PushBack(child, doc.GetAllocator());
  62. }
  63. }
  64. void accept_object_message(object_message const& msg,Value& val,Document& doc,vector<shared_ptr<const string> >& buffers)
  65. {
  66. val.SetObject();
  67. for (map<string,message::ptr>::const_iterator it = msg.get_map().begin(); it!= msg.get_map().end(); ++it) {
  68. Value nameVal;
  69. nameVal.SetString(it->first.data(), (SizeType)it->first.length(), doc.GetAllocator());
  70. Value valueVal;
  71. accept_message(*(it->second), valueVal, doc,buffers);
  72. val.AddMember(nameVal, valueVal, doc.GetAllocator());
  73. }
  74. }
  75. void accept_message(message const& msg,Value& val, Document& doc,vector<shared_ptr<const string> >& buffers)
  76. {
  77. const message* msg_ptr = &msg;
  78. switch(msg.get_flag())
  79. {
  80. case message::flag_integer:
  81. {
  82. accept_int_message(*(static_cast<const int_message*>(msg_ptr)), val);
  83. break;
  84. }
  85. case message::flag_double:
  86. {
  87. accept_double_message(*(static_cast<const double_message*>(msg_ptr)), val);
  88. break;
  89. }
  90. case message::flag_string:
  91. {
  92. accept_string_message(*(static_cast<const string_message*>(msg_ptr)), val);
  93. break;
  94. }
  95. case message::flag_boolean:
  96. {
  97. accept_bool_message(*(static_cast<const bool_message*>(msg_ptr)), val);
  98. break;
  99. }
  100. case message::flag_null:
  101. {
  102. accept_null_message(val);
  103. break;
  104. }
  105. case message::flag_binary:
  106. {
  107. accept_binary_message(*(static_cast<const binary_message*>(msg_ptr)), val,doc,buffers);
  108. break;
  109. }
  110. case message::flag_array:
  111. {
  112. accept_array_message(*(static_cast<const array_message*>(msg_ptr)), val,doc,buffers);
  113. break;
  114. }
  115. case message::flag_object:
  116. {
  117. accept_object_message(*(static_cast<const object_message*>(msg_ptr)), val,doc,buffers);
  118. break;
  119. }
  120. default:
  121. break;
  122. }
  123. }
  124. message::ptr from_json(Value const& value, vector<shared_ptr<const string> > const& buffers)
  125. {
  126. if(value.IsInt64())
  127. {
  128. return int_message::create(value.GetInt64());
  129. }
  130. else if(value.IsDouble())
  131. {
  132. return double_message::create(value.GetDouble());
  133. }
  134. else if(value.IsString())
  135. {
  136. string str(value.GetString(),value.GetStringLength());
  137. return string_message::create(str);
  138. }
  139. else if(value.IsArray())
  140. {
  141. message::ptr ptr = array_message::create();
  142. for (SizeType i = 0; i< value.Size(); ++i) {
  143. static_cast<array_message*>(ptr.get())->get_vector().push_back(from_json(value[i],buffers));
  144. }
  145. return ptr;
  146. }
  147. else if(value.IsObject())
  148. {
  149. //binary placeholder
  150. auto mem_it = value.FindMember(kBIN_PLACE_HOLDER);
  151. if (mem_it!=value.MemberEnd() && mem_it->value.GetBool()) {
  152. int num = value["num"].GetInt();
  153. if(num >= 0 && num < static_cast<int>(buffers.size()))
  154. {
  155. return binary_message::create(buffers[num]);
  156. }
  157. return message::ptr();
  158. }
  159. //real object message.
  160. message::ptr ptr = object_message::create();
  161. for (auto it = value.MemberBegin();it!=value.MemberEnd();++it)
  162. {
  163. if(it->name.IsString())
  164. {
  165. string key(it->name.GetString(),it->name.GetStringLength());
  166. static_cast<object_message*>(ptr.get())->get_map()[key] = from_json(it->value,buffers);
  167. }
  168. }
  169. return ptr;
  170. }
  171. else if(value.IsBool())
  172. {
  173. return bool_message::create(value.GetBool());
  174. }
  175. else if(value.IsNull())
  176. {
  177. return null_message::create();
  178. }
  179. return message::ptr();
  180. }
  181. packet::packet(string const& nsp,message::ptr const& msg,int pack_id, bool isAck):
  182. _frame(frame_message),
  183. _type((isAck?type_ack : type_event) | type_undetermined),
  184. _nsp(nsp),
  185. _pack_id(pack_id),
  186. _message(msg),
  187. _pending_buffers(0)
  188. {
  189. assert((!isAck
  190. || (isAck&&pack_id>=0)));
  191. }
  192. packet::packet(type type,string const& nsp, message::ptr const& msg):
  193. _frame(frame_message),
  194. _type(type),
  195. _nsp(nsp),
  196. _pack_id(-1),
  197. _message(msg),
  198. _pending_buffers(0)
  199. {
  200. }
  201. packet::packet(packet::frame_type frame):
  202. _frame(frame),
  203. _type(type_undetermined),
  204. _pack_id(-1),
  205. _pending_buffers(0)
  206. {
  207. }
  208. packet::packet():
  209. _type(type_undetermined),
  210. _pack_id(-1),
  211. _pending_buffers(0)
  212. {
  213. }
  214. bool packet::is_binary_message(string const& payload_ptr)
  215. {
  216. return payload_ptr.size()>0 && payload_ptr[0] == frame_message;
  217. }
  218. bool packet::is_text_message(string const& payload_ptr)
  219. {
  220. return payload_ptr.size()>0 && payload_ptr[0] == (frame_message + '0');
  221. }
  222. bool packet::is_message(string const& payload_ptr)
  223. {
  224. return is_binary_message(payload_ptr) || is_text_message(payload_ptr);
  225. }
  226. bool packet::parse_buffer(const string &buf_payload)
  227. {
  228. if (_pending_buffers > 0) {
  229. assert(is_binary_message(buf_payload));//this is ensured by outside.
  230. _buffers.push_back(std::make_shared<string>(buf_payload.data()+1,buf_payload.size()-1));
  231. _pending_buffers--;
  232. if (_pending_buffers == 0) {
  233. Document doc;
  234. doc.Parse<0>(_buffers.front()->data());
  235. _buffers.erase(_buffers.begin());
  236. _message = from_json(doc, _buffers);
  237. _buffers.clear();
  238. return false;
  239. }
  240. return true;
  241. }
  242. return false;
  243. }
  244. bool packet::parse(const string& payload_ptr)
  245. {
  246. assert(!is_binary_message(payload_ptr)); //this is ensured by outside
  247. _frame = (packet::frame_type) (payload_ptr[0] - '0');
  248. _message.reset();
  249. _pack_id = -1;
  250. _buffers.clear();
  251. _pending_buffers = 0;
  252. size_t pos = 1;
  253. if (_frame == frame_message) {
  254. _type = (packet::type)(payload_ptr[pos] - '0');
  255. if(_type < type_min || _type > type_max)
  256. {
  257. return false;
  258. }
  259. pos++;
  260. if (_type == type_binary_event || _type == type_binary_ack) {
  261. size_t score_pos = payload_ptr.find('-');
  262. _pending_buffers = boost::lexical_cast<unsigned>(payload_ptr.substr(pos,score_pos - pos));
  263. pos = score_pos+1;
  264. }
  265. }
  266. size_t nsp_json_pos = payload_ptr.find_first_of("{[\"/",pos,4);
  267. if(nsp_json_pos==string::npos)//no namespace and no message,the end.
  268. {
  269. _nsp = "/";
  270. return false;
  271. }
  272. size_t json_pos = nsp_json_pos;
  273. if(payload_ptr[nsp_json_pos] == '/')//nsp_json_pos is start of nsp
  274. {
  275. size_t comma_pos = payload_ptr.find_first_of(",");//end of nsp
  276. if(comma_pos == string::npos)//packet end with nsp
  277. {
  278. _nsp = payload_ptr.substr(nsp_json_pos);
  279. return false;
  280. }
  281. else//we have a message, maybe the message have an id.
  282. {
  283. _nsp = payload_ptr.substr(nsp_json_pos,comma_pos - nsp_json_pos);
  284. pos = comma_pos+1;//start of the message
  285. json_pos = payload_ptr.find_first_of("\"[{", pos, 3);//start of the json part of message
  286. if(json_pos == string::npos)
  287. {
  288. //no message,the end
  289. //assume if there's no message, there's no message id.
  290. return false;
  291. }
  292. }
  293. }
  294. else
  295. {
  296. _nsp = "/";
  297. }
  298. if(pos<json_pos)//we've got pack id.
  299. {
  300. _pack_id = boost::lexical_cast<int>(payload_ptr.substr(pos,json_pos - pos));
  301. }
  302. if (_frame == frame_message && (_type == type_binary_event || _type == type_binary_ack)) {
  303. //parse later when all buffers are arrived.
  304. _buffers.push_back(make_shared<string>(payload_ptr.data() + json_pos, payload_ptr.length() - json_pos));
  305. return true;
  306. }
  307. else
  308. {
  309. Document doc;
  310. doc.Parse<0>(payload_ptr.data()+json_pos);
  311. _message = from_json(doc, vector<shared_ptr<const string> >());
  312. return false;
  313. }
  314. }
  315. bool packet::accept(string& payload_ptr, vector<shared_ptr<const string> >&buffers)
  316. {
  317. char frame_char = _frame+'0';
  318. payload_ptr.append(&frame_char,1);
  319. if (_frame!=frame_message) {
  320. return false;
  321. }
  322. bool hasMessage = false;
  323. Document doc;
  324. if (_message) {
  325. accept_message(*_message, doc, doc, buffers);
  326. hasMessage = true;
  327. }
  328. bool hasBinary = buffers.size()>0;
  329. _type = _type&(~type_undetermined);
  330. if(_type == type_event)
  331. {
  332. _type = hasBinary?type_binary_event:type_event;
  333. }
  334. else if(_type == type_ack)
  335. {
  336. _type = hasBinary? type_binary_ack : type_ack;
  337. }
  338. ostringstream ss;
  339. ss.precision(8);
  340. ss<<_type;
  341. if (hasBinary) {
  342. ss<<buffers.size()<<"-";
  343. }
  344. if(_nsp.size()>0 && _nsp!="/")
  345. {
  346. ss<<_nsp;
  347. if (hasMessage || _pack_id>=0) {
  348. ss<<",";
  349. }
  350. }
  351. if(_pack_id>=0)
  352. {
  353. ss<<_pack_id;
  354. }
  355. payload_ptr.append(ss.str());
  356. if (hasMessage)
  357. {
  358. StringBuffer buffer;
  359. Writer<StringBuffer> writer(buffer);
  360. doc.Accept(writer);
  361. payload_ptr.append(buffer.GetString(),buffer.GetSize());
  362. }
  363. return hasBinary;
  364. }
  365. packet::frame_type packet::get_frame() const
  366. {
  367. return _frame;
  368. }
  369. packet::type packet::get_type() const
  370. {
  371. assert((_type & type_undetermined) == 0);
  372. return (type)_type;
  373. }
  374. string const& packet::get_nsp() const
  375. {
  376. return _nsp;
  377. }
  378. message::ptr const& packet::get_message() const
  379. {
  380. return _message;
  381. }
  382. unsigned packet::get_pack_id() const
  383. {
  384. return _pack_id;
  385. }
  386. void packet_manager::set_decode_callback(function<void (packet const&)> const& decode_callback)
  387. {
  388. m_decode_callback = decode_callback;
  389. }
  390. void packet_manager::set_encode_callback(function<void (bool,shared_ptr<const string> const&)> const& encode_callback)
  391. {
  392. m_encode_callback = encode_callback;
  393. }
  394. void packet_manager::reset()
  395. {
  396. m_partial_packet.reset();
  397. }
  398. void packet_manager::encode(packet& pack,encode_callback_function const& override_encode_callback) const
  399. {
  400. shared_ptr<string> ptr = make_shared<string>();
  401. vector<shared_ptr<const string> > buffers;
  402. const encode_callback_function *cb_ptr = &m_encode_callback;
  403. if(override_encode_callback)
  404. {
  405. cb_ptr = &override_encode_callback;
  406. }
  407. if(pack.accept(*ptr,buffers))
  408. {
  409. if((*cb_ptr))
  410. {
  411. (*cb_ptr)(false,ptr);
  412. }
  413. for(auto it = buffers.begin();it!=buffers.end();++it)
  414. {
  415. if((*cb_ptr))
  416. {
  417. (*cb_ptr)(true,*it);
  418. }
  419. }
  420. }
  421. else
  422. {
  423. if((*cb_ptr))
  424. {
  425. (*cb_ptr)(false,ptr);
  426. }
  427. }
  428. }
  429. void packet_manager::put_payload(string const& payload)
  430. {
  431. unique_ptr<packet> p;
  432. do
  433. {
  434. if(packet::is_text_message(payload))
  435. {
  436. p.reset(new packet());
  437. if(p->parse(payload))
  438. {
  439. m_partial_packet = std::move(p);
  440. }
  441. else
  442. {
  443. break;
  444. }
  445. }
  446. else if(packet::is_binary_message(payload))
  447. {
  448. if(m_partial_packet)
  449. {
  450. if(!m_partial_packet->parse_buffer(payload))
  451. {
  452. p = std::move(m_partial_packet);
  453. break;
  454. }
  455. }
  456. }
  457. else
  458. {
  459. p.reset(new packet());
  460. p->parse(payload);
  461. break;
  462. }
  463. return;
  464. }while(0);
  465. if(m_decode_callback)
  466. {
  467. m_decode_callback(*p);
  468. }
  469. }
  470. }