Advertisement
Guest User

test-echo-server

a guest
Apr 17th, 2016
302
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 12.34 KB | None | 0 0
  1. /*
  2.  * libwebsockets-test-echo
  3.  *
  4.  * Copyright (C) 2010-2016 Andy Green <andy@warmcat.com>
  5.  *
  6.  * This file is made available under the Creative Commons CC0 1.0
  7.  * Universal Public Domain Dedication.
  8.  *
  9.  * The person who associated a work with this deed has dedicated
  10.  * the work to the public domain by waiving all of his or her rights
  11.  * to the work worldwide under copyright law, including all related
  12.  * and neighboring rights, to the extent allowed by law. You can copy,
  13.  * modify, distribute and perform the work, even for commercial purposes,
  14.  * all without asking permission.
  15.  *
  16.  * The test apps are intended to be adapted for use in your code, which
  17.  * may be proprietary.  So unlike the library itself, they are licensed
  18.  * Public Domain.
  19.  */
  20.  
  21. #include <stdio.h>
  22. #include <stdlib.h>
  23. #include <getopt.h>
  24. #include <string.h>
  25. #include <assert.h>
  26. #include <signal.h>
  27.  
  28. #include <libwebsockets.h>
  29.  
  30. #ifndef _WIN32
  31. #include <syslog.h>
  32. #include <sys/time.h>
  33. #include <unistd.h>
  34. #else
  35. #include "gettimeofday.h"
  36. #include <process.h>
  37. #endif
  38.  
  39. static volatile int force_exit = 0;
  40. static int versa, state;
  41. static int times = -1;
  42.  
  43. #define LOCAL_RESOURCE_PATH "/libwebsockets-test-server"
  44.  
  45. #define MAX_ECHO_PAYLOAD 1024
  46.  
  47. struct per_session_data__echo {
  48.     size_t rx, tx;
  49.     unsigned char buf[LWS_PRE + MAX_ECHO_PAYLOAD];
  50.     unsigned int len;
  51.     unsigned int index;
  52.     int final;
  53.     int continuation;
  54.     int binary;
  55. };
  56.  
  57. static int
  58. callback_echo(struct lws *wsi, enum lws_callback_reasons reason, void *user,
  59.           void *in, size_t len)
  60. {
  61.     struct per_session_data__echo *pss =
  62.             (struct per_session_data__echo *)user;
  63.     int n;
  64.  
  65.     switch (reason) {
  66.  
  67. #ifndef LWS_NO_SERVER
  68.  
  69.     case LWS_CALLBACK_SERVER_WRITEABLE:
  70. do_tx:
  71.  
  72.         n = LWS_WRITE_CONTINUATION;
  73.         if (!pss->continuation) {
  74.             if (pss->binary)
  75.                 n = LWS_WRITE_BINARY;
  76.             else
  77.                 n = LWS_WRITE_TEXT;
  78.             pss->continuation = 1;
  79.         }
  80.         if (!pss->final)
  81.             n |= LWS_WRITE_NO_FIN;
  82.         lwsl_info("+++ test-echo: writing %d, with final %d\n",
  83.               pss->len, pss->final);
  84.  
  85.         pss->tx += pss->len;
  86.         n = lws_write(wsi, &pss->buf[LWS_PRE], pss->len, n);
  87.         if (n < 0) {
  88.             lwsl_err("ERROR %d writing to socket, hanging up\n", n);
  89.             return 1;
  90.         }
  91.         if (n < (int)pss->len) {
  92.             lwsl_err("Partial write\n");
  93.             return -1;
  94.         }
  95.         pss->len = -1;
  96.         if (pss->final)
  97.             pss->continuation = 0;
  98.         lws_rx_flow_control(wsi, 1);
  99.         break;
  100.  
  101.     case LWS_CALLBACK_RECEIVE:
  102. do_rx:
  103.         pss->final = lws_is_final_fragment(wsi);
  104.         pss->binary = lws_frame_is_binary(wsi);
  105.         lwsl_info("+++ test-echo: RX len %d final %d, pss->len=%d\n",
  106.               len, pss->final, (int)pss->len);
  107.  
  108.         memcpy(&pss->buf[LWS_PRE], in, len);
  109.         assert((int)pss->len == -1);
  110.         pss->len = (unsigned int)len;
  111.         pss->rx += len;
  112.  
  113.         lws_rx_flow_control(wsi, 0);
  114.         lws_callback_on_writable(wsi);
  115.         break;
  116. #endif
  117.  
  118. #ifndef LWS_NO_CLIENT
  119.     /* when the callback is used for client operations --> */
  120.  
  121.     case LWS_CALLBACK_CLOSED:
  122.     case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
  123.         lwsl_debug("closed\n");
  124.         state = 0;
  125.         break;
  126.  
  127.     case LWS_CALLBACK_CLIENT_ESTABLISHED:
  128.         lwsl_debug("Client has connected\n");
  129.         pss->index = 0;
  130.         pss->len = -1;
  131.         state = 2;
  132.         break;
  133.  
  134.     case LWS_CALLBACK_CLIENT_RECEIVE:
  135. #ifndef LWS_NO_SERVER
  136.         if (versa)
  137.             goto do_rx;
  138. #endif
  139.         lwsl_notice("Client RX: %s", (char *)in);
  140.         break;
  141.  
  142.     case LWS_CALLBACK_CLIENT_WRITEABLE:
  143. #ifndef LWS_NO_SERVER
  144.         if (versa) {
  145.             if (pss->len != (unsigned int)-1)
  146.                 goto do_tx;
  147.             break;
  148.         }
  149. #endif
  150.         /* we will send our packet... */
  151.         pss->len = sprintf((char *)&pss->buf[LWS_PRE],
  152.                    "hello from libwebsockets-test-echo client pid %d index %d\n",
  153.                    getpid(), pss->index++);
  154.         lwsl_notice("Client TX: %s", &pss->buf[LWS_PRE]);
  155.         n = lws_write(wsi, &pss->buf[LWS_PRE], pss->len, LWS_WRITE_TEXT);
  156.         if (n < 0) {
  157.             lwsl_err("ERROR %d writing to socket, hanging up\n", n);
  158.             return -1;
  159.         }
  160.         if (n < (int)pss->len) {
  161.             lwsl_err("Partial write\n");
  162.             return -1;
  163.         }
  164.         break;
  165. #endif
  166.     case LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED:
  167.         /* reject everything else except permessage-deflate */
  168.         if (strcmp(in, "permessage-deflate"))
  169.             return 1;
  170.         break;
  171.  
  172.     default:
  173.         break;
  174.     }
  175.  
  176.     return 0;
  177. }
  178.  
  179.  
  180.  
  181. static struct lws_protocols protocols[] = {
  182.     /* first protocol must always be HTTP handler */
  183.  
  184.     {
  185.         "",     /* name - can be overriden with -e */
  186.         callback_echo,
  187.         sizeof(struct per_session_data__echo),  /* per_session_data_size */
  188.         MAX_ECHO_PAYLOAD,
  189.     },
  190.     {
  191.         NULL, NULL, 0       /* End of list */
  192.     }
  193. };
  194.  
  195. static const struct lws_extension exts[] = {
  196.     { NULL, NULL, NULL /* terminator */ }
  197. };
  198.  
  199.  
  200. void sighandler(int sig)
  201. {
  202.     force_exit = 1;
  203. }
  204.  
  205. static struct option options[] = {
  206.     { "help",   no_argument,        NULL, 'h' },
  207.     { "debug",  required_argument,  NULL, 'd' },
  208.     { "port",   required_argument,  NULL, 'p' },
  209.     { "ssl-cert",   required_argument,  NULL, 'C' },
  210.     { "ssl-key",    required_argument,  NULL, 'k' },
  211. #ifndef LWS_NO_CLIENT
  212.     { "client", required_argument,  NULL, 'c' },
  213.     { "ratems", required_argument,  NULL, 'r' },
  214. #endif
  215.     { "ssl",    no_argument,        NULL, 's' },
  216.     { "versa",  no_argument,        NULL, 'v' },
  217.     { "uri",    required_argument,  NULL, 'u' },
  218.     { "passphrase", required_argument,  NULL, 'P' },
  219.     { "interface",  required_argument,  NULL, 'i' },
  220.     { "times",  required_argument,  NULL, 'n' },
  221.     { "echogen",    no_argument,        NULL, 'e' },
  222. #ifndef LWS_NO_DAEMONIZE
  223.     { "daemonize",  no_argument,        NULL, 'D' },
  224. #endif
  225.     { NULL, 0, 0, 0 }
  226. };
  227.  
  228. int main(int argc, char **argv)
  229. {
  230.     int n = 0;
  231.     int port = 7681;
  232.     int use_ssl = 0;
  233.     struct lws_context *context;
  234.     int opts = 0;
  235.     char interface_name[128] = "";
  236.     const char *_interface = NULL;
  237.     char ssl_cert[256] = LOCAL_RESOURCE_PATH"/libwebsockets-test-server.pem";
  238.     char ssl_key[256] = LOCAL_RESOURCE_PATH"/libwebsockets-test-server.key.pem";
  239. #ifndef _WIN32
  240.     int syslog_options = LOG_PID | LOG_PERROR;
  241. #endif
  242.     int client = 0;
  243.     int listen_port = 80;
  244.     struct lws_context_creation_info info;
  245.     char passphrase[256];
  246.     char uri[256] = "/";
  247. #ifndef LWS_NO_CLIENT
  248.     char address[256], ads_port[256 + 30];
  249.     int rate_us = 250000;
  250.     unsigned long long oldus;
  251.     struct lws *wsi;
  252.     int disallow_selfsigned = 0;
  253.     struct timeval tv;
  254.     const char *connect_protocol = NULL;
  255.     struct lws_client_connect_info i;
  256. #endif
  257.  
  258.     int debug_level = 7;
  259. #ifndef LWS_NO_DAEMONIZE
  260.     int daemonize = 0;
  261. #endif
  262.  
  263.     memset(&info, 0, sizeof info);
  264.  
  265. #ifndef LWS_NO_CLIENT
  266.     lwsl_notice("Built to support client operations\n");
  267. #endif
  268. #ifndef LWS_NO_SERVER
  269.     lwsl_notice("Built to support server operations\n");
  270. #endif
  271.  
  272.     while (n >= 0) {
  273.         n = getopt_long(argc, argv, "i:hsp:d:DC:k:P:vu:n:e"
  274. #ifndef LWS_NO_CLIENT
  275.             "c:r:"
  276. #endif
  277.                 , options, NULL);
  278.         if (n < 0)
  279.             continue;
  280.         switch (n) {
  281.         case 'P':
  282.             strncpy(passphrase, optarg, sizeof(passphrase));
  283.             passphrase[sizeof(passphrase) - 1] = '\0';
  284.             info.ssl_private_key_password = passphrase;
  285.             break;
  286.         case 'C':
  287.             strncpy(ssl_cert, optarg, sizeof(ssl_cert));
  288.             ssl_cert[sizeof(ssl_cert) - 1] = '\0';
  289.             disallow_selfsigned = 1;
  290.             break;
  291.         case 'k':
  292.             strncpy(ssl_key, optarg, sizeof(ssl_key));
  293.             ssl_key[sizeof(ssl_key) - 1] = '\0';
  294.             break;
  295.         case 'u':
  296.             strncpy(uri, optarg, sizeof(uri));
  297.             uri[sizeof(uri) - 1] = '\0';
  298.             break;
  299.  
  300. #ifndef LWS_NO_DAEMONIZE
  301.         case 'D':
  302.             daemonize = 1;
  303. #ifndef _WIN32
  304.             syslog_options &= ~LOG_PERROR;
  305. #endif
  306.             break;
  307. #endif
  308. #ifndef LWS_NO_CLIENT
  309.         case 'c':
  310.             client = 1;
  311.             strncpy(address, optarg, sizeof(address) - 1);
  312.             address[sizeof(address) - 1] = '\0';
  313.             port = 80;
  314.             break;
  315.         case 'r':
  316.             rate_us = atoi(optarg) * 1000;
  317.             break;
  318. #endif
  319.         case 'd':
  320.             debug_level = atoi(optarg);
  321.             break;
  322.         case 's':
  323.             use_ssl = 1; /* 1 = take care about cert verification, 2 = allow anything */
  324.             break;
  325.         case 'p':
  326.             port = atoi(optarg);
  327.             break;
  328.         case 'v':
  329.             versa = 1;
  330.             break;
  331.         case 'e':
  332.             protocols[0].name = "lws-echogen";
  333.             connect_protocol = protocols[0].name;
  334.             lwsl_err("using lws-echogen\n");
  335.             break;
  336.         case 'i':
  337.             strncpy(interface_name, optarg, sizeof interface_name);
  338.             interface_name[(sizeof interface_name) - 1] = '\0';
  339.             _interface = interface_name;
  340.             break;
  341.         case 'n':
  342.             times = atoi(optarg);
  343.             break;
  344.         case '?':
  345.         case 'h':
  346.             fprintf(stderr, "Usage: libwebsockets-test-echo\n"
  347.                 "  --debug      / -d <debug bitfield>\n"
  348.                 "  --port       / -p <port>\n"
  349.                 "  --ssl-cert   / -C <cert path>\n"
  350.                 "  --ssl-key    / -k <key path>\n"
  351. #ifndef LWS_NO_CLIENT
  352.                 "  --client     / -c <server IP>\n"
  353.                 "  --ratems     / -r <rate in ms>\n"
  354. #endif
  355.                 "  --ssl        / -s\n"
  356.                 "  --passphrase / -P <passphrase>\n"
  357.                 "  --interface  / -i <interface>\n"
  358.                 "  --uri        / -u <uri path>\n"
  359.                 "  --times      / -n <-1 unlimited or times to echo>\n"
  360. #ifndef LWS_NO_DAEMONIZE
  361.                 "  --daemonize  / -D\n"
  362. #endif
  363.             );
  364.             exit(1);
  365.         }
  366.     }
  367.  
  368. #ifndef LWS_NO_DAEMONIZE
  369.     /*
  370.      * normally lock path would be /var/lock/lwsts or similar, to
  371.      * simplify getting started without having to take care about
  372.      * permissions or running as root, set to /tmp/.lwsts-lock
  373.      */
  374. #if defined(WIN32) || defined(_WIN32)
  375. #else
  376.     if (!client && daemonize && lws_daemonize("/tmp/.lwstecho-lock")) {
  377.         fprintf(stderr, "Failed to daemonize\n");
  378.         return 1;
  379.     }
  380. #endif
  381. #endif
  382.  
  383. #ifndef _WIN32
  384.     /* we will only try to log things according to our debug_level */
  385.     setlogmask(LOG_UPTO (LOG_DEBUG));
  386.     openlog("lwsts", syslog_options, LOG_DAEMON);
  387. #endif
  388.  
  389.     /* tell the library what debug level to emit and to send it to syslog */
  390.     lws_set_log_level(debug_level, lwsl_emit_syslog);
  391.  
  392.     lwsl_notice("libwebsockets test server echo - license LGPL2.1+SLE\n");
  393.     lwsl_notice("(C) Copyright 2010-2016 Andy Green <andy@warmcat.com>\n");
  394.  
  395. #ifndef LWS_NO_CLIENT
  396.     if (client) {
  397.         lwsl_notice("Running in client mode\n");
  398.         listen_port = CONTEXT_PORT_NO_LISTEN;
  399.         if (use_ssl && !disallow_selfsigned) {
  400.             lwsl_info("allowing selfsigned\n");
  401.             use_ssl = 2;
  402.         } else {
  403.             lwsl_info("requiring server cert validation against %s\n",
  404.                   ssl_cert);
  405.             info.ssl_ca_filepath = ssl_cert;
  406.         }
  407.     } else {
  408. #endif
  409. #ifndef LWS_NO_SERVER
  410.         lwsl_notice("Running in server mode\n");
  411.         listen_port = port;
  412. #endif
  413. #ifndef LWS_NO_CLIENT
  414.     }
  415. #endif
  416.  
  417.     info.port = listen_port;
  418.     info.iface = _interface;
  419.     info.protocols = protocols;
  420.     if (use_ssl && !client) {
  421.         info.ssl_cert_filepath = ssl_cert;
  422.         info.ssl_private_key_filepath = ssl_key;
  423.     } else
  424.         if (use_ssl && client) {
  425.             info.ssl_cert_filepath = NULL;
  426.             info.ssl_private_key_filepath = NULL;
  427.         }
  428.     info.gid = -1;
  429.     info.uid = -1;
  430.     info.options = opts | LWS_SERVER_OPTION_VALIDATE_UTF8;
  431.  
  432.     if (use_ssl)
  433.         info.options |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
  434. #ifndef LWS_NO_EXTENSIONS
  435.     info.extensions = exts;
  436. #endif
  437.  
  438.     context = lws_create_context(&info);
  439.     if (context == NULL) {
  440.         lwsl_err("libwebsocket init failed\n");
  441.         return -1;
  442.     }
  443.  
  444.  
  445.     signal(SIGINT, sighandler);
  446.  
  447. #ifndef LWS_NO_CLIENT
  448.     gettimeofday(&tv, NULL);
  449.     oldus = ((unsigned long long)tv.tv_sec * 1000000) + tv.tv_usec;
  450. #endif
  451.  
  452.     n = 0;
  453.     while (n >= 0 && !force_exit) {
  454. #ifndef LWS_NO_CLIENT
  455.         if (client && !state && times) {
  456.             state = 1;
  457.             lwsl_notice("Client connecting to %s:%u....\n",
  458.                     address, port);
  459.             /* we are in client mode */
  460.  
  461.             address[sizeof(address) - 1] = '\0';
  462.             sprintf(ads_port, "%s:%u", address, port & 65535);
  463.             if (times > 0)
  464.                 times--;
  465.  
  466.             memset(&i, 0, sizeof(i));
  467.  
  468.             i.context = context;
  469.             i.address = address;
  470.             i.port = port;
  471.             i.ssl_connection = use_ssl;
  472.             i.path = uri;
  473.             i.host = ads_port;
  474.             i.origin = ads_port;
  475.             i.protocol = connect_protocol;
  476.             i.client_exts = exts;
  477.  
  478.             wsi = lws_client_connect_via_info(&i);
  479.             if (!wsi) {
  480.                 lwsl_err("Client failed to connect to %s:%u\n",
  481.                      address, port);
  482.                 goto bail;
  483.             }
  484.         }
  485.  
  486.         if (client && !versa && times) {
  487.             gettimeofday(&tv, NULL);
  488.  
  489.             if (((((unsigned long long)tv.tv_sec * 1000000) + tv.tv_usec) - oldus) > rate_us) {
  490.                 lws_callback_on_writable_all_protocol(context,
  491.                         &protocols[0]);
  492.                 oldus = ((unsigned long long)tv.tv_sec * 1000000) + tv.tv_usec;
  493.                 if (times > 0)
  494.                     times--;
  495.             }
  496.         }
  497.  
  498.         if (client && !state && !times)
  499.             break;
  500. #endif
  501.         n = lws_service(context, 10);
  502.     }
  503. #ifndef LWS_NO_CLIENT
  504. bail:
  505. #endif
  506.     lws_context_destroy(context);
  507.  
  508.     lwsl_notice("libwebsockets-test-echo exited cleanly\n");
  509. #ifndef _WIN32
  510.     closelog();
  511. #endif
  512.  
  513.     return 0;
  514. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement