testclient.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. {
  54. struct addrinfo hints;
  55. int fd = -1;
  56. int r;
  57. memset(&hints, 0, sizeof(struct addrinfo));
  58. hints.ai_family = AF_UNSPEC;
  59. hints.ai_socktype = SOCK_STREAM;
  60. struct addrinfo *res;
  61. r = getaddrinfo(host, service, &hints, &res);
  62. if(r != 0) {
  63. std::cerr << "getaddrinfo: " << gai_strerror(r) << std::endl;
  64. return -1;
  65. }
  66. for(struct addrinfo *rp = res; rp; rp = rp->ai_next) {
  67. fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  68. if(fd == -1) {
  69. continue;
  70. }
  71. while((r = connect(fd, rp->ai_addr, rp->ai_addrlen)) == -1 &&
  72. errno == EINTR);
  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. {
  84. int flags, r;
  85. while((flags = fcntl(fd, F_GETFL, 0)) == -1 && errno == EINTR);
  86. if(flags == -1) {
  87. return -1;
  88. }
  89. while((r = fcntl(fd, F_SETFL, flags | O_NONBLOCK)) == -1 && errno == EINTR);
  90. if(r == -1) {
  91. return -1;
  92. }
  93. return 0;
  94. }
  95. std::string sha1(const std::string& src)
  96. {
  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. {
  107. base64_encode_ctx ctx;
  108. base64_encode_init(&ctx);
  109. int dstlen = BASE64_ENCODE_RAW_LENGTH(src.size());
  110. uint8_t *dst = new uint8_t[dstlen];
  111. base64_encode_raw(dst, src.size(),
  112. reinterpret_cast<const uint8_t*>(src.c_str()));
  113. std::string res(&dst[0], &dst[dstlen]);
  114. delete [] dst;
  115. return res;
  116. }
  117. std::string create_acceptkey(const std::string& clientkey)
  118. {
  119. std::string s = clientkey+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  120. return base64(sha1(s));
  121. }
  122. class WebSocketClient {
  123. public:
  124. WebSocketClient(int fd, struct wslay_event_callbacks *callbacks,
  125. const std::string& body)
  126. : fd_(fd),
  127. body_(body),
  128. body_off_(0),
  129. dev_urand_("/dev/urandom")
  130. {
  131. wslay_event_context_client_init(&ctx_, callbacks, this);
  132. }
  133. ~WebSocketClient()
  134. {
  135. wslay_event_context_free(ctx_);
  136. shutdown(fd_, SHUT_WR);
  137. close(fd_);
  138. }
  139. int on_read_event()
  140. {
  141. return wslay_event_recv(ctx_);
  142. }
  143. int on_write_event()
  144. {
  145. return wslay_event_send(ctx_);
  146. }
  147. ssize_t send_data(const uint8_t *data, size_t len, int flags)
  148. {
  149. ssize_t r;
  150. int sflags = 0;
  151. #ifdef MSG_MORE
  152. if(flags & WSLAY_MSG_MORE) {
  153. sflags |= MSG_MORE;
  154. }
  155. #endif // MSG_MORE
  156. while((r = send(fd_, data, len, sflags)) == -1 && errno == EINTR);
  157. return r;
  158. }
  159. ssize_t feed_body(uint8_t *data, size_t len)
  160. {
  161. if(body_off_ < body_.size()) {
  162. size_t wlen = std::min(len, body_.size()-body_off_);
  163. memcpy(data, body_.c_str(), wlen);
  164. body_off_ += wlen;
  165. return wlen;
  166. } else {
  167. return 0;
  168. }
  169. }
  170. ssize_t recv_data(uint8_t *data, size_t len, int flags)
  171. {
  172. ssize_t r;
  173. while((r = recv(fd_, data, len, 0)) == -1 && errno == EINTR);
  174. return r;
  175. }
  176. bool want_read()
  177. {
  178. return wslay_event_want_read(ctx_);
  179. }
  180. bool want_write()
  181. {
  182. return wslay_event_want_write(ctx_);
  183. }
  184. int fd() const
  185. {
  186. return fd_;
  187. }
  188. void get_random(uint8_t *buf, size_t len)
  189. {
  190. dev_urand_.read((char*)buf, len);
  191. }
  192. void set_callbacks(const struct wslay_event_callbacks *callbacks)
  193. {
  194. wslay_event_config_set_callbacks(ctx_, callbacks);
  195. }
  196. private:
  197. int fd_;
  198. wslay_event_context_ptr ctx_;
  199. std::string body_;
  200. size_t body_off_;
  201. std::fstream dev_urand_;
  202. };
  203. ssize_t send_callback(wslay_event_context_ptr ctx,
  204. const uint8_t *data, size_t len, int flags,
  205. void *user_data)
  206. {
  207. WebSocketClient *ws = (WebSocketClient*)user_data;
  208. ssize_t r = ws->send_data(data, len, flags);
  209. if(r == -1) {
  210. if(errno == EAGAIN || errno == EWOULDBLOCK) {
  211. wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK);
  212. } else {
  213. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  214. }
  215. }
  216. return r;
  217. }
  218. ssize_t recv_callback(wslay_event_context_ptr ctx, uint8_t *data, size_t len,
  219. int flags, void *user_data)
  220. {
  221. WebSocketClient *ws = (WebSocketClient*)user_data;
  222. ssize_t r = ws->recv_data(data, len, flags);
  223. if(r == -1) {
  224. if(errno == EAGAIN || errno == EWOULDBLOCK) {
  225. wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK);
  226. } else {
  227. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  228. }
  229. } else if(r == 0) {
  230. wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
  231. r = -1;
  232. }
  233. return r;
  234. }
  235. ssize_t feed_body_callback
  236. (wslay_event_context_ptr ctx, uint8_t *data, size_t len, int flags,
  237. void *user_data)
  238. {
  239. WebSocketClient *ws = (WebSocketClient*)user_data;
  240. return ws->feed_body(data, len);
  241. }
  242. int genmask_callback(wslay_event_context_ptr ctx, uint8_t *buf, size_t len,
  243. void *user_data)
  244. {
  245. WebSocketClient *ws = (WebSocketClient*)user_data;
  246. ws->get_random(buf, len);
  247. return 0;
  248. }
  249. void on_msg_recv_callback(wslay_event_context_ptr ctx,
  250. const struct wslay_event_on_msg_recv_arg *arg,
  251. void *user_data)
  252. {
  253. if(!wslay_is_ctrl_frame(arg->opcode)) {
  254. struct wslay_event_msg msgarg = {
  255. arg->opcode, arg->msg, arg->msg_length
  256. };
  257. wslay_event_queue_msg(ctx, &msgarg);
  258. }
  259. }
  260. std::string casecntjson;
  261. void get_casecnt_on_msg_recv_callback
  262. (wslay_event_context_ptr ctx,
  263. const struct wslay_event_on_msg_recv_arg *arg,
  264. void *user_data)
  265. {
  266. if(arg->opcode == WSLAY_TEXT_FRAME) {
  267. casecntjson.assign(arg->msg, arg->msg+arg->msg_length);
  268. }
  269. }
  270. int send_http_handshake(int fd, const std::string& reqheader)
  271. {
  272. size_t off = 0;
  273. while(off < reqheader.size()) {
  274. ssize_t r;
  275. size_t len = reqheader.size()-off;
  276. while((r = write(fd, reqheader.c_str()+off, len)) == -1 && errno == EINTR);
  277. if(r == -1) {
  278. perror("write");
  279. return -1;
  280. }
  281. off += r;
  282. }
  283. return 0;
  284. }
  285. int recv_http_handshake(int fd, std::string& resheader)
  286. {
  287. char buf[4096];
  288. while(1) {
  289. ssize_t r;
  290. while((r = read(fd, buf, sizeof(buf))) == -1 && errno == EINTR);
  291. if(r <= 0) {
  292. return -1;
  293. }
  294. resheader.append(buf, buf+r);
  295. if(resheader.find("\r\n\r\n") != std::string::npos) {
  296. break;
  297. }
  298. if(resheader.size() > 8192) {
  299. std::cerr << "Too big response header" << std::endl;
  300. return -1;
  301. }
  302. }
  303. return 0;
  304. }
  305. std::string get_random16()
  306. {
  307. char buf[16];
  308. std::fstream f("/dev/urandom");
  309. f.read(buf, 16);
  310. return std::string(buf, buf+16);
  311. }
  312. int http_handshake(int fd, const char *host, const char *service,
  313. const char *path, std::string& body)
  314. {
  315. char buf[4096];
  316. std::string client_key = base64(get_random16());
  317. snprintf(buf, sizeof(buf),
  318. "GET %s HTTP/1.1\r\n"
  319. "Host: %s:%s\r\n"
  320. "Upgrade: websocket\r\n"
  321. "Connection: Upgrade\r\n"
  322. "Sec-WebSocket-Key: %s\r\n"
  323. "Sec-WebSocket-Version: 13\r\n"
  324. "\r\n",
  325. path, host, service, client_key.c_str());
  326. std::string reqheader = buf;
  327. if(send_http_handshake(fd, reqheader) == -1) {
  328. return -1;
  329. }
  330. std::string resheader;
  331. if(recv_http_handshake(fd, resheader) == -1) {
  332. return -1;
  333. }
  334. std::string::size_type keyhdstart;
  335. if((keyhdstart = resheader.find("Sec-WebSocket-Accept: ")) ==
  336. std::string::npos) {
  337. std::cerr << "http_upgrade: missing required headers" << std::endl;
  338. return -1;
  339. }
  340. keyhdstart += 22;
  341. std::string::size_type keyhdend = resheader.find("\r\n", keyhdstart);
  342. std::string accept_key = resheader.substr(keyhdstart, keyhdend-keyhdstart);
  343. if(accept_key == create_acceptkey(client_key)) {
  344. body = resheader.substr(resheader.find("\r\n\r\n")+4);
  345. return 0;
  346. } else {
  347. return -1;
  348. }
  349. }
  350. void ctl_epollev(int epollfd, int op, WebSocketClient& ws)
  351. {
  352. epoll_event ev;
  353. memset(&ev, 0, sizeof(ev));
  354. if(ws.want_read()) {
  355. ev.events |= EPOLLIN;
  356. }
  357. if(ws.want_write()) {
  358. ev.events |= EPOLLOUT;
  359. }
  360. if(epoll_ctl(epollfd, op, ws.fd(), &ev) == -1) {
  361. perror("epoll_ctl");
  362. exit(EXIT_FAILURE);
  363. }
  364. }
  365. int communicate(const char *host, const char *service, const char *path,
  366. const struct wslay_event_callbacks *callbacks)
  367. {
  368. struct wslay_event_callbacks cb = *callbacks;
  369. cb.recv_callback = feed_body_callback;
  370. int fd = connect_to(host, service);
  371. if(fd == -1) {
  372. std::cerr << "Could not connect to the host" << std::endl;
  373. return -1;
  374. }
  375. std::string body;
  376. if(http_handshake(fd, host, service, path, body) == -1) {
  377. std::cerr << "Failed handshake" << std::endl;
  378. close(fd);
  379. return -1;
  380. }
  381. make_non_block(fd);
  382. int val = 1;
  383. if(setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, (socklen_t)sizeof(val))
  384. == -1) {
  385. perror("setsockopt: TCP_NODELAY");
  386. return -1;
  387. }
  388. WebSocketClient ws(fd, &cb, body);
  389. if(ws.on_read_event() == -1) {
  390. return -1;
  391. }
  392. cb.recv_callback = callbacks->recv_callback;
  393. ws.set_callbacks(&cb);
  394. int epollfd = epoll_create(1);
  395. if(epollfd == -1) {
  396. perror("epoll_create");
  397. return -1;
  398. }
  399. ctl_epollev(epollfd, EPOLL_CTL_ADD, ws);
  400. static const size_t MAX_EVENTS = 1;
  401. epoll_event events[MAX_EVENTS];
  402. bool ok = true;
  403. while(ws.want_read() || ws.want_write()) {
  404. int nfds = epoll_wait(epollfd, events, MAX_EVENTS, -1);
  405. if(nfds == -1) {
  406. perror("epoll_wait");
  407. return -1;
  408. }
  409. for(int n = 0; n < nfds; ++n) {
  410. if(((events[n].events & EPOLLIN) && ws.on_read_event() != 0) ||
  411. ((events[n].events & EPOLLOUT) && ws.on_write_event() != 0)) {
  412. ok = false;
  413. break;
  414. }
  415. }
  416. if(!ok) {
  417. break;
  418. }
  419. ctl_epollev(epollfd, EPOLL_CTL_MOD, ws);
  420. }
  421. return ok ? 0 : -1;
  422. }
  423. int get_casecnt(const char *host, const char *service)
  424. {
  425. struct wslay_event_callbacks callbacks = {
  426. recv_callback,
  427. send_callback,
  428. genmask_callback,
  429. NULL, /* on_frame_recv_start_callback */
  430. NULL, /* on_frame_recv_callback */
  431. NULL, /* on_frame_recv_end_callback */
  432. get_casecnt_on_msg_recv_callback
  433. };
  434. if(communicate(host, service, "/getCaseCount", &callbacks) == -1) {
  435. return -1;
  436. }
  437. errno = 0;
  438. int casecnt = strtol(casecntjson.c_str(), 0, 10);
  439. if(errno == ERANGE) {
  440. return -1;
  441. } else {
  442. return casecnt;
  443. }
  444. }
  445. int run_testcase(const char *host, const char *service, int casenum)
  446. {
  447. struct wslay_event_callbacks callbacks = {
  448. recv_callback,
  449. send_callback,
  450. genmask_callback,
  451. NULL, /* on_frame_recv_start_callback */
  452. NULL, /* on_frame_recv_callback */
  453. NULL, /* on_frame_recv_end_callback */
  454. on_msg_recv_callback
  455. };
  456. char buf[1024];
  457. snprintf(buf, sizeof(buf), "/runCase?case=%d&agent=wslay", casenum);
  458. return communicate(host, service, buf, &callbacks);
  459. }
  460. int update_reports(const char *host, const char *service)
  461. {
  462. struct wslay_event_callbacks callbacks = {
  463. recv_callback,
  464. send_callback,
  465. genmask_callback,
  466. NULL, /* on_frame_recv_start_callback */
  467. NULL, /* on_frame_recv_callback */
  468. NULL, /* on_frame_recv_end_callback */
  469. NULL, /* on_msg_recv_callback */
  470. };
  471. return communicate(host, service, "/updateReports?&agent=wslay", &callbacks);
  472. }
  473. int main(int argc, char **argv)
  474. {
  475. if(argc < 3) {
  476. std::cerr << "Usage: " << argv[0] << " HOST SERV" << std::endl;
  477. exit(EXIT_FAILURE);
  478. }
  479. struct sigaction act;
  480. memset(&act, 0, sizeof(struct sigaction));
  481. act.sa_handler = SIG_IGN;
  482. sigaction(SIGPIPE, &act, 0);
  483. const char *host = argv[1];
  484. const char *service = argv[2];
  485. int casecnt = get_casecnt(host, service);
  486. if(casecnt == -1) {
  487. std::cerr << "Failed to get case count." << std::endl;
  488. exit(EXIT_FAILURE);
  489. }
  490. for(int i = 1; i <= casecnt; ++i) {
  491. std::cout << "Running test case " << i << std::endl;
  492. if(run_testcase(host, service, i) == -1) {
  493. std::cout << "Detected error during test" << std::endl;
  494. }
  495. }
  496. if(update_reports(host, service) == -1) {
  497. std::cerr << "Failed to update reports." << std::endl;
  498. exit(EXIT_FAILURE);
  499. }
  500. }