libwebsockets-test-server-v2.0 showing how to use mounts and plugins
[platform/upstream/libwebsockets.git] / test-server / test-client.c
1 /*
2  * libwebsockets-test-client - libwebsockets test implementation
3  *
4  * Copyright (C) 2011-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 "lws_config.h"
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <getopt.h>
26 #include <string.h>
27 #include <signal.h>
28
29 #ifdef _WIN32
30 #define random rand
31 #include "gettimeofday.h"
32 #else
33 #include <syslog.h>
34 #include <sys/time.h>
35 #include <unistd.h>
36 #endif
37
38 #include "../lib/libwebsockets.h"
39
40 static int deny_deflate, deny_mux, longlived, mirror_lifetime;
41 static struct lws *wsi_dumb, *wsi_mirror;
42 static volatile int force_exit;
43 static unsigned int opts;
44 #if defined(LWS_USE_POLARSSL)
45 #else
46 #if defined(LWS_USE_MBEDTLS)
47 #else
48 #if defined(LWS_OPENSSL_SUPPORT) && defined(LWS_HAVE_SSL_CTX_set1_param)
49 char crl_path[1024] = "";
50 #endif
51 #endif
52 #endif
53
54 /*
55  * This demo shows how to connect multiple websockets simultaneously to a
56  * websocket server (there is no restriction on their having to be the same
57  * server just it simplifies the demo).
58  *
59  *  dumb-increment-protocol:  we connect to the server and print the number
60  *                              we are given
61  *
62  *  lws-mirror-protocol: draws random circles, which are mirrored on to every
63  *                              client (see them being drawn in every browser
64  *                              session also using the test server)
65  */
66
67 enum demo_protocols {
68
69         PROTOCOL_DUMB_INCREMENT,
70         PROTOCOL_LWS_MIRROR,
71
72         /* always last */
73         DEMO_PROTOCOL_COUNT
74 };
75
76
77 /*
78  * dumb_increment protocol
79  *
80  * since this also happens to be protocols[0], some callbacks that are not
81  * bound to a specific protocol also turn up here.
82  */
83
84 static int
85 callback_dumb_increment(struct lws *wsi, enum lws_callback_reasons reason,
86                         void *user, void *in, size_t len)
87 {
88         switch (reason) {
89
90         case LWS_CALLBACK_CLIENT_ESTABLISHED:
91                 lwsl_info("dumb: LWS_CALLBACK_CLIENT_ESTABLISHED\n");
92                 break;
93
94         case LWS_CALLBACK_CLOSED:
95                 lwsl_notice("dumb: LWS_CALLBACK_CLOSED\n");
96                 wsi_dumb = NULL;
97                 break;
98
99         case LWS_CALLBACK_CLIENT_RECEIVE:
100                 ((char *)in)[len] = '\0';
101                 lwsl_info("rx %d '%s'\n", (int)len, (char *)in);
102                 break;
103
104         /* because we are protocols[0] ... */
105
106         case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
107                 if (wsi == wsi_dumb) {
108                         lwsl_err("dumb: LWS_CALLBACK_CLIENT_CONNECTION_ERROR\n");
109                         wsi_dumb = NULL;
110                 }
111                 if (wsi == wsi_mirror) {
112                         lwsl_err("mirror: LWS_CALLBACK_CLIENT_CONNECTION_ERROR\n");
113                         wsi_mirror = NULL;
114                 }
115                 break;
116
117         case LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED:
118                 if ((strcmp(in, "deflate-stream") == 0) && deny_deflate) {
119                         lwsl_notice("denied deflate-stream extension\n");
120                         return 1;
121                 }
122                 if ((strcmp(in, "x-webkit-deflate-frame") == 0))
123                         return 1;
124                 if ((strcmp(in, "deflate-frame") == 0))
125                         return 1;
126                 break;
127
128         case LWS_CALLBACK_RECEIVE_CLIENT_HTTP:
129                 {
130                         char buffer[1024 + LWS_PRE];
131                         char *px = buffer + LWS_PRE;
132                         int lenx = sizeof(buffer) - LWS_PRE;
133
134                         lwsl_notice("LWS_CALLBACK_RECEIVE_CLIENT_HTTP\n");
135
136                         /*
137                          * Often you need to flow control this by something
138                          * else being writable.  In that case call the api
139                          * to get a callback when writable here, and do the
140                          * pending client read in the writeable callback of
141                          * the output.
142                          */
143                         if (lws_http_client_read(wsi, &px, &lenx) < 0)
144                                 return -1;
145                         while (lenx--)
146                                 putchar(*px++);
147                 }
148                 break;
149
150         case LWS_CALLBACK_COMPLETED_CLIENT_HTTP:
151                 wsi_dumb = NULL;
152                 force_exit = 1;
153                 break;
154
155 #if defined(LWS_USE_POLARSSL)
156 #else
157 #if defined(LWS_USE_MBEDTLS)
158 #else
159 #if defined(LWS_OPENSSL_SUPPORT) && defined(LWS_HAVE_SSL_CTX_set1_param)
160         case LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS:
161                 if (crl_path[0]) {
162                         /* Enable CRL checking of the server certificate */
163                         X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new();
164                         X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK);
165                         SSL_CTX_set1_param((SSL_CTX*)user, param);
166                         X509_STORE *store = SSL_CTX_get_cert_store((SSL_CTX*)user);
167                         X509_LOOKUP *lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
168                         int n = X509_load_cert_crl_file(lookup, crl_path, X509_FILETYPE_PEM);
169                         X509_VERIFY_PARAM_free(param);
170                         if (n != 1) {
171                                 char errbuf[256];
172                                 n = ERR_get_error();
173                                 lwsl_err("LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS: SSL error: %s (%d)\n", ERR_error_string(n, errbuf), n);
174                                 return 1;
175                         }
176                 }
177                 break;
178 #endif
179 #endif
180 #endif
181
182         default:
183                 break;
184         }
185
186         return 0;
187 }
188
189
190 /* lws-mirror_protocol */
191
192
193 static int
194 callback_lws_mirror(struct lws *wsi, enum lws_callback_reasons reason,
195                     void *user, void *in, size_t len)
196 {
197         unsigned char buf[LWS_PRE + 4096];
198         unsigned int rands[4];
199         int l = 0;
200         int n;
201
202         switch (reason) {
203         case LWS_CALLBACK_CLIENT_ESTABLISHED:
204
205                 lwsl_notice("mirror: LWS_CALLBACK_CLIENT_ESTABLISHED\n");
206
207                 lws_get_random(lws_get_context(wsi), rands, sizeof(rands[0]));
208                 mirror_lifetime = 16384 + (rands[0] & 65535);
209                 /* useful to test single connection stability */
210                 if (longlived)
211                         mirror_lifetime += 500000;
212
213                 lwsl_info("opened mirror connection with "
214                           "%d lifetime\n", mirror_lifetime);
215
216                 /*
217                  * mirror_lifetime is decremented each send, when it reaches
218                  * zero the connection is closed in the send callback.
219                  * When the close callback comes, wsi_mirror is set to NULL
220                  * so a new connection will be opened
221                  *
222                  * start the ball rolling,
223                  * LWS_CALLBACK_CLIENT_WRITEABLE will come next service
224                  */
225                 lws_callback_on_writable(wsi);
226                 break;
227
228         case LWS_CALLBACK_CLOSED:
229                 lwsl_notice("mirror: LWS_CALLBACK_CLOSED mirror_lifetime=%d\n", mirror_lifetime);
230                 wsi_mirror = NULL;
231                 break;
232
233         case LWS_CALLBACK_CLIENT_WRITEABLE:
234                 for (n = 0; n < 1; n++) {
235                         lws_get_random(lws_get_context(wsi), rands, sizeof(rands));
236                         l += sprintf((char *)&buf[LWS_PRE + l],
237                                         "c #%06X %u %u %u;",
238                                         rands[0] & 0xffffff,    /* colour */
239                                         rands[1] & 511,         /* x */
240                                         rands[2] & 255,         /* y */
241                                         (rands[3] & 31) + 1);   /* radius */
242                 }
243
244                 n = lws_write(wsi, &buf[LWS_PRE], l,
245                               opts | LWS_WRITE_TEXT);
246                 if (n < 0)
247                         return -1;
248                 if (n < l) {
249                         lwsl_err("Partial write LWS_CALLBACK_CLIENT_WRITEABLE\n");
250                         return -1;
251                 }
252
253                 mirror_lifetime--;
254                 if (!mirror_lifetime) {
255                         lwsl_info("closing mirror session\n");
256                         return -1;
257                 }
258                 /* get notified as soon as we can write again */
259                 lws_callback_on_writable(wsi);
260                 break;
261
262         default:
263                 break;
264         }
265
266         return 0;
267 }
268
269
270 /* list of supported protocols and callbacks */
271
272 static struct lws_protocols protocols[] = {
273         {
274                 "dumb-increment-protocol,fake-nonexistant-protocol",
275                 callback_dumb_increment,
276                 0,
277                 20,
278         },
279         {
280                 "fake-nonexistant-protocol,lws-mirror-protocol",
281                 callback_lws_mirror,
282                 0,
283                 128,
284         },
285         { NULL, NULL, 0, 0 } /* end */
286 };
287
288 static const struct lws_extension exts[] = {
289         {
290                 "permessage-deflate",
291                 lws_extension_callback_pm_deflate,
292                 "permessage-deflate; client_max_window_bits"
293         },
294         {
295                 "deflate-frame",
296                 lws_extension_callback_pm_deflate,
297                 "deflate_frame"
298         },
299         { NULL, NULL, NULL /* terminator */ }
300 };
301
302
303
304 void sighandler(int sig)
305 {
306         force_exit = 1;
307 }
308
309 static struct option options[] = {
310         { "help",       no_argument,            NULL, 'h' },
311         { "debug",      required_argument,      NULL, 'd' },
312         { "port",       required_argument,      NULL, 'p' },
313         { "ssl",        no_argument,            NULL, 's' },
314         { "version",    required_argument,      NULL, 'v' },
315         { "undeflated", no_argument,            NULL, 'u' },
316         { "nomux",      no_argument,            NULL, 'n' },
317         { "longlived",  no_argument,            NULL, 'l' },
318         { "ssl-cert",  required_argument,       NULL, 'C' },
319         { "ssl-key",  required_argument,        NULL, 'K' },
320         { "ssl-ca",  required_argument,         NULL, 'A' },
321 #if defined(LWS_OPENSSL_SUPPORT) && defined(LWS_HAVE_SSL_CTX_set1_param)
322         { "ssl-crl",  required_argument,                NULL, 'R' },
323 #endif
324         { NULL, 0, 0, 0 }
325 };
326
327 static int ratelimit_connects(unsigned int *last, unsigned int secs)
328 {
329         struct timeval tv;
330
331         gettimeofday(&tv, NULL);
332         if (tv.tv_sec - (*last) < secs)
333                 return 0;
334
335         *last = tv.tv_sec;
336
337         return 1;
338 }
339
340 int main(int argc, char **argv)
341 {
342         int n = 0, ret = 0, port = 7681, use_ssl = 0, ietf_version = -1;
343         unsigned int rl_dumb = 0, rl_mirror = 0, do_ws = 1;
344         struct lws_context_creation_info info;
345         struct lws_client_connect_info i;
346         struct lws_context *context;
347         const char *prot, *p;
348         char path[300];
349         char cert_path[1024] = "";
350         char key_path[1024] = "";
351         char ca_path[1024] = "";
352
353         memset(&info, 0, sizeof info);
354
355         lwsl_notice("libwebsockets test client - license LGPL2.1+SLE\n");
356         lwsl_notice("(C) Copyright 2010-2016 Andy Green <andy@warmcat.com>\n");
357
358         if (argc < 2)
359                 goto usage;
360
361         while (n >= 0) {
362                 n = getopt_long(argc, argv, "nuv:hsp:d:lC:K:A:", options, NULL);
363                 if (n < 0)
364                         continue;
365                 switch (n) {
366                 case 'd':
367                         lws_set_log_level(atoi(optarg), NULL);
368                         break;
369                 case 's':
370                         use_ssl = 2; /* 2 = allow selfsigned */
371                         break;
372                 case 'p':
373                         port = atoi(optarg);
374                         break;
375                 case 'l':
376                         longlived = 1;
377                         break;
378                 case 'v':
379                         ietf_version = atoi(optarg);
380                         break;
381                 case 'u':
382                         deny_deflate = 1;
383                         break;
384                 case 'n':
385                         deny_mux = 1;
386                         break;
387                 case 'C':
388                         strncpy(cert_path, optarg, sizeof(cert_path) - 1);
389                         cert_path[sizeof(cert_path) - 1] = '\0';
390                         break;
391                 case 'K':
392                         strncpy(key_path, optarg, sizeof(key_path) - 1);
393                         key_path[sizeof(key_path) - 1] = '\0';
394                         break;
395                 case 'A':
396                         strncpy(ca_path, optarg, sizeof(ca_path) - 1);
397                         ca_path[sizeof(ca_path) - 1] = '\0';
398                         break;
399 #if defined(LWS_USE_POLARSSL)
400 #else
401 #if defined(LWS_USE_MBEDTLS)
402 #else
403 #if defined(LWS_OPENSSL_SUPPORT) && defined(LWS_HAVE_SSL_CTX_set1_param)
404                 case 'R':
405                         strncpy(crl_path, optarg, sizeof(crl_path) - 1);
406                         crl_path[sizeof(crl_path) - 1] = '\0';
407                         break;
408 #endif
409 #endif
410 #endif
411                 case 'h':
412                         goto usage;
413                 }
414         }
415
416         if (optind >= argc)
417                 goto usage;
418
419         signal(SIGINT, sighandler);
420
421         memset(&i, 0, sizeof(i));
422
423         i.port = port;
424         if (lws_parse_uri(argv[optind], &prot, &i.address, &i.port, &p))
425                 goto usage;
426
427         /* add back the leading / on path */
428         path[0] = '/';
429         strncpy(path + 1, p, sizeof(path) - 2);
430         path[sizeof(path) - 1] = '\0';
431         i.path = path;
432
433         if (!strcmp(prot, "http") || !strcmp(prot, "ws"))
434                 use_ssl = 0;
435         if (!strcmp(prot, "https") || !strcmp(prot, "wss"))
436                 use_ssl = 1;
437
438         /*
439          * create the websockets context.  This tracks open connections and
440          * knows how to route any traffic and which protocol version to use,
441          * and if each connection is client or server side.
442          *
443          * For this client-only demo, we tell it to not listen on any port.
444          */
445
446         info.port = CONTEXT_PORT_NO_LISTEN;
447         info.protocols = protocols;
448         info.gid = -1;
449         info.uid = -1;
450
451         if (use_ssl) {
452                 info.options |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
453
454                 /*
455                  * If the server wants us to present a valid SSL client certificate
456                  * then we can set it up here.
457                  */
458
459                 if (cert_path[0])
460                         info.ssl_cert_filepath = cert_path;
461                 if (key_path[0])
462                         info.ssl_private_key_filepath = key_path;
463
464                 /*
465                  * A CA cert and CRL can be used to validate the cert send by the server
466                  */
467                 if (ca_path[0])
468                         info.ssl_ca_filepath = ca_path;
469 #if defined(LWS_USE_POLARSSL)
470 #else
471 #if defined(LWS_USE_MBEDTLS)
472 #else
473 #if defined(LWS_OPENSSL_SUPPORT) && defined(LWS_HAVE_SSL_CTX_set1_param)
474                 else if (crl_path[0])
475                         lwsl_notice("WARNING, providing a CRL requires a CA cert!\n");
476 #endif
477 #endif
478 #endif
479         }
480
481         context = lws_create_context(&info);
482         if (context == NULL) {
483                 fprintf(stderr, "Creating libwebsocket context failed\n");
484                 return 1;
485         }
486
487         i.context = context;
488         i.ssl_connection = use_ssl;
489         i.host = i.address;
490         i.origin = i.address;
491         i.ietf_version_or_minus_one = ietf_version;
492         i.client_exts = exts;
493
494         if (!strcmp(prot, "http") || !strcmp(prot, "https")) {
495                 lwsl_notice("using %s mode (non-ws)\n", prot);
496                 i.method = "GET";
497                 do_ws = 0;
498         } else
499                 lwsl_notice("using %s mode (ws)\n", prot);
500
501         /*
502          * sit there servicing the websocket context to handle incoming
503          * packets, and drawing random circles on the mirror protocol websocket
504          *
505          * nothing happens until the client websocket connection is
506          * asynchronously established... calling lws_client_connect() only
507          * instantiates the connection logically, lws_service() progresses it
508          * asynchronously.
509          */
510
511         while (!force_exit) {
512
513                 if (do_ws) {
514                         if (!wsi_dumb && ratelimit_connects(&rl_dumb, 2u)) {
515                                 lwsl_notice("dumb: connecting\n");
516                                 i.protocol = protocols[PROTOCOL_DUMB_INCREMENT].name;
517                                 wsi_dumb = lws_client_connect_via_info(&i);
518                         }
519
520                         if (!wsi_mirror && ratelimit_connects(&rl_mirror, 2u)) {
521                                 lwsl_notice("mirror: connecting\n");
522                                 i.protocol = protocols[PROTOCOL_LWS_MIRROR].name;
523                                 wsi_mirror = lws_client_connect_via_info(&i);
524                         }
525                 } else
526                         if (!wsi_dumb && ratelimit_connects(&rl_dumb, 2u)) {
527                                 lwsl_notice("http: connecting\n");
528                                 wsi_dumb = lws_client_connect_via_info(&i);
529                         }
530
531                 lws_service(context, 500);
532         }
533
534         lwsl_err("Exiting\n");
535         lws_context_destroy(context);
536
537         return ret;
538
539 usage:
540         fprintf(stderr, "Usage: libwebsockets-test-client "
541                                 "<server address> [--port=<p>] "
542                                 "[--ssl] [-k] [-v <ver>] "
543                                 "[-d <log bitfield>] [-l]\n");
544         return 1;
545 }