NonBlockingUnixCommunicationSocket.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. /*
  2. * Copyright (C) 2011-2017 Intel Corporation. All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions
  6. * are met:
  7. *
  8. * * Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * * Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in
  12. * the documentation and/or other materials provided with the
  13. * distribution.
  14. * * Neither the name of Intel Corporation nor the names of its
  15. * contributors may be used to endorse or promote products derived
  16. * from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. *
  30. */
  31. #ifndef __STDC_LIMIT_MACROS
  32. #define __STDC_LIMIT_MACROS
  33. #endif
  34. #include <stdint.h>
  35. #include <NonBlockingUnixCommunicationSocket.h>
  36. #include <arch.h>
  37. #include <sys/types.h>
  38. #include <unistd.h>
  39. #include <fcntl.h>
  40. #include <stdio.h>
  41. #include <stdlib.h>
  42. #include <errno.h>
  43. #include <sys/epoll.h>
  44. #include <string.h>
  45. NonBlockingUnixCommunicationSocket::~NonBlockingUnixCommunicationSocket()
  46. {
  47. if (mEvents != NULL)
  48. delete [] mEvents;
  49. close(mEpoll);
  50. close(mCommandPipe[0]);
  51. close(mCommandPipe[1]);
  52. }
  53. se_static_assert(MAX_EVENTS<=UINT32_MAX/sizeof(struct epoll_event));
  54. bool NonBlockingUnixCommunicationSocket::init()
  55. {
  56. //create the epoll structure
  57. mEpoll = epoll_create(1);
  58. if (mEpoll < 0)
  59. return false;
  60. //create the command pipe
  61. int ret;
  62. ret = pipe(mCommandPipe);
  63. if (ret != 0)
  64. {
  65. close(mEpoll);
  66. return false;
  67. }
  68. //place one end of the pipe in the epoll list
  69. struct epoll_event event;
  70. event.data.fd = mCommandPipe[0];
  71. event.events = EPOLLIN | EPOLLET;
  72. int registerCommand = epoll_ctl (mEpoll, EPOLL_CTL_ADD, mCommandPipe[0], &event);
  73. //connect to the AESM - blocking connect
  74. bool connectInit = UnixCommunicationSocket::init();
  75. //register the event
  76. event.data.fd = mSocket;
  77. event.events = EPOLLET;
  78. int registerSocket = epoll_ctl (mEpoll, EPOLL_CTL_ADD, mSocket, &event);
  79. if (registerCommand != 0 || registerSocket != 0 || connectInit == false)
  80. {
  81. close(mEpoll);
  82. close(mCommandPipe[0]);
  83. close(mCommandPipe[1]);
  84. return false;
  85. }
  86. //create events buffer
  87. mEvents = new struct epoll_event[MAX_EVENTS];
  88. memset((char*)mEvents, 0, MAX_EVENTS * sizeof(struct epoll_event));
  89. return MakeNonBlocking();
  90. }
  91. char* NonBlockingUnixCommunicationSocket::readRaw(ssize_t length)
  92. {
  93. if (mSocket == -1)
  94. return NULL;
  95. // Add read event
  96. struct epoll_event event;
  97. event.data.fd = mSocket;
  98. event.events = EPOLLIN | EPOLLET;
  99. int registerSocket = epoll_ctl (mEpoll, EPOLL_CTL_MOD, mSocket, &event);
  100. if (registerSocket != 0)
  101. {
  102. return NULL;
  103. }
  104. ssize_t total_read = 0;
  105. ssize_t step = 0;
  106. char * recBuf = NULL;
  107. recBuf = new char[length];
  108. memset(recBuf, 0, length);
  109. int32_t epollTimeout = (mTimeoutMseconds > 0 ? mTimeoutMseconds : -1);
  110. int eventNum = 0;
  111. int i = 0;
  112. bool errorDetected = false;
  113. bool cancellationDetected = false;
  114. bool peerSocketClosed = false;
  115. MarkStartTime();
  116. do{
  117. //try a direct read (maybe all data is available already)
  118. step = read(mSocket, recBuf, length);
  119. if (step == -1 && errno != EAGAIN)
  120. {
  121. errorDetected = true;
  122. }
  123. else
  124. {
  125. if (step != -1)
  126. {
  127. total_read += step;
  128. }
  129. if (total_read == length)
  130. {
  131. break; //we are finished here
  132. }
  133. }
  134. //wait for events
  135. eventNum = epoll_wait(mEpoll, mEvents, MAX_EVENTS, epollTimeout);
  136. if (eventNum == -1)
  137. {
  138. errorDetected = true;
  139. }
  140. for (i = 0;
  141. CheckForTimeout() == false && //need to be sure to check this first
  142. errorDetected == false &&
  143. cancellationDetected == false &&
  144. peerSocketClosed == false &&
  145. i < eventNum;
  146. i++)
  147. {
  148. if (mEvents[i].events & EPOLLHUP)
  149. {
  150. peerSocketClosed = true;
  151. //peer closed socket. one more reading all remaining data.
  152. }
  153. if ((mEvents[i].events & EPOLLERR) ||
  154. (!(mEvents[i].events & EPOLLIN)))
  155. {
  156. //error
  157. errorDetected = true;
  158. }
  159. else
  160. {
  161. if (mEvents[i].data.fd == mCommandPipe[0])
  162. {
  163. //cancellation -- in the case this logic would complicate by needing more commands, we will detach this into
  164. //a CommandManager of some sort
  165. cancellationDetected = true;
  166. }
  167. else
  168. {
  169. //read data
  170. step = partialRead(recBuf + total_read, length - total_read);
  171. if (step == -1)
  172. {
  173. errorDetected = true;
  174. }
  175. if (step == 0) //peer closed socket
  176. {
  177. //did this happen before getting the entire data ?
  178. if (total_read != length)
  179. errorDetected = true;
  180. }
  181. total_read += step;
  182. }
  183. }
  184. }
  185. if (total_read != length)
  186. {
  187. if (errorDetected || cancellationDetected || wasTimeoutDetected())
  188. {
  189. disconnect();
  190. delete [] recBuf;
  191. recBuf = NULL;
  192. break;
  193. }
  194. }
  195. //clear events
  196. memset((char*)mEvents, 0, MAX_EVENTS * sizeof(struct epoll_event));
  197. }while (total_read < length);
  198. event.data.fd = mSocket;
  199. event.events = EPOLLET;
  200. registerSocket = epoll_ctl (mEpoll, EPOLL_CTL_MOD, mSocket, &event);
  201. if (registerSocket != 0)
  202. {
  203. disconnect();
  204. if (NULL != recBuf)
  205. delete [] recBuf;
  206. return NULL;
  207. }
  208. return recBuf;
  209. }
  210. /**
  211. * Read no more than maxLength bytes
  212. */
  213. ssize_t NonBlockingUnixCommunicationSocket::partialRead(char* buffer, ssize_t maxLength)
  214. {
  215. ssize_t step = 0;
  216. ssize_t chunkSize = (maxLength < 512 ? maxLength : 512);
  217. ssize_t totalRead = 0;
  218. ssize_t remaining = maxLength;
  219. while (totalRead < maxLength)
  220. {
  221. remaining = maxLength - totalRead;
  222. step = read(mSocket, buffer + totalRead, (remaining > chunkSize ? chunkSize : remaining));
  223. if (step == -1)
  224. {
  225. if (errno != EAGAIN)
  226. return -1;
  227. break;
  228. }
  229. totalRead += step;
  230. if (step == 0)
  231. break;
  232. }
  233. return totalRead;
  234. }
  235. ssize_t NonBlockingUnixCommunicationSocket::writeRaw(const char* data, ssize_t length)
  236. {
  237. if (mSocket == -1)
  238. return -1;
  239. ssize_t total_write = 0;
  240. ssize_t step = 0;
  241. int32_t epollTimeout = (mTimeoutMseconds > 0 ? mTimeoutMseconds : -1);
  242. int eventNum = 0;
  243. int i = 0;
  244. bool errorDetected = false;
  245. bool cancellationDetected = false;
  246. bool peerSocketClosed = false;
  247. bool lastWriteSuccessful = false;
  248. struct epoll_event event;
  249. int registerSocket;
  250. MarkStartTime();
  251. do
  252. {
  253. step = write(mSocket, data + total_write, length - total_write);
  254. if (step == -1 && errno != EAGAIN)
  255. {
  256. // an error occured
  257. errorDetected = true;
  258. }
  259. else
  260. {
  261. if (step == -1 && errno == EAGAIN)
  262. {
  263. // the internal buffer is full
  264. // EPOLLOUT is added so that an event is generated when there is
  265. // empty space in the buffer
  266. lastWriteSuccessful = false;
  267. event.data.fd = mSocket;
  268. event.events = EPOLLET | EPOLLOUT;
  269. registerSocket = epoll_ctl (mEpoll, EPOLL_CTL_MOD, mSocket, &event);
  270. if (registerSocket != 0)
  271. {
  272. return -1;
  273. }
  274. }
  275. else
  276. {
  277. // the write was successful
  278. if (!lastWriteSuccessful)
  279. {
  280. // remove EPOLLOUT
  281. lastWriteSuccessful = true;
  282. event.data.fd = mSocket;
  283. event.events = EPOLLET;
  284. registerSocket = epoll_ctl (mEpoll, EPOLL_CTL_MOD, mSocket, &event);
  285. if (registerSocket != 0)
  286. {
  287. return -1;
  288. }
  289. }
  290. total_write += step;
  291. if (total_write == length)
  292. {
  293. break;
  294. }
  295. continue;
  296. }
  297. }
  298. eventNum = epoll_wait(mEpoll, mEvents, MAX_EVENTS, epollTimeout);
  299. if (eventNum == -1)
  300. {
  301. errorDetected = true;
  302. }
  303. for (i = 0;
  304. CheckForTimeout() == false &&
  305. errorDetected == false &&
  306. cancellationDetected == false &&
  307. peerSocketClosed == false &&
  308. i < eventNum;
  309. i++)
  310. {
  311. if (mEvents[i].events & EPOLLHUP)
  312. {
  313. // the socket or that pipe have been closed
  314. peerSocketClosed = true;
  315. continue;
  316. }
  317. if ((mEvents[i].events & EPOLLERR) ||
  318. (!(mEvents[i].events & EPOLLOUT)))
  319. {
  320. // received an event other than EPOLLOUT
  321. errorDetected = true;
  322. }
  323. else
  324. {
  325. if (mEvents[i].data.fd == mCommandPipe[0])
  326. {
  327. cancellationDetected = true;
  328. }
  329. }
  330. }
  331. if (errorDetected || cancellationDetected || wasTimeoutDetected() || peerSocketClosed)
  332. {
  333. disconnect();
  334. break;
  335. }
  336. memset((char*)mEvents, 0, MAX_EVENTS * sizeof(struct epoll_event));
  337. }
  338. while(total_write < length);
  339. event.data.fd = mSocket;
  340. event.events = EPOLLET;
  341. registerSocket = epoll_ctl (mEpoll, EPOLL_CTL_MOD, mSocket, &event);
  342. if (registerSocket != 0)
  343. {
  344. return -1;
  345. }
  346. return total_write;
  347. }
  348. int NonBlockingUnixCommunicationSocket::getSockDescriptor()
  349. {
  350. return UnixCommunicationSocket::getSockDescriptor();
  351. }
  352. bool NonBlockingUnixCommunicationSocket::wasTimeoutDetected()
  353. {
  354. return UnixCommunicationSocket::wasTimeoutDetected();
  355. }
  356. bool NonBlockingUnixCommunicationSocket::setTimeout(uint32_t milliseconds)
  357. {
  358. mTimeoutMseconds = milliseconds;
  359. return true;
  360. }
  361. bool NonBlockingUnixCommunicationSocket::MakeNonBlocking()
  362. {
  363. int flags, ret;
  364. flags = fcntl (mSocket, F_GETFL, 0);
  365. if (flags == -1)
  366. {
  367. return false;
  368. }
  369. flags |= (int)O_NONBLOCK;
  370. ret = fcntl (mSocket, F_SETFL, flags);
  371. if (ret == -1)
  372. {
  373. return false;
  374. }
  375. return true;
  376. }
  377. void NonBlockingUnixCommunicationSocket::Cancel() const
  378. {
  379. //write anything on the pipe
  380. char cmd = '1';
  381. if (write(mCommandPipe[0],&cmd,1) < 0)
  382. {
  383. // do nothing
  384. }
  385. }