client.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. /* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
  2. *
  3. * Data Differential YATL (i.e. libtest) library
  4. *
  5. * Copyright (C) 2012 Data Differential, http://datadifferential.com/
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are
  9. * met:
  10. *
  11. * * Redistributions of source code must retain the above copyright
  12. * notice, this list of conditions and the following disclaimer.
  13. *
  14. * * Redistributions in binary form must reproduce the above
  15. * copyright notice, this list of conditions and the following disclaimer
  16. * in the documentation and/or other materials provided with the
  17. * distribution.
  18. *
  19. * * The names of its contributors may not be used to endorse or
  20. * promote products derived from this software without specific prior
  21. * written permission.
  22. *
  23. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  24. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  25. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  26. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  27. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  28. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  29. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  30. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  31. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  32. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  33. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  34. *
  35. */
  36. #include "libtest/yatlcon.h"
  37. #include <libtest/common.h>
  38. #include <sys/types.h>
  39. #include <sys/socket.h>
  40. #include <unistd.h>
  41. #include <string>
  42. #ifdef HAVE_POLL_H
  43. # include <poll.h>
  44. #endif
  45. #ifndef HAVE_MSG_NOSIGNAL
  46. # define MSG_NOSIGNAL 0
  47. #endif
  48. namespace libtest {
  49. SimpleClient::SimpleClient(const std::string& hostname_, in_port_t port_) :
  50. _is_connected(false),
  51. _is_ssl(false),
  52. _hostname(hostname_),
  53. _port(port_),
  54. sock_fd(INVALID_SOCKET),
  55. _error_file(NULL),
  56. _error_line(0),
  57. requested_message(1),
  58. _ctx_ssl(NULL),
  59. _ssl(NULL),
  60. _ai{nullptr}
  61. {
  62. if (is_ssl())
  63. {
  64. _is_ssl= true;
  65. }
  66. init_ssl();
  67. }
  68. void SimpleClient::init_ssl()
  69. {
  70. if (_is_ssl)
  71. {
  72. #if defined(HAVE_SSL) && HAVE_SSL
  73. SSL_load_error_strings();
  74. SSL_library_init();
  75. #if (OPENSSL_VERSION_NUMBER < 0x10100000L)
  76. if ((_ctx_ssl= SSL_CTX_new(TLSv1_2_client_method())) == NULL)
  77. #else
  78. if ((_ctx_ssl= SSL_CTX_new(TLS_client_method())) == NULL)
  79. #endif
  80. {
  81. FATAL("SSL_CTX_new error" == NULL);
  82. }
  83. if (SSL_CTX_load_verify_locations(_ctx_ssl, YATL_CA_CERT_PEM, 0) != SSL_SUCCESS)
  84. {
  85. FATAL("SSL_CTX_load_verify_locations(%s) cannot obtain certificate", YATL_CA_CERT_PEM);
  86. }
  87. if (SSL_CTX_use_certificate_file(_ctx_ssl, YATL_CERT_PEM, SSL_FILETYPE_PEM) != SSL_SUCCESS)
  88. {
  89. FATAL("SSL_CTX_use_certificate_file(%s) cannot obtain certificate", YATL_CERT_PEM);
  90. }
  91. if (SSL_CTX_use_PrivateKey_file(_ctx_ssl, YATL_CERT_KEY_PEM, SSL_FILETYPE_PEM) != SSL_SUCCESS)
  92. {
  93. FATAL("SSL_CTX_use_PrivateKey_file(%s) cannot obtain certificate", YATL_CERT_KEY_PEM);
  94. }
  95. #endif // defined(HAVE_SSL) && HAVE_SSL
  96. }
  97. }
  98. void SimpleClient::error(const char* file_, int line_, const std::string& error_)
  99. {
  100. _error.clear();
  101. _error_file= file_;
  102. _error_line= line_;
  103. vchar_t buffer;
  104. buffer.resize(1024);
  105. snprintf(&buffer[0], buffer.size() -1, "%s:%d: %s", file_, line_, error_.c_str());
  106. _error.append(&buffer[0]);
  107. }
  108. bool SimpleClient::ready(int event_)
  109. {
  110. struct pollfd fds[1];
  111. fds[0].fd= sock_fd;
  112. fds[0].events= event_;
  113. fds[0].revents= 0;
  114. int timeout= 5000;
  115. if (_is_connected == false)
  116. {
  117. timeout= timeout * 30;
  118. }
  119. int ready_fds= poll(fds, 1, timeout);
  120. if (ready_fds == -1)
  121. {
  122. error(__FILE__, __LINE__, strerror(errno));
  123. return false;
  124. }
  125. else if (ready_fds == 1)
  126. {
  127. if (fds[0].revents & (POLLERR | POLLHUP | POLLNVAL))
  128. {
  129. int err;
  130. socklen_t len= sizeof (err);
  131. // We replace errno with err if getsockopt() passes, but err has been
  132. // set.
  133. if (getsockopt(fds[0].fd, SOL_SOCKET, SO_ERROR, &err, &len) == 0)
  134. {
  135. // We check the value to see what happened wth the socket.
  136. if (err == 0)
  137. {
  138. error(__FILE__, __LINE__, "getsockopt() returned no error but poll() indicated one existed");
  139. return false;
  140. }
  141. errno= err;
  142. }
  143. error(__FILE__, __LINE__, strerror(errno));
  144. return false;
  145. }
  146. _is_connected= true;
  147. if (fds[0].revents & event_)
  148. {
  149. return true;
  150. }
  151. }
  152. fatal_assert(ready_fds == 0);
  153. error(__FILE__, __LINE__, "TIMEOUT");
  154. return false;
  155. }
  156. struct addrinfo* SimpleClient::lookup()
  157. {
  158. struct addrinfo hints;
  159. memset(&hints, 0, sizeof(struct addrinfo));
  160. hints.ai_socktype= SOCK_STREAM;
  161. hints.ai_protocol= IPPROTO_TCP;
  162. libtest::vchar_t service;
  163. service.resize(NI_MAXSERV);
  164. (void)snprintf(&service[0], service.size(), "%d", _port);
  165. int getaddrinfo_error;
  166. if ((getaddrinfo_error= getaddrinfo(_hostname.c_str(), &service[0], &hints, &_ai)) != 0)
  167. {
  168. if (getaddrinfo_error != EAI_SYSTEM)
  169. {
  170. error(__FILE__, __LINE__, gai_strerror(getaddrinfo_error));
  171. return NULL;
  172. }
  173. else
  174. {
  175. error(__FILE__, __LINE__, strerror(getaddrinfo_error));
  176. return NULL;
  177. }
  178. }
  179. return _ai;
  180. }
  181. SimpleClient::~SimpleClient()
  182. {
  183. free_addrinfo();
  184. close_socket();
  185. #if defined(HAVE_SSL) && HAVE_SSL
  186. {
  187. if (_ctx_ssl)
  188. {
  189. SSL_CTX_free(_ctx_ssl);
  190. _ctx_ssl= NULL;
  191. }
  192. # if defined(HAVE_OPENSSL) && HAVE_OPENSSL
  193. ERR_free_strings();
  194. # endif
  195. }
  196. #endif
  197. }
  198. void SimpleClient::close_socket()
  199. {
  200. if (sock_fd != INVALID_SOCKET)
  201. {
  202. #if defined(HAVE_SSL) && HAVE_SSL
  203. if (_ssl)
  204. {
  205. SSL_shutdown(_ssl);
  206. SSL_free(_ssl);
  207. _ssl= NULL;
  208. }
  209. #endif // defined(HAVE_SSL)
  210. close(sock_fd);
  211. sock_fd= INVALID_SOCKET;
  212. }
  213. }
  214. bool SimpleClient::instance_connect()
  215. {
  216. _is_connected= false;
  217. if (lookup())
  218. {
  219. {
  220. struct addrinfo* address_info_next= _ai;
  221. while (address_info_next and sock_fd == INVALID_SOCKET)
  222. {
  223. if ((sock_fd= socket(address_info_next->ai_family, address_info_next->ai_socktype, address_info_next->ai_protocol)) != SOCKET_ERROR)
  224. {
  225. if (connect(sock_fd, address_info_next->ai_addr, address_info_next->ai_addrlen) == SOCKET_ERROR)
  226. {
  227. switch (errno)
  228. {
  229. case EINTR:
  230. close_socket();
  231. continue;
  232. case EINPROGRESS: // nonblocking mode - first return
  233. case EALREADY: // nonblocking mode - subsequent returns
  234. continue; // Jump to while() and continue on
  235. case ECONNREFUSED:
  236. default:
  237. break;
  238. }
  239. close_socket();
  240. error(__FILE__, __LINE__, strerror(errno));
  241. }
  242. else
  243. {
  244. return true;
  245. }
  246. }
  247. else
  248. {
  249. FATAL(strerror(errno));
  250. }
  251. address_info_next= address_info_next->ai_next;
  252. }
  253. free_addrinfo();
  254. }
  255. if (sock_fd == INVALID_SOCKET)
  256. {
  257. fatal_assert(is_error());
  258. }
  259. return bool(sock_fd != INVALID_SOCKET);
  260. }
  261. return false;
  262. }
  263. bool SimpleClient::is_valid()
  264. {
  265. _error.clear();
  266. if (sock_fd == INVALID_SOCKET)
  267. {
  268. if (instance_connect())
  269. {
  270. #if defined(HAVE_SSL) && HAVE_SSL
  271. if (_ctx_ssl)
  272. {
  273. _ssl= SSL_new(_ctx_ssl);
  274. if (_ssl == NULL)
  275. {
  276. error(__FILE__, __LINE__, "SSL_new failed");
  277. return false;
  278. }
  279. int ssl_error;
  280. if ((ssl_error= SSL_set_fd(_ssl, sock_fd)) != SSL_SUCCESS)
  281. {
  282. error(__FILE__, __LINE__, "SSL_set_fd() should not be returning an error.");
  283. return false;
  284. }
  285. }
  286. #endif
  287. return true;
  288. }
  289. return false;
  290. }
  291. return true;
  292. }
  293. #if __GNUC__ >= 7
  294. #pragma GCC diagnostic warning "-Wimplicit-fallthrough"
  295. #endif
  296. bool SimpleClient::message(const char* ptr, const size_t len)
  297. {
  298. if (is_valid())
  299. {
  300. if (ready(POLLOUT))
  301. {
  302. off_t offset= 0;
  303. do
  304. {
  305. ssize_t write_size;
  306. #if defined(HAVE_SSL) && HAVE_SSL
  307. if (_ssl)
  308. {
  309. int ssl_error;
  310. int write_size_int= SSL_write(_ssl, (const void*)(ptr +offset), int(len -offset));
  311. write_size= write_size_int;
  312. switch (ssl_error= SSL_get_error(_ssl, write_size_int))
  313. {
  314. case SSL_ERROR_NONE:
  315. break;
  316. case SSL_ERROR_ZERO_RETURN:
  317. errno= ECONNRESET;
  318. write_size= SOCKET_ERROR;
  319. break;
  320. case SSL_ERROR_WANT_ACCEPT:
  321. case SSL_ERROR_WANT_CONNECT:
  322. case SSL_ERROR_WANT_READ:
  323. case SSL_ERROR_WANT_WRITE:
  324. case SSL_ERROR_WANT_X509_LOOKUP:
  325. errno= EAGAIN;
  326. write_size= SOCKET_ERROR;
  327. continue;
  328. case SSL_ERROR_SYSCALL:
  329. if (errno) // If errno is really set, then let our normal error logic handle.
  330. {
  331. write_size= SOCKET_ERROR;
  332. break;
  333. }
  334. /* fall-thru */
  335. case SSL_ERROR_SSL:
  336. default:
  337. {
  338. char errorString[SSL_ERROR_SIZE]= { 0 };
  339. ERR_error_string_n(ssl_error, errorString, sizeof(errorString));
  340. error(__FILE__, __LINE__, errorString);
  341. close_socket();
  342. return false;
  343. }
  344. }
  345. }
  346. else
  347. #endif
  348. {
  349. write_size= send(sock_fd, ptr + offset, len - offset, MSG_NOSIGNAL);
  350. }
  351. if (write_size == SOCKET_ERROR)
  352. {
  353. if (errno != EINTR)
  354. {
  355. error(__FILE__, __LINE__, strerror(errno));
  356. return false;
  357. }
  358. }
  359. else
  360. {
  361. offset += write_size;
  362. }
  363. } while (offset < ssize_t(len));
  364. return true;
  365. }
  366. }
  367. fatal_assert(is_error());
  368. return false;
  369. }
  370. bool SimpleClient::send_message(const std::string& arg)
  371. {
  372. if (message(arg.c_str(), arg.size()) == true)
  373. {
  374. return message("\r\n", 2);
  375. }
  376. return false;
  377. }
  378. bool SimpleClient::send_data(const libtest::vchar_t& message_, libtest::vchar_t& response_)
  379. {
  380. requested_message++;
  381. if (message(&message_[0], message_.size()))
  382. {
  383. return response(response_);
  384. }
  385. return false;
  386. }
  387. bool SimpleClient::send_message(const std::string& message_, std::string& response_)
  388. {
  389. requested_message++;
  390. if (send_message(message_))
  391. {
  392. return response(response_);
  393. }
  394. return false;
  395. }
  396. #if __GNUC__ >= 7
  397. #pragma GCC diagnostic warning "-Wimplicit-fallthrough"
  398. #endif
  399. bool SimpleClient::response(libtest::vchar_t& response_)
  400. {
  401. response_.clear();
  402. if (is_valid())
  403. {
  404. if (ready(POLLIN))
  405. {
  406. bool more= true;
  407. char buffer[2];
  408. buffer[1]= 0;
  409. do
  410. {
  411. ssize_t read_size;
  412. #if defined(HAVE_SSL) && HAVE_SSL
  413. if (_ssl)
  414. {
  415. int readErr;
  416. int read_size_int= SSL_read(_ssl, buffer, 1);
  417. read_size= read_size_int;
  418. switch (readErr= SSL_get_error(_ssl, read_size_int))
  419. {
  420. case SSL_ERROR_NONE:
  421. break;
  422. case SSL_ERROR_ZERO_RETURN:
  423. // Fall through to normal recv logic
  424. read_size= 0;
  425. break;
  426. case SSL_ERROR_WANT_ACCEPT:
  427. case SSL_ERROR_WANT_CONNECT:
  428. case SSL_ERROR_WANT_READ:
  429. case SSL_ERROR_WANT_WRITE:
  430. case SSL_ERROR_WANT_X509_LOOKUP:
  431. errno= EAGAIN;
  432. read_size= SOCKET_ERROR;
  433. break;
  434. case SSL_ERROR_SYSCALL:
  435. if (errno) // If errno is really set, then let our normal error logic handle.
  436. {
  437. read_size= SOCKET_ERROR;
  438. break;
  439. }
  440. /* fall-thru */
  441. case SSL_ERROR_SSL:
  442. default:
  443. {
  444. char errorString[SSL_ERROR_SIZE]= { 0 };
  445. ERR_error_string_n(readErr, errorString, sizeof(errorString));
  446. error(__FILE__, __LINE__, errorString);
  447. return false;
  448. }
  449. }
  450. }
  451. else
  452. #endif
  453. {
  454. read_size= recv(sock_fd, buffer, 1, MSG_NOSIGNAL);
  455. }
  456. if (read_size == SOCKET_ERROR)
  457. {
  458. // For all errors other then EINTR fail
  459. if (errno != EINTR)
  460. {
  461. error(__FILE__, __LINE__, strerror(errno));
  462. return false;
  463. }
  464. }
  465. else if (read_size == 0)
  466. {
  467. close_socket();
  468. more= false;
  469. }
  470. else
  471. {
  472. response_.reserve(response_.size() + read_size +1);
  473. fatal_assert(read_size == 1);
  474. if (buffer[0] == '\n')
  475. {
  476. more= false;
  477. }
  478. response_.insert(response_.end(), buffer, buffer +read_size);
  479. }
  480. } while (more);
  481. return response_.size();
  482. }
  483. }
  484. fatal_assert(is_error());
  485. return false;
  486. }
  487. bool SimpleClient::response(std::string& response_)
  488. {
  489. response_.clear();
  490. if (is_valid())
  491. {
  492. if (ready(POLLIN))
  493. {
  494. bool more= true;
  495. char buffer[2];
  496. buffer[1]= 0;
  497. do
  498. {
  499. ssize_t read_size;
  500. #if defined(HAVE_SSL) && HAVE_SSL
  501. if (_ssl)
  502. {
  503. int readErr;
  504. int read_size_int= SSL_read(_ssl, buffer, 1);
  505. read_size= read_size_int;
  506. switch (readErr= SSL_get_error(_ssl, read_size_int))
  507. {
  508. case SSL_ERROR_NONE:
  509. break;
  510. case SSL_ERROR_ZERO_RETURN:
  511. // Fall through to normal recv logic
  512. read_size= 0;
  513. break;
  514. case SSL_ERROR_WANT_ACCEPT:
  515. case SSL_ERROR_WANT_CONNECT:
  516. case SSL_ERROR_WANT_READ:
  517. case SSL_ERROR_WANT_WRITE:
  518. case SSL_ERROR_WANT_X509_LOOKUP:
  519. errno= EAGAIN;
  520. read_size= SOCKET_ERROR;
  521. break;
  522. case SSL_ERROR_SYSCALL:
  523. if (errno) // If errno is really set, then let our normal error logic handle.
  524. {
  525. break;
  526. }
  527. /* fall-thru */
  528. case SSL_ERROR_SSL:
  529. default:
  530. error(__FILE__, __LINE__, "SSL_read failed");
  531. return false;
  532. }
  533. }
  534. else
  535. #endif
  536. {
  537. read_size= recv(sock_fd, buffer, 1, MSG_NOSIGNAL);
  538. }
  539. if (read_size == SOCKET_ERROR)
  540. {
  541. if (errno != EINTR)
  542. {
  543. close_socket();
  544. error(__FILE__, __LINE__, strerror(errno));
  545. return false;
  546. }
  547. }
  548. else if (read_size == 0)
  549. {
  550. close_socket();
  551. more= false;
  552. }
  553. else
  554. {
  555. fatal_assert(read_size == 1);
  556. if (buffer[0] == '\n')
  557. {
  558. more= false;
  559. }
  560. response_.append(buffer);
  561. }
  562. } while (more);
  563. return response_.size();
  564. }
  565. }
  566. fatal_assert(is_error());
  567. return false;
  568. }
  569. } // namespace libtest