Pipe.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. #include "util/events/libuv/UvWrapper.h"
  16. #include "memory/Allocator.h"
  17. #include "util/events/Pipe.h"
  18. #include "util/events/libuv/EventBase_pvt.h"
  19. #include "util/log/Log.h"
  20. #include "util/Identity.h"
  21. #include "util/CString.h"
  22. #include "wire/Message.h"
  23. #include "wire/Error.h"
  24. #include <inttypes.h>
  25. #include <stdio.h>
  26. struct Pipe_WriteRequest_pvt;
  27. struct Pipe_pvt
  28. {
  29. struct Pipe pub;
  30. uv_pipe_t server;
  31. uv_pipe_t peer;
  32. /** Job to close the handles when the allocator is freed */
  33. struct Allocator_OnFreeJob* closeHandlesOnFree;
  34. /** Job which blocks the freeing until the callback completes */
  35. struct Allocator_OnFreeJob* blockFreeInsideCallback;
  36. /**
  37. * If the output pipe is same as the input, this points to peer.
  38. * Otherwise it points to server which is reused.
  39. */
  40. uv_pipe_t* out;
  41. /** 1 when the pipe becomes active. */
  42. int isActive;
  43. int queueLen;
  44. /** Used by blockFreeInsideCallback */
  45. int isInCallback;
  46. /** only non-null before the connection is setup. */
  47. struct Pipe_WriteRequest_pvt* bufferedRequest;
  48. struct Allocator* alloc;
  49. Identity
  50. };
  51. struct Pipe_WriteRequest_pvt {
  52. uv_write_t uvReq;
  53. struct Pipe_pvt* pipe;
  54. struct Message* msg;
  55. struct Allocator* alloc;
  56. Identity
  57. };
  58. static void sendMessageCallback(uv_write_t* uvReq, int error)
  59. {
  60. struct Pipe_WriteRequest_pvt* req = Identity_check((struct Pipe_WriteRequest_pvt*) uvReq);
  61. if (error) {
  62. Log_info(req->pipe->pub.logger, "Failed to write to pipe [%s] [%s]",
  63. req->pipe->pub.fullName, uv_strerror(error) );
  64. }
  65. req->pipe->queueLen -= req->msg->length;
  66. Assert_ifParanoid(req->pipe->queueLen >= 0);
  67. Allocator_free(req->alloc);
  68. }
  69. static uint8_t sendMessage2(struct Pipe_WriteRequest_pvt* req)
  70. {
  71. struct Pipe_pvt* pipe = req->pipe;
  72. struct Message* m = req->msg;
  73. uv_buf_t buffers[] = {
  74. { .base = (char*)m->bytes, .len = m->length }
  75. };
  76. int ret = uv_write(&req->uvReq, (uv_stream_t*) pipe->out, buffers, 1, sendMessageCallback);
  77. if (ret) {
  78. Log_info(pipe->pub.logger, "Failed writing to pipe [%s] [%s]",
  79. pipe->pub.fullName, uv_strerror(ret) );
  80. Allocator_free(req->alloc);
  81. return Error_UNDELIVERABLE;
  82. }
  83. pipe->queueLen += m->length;
  84. return Error_NONE;
  85. }
  86. static Iface_DEFUN sendMessage(struct Message* m, struct Iface* iface)
  87. {
  88. struct Pipe_pvt* pipe = Identity_check((struct Pipe_pvt*) iface);
  89. if (pipe->queueLen > 50000) {
  90. return 0;
  91. }
  92. // This allocator will hold the message allocator in existance after it is freed.
  93. struct Allocator* reqAlloc = Allocator_child(pipe->alloc);
  94. if (m->alloc) {
  95. Allocator_adopt(reqAlloc, m->alloc);
  96. } else {
  97. m = Message_clone(m, reqAlloc);
  98. }
  99. struct Pipe_WriteRequest_pvt* req =
  100. Allocator_clone(reqAlloc, (&(struct Pipe_WriteRequest_pvt) {
  101. .pipe = pipe,
  102. .msg = m,
  103. .alloc = reqAlloc
  104. }));
  105. Identity_set(req);
  106. if (pipe->isActive) {
  107. sendMessage2(req);
  108. } else {
  109. if (!pipe->bufferedRequest) {
  110. Log_debug(pipe->pub.logger, "Buffering a message");
  111. pipe->bufferedRequest = req;
  112. } else {
  113. Log_debug(pipe->pub.logger, "Appending to the buffered message");
  114. uint8_t* buff =
  115. Allocator_malloc(reqAlloc, m->length + pipe->bufferedRequest->msg->length);
  116. Bits_memcpy(buff,
  117. pipe->bufferedRequest->msg->bytes,
  118. pipe->bufferedRequest->msg->length);
  119. Bits_memcpy(buff+pipe->bufferedRequest->msg->length, m->bytes, m->length);
  120. m->length += pipe->bufferedRequest->msg->length;
  121. m->capacity = m->length;
  122. m->bytes = buff;
  123. Allocator_free(pipe->bufferedRequest->alloc);
  124. pipe->bufferedRequest = req;
  125. }
  126. }
  127. return Error_NONE;
  128. }
  129. /** Asynchronous allocator freeing. */
  130. static void onClose(uv_handle_t* handle)
  131. {
  132. struct Pipe_pvt* pipe = Identity_check((struct Pipe_pvt*)handle->data);
  133. handle->data = NULL;
  134. if (pipe->closeHandlesOnFree && !pipe->server.data && !pipe->peer.data) {
  135. Allocator_onFreeComplete((struct Allocator_OnFreeJob*) pipe->closeHandlesOnFree);
  136. }
  137. }
  138. #if Pipe_PADDING_AMOUNT < 8
  139. #error
  140. #endif
  141. #define ALLOC(buff) (((struct Allocator**) &(buff[-(8 + (((uintptr_t)buff) % 8))]))[0])
  142. static void incoming(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf)
  143. {
  144. struct Pipe_pvt* pipe = Identity_check((struct Pipe_pvt*) stream->data);
  145. // Grab out the allocator which was placed there by allocate()
  146. struct Allocator* alloc = buf->base ? ALLOC(buf->base) : NULL;
  147. pipe->isInCallback = 1;
  148. Assert_true(!alloc || alloc->fileName == pipe->alloc->fileName);
  149. if (nread < 0) {
  150. if (pipe->pub.onClose) {
  151. pipe->pub.onClose(&pipe->pub, 0);
  152. }
  153. uv_close((uv_handle_t*) stream, onClose);
  154. } else if (nread == 0) {
  155. // This is common.
  156. //Log_debug(pipe->pub.logger, "Pipe 0 length read [%s]", pipe->pub.fullName);
  157. } else {
  158. Assert_true(alloc);
  159. struct Message* m = Allocator_calloc(alloc, sizeof(struct Message), 1);
  160. m->length = nread;
  161. m->padding = Pipe_PADDING_AMOUNT;
  162. m->capacity = buf->len;
  163. m->bytes = (uint8_t*)buf->base;
  164. m->alloc = alloc;
  165. Iface_send(&pipe->pub.iface, m);
  166. }
  167. if (alloc) {
  168. Allocator_free(alloc);
  169. }
  170. pipe->isInCallback = 0;
  171. if (pipe->blockFreeInsideCallback) {
  172. Allocator_onFreeComplete((struct Allocator_OnFreeJob*) pipe->blockFreeInsideCallback);
  173. }
  174. }
  175. static void allocate(uv_handle_t* handle, size_t size, uv_buf_t* buf)
  176. {
  177. struct Pipe_pvt* pipe = Identity_check((struct Pipe_pvt*) handle->data);
  178. size = Pipe_BUFFER_CAP;
  179. size_t fullSize = size + Pipe_PADDING_AMOUNT;
  180. struct Allocator* child = Allocator_child(pipe->alloc);
  181. char* buff = Allocator_malloc(child, fullSize);
  182. buff += Pipe_PADDING_AMOUNT;
  183. ALLOC(buff) = child;
  184. buf->base = buff;
  185. buf->len = size;
  186. }
  187. static void connected(uv_connect_t* req, int status)
  188. {
  189. uv_stream_t* link = req->handle;
  190. struct Pipe_pvt* pipe = Identity_check((struct Pipe_pvt*) link->data);
  191. Log_debug(pipe->pub.logger, "Pipe [%s] established connection", pipe->pub.fullName);
  192. int ret;
  193. if (status) {
  194. Log_info(pipe->pub.logger, "uv_pipe_connect() failed for pipe [%s] [%s]",
  195. pipe->pub.fullName, uv_strerror(status) );
  196. uv_close((uv_handle_t*) &pipe->peer, onClose);
  197. } else if ((ret = uv_read_start((uv_stream_t*)&pipe->peer, allocate, incoming))) {
  198. Log_info(pipe->pub.logger, "uv_read_start() failed for pipe [%s] [%s]",
  199. pipe->pub.fullName, uv_strerror(ret));
  200. uv_close((uv_handle_t*) &pipe->peer, onClose);
  201. } else {
  202. pipe->isActive = 1;
  203. if (pipe->pub.onConnection) {
  204. pipe->pub.onConnection(&pipe->pub, status);
  205. }
  206. // If there's anything buffered then send it.
  207. if (pipe->bufferedRequest) {
  208. Log_debug(pipe->pub.logger, "Sending buffered message");
  209. sendMessage2(pipe->bufferedRequest);
  210. pipe->bufferedRequest = NULL;
  211. }
  212. }
  213. }
  214. static void listenCallback(uv_stream_t* server, int status)
  215. {
  216. struct Pipe_pvt* pipe = Identity_check((struct Pipe_pvt*) server->data);
  217. if (pipe->isActive) {
  218. // first connection wins.
  219. return;
  220. }
  221. if (status == -1) {
  222. Log_info(pipe->pub.logger, "failed to accept pipe connection [%s] [%s]",
  223. pipe->pub.fullName, uv_strerror(status) );
  224. if (pipe->pub.onConnection) {
  225. pipe->pub.onConnection(&pipe->pub, status);
  226. }
  227. return;
  228. }
  229. int ret = uv_accept(server, (uv_stream_t*) &pipe->peer);
  230. if (ret) {
  231. Log_warn(pipe->pub.logger, "uv_accept() failed: pipe [%s] [%s]",
  232. pipe->pub.fullName, uv_strerror(ret) );
  233. if (pipe->pub.onConnection) {
  234. pipe->pub.onConnection(&pipe->pub, -1);
  235. }
  236. uv_close((uv_handle_t*) &pipe->peer, onClose);
  237. } else {
  238. uv_connect_t req = { .handle = (uv_stream_t*) &pipe->peer };
  239. connected(&req, 0);
  240. }
  241. uv_close((uv_handle_t*) &pipe->server, onClose);
  242. #ifndef win32
  243. // get rid of the pipe after it has been connected.
  244. uv_fs_t req;
  245. uv_fs_unlink(pipe->peer.loop, &req, pipe->pub.fullName, NULL);
  246. #endif
  247. }
  248. static int blockFreeInsideCallback(struct Allocator_OnFreeJob* job)
  249. {
  250. struct Pipe_pvt* pipe = Identity_check((struct Pipe_pvt*)job->userData);
  251. if (!pipe->isInCallback) {
  252. return 0;
  253. }
  254. pipe->blockFreeInsideCallback = job;
  255. return Allocator_ONFREE_ASYNC;
  256. }
  257. static int closeHandlesOnFree(struct Allocator_OnFreeJob* job)
  258. {
  259. struct Pipe_pvt* pipe = Identity_check((struct Pipe_pvt*)job->userData);
  260. pipe->closeHandlesOnFree = job;
  261. int skip = 2;
  262. if (pipe->server.data) {
  263. uv_close((uv_handle_t*) &pipe->server, onClose);
  264. skip--;
  265. }
  266. if (pipe->peer.data) {
  267. uv_close((uv_handle_t*) &pipe->peer, onClose);
  268. skip--;
  269. }
  270. if (skip == 2) {
  271. return 0;
  272. }
  273. return Allocator_ONFREE_ASYNC;
  274. }
  275. static struct Pipe_pvt* newPipe(struct EventBase* eb,
  276. const char* name,
  277. struct Except* eh,
  278. struct Allocator* userAlloc)
  279. {
  280. struct EventBase_pvt* ctx = EventBase_privatize(eb);
  281. struct Allocator* alloc = Allocator_child(userAlloc);
  282. char* cname = Allocator_malloc(alloc, CString_strlen(Pipe_PREFIX)+CString_strlen(name)+1);
  283. Bits_memcpy(cname, Pipe_PREFIX, CString_strlen(Pipe_PREFIX));
  284. Bits_memcpy(cname+CString_strlen(Pipe_PREFIX), name, CString_strlen(name)+1);
  285. struct Pipe_pvt* out = Allocator_clone(alloc, (&(struct Pipe_pvt) {
  286. .pub = {
  287. .iface = {
  288. .send = sendMessage
  289. },
  290. .fullName = cname,
  291. .name = &cname[sizeof(Pipe_PREFIX) - 1],
  292. .base = eb
  293. },
  294. .alloc = alloc
  295. }));
  296. int ret;
  297. ret = uv_pipe_init(ctx->loop, &out->peer, 0);
  298. if (ret) {
  299. Except_throw(eh, "uv_pipe_init() failed [%s]", uv_strerror(ret));
  300. }
  301. ret = uv_pipe_init(ctx->loop, &out->server, 0);
  302. if (ret) {
  303. Except_throw(eh, "uv_pipe_init() failed [%s]", uv_strerror(ret));
  304. }
  305. #ifdef win32
  306. out->pub.fd = &out->peer.handle;
  307. #else
  308. out->pub.fd = &out->peer.io_watcher.fd;
  309. #endif
  310. Allocator_onFree(alloc, closeHandlesOnFree, out);
  311. Allocator_onFree(alloc, blockFreeInsideCallback, out);
  312. out->peer.data = out;
  313. out->server.data = out;
  314. out->out = &out->peer;
  315. Identity_set(out);
  316. return out;
  317. }
  318. struct Pipe* Pipe_forFiles(int inFd,
  319. int outFd,
  320. struct EventBase* eb,
  321. struct Except* eh,
  322. struct Allocator* userAlloc)
  323. {
  324. char buff[32] = {0};
  325. snprintf(buff, 31, "forFiles(%d,%d)", inFd, outFd);
  326. struct Pipe_pvt* out = newPipe(eb, buff, eh, userAlloc);
  327. int ret = uv_pipe_open(&out->peer, inFd);
  328. if (ret) {
  329. Except_throw(eh, "uv_pipe_open(inFd) failed [%s]",
  330. uv_strerror(ret));
  331. }
  332. if (inFd != outFd) {
  333. out->out = &out->server;
  334. ret = uv_pipe_open(out->out, outFd);
  335. if (ret) {
  336. Except_throw(eh, "uv_pipe_open(outFd) failed [%s]",
  337. uv_strerror(ret));
  338. }
  339. }
  340. uv_connect_t req = { .handle = (uv_stream_t*) &out->peer };
  341. connected(&req, 0);
  342. return &out->pub;
  343. }
  344. struct Pipe* Pipe_named(const char* name,
  345. struct EventBase* eb,
  346. struct Except* eh,
  347. struct Allocator* userAlloc)
  348. {
  349. struct Pipe_pvt* out = newPipe(eb, name, eh, userAlloc);
  350. int ret;
  351. // Attempt to create pipe.
  352. ret = uv_pipe_bind(&out->server, out->pub.fullName);
  353. if (!ret) {
  354. ret = uv_listen((uv_stream_t*) &out->server, 1, listenCallback);
  355. if (ret) {
  356. Except_throw(eh, "uv_listen() failed [%s] for pipe [%s]",
  357. uv_strerror(ret), out->pub.fullName);
  358. }
  359. return &out->pub;
  360. }
  361. if (ret == UV_EADDRINUSE) {
  362. // Pipe exists, connect to it.
  363. uv_connect_t* req = Allocator_malloc(out->alloc, sizeof(uv_connect_t));
  364. req->data = out;
  365. uv_pipe_connect(req, &out->peer, out->pub.fullName, connected);
  366. return &out->pub;
  367. }
  368. Except_throw(eh, "uv_pipe_bind() failed [%s] for pipe [%s]",
  369. uv_strerror(ret), out->pub.fullName);
  370. return &out->pub;
  371. }