net.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. #include <iostream>
  2. #include "Enclave_u.h"
  3. #include "Untrusted.hpp"
  4. #include "net.hpp"
  5. // The command type byte values
  6. #define COMMAND_EPOCH 0x00
  7. #define COMMAND_MESSAGE 0x01
  8. #define COMMAND_CHUNK 0x02
  9. NetIO *g_netio = NULL;
  10. NodeIO::NodeIO(tcp::socket &&socket, nodenum_t nodenum) :
  11. sock(std::move(socket)), node_num(nodenum)
  12. {
  13. }
  14. uint8_t *NodeIO::request_frame()
  15. {
  16. if (frames_available.empty()) {
  17. // Allocate a new frame. Note that this memory will (at this
  18. // time) never get deallocated. In theory, we could deallocate
  19. // it in return_frame, but if a certain number of frames were
  20. // allocated here, it means we had that much data in flight
  21. // (queued but not accepted for sending by the OS), and we're
  22. // likely to need that much again. Subsequent messages will
  23. // _reuse_ the allocated data, though, so the used memory won't
  24. // grow forever, and will be limited to the amount of in-flight
  25. // data needed.
  26. return new uint8_t[FRAME_SIZE];
  27. }
  28. // Copy the pointer to the frame out of the deque and remove it from
  29. // the deque. Note this is _not_ taking the address of the element
  30. // *in* the deque (and then popping it, which would invalidate that
  31. // pointer).
  32. frame_deque_lock.lock();
  33. uint8_t *frame = frames_available.back();
  34. frames_available.pop_back();
  35. frame_deque_lock.unlock();
  36. return frame;
  37. }
  38. void NodeIO::return_frame(uint8_t *frame)
  39. {
  40. if (!frame) return;
  41. // We push the frame back on to the end of the deque so that it will
  42. // be the next one used. This may lead to better cache behaviour?
  43. frame_deque_lock.lock();
  44. frames_available.push_back(frame);
  45. frame_deque_lock.unlock();
  46. }
  47. void NodeIO::send_header_data(uint64_t header, uint8_t *data, size_t len)
  48. {
  49. commands_deque_lock.lock();
  50. commands_inflight.push_back({header, data, len});
  51. if (commands_inflight.size() == 1) {
  52. async_send_commands();
  53. }
  54. commands_deque_lock.unlock();
  55. }
  56. void NodeIO::async_send_commands()
  57. {
  58. std::vector<boost::asio::const_buffer> tosend;
  59. CommandTuple *commandp = &(commands_inflight.front());
  60. tosend.push_back(boost::asio::buffer(&(std::get<0>(*commandp)), 5));
  61. if (std::get<1>(*commandp) != NULL && std::get<2>(*commandp) > 0) {
  62. tosend.push_back(boost::asio::buffer(std::get<1>(*commandp),
  63. std::get<2>(*commandp)));
  64. }
  65. boost::asio::async_write(sock, tosend,
  66. [this, commandp](boost::system::error_code, std::size_t){
  67. // When the write completes, pop the command from the deque
  68. // (which should now be in the front)
  69. commands_deque_lock.lock();
  70. assert(!commands_inflight.empty() &&
  71. &(commands_inflight.front()) == commandp);
  72. uint8_t *data = std::get<1>(*commandp);
  73. commands_inflight.pop_front();
  74. if (commands_inflight.size() > 0) {
  75. async_send_commands();
  76. }
  77. // And return the frame
  78. return_frame(data);
  79. commands_deque_lock.unlock();
  80. });
  81. }
  82. void NodeIO::send_epoch(uint32_t epoch_num)
  83. {
  84. uint64_t header = (uint64_t(epoch_num) << 8) + COMMAND_EPOCH;
  85. send_header_data(header, NULL, 0);
  86. }
  87. void NodeIO::send_message_header(uint32_t tot_message_len)
  88. {
  89. uint64_t header = (uint64_t(tot_message_len) << 8) + COMMAND_MESSAGE;
  90. send_header_data(header, NULL, 0);
  91. // If we're sending a new message header, we have to have finished
  92. // sending the previous message.
  93. assert(chunksize_inflight == msgsize_inflight);
  94. msgsize_inflight = tot_message_len;
  95. chunksize_inflight = 0;
  96. }
  97. bool NodeIO::send_chunk(uint8_t *data, uint32_t chunk_len)
  98. {
  99. assert(chunk_len <= FRAME_SIZE);
  100. uint64_t header = (uint64_t(chunk_len) << 8) + COMMAND_CHUNK;
  101. send_header_data(header, data, chunk_len);
  102. chunksize_inflight += chunk_len;
  103. assert(chunksize_inflight <= msgsize_inflight);
  104. return (chunksize_inflight < msgsize_inflight);
  105. }
  106. void NodeIO::recv_commands(
  107. std::function<void(boost::system::error_code)> error_cb,
  108. std::function<void(uint32_t)> epoch_cb)
  109. {
  110. // Asynchronously read the header
  111. receive_header = 0;
  112. boost::asio::async_read(sock, boost::asio::buffer(&receive_header, 5),
  113. [this, error_cb, epoch_cb]
  114. (boost::system::error_code ec, std::size_t) {
  115. if (ec) {
  116. error_cb(ec);
  117. return;
  118. }
  119. if ((receive_header & 0xff) == COMMAND_EPOCH) {
  120. epoch_cb(uint32_t(receive_header >> 8));
  121. recv_commands(error_cb, epoch_cb);
  122. } else if ((receive_header & 0xff) == COMMAND_MESSAGE) {
  123. assert(recv_msgsize_inflight == recv_chunksize_inflight);
  124. recv_msgsize_inflight = uint32_t(receive_header >> 8);
  125. recv_chunksize_inflight = 0;
  126. if (ecall_message(node_num, recv_msgsize_inflight)) {
  127. recv_commands(error_cb, epoch_cb);
  128. } else {
  129. printf("ecall_message failed\n");
  130. }
  131. } else if ((receive_header & 0xff) == COMMAND_CHUNK) {
  132. uint32_t this_chunk_size = uint32_t(receive_header >> 8);
  133. assert(recv_chunksize_inflight + this_chunk_size <=
  134. recv_msgsize_inflight);
  135. recv_chunksize_inflight += this_chunk_size;
  136. boost::asio::async_read(sock, boost::asio::buffer(
  137. receive_frame, this_chunk_size),
  138. [this, error_cb, epoch_cb, this_chunk_size]
  139. (boost::system::error_code ecc, std::size_t) {
  140. if (ecc) {
  141. error_cb(ecc);
  142. return;
  143. }
  144. if (ecall_chunk(node_num, receive_frame,
  145. this_chunk_size)) {
  146. recv_commands(error_cb, epoch_cb);
  147. } else {
  148. printf("ecall_chunk failed\n");
  149. }
  150. });
  151. } else {
  152. error_cb(boost::system::errc::make_error_code(
  153. boost::system::errc::errc_t::invalid_argument));
  154. }
  155. });
  156. }
  157. void accept_handler(const boost::system::error_code& error) {
  158. if(!error) {
  159. printf("Accept handler success\n");
  160. // Read 2 bytes from the socket, which will be the
  161. // connecting node's node number
  162. //unsigned short node_num;
  163. //boost::asio::read(acc_sock,
  164. // boost::asio::buffer(&node_num, sizeof(node_num)));
  165. //printf("node_num received = %d\n", node_num);
  166. } else {
  167. }
  168. }
  169. /*
  170. void start_accept(boost::asio::io_context& io_context, const NodeConfig& myconf);
  171. void handle_accept(boost::asio::io_context& io_context, const NodeConfig &myconf, tcp_connection::pointer new_connection,
  172. const boost::system::error_code& error)
  173. {
  174. if (!error)
  175. {
  176. new_connection->start();
  177. }
  178. start_accept(io_context, myconf);
  179. }
  180. void start_accept(boost::asio::io_context& io_context, const NodeConfig& myconf) {
  181. tcp::resolver resolver(io_context);
  182. tcp::acceptor async_acceptor(io_context,
  183. resolver.resolve(myconf.clistenhost, myconf.clistenport)->endpoint());
  184. tcp_connection::pointer new_connection =
  185. tcp_connection::create(io_context);
  186. async_acceptor.async_accept(new_connection->socket(),
  187. boost::bind(&handle_accept, io_context, myconf, new_connection,
  188. boost::asio::placeholders::error));
  189. }
  190. */
  191. NetIO::NetIO(boost::asio::io_context &io_context, const Config &config)
  192. : conf(config), myconf(config.nodes[config.my_node_num])
  193. {
  194. num_nodes = nodenum_t(conf.nodes.size());
  195. nodeios.resize(num_nodes);
  196. me = conf.my_node_num;
  197. // Node number n will accept connections from nodes 0, ..., n-1 and
  198. // make connections to nodes n+1, ..., num_nodes-1. This is all
  199. // single threaded, but it doesn't deadlock because node 0 isn't
  200. // waiting for any incoming connections, so it immediately makes
  201. // outgoing connections. When it connects to node 1, that node
  202. // accepts its (only) incoming connection, and then starts making
  203. // its outgoing connections, etc.
  204. tcp::resolver resolver(io_context);
  205. tcp::acceptor acceptor(io_context,
  206. resolver.resolve(myconf.listenhost, myconf.listenport)->endpoint());
  207. for(size_t i=0; i<me; ++i) {
  208. #ifdef VERBOSE_NET
  209. std::cerr << "Accepting number " << i << "\n";
  210. #endif
  211. tcp::socket nodesock = acceptor.accept();
  212. #ifdef VERBOSE_NET
  213. std::cerr << "Accepted number " << i << "\n";
  214. #endif
  215. // Read 2 bytes from the socket, which will be the
  216. // connecting node's node number
  217. unsigned short node_num;
  218. boost::asio::read(nodesock,
  219. boost::asio::buffer(&node_num, sizeof(node_num)));
  220. if (node_num >= num_nodes) {
  221. std::cerr << "Received bad node number\n";
  222. } else {
  223. nodeios[node_num].emplace(std::move(nodesock), node_num);
  224. #ifdef VERBOSE_NET
  225. std::cerr << "Received connection from " <<
  226. config.nodes[node_num].name << "\n";
  227. #endif
  228. }
  229. }
  230. for(size_t i=me+1; i<num_nodes; ++i) {
  231. boost::system::error_code err;
  232. tcp::socket nodesock(io_context);
  233. while(1) {
  234. #ifdef VERBOSE_NET
  235. std::cerr << "Connecting to " << config.nodes[i].name << "...\n";
  236. #endif
  237. boost::asio::connect(nodesock,
  238. resolver.resolve(config.nodes[i].listenhost,
  239. config.nodes[i].listenport), err);
  240. if (!err) break;
  241. std::cerr << "Connection to " << config.nodes[i].name <<
  242. " refused, will retry.\n";
  243. sleep(1);
  244. }
  245. // Write 2 bytes to the socket to tell the peer node our node
  246. // number
  247. nodenum_t node_num = (nodenum_t)me;
  248. boost::asio::write(nodesock,
  249. boost::asio::buffer(&node_num, sizeof(node_num)));
  250. nodeios[i].emplace(std::move(nodesock), i);
  251. #ifdef VERBOSE_NET
  252. std::cerr << "Connected to " << config.nodes[i].name << "\n";
  253. #endif
  254. }
  255. if(me==0) {
  256. tcp::acceptor async_acceptor(io_context,
  257. resolver.resolve(myconf.clistenhost, myconf.clistenport)->endpoint());
  258. std::shared_ptr<tcp::socket> new_socket(new tcp::socket(io_context));
  259. std::cout << myconf.clistenhost << ":" << myconf.clistenport;
  260. async_acceptor.async_accept(*new_socket, accept_handler);
  261. }
  262. /*
  263. if(me==0) {
  264. start_accept(io_context, myconf);
  265. }
  266. */
  267. }
  268. void NetIO::recv_commands(
  269. std::function<void(boost::system::error_code)> error_cb,
  270. std::function<void(uint32_t)> epoch_cb)
  271. {
  272. for (nodenum_t node_num = 0; node_num < num_nodes; ++node_num) {
  273. if (node_num == me) continue;
  274. NodeIO &n = node(node_num);
  275. n.recv_commands(error_cb, epoch_cb);
  276. }
  277. }
  278. void NetIO::close()
  279. {
  280. for (nodenum_t node_num = 0; node_num < num_nodes; ++node_num) {
  281. if (node_num == me) continue;
  282. NodeIO &n = node(node_num);
  283. n.close();
  284. }
  285. }
  286. /* The enclave calls this to inform the untrusted app that there's a new
  287. * messaage to send. The return value is the frame the enclave should
  288. * use to store the first (encrypted) chunk of this message. */
  289. uint8_t *ocall_message(nodenum_t node_num, uint32_t message_len)
  290. {
  291. assert(g_netio != NULL);
  292. NodeIO &node = g_netio->node(node_num);
  293. node.send_message_header(message_len);
  294. return node.request_frame();
  295. }
  296. /* The enclave calls this to inform the untrusted app that there's a new
  297. * chunk to send. The return value is the frame the enclave should use
  298. * to store the next (encrypted) chunk of this message, or NULL if this
  299. * was the last chunk. */
  300. uint8_t *ocall_chunk(nodenum_t node_num, uint8_t *chunkdata,
  301. uint32_t chunklen)
  302. {
  303. assert(g_netio != NULL);
  304. NodeIO &node = g_netio->node(node_num);
  305. bool morechunks = node.send_chunk(chunkdata, chunklen);
  306. if (morechunks) {
  307. return node.request_frame();
  308. }
  309. return NULL;
  310. }