net.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. NetIO::NetIO(boost::asio::io_context &io_context, const Config &config)
  158. : conf(config), myconf(config.nodes[config.my_node_num])
  159. {
  160. num_nodes = nodenum_t(conf.nodes.size());
  161. nodeios.resize(num_nodes);
  162. me = conf.my_node_num;
  163. // Node number n will accept connections from nodes 0, ..., n-1 and
  164. // make connections to nodes n+1, ..., num_nodes-1. This is all
  165. // single threaded, but it doesn't deadlock because node 0 isn't
  166. // waiting for any incoming connections, so it immediately makes
  167. // outgoing connections. When it connects to node 1, that node
  168. // accepts its (only) incoming connection, and then starts making
  169. // its outgoing connections, etc.
  170. tcp::resolver resolver(io_context);
  171. tcp::acceptor acceptor(io_context,
  172. resolver.resolve(myconf.listenhost, myconf.listenport)->endpoint());
  173. for(size_t i=0; i<me; ++i) {
  174. #ifdef VERBOSE_NET
  175. std::cerr << "Accepting number " << i << "\n";
  176. #endif
  177. tcp::socket nodesock = acceptor.accept();
  178. #ifdef VERBOSE_NET
  179. std::cerr << "Accepted number " << i << "\n";
  180. #endif
  181. // Read 2 bytes from the socket, which will be the
  182. // connecting node's node number
  183. unsigned short node_num;
  184. boost::asio::read(nodesock,
  185. boost::asio::buffer(&node_num, sizeof(node_num)));
  186. if (node_num >= num_nodes) {
  187. std::cerr << "Received bad node number\n";
  188. } else {
  189. nodeios[node_num].emplace(std::move(nodesock), node_num);
  190. #ifdef VERBOSE_NET
  191. std::cerr << "Received connection from " <<
  192. config.nodes[node_num].name << "\n";
  193. #endif
  194. }
  195. }
  196. for(size_t i=me+1; i<num_nodes; ++i) {
  197. boost::system::error_code err;
  198. tcp::socket nodesock(io_context);
  199. while(1) {
  200. #ifdef VERBOSE_NET
  201. std::cerr << "Connecting to " << config.nodes[i].name << "...\n";
  202. #endif
  203. boost::asio::connect(nodesock,
  204. resolver.resolve(config.nodes[i].listenhost,
  205. config.nodes[i].listenport), err);
  206. if (!err) break;
  207. std::cerr << "Connection to " << config.nodes[i].name <<
  208. " refused, will retry.\n";
  209. sleep(1);
  210. }
  211. // Write 2 bytes to the socket to tell the peer node our node
  212. // number
  213. nodenum_t node_num = (nodenum_t)me;
  214. boost::asio::write(nodesock,
  215. boost::asio::buffer(&node_num, sizeof(node_num)));
  216. nodeios[i].emplace(std::move(nodesock), i);
  217. #ifdef VERBOSE_NET
  218. std::cerr << "Connected to " << config.nodes[i].name << "\n";
  219. #endif
  220. }
  221. }
  222. /* The enclave calls this to inform the untrusted app that there's a new
  223. * messaage to send. The return value is the frame the enclave should
  224. * use to store the first (encrypted) chunk of this message. */
  225. uint8_t *ocall_message(nodenum_t node_num, uint32_t message_len)
  226. {
  227. assert(g_netio != NULL);
  228. NodeIO &node = g_netio->node(node_num);
  229. node.send_message_header(message_len);
  230. return node.request_frame();
  231. }
  232. /* The enclave calls this to inform the untrusted app that there's a new
  233. * chunk to send. The return value is the frame the enclave should use
  234. * to store the next (encrypted) chunk of this message, or NULL if this
  235. * was the last chunk. */
  236. uint8_t *ocall_chunk(nodenum_t node_num, uint8_t *chunkdata,
  237. uint32_t chunklen)
  238. {
  239. assert(g_netio != NULL);
  240. NodeIO &node = g_netio->node(node_num);
  241. bool morechunks = node.send_chunk(chunkdata, chunklen);
  242. if (morechunks) {
  243. return node.request_frame();
  244. }
  245. return NULL;
  246. }