test client reconnect if server disappears
[platform/upstream/libwebsockets.git] / test-server / test-client.c
1 /*
2  * libwebsockets-test-client - libwebsockets test implementation
3  *
4  * Copyright (C) 2011 Andy Green <andy@warmcat.com>
5  *
6  *  This library is free software; you can redistribute it and/or
7  *  modify it under the terms of the GNU Lesser General Public
8  *  License as published by the Free Software Foundation:
9  *  version 2.1 of the License.
10  *
11  *  This library is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  *  Lesser General Public License for more details.
15  *
16  *  You should have received a copy of the GNU Lesser General Public
17  *  License along with this library; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19  *  MA  02110-1301  USA
20  */
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <getopt.h>
25 #include <string.h>
26 #include <signal.h>
27
28 #ifdef _WIN32
29 #define random rand
30 #include "gettimeofday.h"
31 #else
32 #include <syslog.h>
33 #include <sys/time.h>
34 #include <unistd.h>
35 #endif
36
37 #include "../lib/libwebsockets.h"
38
39 static unsigned int opts;
40 static int deny_deflate;
41 static int deny_mux;
42 static struct lws *wsi_dumb, *wsi_mirror;
43 static int mirror_lifetime = 0;
44 static volatile int force_exit = 0;
45 static int longlived = 0;
46
47 /*
48  * This demo shows how to connect multiple websockets simultaneously to a
49  * websocket server (there is no restriction on their having to be the same
50  * server just it simplifies the demo).
51  *
52  *  dumb-increment-protocol:  we connect to the server and print the number
53  *                              we are given
54  *
55  *  lws-mirror-protocol: draws random circles, which are mirrored on to every
56  *                              client (see them being drawn in every browser
57  *                              session also using the test server)
58  */
59
60 enum demo_protocols {
61
62         PROTOCOL_DUMB_INCREMENT,
63         PROTOCOL_LWS_MIRROR,
64
65         /* always last */
66         DEMO_PROTOCOL_COUNT
67 };
68
69
70 /* dumb_increment protocol */
71
72 static int
73 callback_dumb_increment(struct lws_context *this,
74                         struct lws *wsi,
75                         enum lws_callback_reasons reason,
76                         void *user, void *in, size_t len)
77 {
78         switch (reason) {
79
80         case LWS_CALLBACK_CLIENT_ESTABLISHED:
81                 fprintf(stderr, "dumb: LWS_CALLBACK_CLIENT_ESTABLISHED\n");
82                 break;
83
84         /* this callback comes only at protocols[0] handler
85          * since at this time, no protocol had been negotiated
86          */
87         case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
88                 if (wsi == wsi_dumb) {
89                         lwsl_err("dumb: LWS_CALLBACK_CLIENT_CONNECTION_ERROR\n");
90                         wsi_dumb = NULL;
91                 }
92                 if (wsi == wsi_mirror) {
93                         lwsl_err("mirror: LWS_CALLBACK_CLIENT_CONNECTION_ERROR\n");
94                         wsi_mirror = NULL;
95                 }
96                 break;
97
98         case LWS_CALLBACK_CLOSED:
99                 lwsl_notice("dumb: LWS_CALLBACK_CLOSED\n");
100                 wsi_dumb = NULL;
101                 break;
102
103         case LWS_CALLBACK_CLIENT_RECEIVE:
104                 ((char *)in)[len] = '\0';
105                 fprintf(stderr, "rx %d '%s'\n", (int)len, (char *)in);
106                 break;
107
108         /* because we are protocols[0] ... */
109
110         case LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED:
111                 if ((strcmp(in, "deflate-stream") == 0) && deny_deflate) {
112                         fprintf(stderr, "denied deflate-stream extension\n");
113                         return 1;
114                 }
115                 if ((strcmp(in, "deflate-frame") == 0) && deny_deflate) {
116                         fprintf(stderr, "denied deflate-frame extension\n");
117                         return 1;
118                 }
119                 if ((strcmp(in, "x-google-mux") == 0) && deny_mux) {
120                         fprintf(stderr, "denied x-google-mux extension\n");
121                         return 1;
122                 }
123
124                 break;
125
126         default:
127                 break;
128         }
129
130         return 0;
131 }
132
133
134 /* lws-mirror_protocol */
135
136
137 static int
138 callback_lws_mirror(struct lws_context *context,
139                         struct lws *wsi,
140                         enum lws_callback_reasons reason,
141                                                void *user, void *in, size_t len)
142 {
143         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 4096 +
144                                                   LWS_SEND_BUFFER_POST_PADDING];
145         int l = 0;
146         int n;
147         unsigned int rands[4];
148
149         switch (reason) {
150
151         case LWS_CALLBACK_CLIENT_ESTABLISHED:
152
153                 lwsl_notice("mirror: LWS_CALLBACK_CLIENT_ESTABLISHED\n");
154
155                 lws_get_random(context, rands, sizeof(rands[0]));
156                 mirror_lifetime = 65535 + (rands[0] & 65535);
157                 /* useful to test single connection stability */
158                 if (longlived)
159                         mirror_lifetime += 500000;
160
161                 lwsl_info("opened mirror connection with "
162                           "%d lifetime\n", mirror_lifetime);
163
164                 /*
165                  * mirror_lifetime is decremented each send, when it reaches
166                  * zero the connection is closed in the send callback.
167                  * When the close callback comes, wsi_mirror is set to NULL
168                  * so a new connection will be opened
169                  */
170
171                 /*
172                  * start the ball rolling,
173                  * LWS_CALLBACK_CLIENT_WRITEABLE will come next service
174                  */
175
176                 lws_callback_on_writable(context, wsi);
177                 break;
178
179         case LWS_CALLBACK_CLOSED:
180                 lwsl_notice("mirror: LWS_CALLBACK_CLOSED mirror_lifetime=%d\n", mirror_lifetime);
181                 wsi_mirror = NULL;
182                 break;
183
184         case LWS_CALLBACK_CLIENT_RECEIVE:
185 /*              fprintf(stderr, "rx %d '%s'\n", (int)len, (char *)in); */
186                 break;
187
188         case LWS_CALLBACK_CLIENT_WRITEABLE:
189
190                 for (n = 0; n < 1; n++) {
191                         lws_get_random(context, rands, sizeof(rands));
192                         l += sprintf((char *)&buf[LWS_SEND_BUFFER_PRE_PADDING + l],
193                                         "c #%06X %d %d %d;",
194                                         (int)rands[0] & 0xffffff,
195                                         (int)rands[1] % 500,
196                                         (int)rands[2] % 250,
197                                         (int)rands[3] % 24);
198                 }
199
200                 n = lws_write(wsi,
201                    &buf[LWS_SEND_BUFFER_PRE_PADDING], l, opts | LWS_WRITE_TEXT);
202
203                 if (n < 0)
204                         return -1;
205                 if (n < l) {
206                         lwsl_err("Partial write LWS_CALLBACK_CLIENT_WRITEABLE\n");
207                         return -1;
208                 }
209
210                 mirror_lifetime--;
211                 if (!mirror_lifetime) {
212                         fprintf(stderr, "closing mirror session\n");
213                         return -1;
214                 } else
215                         /* get notified as soon as we can write again */
216                         lws_callback_on_writable(context, wsi);
217                 break;
218
219         default:
220                 break;
221         }
222
223         return 0;
224 }
225
226
227 /* list of supported protocols and callbacks */
228
229 static struct lws_protocols protocols[] = {
230         {
231                 "dumb-increment-protocol,fake-nonexistant-protocol",
232                 callback_dumb_increment,
233                 0,
234                 20,
235         },
236         {
237                 "fake-nonexistant-protocol,lws-mirror-protocol",
238                 callback_lws_mirror,
239                 0,
240                 128,
241         },
242         { NULL, NULL, 0, 0 } /* end */
243 };
244
245 void sighandler(int sig)
246 {
247         force_exit = 1;
248 }
249
250 static struct option options[] = {
251         { "help",       no_argument,            NULL, 'h' },
252         { "debug",      required_argument,      NULL, 'd' },
253         { "port",       required_argument,      NULL, 'p' },
254         { "ssl",        no_argument,            NULL, 's' },
255         { "version",    required_argument,      NULL, 'v' },
256         { "undeflated", no_argument,            NULL, 'u' },
257         { "nomux",      no_argument,            NULL, 'n' },
258         { "longlived",  no_argument,            NULL, 'l' },
259         { NULL, 0, 0, 0 }
260 };
261
262 static int ratelimit_connects(unsigned int *last, int secs)
263 {
264         struct timeval tv;
265
266         gettimeofday(&tv, NULL);
267         if (tv.tv_sec - (*last) < secs)
268                 return 0;
269
270         *last = tv.tv_sec;
271
272         return 1;
273 }
274
275 int main(int argc, char **argv)
276 {
277         int n = 0, ret = 0, port = 7681, use_ssl = 0;
278         unsigned int rl_dumb = 0, rl_mirror = 0;
279         struct lws_context_creation_info info;
280         struct lws_context *context;
281         int ietf_version = -1; /* latest */
282         const char *address;
283
284         memset(&info, 0, sizeof info);
285
286         fprintf(stderr, "libwebsockets test client\n"
287                         "(C) Copyright 2010-2015 Andy Green <andy@warmcat.com> "
288                         "licensed under LGPL2.1\n");
289
290         if (argc < 2)
291                 goto usage;
292
293         while (n >= 0) {
294                 n = getopt_long(argc, argv, "nuv:hsp:d:l", options, NULL);
295                 if (n < 0)
296                         continue;
297                 switch (n) {
298                 case 'd':
299                         lws_set_log_level(atoi(optarg), NULL);
300                         break;
301                 case 's':
302                         use_ssl = 2; /* 2 = allow selfsigned */
303                         break;
304                 case 'p':
305                         port = atoi(optarg);
306                         break;
307                 case 'l':
308                         longlived = 1;
309                         break;
310                 case 'v':
311                         ietf_version = atoi(optarg);
312                         break;
313                 case 'u':
314                         deny_deflate = 1;
315                         break;
316                 case 'n':
317                         deny_mux = 1;
318                         break;
319                 case 'h':
320                         goto usage;
321                 }
322         }
323
324         if (optind >= argc)
325                 goto usage;
326
327         signal(SIGINT, sighandler);
328
329         address = argv[optind];
330
331         /*
332          * create the websockets context.  This tracks open connections and
333          * knows how to route any traffic and which protocol version to use,
334          * and if each connection is client or server side.
335          *
336          * For this client-only demo, we tell it to not listen on any port.
337          */
338
339         info.port = CONTEXT_PORT_NO_LISTEN;
340         info.protocols = protocols;
341 #ifndef LWS_NO_EXTENSIONS
342         info.extensions = lws_get_internal_extensions();
343 #endif
344         info.gid = -1;
345         info.uid = -1;
346
347         context = lws_create_context(&info);
348         if (context == NULL) {
349                 fprintf(stderr, "Creating libwebsocket context failed\n");
350                 return 1;
351         }
352
353         /*
354          * sit there servicing the websocket context to handle incoming
355          * packets, and drawing random circles on the mirror protocol websocket
356          * nothing happens until the client websocket connection is
357          * asynchronously established
358          */
359
360         while (!force_exit) {
361
362                 if (!wsi_dumb && ratelimit_connects(&rl_dumb, 2)) {
363                         lwsl_notice("dumb: connecting\n");
364                         wsi_dumb = lws_client_connect(context, address, port,
365                                 use_ssl, "/", argv[optind], argv[optind],
366                                 protocols[PROTOCOL_DUMB_INCREMENT].name,
367                                 ietf_version);
368                 }
369
370                 if (!wsi_mirror && ratelimit_connects(&rl_mirror, 2)) {
371                         lwsl_notice("mirror: connecting\n");
372                         wsi_mirror = lws_client_connect(context,
373                                 address, port, use_ssl,  "/",
374                                 argv[optind], argv[optind],
375                                 protocols[PROTOCOL_LWS_MIRROR].name,
376                                 ietf_version);
377                 }
378
379                 lws_service(context, 500);
380         }
381
382         lwsl_err("Exiting\n");
383         lws_context_destroy(context);
384
385         return ret;
386
387 usage:
388         fprintf(stderr, "Usage: libwebsockets-test-client "
389                                 "<server address> [--port=<p>] "
390                                 "[--ssl] [-k] [-v <ver>] "
391                                 "[-d <log bitfield>] [-l]\n");
392         return 1;
393 }