testclient.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. /*
  2. * Wslay - The WebSocket Library
  3. *
  4. * Copyright (c) 2011, 2012 Tatsuhiro Tsujikawa
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining
  7. * a copy of this software and associated documentation files (the
  8. * "Software"), to deal in the Software without restriction, including
  9. * without limitation the rights to use, copy, modify, merge, publish,
  10. * distribute, sublicense, and/or sell copies of the Software, and to
  11. * permit persons to whom the Software is furnished to do so, subject to
  12. * the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be
  15. * included in all copies or substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  18. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  20. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  21. * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  22. * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  23. * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  24. */
  25. // WebSocket Test Client for Autobahn client test
  26. // $ g++ -Wall -O2 -g -o testclient testclient.cc -L../lib/.libs -I../lib/includes -lwslay -lnettle
  27. // $ export LD_LIBRARY_PATH=../lib/.libs
  28. // $ ./a.out localhost 9001
  29. #include <sys/types.h>
  30. #include <sys/socket.h>
  31. #include <netdb.h>
  32. #include <unistd.h>
  33. #include <fcntl.h>
  34. #include <sys/epoll.h>
  35. #include <netinet/in.h>
  36. #include <netinet/tcp.h>
  37. #include <signal.h>
  38. #include <cassert>
  39. #include <cstdio>
  40. #include <cerrno>
  41. #include <cstdlib>
  42. #include <cstring>
  43. #include <string>
  44. #include <iostream>
  45. #include <string>
  46. #include <set>
  47. #include <iomanip>
  48. #include <fstream>
  49. #include <nettle/base64.h>
  50. #include <nettle/sha.h>
  51. #include <wslay/wslay.h>
  52. int connect_to(const char *host, const char *service) {
  53. struct addrinfo hints;
  54. int fd = -1;
  55. int r;
  56. memset(&hints, 0, sizeof(struct addrinfo));
  57. hints.ai_family = AF_UNSPEC;
  58. hints.ai_socktype = SOCK_STREAM;
  59. struct addrinfo *res;
  60. r = getaddrinfo(host, service, &hints, &res);
  61. if (r != 0) {
  62. std::cerr << "getaddrinfo: " << gai_strerror(r) << std::endl;
  63. return -1;
  64. }
  65. for (struct addrinfo *rp = res; rp; rp = rp->ai_next) {
  66. fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  67. if (fd == -1) {
  68. continue;
  69. }
  70. while ((r = connect(fd, rp->ai_addr, rp->ai_addrlen)) == -1 &&
  71. errno == EINTR)
  72. ;
  73. if (r == 0) {
  74. break;
  75. }
  76. close(fd);
  77. fd = -1;
  78. }
  79. freeaddrinfo(res);
  80. return fd;
  81. }
  82. int make_non_block(int fd) {
  83. int flags, r;
  84. while ((flags = fcntl(fd, F_GETFL, 0)) == -1 && errno == EINTR)
  85. ;
  86. if (flags == -1) {
  87. return -1;
  88. }
  89. while ((r = fcntl(fd, F_SETFL, flags | O_NONBLOCK)) == -1 && errno == EINTR)
  90. ;
  91. if (r == -1) {
  92. return -1;
  93. }
  94. return 0;
  95. }
  96. std::string sha1(const std::string &src) {
  97. sha1_ctx ctx;
  98. sha1_init(&ctx);
  99. sha1_update(&ctx, src.size(), reinterpret_cast<const uint8_t *>(src.c_str()));
  100. uint8_t temp[SHA1_DIGEST_SIZE];
  101. sha1_digest(&ctx, SHA1_DIGEST_SIZE, temp);
  102. std::string res(&temp[0], &temp[SHA1_DIGEST_SIZE]);
  103. return res;
  104. }
  105. std::string base64(const std::string &src) {
  106. base64_encode_ctx ctx;
  107. base64_encode_init(&ctx);
  108. int dstlen = BASE64_ENCODE_RAW_LENGTH(src.size());
  109. char *dst = new char[dstlen];
  110. base64_encode_raw(dst, src.size(),
  111. reinterpret_cast<const uint8_t *>(src.c_str()));
  112. std::string res(&dst[0], &dst[dstlen]);
  113. delete[] dst;
  114. return res;
  115. }
  116. std::string create_acceptkey(const std::string &clientkey) {
  117. std::string s = clientkey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  118. return base64(sha1(s));
  119. }
  120. class WebSocketClient {
  121. public:
  122. WebSocketClient(int fd, struct wslay_event_callbacks *callbacks,
  123. const std::string &body)
  124. : fd_(fd), body_(body), body_off_(0), dev_urand_("/dev/urandom") {
  125. wslay_event_context_client_init(&ctx_, callbacks, this);
  126. }
  127. ~WebSocketClient() {
  128. wslay_event_context_free(ctx_);
  129. shutdown(fd_, SHUT_WR);
  130. close(fd_);
  131. }
  132. int on_read_event() { return wslay_event_recv(ctx_); }
  133. int on_write_event() { return wslay_event_send(ctx_); }
  134. ssize_t send_data(const uint8_t *data, size_t len, int flags) {
  135. ssize_t r;
  136. int sflags = 0;
  137. #ifdef MSG_MORE
  138. if (flags & WSLAY_MSG_MORE) {
  139. sflags |= MSG_MORE;
  140. }
  141. #endif // MSG_MORE
  142. while ((r = send(fd_, data, len, sflags)) == -1 && errno == EINTR)
  143. ;
  144. return r;
  145. }
  146. ssize_t feed_body(uint8_t *data, size_t len) {
  147. if (body_off_ < body_.size()) {
  148. size_t wlen = std::min(len, body_.size() - body_off_);
  149. memcpy(data, body_.c_str(), wlen);
  150. body_off_ += wlen;
  151. return wlen;
  152. } else {
  153. return 0;
  154. }
  155. }
  156. ssize_t recv_data(uint8_t *data, size_t len, int flags) {
  157. ssize_t r;
  158. while ((r = recv(fd_, data, len, 0)) == -1 && errno == EINTR)
  159. ;
  160. return r;
  161. }
  162. bool want_read() { return wslay_event_want_read(ctx_); }
  163. bool want_write() { return wslay_event_want_write(ctx_); }
  164. int fd() const { return fd_; }
  165. void get_random(uint8_t *buf, size_t len) {
  166. dev_urand_.read((char *)buf, len);
  167. }
  168. void set_callbacks(const struct wslay_event_callbacks *callbacks) {
  169. wslay_event_config_set_callbacks(ctx_, callbacks);
  170. }
  171. private:
  172. int fd_;
  173. wslay_event_context_ptr ctx_;
  174. std::string body_;
  175. size_t body_off_;
  176. std::fstream dev_urand_;
  177. };
  178. ssize_t send_callback(wslay_event_context_ptr ctx, const uint8_t *data,
  179. size_t len, int flags, void *user_data) {
  180. WebSocketClient *ws = (WebSocketClient *)user_data;
  181. ssize_t r = ws->send_data(data, len, flags);
  182. if (r == -1) {
  183. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  184. wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK);
  185. } else {
  186. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  187. }
  188. }
  189. return r;
  190. }
  191. ssize_t recv_callback(wslay_event_context_ptr ctx, uint8_t *data, size_t len,
  192. int flags, void *user_data) {
  193. WebSocketClient *ws = (WebSocketClient *)user_data;
  194. ssize_t r = ws->recv_data(data, len, flags);
  195. if (r == -1) {
  196. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  197. wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK);
  198. } else {
  199. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  200. }
  201. } else if (r == 0) {
  202. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  203. r = -1;
  204. }
  205. return r;
  206. }
  207. ssize_t feed_body_callback(wslay_event_context_ptr ctx, uint8_t *data,
  208. size_t len, int flags, void *user_data) {
  209. WebSocketClient *ws = (WebSocketClient *)user_data;
  210. return ws->feed_body(data, len);
  211. }
  212. int genmask_callback(wslay_event_context_ptr ctx, uint8_t *buf, size_t len,
  213. void *user_data) {
  214. WebSocketClient *ws = (WebSocketClient *)user_data;
  215. ws->get_random(buf, len);
  216. return 0;
  217. }
  218. void on_msg_recv_callback(wslay_event_context_ptr ctx,
  219. const struct wslay_event_on_msg_recv_arg *arg,
  220. void *user_data) {
  221. if (!wslay_is_ctrl_frame(arg->opcode)) {
  222. struct wslay_event_msg msgarg = {arg->opcode, arg->msg, arg->msg_length};
  223. wslay_event_queue_msg(ctx, &msgarg);
  224. }
  225. }
  226. std::string casecntjson;
  227. void get_casecnt_on_msg_recv_callback(
  228. wslay_event_context_ptr ctx, const struct wslay_event_on_msg_recv_arg *arg,
  229. void *user_data) {
  230. if (arg->opcode == WSLAY_TEXT_FRAME) {
  231. casecntjson.assign(arg->msg, arg->msg + arg->msg_length);
  232. }
  233. }
  234. int send_http_handshake(int fd, const std::string &reqheader) {
  235. size_t off = 0;
  236. while (off < reqheader.size()) {
  237. ssize_t r;
  238. size_t len = reqheader.size() - off;
  239. while ((r = write(fd, reqheader.c_str() + off, len)) == -1 &&
  240. errno == EINTR)
  241. ;
  242. if (r == -1) {
  243. perror("write");
  244. return -1;
  245. }
  246. off += r;
  247. }
  248. return 0;
  249. }
  250. int recv_http_handshake(int fd, std::string &resheader) {
  251. char buf[4096];
  252. while (1) {
  253. ssize_t r;
  254. while ((r = read(fd, buf, sizeof(buf))) == -1 && errno == EINTR)
  255. ;
  256. if (r <= 0) {
  257. return -1;
  258. }
  259. resheader.append(buf, buf + r);
  260. if (resheader.find("\r\n\r\n") != std::string::npos) {
  261. break;
  262. }
  263. if (resheader.size() > 8192) {
  264. std::cerr << "Too big response header" << std::endl;
  265. return -1;
  266. }
  267. }
  268. return 0;
  269. }
  270. std::string get_random16() {
  271. char buf[16];
  272. std::fstream f("/dev/urandom");
  273. f.read(buf, 16);
  274. return std::string(buf, buf + 16);
  275. }
  276. int http_handshake(int fd, const char *host, const char *service,
  277. const char *path, std::string &body) {
  278. char buf[4096];
  279. std::string client_key = base64(get_random16());
  280. snprintf(buf, sizeof(buf),
  281. "GET %s HTTP/1.1\r\n"
  282. "Host: %s:%s\r\n"
  283. "Upgrade: websocket\r\n"
  284. "Connection: Upgrade\r\n"
  285. "Sec-WebSocket-Key: %s\r\n"
  286. "Sec-WebSocket-Version: 13\r\n"
  287. "\r\n",
  288. path, host, service, client_key.c_str());
  289. std::string reqheader = buf;
  290. if (send_http_handshake(fd, reqheader) == -1) {
  291. return -1;
  292. }
  293. std::string resheader;
  294. if (recv_http_handshake(fd, resheader) == -1) {
  295. return -1;
  296. }
  297. std::string::size_type keyhdstart;
  298. if ((keyhdstart = resheader.find("Sec-WebSocket-Accept: ")) ==
  299. std::string::npos) {
  300. std::cerr << "http_upgrade: missing required headers" << std::endl;
  301. return -1;
  302. }
  303. keyhdstart += 22;
  304. std::string::size_type keyhdend = resheader.find("\r\n", keyhdstart);
  305. std::string accept_key = resheader.substr(keyhdstart, keyhdend - keyhdstart);
  306. if (accept_key == create_acceptkey(client_key)) {
  307. body = resheader.substr(resheader.find("\r\n\r\n") + 4);
  308. return 0;
  309. } else {
  310. return -1;
  311. }
  312. }
  313. void ctl_epollev(int epollfd, int op, WebSocketClient &ws) {
  314. epoll_event ev;
  315. memset(&ev, 0, sizeof(ev));
  316. if (ws.want_read()) {
  317. ev.events |= EPOLLIN;
  318. }
  319. if (ws.want_write()) {
  320. ev.events |= EPOLLOUT;
  321. }
  322. if (epoll_ctl(epollfd, op, ws.fd(), &ev) == -1) {
  323. perror("epoll_ctl");
  324. exit(EXIT_FAILURE);
  325. }
  326. }
  327. int communicate(const char *host, const char *service, const char *path,
  328. const struct wslay_event_callbacks *callbacks) {
  329. struct wslay_event_callbacks cb = *callbacks;
  330. cb.recv_callback = feed_body_callback;
  331. int fd = connect_to(host, service);
  332. if (fd == -1) {
  333. std::cerr << "Could not connect to the host" << std::endl;
  334. return -1;
  335. }
  336. std::string body;
  337. if (http_handshake(fd, host, service, path, body) == -1) {
  338. std::cerr << "Failed handshake" << std::endl;
  339. close(fd);
  340. return -1;
  341. }
  342. make_non_block(fd);
  343. int val = 1;
  344. if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, (socklen_t)sizeof(val)) ==
  345. -1) {
  346. perror("setsockopt: TCP_NODELAY");
  347. return -1;
  348. }
  349. WebSocketClient ws(fd, &cb, body);
  350. if (ws.on_read_event() == -1) {
  351. return -1;
  352. }
  353. cb.recv_callback = callbacks->recv_callback;
  354. ws.set_callbacks(&cb);
  355. int epollfd = epoll_create(1);
  356. if (epollfd == -1) {
  357. perror("epoll_create");
  358. return -1;
  359. }
  360. ctl_epollev(epollfd, EPOLL_CTL_ADD, ws);
  361. static const size_t MAX_EVENTS = 1;
  362. epoll_event events[MAX_EVENTS];
  363. bool ok = true;
  364. while (ws.want_read() || ws.want_write()) {
  365. int nfds = epoll_wait(epollfd, events, MAX_EVENTS, -1);
  366. if (nfds == -1) {
  367. perror("epoll_wait");
  368. return -1;
  369. }
  370. for (int n = 0; n < nfds; ++n) {
  371. if (((events[n].events & EPOLLIN) && ws.on_read_event() != 0) ||
  372. ((events[n].events & EPOLLOUT) && ws.on_write_event() != 0)) {
  373. ok = false;
  374. break;
  375. }
  376. }
  377. if (!ok) {
  378. break;
  379. }
  380. ctl_epollev(epollfd, EPOLL_CTL_MOD, ws);
  381. }
  382. return ok ? 0 : -1;
  383. }
  384. int get_casecnt(const char *host, const char *service) {
  385. struct wslay_event_callbacks callbacks = {
  386. recv_callback,
  387. send_callback,
  388. genmask_callback,
  389. NULL, /* on_frame_recv_start_callback */
  390. NULL, /* on_frame_recv_callback */
  391. NULL, /* on_frame_recv_end_callback */
  392. get_casecnt_on_msg_recv_callback};
  393. if (communicate(host, service, "/getCaseCount", &callbacks) == -1) {
  394. return -1;
  395. }
  396. errno = 0;
  397. int casecnt = strtol(casecntjson.c_str(), 0, 10);
  398. if (errno == ERANGE) {
  399. return -1;
  400. } else {
  401. return casecnt;
  402. }
  403. }
  404. int run_testcase(const char *host, const char *service, int casenum) {
  405. struct wslay_event_callbacks callbacks = {
  406. recv_callback,
  407. send_callback,
  408. genmask_callback,
  409. NULL, /* on_frame_recv_start_callback */
  410. NULL, /* on_frame_recv_callback */
  411. NULL, /* on_frame_recv_end_callback */
  412. on_msg_recv_callback};
  413. char buf[1024];
  414. snprintf(buf, sizeof(buf), "/runCase?case=%d&agent=wslay", casenum);
  415. return communicate(host, service, buf, &callbacks);
  416. }
  417. int update_reports(const char *host, const char *service) {
  418. struct wslay_event_callbacks callbacks = {
  419. recv_callback, send_callback, genmask_callback,
  420. NULL, /* on_frame_recv_start_callback */
  421. NULL, /* on_frame_recv_callback */
  422. NULL, /* on_frame_recv_end_callback */
  423. NULL, /* on_msg_recv_callback */
  424. };
  425. return communicate(host, service, "/updateReports?&agent=wslay", &callbacks);
  426. }
  427. int main(int argc, char **argv) {
  428. if (argc < 3) {
  429. std::cerr << "Usage: " << argv[0] << " HOST SERV" << std::endl;
  430. exit(EXIT_FAILURE);
  431. }
  432. struct sigaction act;
  433. memset(&act, 0, sizeof(struct sigaction));
  434. act.sa_handler = SIG_IGN;
  435. sigaction(SIGPIPE, &act, 0);
  436. const char *host = argv[1];
  437. const char *service = argv[2];
  438. int casecnt = get_casecnt(host, service);
  439. if (casecnt == -1) {
  440. std::cerr << "Failed to get case count." << std::endl;
  441. exit(EXIT_FAILURE);
  442. }
  443. for (int i = 1; i <= casecnt; ++i) {
  444. std::cout << "Running test case " << i << std::endl;
  445. if (run_testcase(host, service, i) == -1) {
  446. std::cout << "Detected error during test" << std::endl;
  447. }
  448. }
  449. if (update_reports(host, service) == -1) {
  450. std::cerr << "Failed to update reports." << std::endl;
  451. exit(EXIT_FAILURE);
  452. }
  453. }