blob: d18f7a7553fed2984ca4b1462bc3308f612b9a88 [file] [log] [blame]
Peter Hinz56885f32011-03-02 22:03:47 +00001/*
Andy Greena0da8a82010-11-08 17:12:19 +00002 * libwebsockets - small server side websockets and web server implementation
Andy Green8f037e42010-12-19 22:13:26 +00003 *
Andy Greena0da8a82010-11-08 17:12:19 +00004 * Copyright (C) 2010 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
Andy Green05a0a7b2010-10-31 17:51:39 +000020 */
21
Andy Green7c212cc2010-11-08 20:20:42 +000022#include "private-libwebsockets.h"
Andy Greenff95d7a2010-10-28 22:36:01 +010023
Peter Hinz56885f32011-03-02 22:03:47 +000024#ifdef WIN32
25
26#else
27#include <ifaddrs.h>
28#endif
Andy Greenbe93fef2011-02-14 20:25:43 +000029/*
30 * In-place str to lower case
31 */
32
33static void
34strtolower(char *s)
35{
36 while (*s) {
37 *s = tolower(*s);
38 s++;
39 }
40}
41
Andy Green0d338332011-02-12 11:57:43 +000042/* file descriptor hash management */
43
44struct libwebsocket *
Peter Hinz56885f32011-03-02 22:03:47 +000045wsi_from_fd(struct libwebsocket_context *context, int fd)
Andy Green0d338332011-02-12 11:57:43 +000046{
47 int h = LWS_FD_HASH(fd);
48 int n = 0;
49
Peter Hinz56885f32011-03-02 22:03:47 +000050 for (n = 0; n < context->fd_hashtable[h].length; n++)
51 if (context->fd_hashtable[h].wsi[n]->sock == fd)
52 return context->fd_hashtable[h].wsi[n];
Andy Green0d338332011-02-12 11:57:43 +000053
54 return NULL;
55}
56
57int
Peter Hinz56885f32011-03-02 22:03:47 +000058insert_wsi(struct libwebsocket_context *context, struct libwebsocket *wsi)
Andy Green0d338332011-02-12 11:57:43 +000059{
60 int h = LWS_FD_HASH(wsi->sock);
61
Peter Hinz56885f32011-03-02 22:03:47 +000062 if (context->fd_hashtable[h].length == MAX_CLIENTS - 1) {
Andy Green0d338332011-02-12 11:57:43 +000063 fprintf(stderr, "hash table overflow\n");
64 return 1;
65 }
66
Peter Hinz56885f32011-03-02 22:03:47 +000067 context->fd_hashtable[h].wsi[context->fd_hashtable[h].length++] = wsi;
Andy Green0d338332011-02-12 11:57:43 +000068
69 return 0;
70}
71
72int
Peter Hinz56885f32011-03-02 22:03:47 +000073delete_from_fd(struct libwebsocket_context *context, int fd)
Andy Green0d338332011-02-12 11:57:43 +000074{
75 int h = LWS_FD_HASH(fd);
76 int n = 0;
77
Peter Hinz56885f32011-03-02 22:03:47 +000078 for (n = 0; n < context->fd_hashtable[h].length; n++)
79 if (context->fd_hashtable[h].wsi[n]->sock == fd) {
80 while (n < context->fd_hashtable[h].length) {
81 context->fd_hashtable[h].wsi[n] =
82 context->fd_hashtable[h].wsi[n + 1];
Andy Green0d338332011-02-12 11:57:43 +000083 n++;
84 }
Peter Hinz56885f32011-03-02 22:03:47 +000085 context->fd_hashtable[h].length--;
Andy Green0d338332011-02-12 11:57:43 +000086
87 return 0;
88 }
89
90 fprintf(stderr, "Failed to find fd %d requested for "
91 "delete in hashtable\n", fd);
92 return 1;
93}
94
Andy Green1f9bf522011-02-14 21:14:37 +000095#ifdef LWS_OPENSSL_SUPPORT
96static void
97libwebsockets_decode_ssl_error(void)
98{
99 char buf[256];
100 u_long err;
101
102 while ((err = ERR_get_error()) != 0) {
103 ERR_error_string_n(err, buf, sizeof(buf));
104 fprintf(stderr, "*** %s\n", buf);
105 }
106}
107#endif
Andy Green0d338332011-02-12 11:57:43 +0000108
Andy Green32375b72011-02-19 08:32:53 +0000109
110static int
111interface_to_sa(const char* ifname, struct sockaddr_in *addr, size_t addrlen)
112{
113 int rc = -1;
Peter Hinz56885f32011-03-02 22:03:47 +0000114#ifdef WIN32
115 // TODO
116#else
Andy Green32375b72011-02-19 08:32:53 +0000117 struct ifaddrs *ifr;
118 struct ifaddrs *ifc;
119 struct sockaddr_in *sin;
120
121 getifaddrs(&ifr);
122 for (ifc = ifr; ifc != NULL; ifc = ifc->ifa_next) {
123 if (strcmp(ifc->ifa_name, ifname))
124 continue;
125 if (ifc->ifa_addr == NULL)
126 continue;
127 sin = (struct sockaddr_in *)ifc->ifa_addr;
128 if (sin->sin_family != AF_INET)
129 continue;
130 memcpy(addr, sin, addrlen);
131 rc = 0;
132 }
133
134 freeifaddrs(ifr);
Peter Hinz56885f32011-03-02 22:03:47 +0000135#endif
Andy Green32375b72011-02-19 08:32:53 +0000136 return rc;
137}
138
Andy Green8f037e42010-12-19 22:13:26 +0000139void
Peter Hinz56885f32011-03-02 22:03:47 +0000140libwebsocket_close_and_free_session(struct libwebsocket_context *context,
Andy Green687b0182011-02-26 11:04:01 +0000141 struct libwebsocket *wsi, enum lws_close_status reason)
Andy Green251f6fa2010-11-03 11:13:06 +0000142{
Andy Greenb45993c2010-12-18 15:13:50 +0000143 int n;
Andy Green62c54d22011-02-14 09:14:25 +0000144 int old_state;
Andy Green5e1fa172011-02-10 09:07:05 +0000145 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
146 LWS_SEND_BUFFER_POST_PADDING];
Andy Greenb45993c2010-12-18 15:13:50 +0000147
Andy Green4b6fbe12011-02-14 08:03:48 +0000148 if (!wsi)
Andy Greenb45993c2010-12-18 15:13:50 +0000149 return;
150
Andy Green62c54d22011-02-14 09:14:25 +0000151 old_state = wsi->state;
Andy Green251f6fa2010-11-03 11:13:06 +0000152
Andy Green62c54d22011-02-14 09:14:25 +0000153 if (old_state == WSI_STATE_DEAD_SOCKET)
Andy Green5e1fa172011-02-10 09:07:05 +0000154 return;
155
Andy Green4b6fbe12011-02-14 08:03:48 +0000156 /* remove this fd from wsi mapping hashtable */
157
Peter Hinz56885f32011-03-02 22:03:47 +0000158 delete_from_fd(context, wsi->sock);
Andy Green4b6fbe12011-02-14 08:03:48 +0000159
160 /* delete it from the internal poll list if still present */
161
Peter Hinz56885f32011-03-02 22:03:47 +0000162 for (n = 0; n < context->fds_count; n++) {
163 if (context->fds[n].fd != wsi->sock)
Andy Green4b6fbe12011-02-14 08:03:48 +0000164 continue;
Peter Hinz56885f32011-03-02 22:03:47 +0000165 while (n < context->fds_count - 1) {
166 context->fds[n] = context->fds[n + 1];
Andy Green4b6fbe12011-02-14 08:03:48 +0000167 n++;
168 }
Peter Hinz56885f32011-03-02 22:03:47 +0000169 context->fds_count--;
Andy Green4b6fbe12011-02-14 08:03:48 +0000170 /* we only have to deal with one */
Peter Hinz56885f32011-03-02 22:03:47 +0000171 n = context->fds_count;
Andy Green4b6fbe12011-02-14 08:03:48 +0000172 }
173
174 /* remove also from external POLL support via protocol 0 */
175
Peter Hinz56885f32011-03-02 22:03:47 +0000176 context->protocols[0].callback(context, wsi,
Andy Green4b6fbe12011-02-14 08:03:48 +0000177 LWS_CALLBACK_DEL_POLL_FD, (void *)(long)wsi->sock, NULL, 0);
178
Andy Green687b0182011-02-26 11:04:01 +0000179 wsi->close_reason = reason;
180
Andy Green5e1fa172011-02-10 09:07:05 +0000181 /*
182 * signal we are closing, libsocket_write will
183 * add any necessary version-specific stuff. If the write fails,
184 * no worries we are closing anyway. If we didn't initiate this
185 * close, then our state has been changed to
Andy Green4b6fbe12011-02-14 08:03:48 +0000186 * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this
Andy Green5e1fa172011-02-10 09:07:05 +0000187 */
188
Andy Green62c54d22011-02-14 09:14:25 +0000189 if (old_state == WSI_STATE_ESTABLISHED)
Andy Green5e1fa172011-02-10 09:07:05 +0000190 libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING], 0,
191 LWS_WRITE_CLOSE);
192
Andy Green251f6fa2010-11-03 11:13:06 +0000193 wsi->state = WSI_STATE_DEAD_SOCKET;
194
Andy Green4b6fbe12011-02-14 08:03:48 +0000195 /* tell the user it's all over for this guy */
196
Andy Greend4302732011-02-28 07:45:29 +0000197 if (wsi->protocol && wsi->protocol->callback &&
198 old_state == WSI_STATE_ESTABLISHED)
Peter Hinz56885f32011-03-02 22:03:47 +0000199 wsi->protocol->callback(context, wsi, LWS_CALLBACK_CLOSED,
Andy Greene77ddd82010-11-13 10:03:47 +0000200 wsi->user_space, NULL, 0);
Andy Green251f6fa2010-11-03 11:13:06 +0000201
Andy Green4b6fbe12011-02-14 08:03:48 +0000202 /* free up his allocations */
203
Andy Green251f6fa2010-11-03 11:13:06 +0000204 for (n = 0; n < WSI_TOKEN_COUNT; n++)
205 if (wsi->utf8_token[n].token)
206 free(wsi->utf8_token[n].token);
207
Andy Green0ca6a172010-12-19 20:50:01 +0000208/* fprintf(stderr, "closing fd=%d\n", wsi->sock); */
Andy Green251f6fa2010-11-03 11:13:06 +0000209
Andy Green3faa9c72010-11-08 17:03:03 +0000210#ifdef LWS_OPENSSL_SUPPORT
Andy Green90c7cbc2011-01-27 06:26:52 +0000211 if (wsi->ssl) {
Andy Green3faa9c72010-11-08 17:03:03 +0000212 n = SSL_get_fd(wsi->ssl);
213 SSL_shutdown(wsi->ssl);
Peter Hinz56885f32011-03-02 22:03:47 +0000214#ifdef WIN32
215 closesocket(n);
216#else
Andy Green3faa9c72010-11-08 17:03:03 +0000217 close(n);
Peter Hinz56885f32011-03-02 22:03:47 +0000218#endif
Andy Green3faa9c72010-11-08 17:03:03 +0000219 SSL_free(wsi->ssl);
220 } else {
221#endif
222 shutdown(wsi->sock, SHUT_RDWR);
Peter Hinz56885f32011-03-02 22:03:47 +0000223#ifdef WIN32
224 closesocket(wsi->sock);
225#else
Andy Green3faa9c72010-11-08 17:03:03 +0000226 close(wsi->sock);
Peter Hinz56885f32011-03-02 22:03:47 +0000227#endif
Andy Green3faa9c72010-11-08 17:03:03 +0000228#ifdef LWS_OPENSSL_SUPPORT
229 }
230#endif
Andy Green4f3943a2010-11-12 10:44:16 +0000231 if (wsi->user_space)
232 free(wsi->user_space);
233
Andy Green251f6fa2010-11-03 11:13:06 +0000234 free(wsi);
235}
236
Andy Green07034092011-02-13 08:37:12 +0000237/**
Andy Greenf7ee5492011-02-13 09:04:21 +0000238 * libwebsockets_hangup_on_client() - Server calls to terminate client
239 * connection
Peter Hinz56885f32011-03-02 22:03:47 +0000240 * @context: libwebsockets context
Andy Greenf7ee5492011-02-13 09:04:21 +0000241 * @fd: Connection socket descriptor
242 */
243
244void
Peter Hinz56885f32011-03-02 22:03:47 +0000245libwebsockets_hangup_on_client(struct libwebsocket_context *context, int fd)
Andy Greenf7ee5492011-02-13 09:04:21 +0000246{
Peter Hinz56885f32011-03-02 22:03:47 +0000247 struct libwebsocket *wsi = wsi_from_fd(context, fd);
Andy Greenf7ee5492011-02-13 09:04:21 +0000248
249 if (wsi == NULL)
250 return;
251
Peter Hinz56885f32011-03-02 22:03:47 +0000252 libwebsocket_close_and_free_session(context, wsi,
Andy Green6da560c2011-02-26 11:06:27 +0000253 LWS_CLOSE_STATUS_NOSTATUS);
Andy Greenf7ee5492011-02-13 09:04:21 +0000254}
255
256
257/**
Andy Green07034092011-02-13 08:37:12 +0000258 * libwebsockets_get_peer_addresses() - Get client address information
259 * @fd: Connection socket descriptor
260 * @name: Buffer to take client address name
261 * @name_len: Length of client address name buffer
262 * @rip: Buffer to take client address IP qotted quad
263 * @rip_len: Length of client address IP buffer
264 *
265 * This function fills in @name and @rip with the name and IP of
266 * the client connected with socket descriptor @fd. Names may be
267 * truncated if there is not enough room. If either cannot be
268 * determined, they will be returned as valid zero-length strings.
269 */
270
271void
272libwebsockets_get_peer_addresses(int fd, char *name, int name_len,
273 char *rip, int rip_len)
274{
275 unsigned int len;
276 struct sockaddr_in sin;
277 struct hostent *host;
278 struct hostent *host1;
279 char ip[128];
280 char *p;
281 int n;
282
283 rip[0] = '\0';
284 name[0] = '\0';
285
286 len = sizeof sin;
287 if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
288 perror("getpeername");
289 return;
290 }
291
292 host = gethostbyaddr((char *) &sin.sin_addr, sizeof sin.sin_addr,
293 AF_INET);
294 if (host == NULL) {
295 perror("gethostbyaddr");
296 return;
297 }
298
299 strncpy(name, host->h_name, name_len);
300 name[name_len - 1] = '\0';
301
302 host1 = gethostbyname(host->h_name);
303 if (host1 == NULL)
304 return;
305 p = (char *)host1;
306 n = 0;
307 while (p != NULL) {
308 p = host1->h_addr_list[n++];
309 if (p == NULL)
310 continue;
311 if (host1->h_addrtype != AF_INET)
312 continue;
313
314 sprintf(ip, "%d.%d.%d.%d",
315 p[0], p[1], p[2], p[3]);
316 p = NULL;
317 strncpy(rip, ip, rip_len);
318 rip[rip_len - 1] = '\0';
319 }
320}
Andy Green9f990342011-02-12 11:57:45 +0000321
Peter Hinz56885f32011-03-02 22:03:47 +0000322int libwebsockets_get_random(struct libwebsocket_context *context,
323 void *buf, int len)
324{
325 int n;
326 char *p = buf;
327
328#ifdef WIN32
329 for (n = 0; n < len; n++)
330 p[n] = (unsigned char)rand();
331#else
332 n = read(context->fd_random, p, len);
333#endif
334
335 return n;
336}
337
Andy Greeneeaacb32011-03-01 20:44:24 +0000338void libwebsockets_00_spaceout(char *key, int spaces, int seed)
339{
340 char *p;
Peter Hinz56885f32011-03-02 22:03:47 +0000341
Andy Greeneeaacb32011-03-01 20:44:24 +0000342 key++;
343 while (spaces--) {
344 if (*key && (seed & 1))
345 key++;
346 seed >>= 1;
Peter Hinz56885f32011-03-02 22:03:47 +0000347
Andy Greeneeaacb32011-03-01 20:44:24 +0000348 p = key + strlen(key);
349 while (p >= key) {
350 p[1] = p[0];
351 p--;
352 }
353 *key++ = ' ';
354 }
355}
356
357void libwebsockets_00_spam(char *key, int count, int seed)
358{
359 char *p;
360
361 key++;
362 while (count--) {
363
364 if (*key && (seed & 1))
365 key++;
366 seed >>= 1;
367
368 p = key + strlen(key);
369 while (p >= key) {
370 p[1] = p[0];
371 p--;
372 }
373 *key++ = 0x21 + ((seed & 0xffff) % 15);
374 /* 4 would use it up too fast.. not like it matters */
375 seed >>= 1;
376 }
377}
378
Andy Green9f990342011-02-12 11:57:45 +0000379/**
380 * libwebsocket_service_fd() - Service polled socket with something waiting
Peter Hinz56885f32011-03-02 22:03:47 +0000381 * @context: Websocket context
Andy Green9f990342011-02-12 11:57:45 +0000382 * @pollfd: The pollfd entry describing the socket fd and which events
383 * happened.
384 *
385 * This function closes any active connections and then frees the
386 * context. After calling this, any further use of the context is
387 * undefined.
388 */
389
390int
Peter Hinz56885f32011-03-02 22:03:47 +0000391libwebsocket_service_fd(struct libwebsocket_context *context,
Andy Green0d338332011-02-12 11:57:43 +0000392 struct pollfd *pollfd)
Andy Greenb45993c2010-12-18 15:13:50 +0000393{
394 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + MAX_BROADCAST_PAYLOAD +
395 LWS_SEND_BUFFER_POST_PADDING];
Andy Greena71eafc2011-02-14 17:59:43 +0000396 struct libwebsocket *wsi;
Andy Green0d338332011-02-12 11:57:43 +0000397 struct libwebsocket *new_wsi;
Andy Greenb45993c2010-12-18 15:13:50 +0000398 int n;
Andy Green0d338332011-02-12 11:57:43 +0000399 int m;
Andy Greenb45993c2010-12-18 15:13:50 +0000400 size_t len;
Andy Green0d338332011-02-12 11:57:43 +0000401 int accept_fd;
402 unsigned int clilen;
403 struct sockaddr_in cli_addr;
Andy Greena71eafc2011-02-14 17:59:43 +0000404 struct timeval tv;
Andy Greenbe93fef2011-02-14 20:25:43 +0000405 static const char magic_websocket_guid[] =
406 "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
407 static const char magic_websocket_04_masking_guid[] =
408 "61AC5F19-FBBA-4540-B96F-6561F1AB40A8";
409 char hash[20];
410 char pkt[1024];
411 char *p = &pkt[0];
412 const char *pc;
413 int okay = 0;
414#ifdef LWS_OPENSSL_SUPPORT
415 char ssl_err_buf[512];
416#endif
Andy Greena71eafc2011-02-14 17:59:43 +0000417 /*
418 * you can call us with pollfd = NULL to just allow the once-per-second
419 * global timeout checks; if less than a second since the last check
420 * it returns immediately then.
421 */
422
423 gettimeofday(&tv, NULL);
424
Peter Hinz56885f32011-03-02 22:03:47 +0000425 if (context->last_timeout_check_s != tv.tv_sec) {
426 context->last_timeout_check_s = tv.tv_sec;
Andy Greena71eafc2011-02-14 17:59:43 +0000427
428 /* global timeout check once per second */
429
Peter Hinz56885f32011-03-02 22:03:47 +0000430 for (n = 0; n < context->fds_count; n++) {
431 wsi = wsi_from_fd(context, context->fds[n].fd);
Andy Greena71eafc2011-02-14 17:59:43 +0000432 if (!wsi->pending_timeout)
433 continue;
434
435 /*
436 * if we went beyond the allowed time, kill the
437 * connection
438 */
439
440 if (tv.tv_sec > wsi->pending_timeout_limit)
Peter Hinz56885f32011-03-02 22:03:47 +0000441 libwebsocket_close_and_free_session(context,
442 wsi, LWS_CLOSE_STATUS_NOSTATUS);
Andy Greena71eafc2011-02-14 17:59:43 +0000443 }
444 }
445
446 /* just here for timeout management? */
447
448 if (pollfd == NULL)
449 return 0;
450
451 /* no, here to service a socket descriptor */
452
Peter Hinz56885f32011-03-02 22:03:47 +0000453 wsi = wsi_from_fd(context, pollfd->fd);
Andy Greenb45993c2010-12-18 15:13:50 +0000454
Andy Green0d338332011-02-12 11:57:43 +0000455 if (wsi == NULL)
456 return 1;
Andy Green8f037e42010-12-19 22:13:26 +0000457
Andy Green0d338332011-02-12 11:57:43 +0000458 switch (wsi->mode) {
459 case LWS_CONNMODE_SERVER_LISTENER:
460
461 /* pollin means a client has connected to us then */
462
463 if (!pollfd->revents & POLLIN)
464 break;
465
466 /* listen socket got an unencrypted connection... */
467
468 clilen = sizeof(cli_addr);
469 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
470 &clilen);
471 if (accept_fd < 0) {
472 fprintf(stderr, "ERROR on accept");
473 break;
474 }
475
Peter Hinz56885f32011-03-02 22:03:47 +0000476 if (context->fds_count >= MAX_CLIENTS) {
Andy Green3221f922011-02-12 13:14:11 +0000477 fprintf(stderr, "too busy to accept new client\n");
Peter Hinz56885f32011-03-02 22:03:47 +0000478#ifdef WIN32
479 closesocket(accept_fd);
480#else
Andy Green0d338332011-02-12 11:57:43 +0000481 close(accept_fd);
Peter Hinz56885f32011-03-02 22:03:47 +0000482#endif
Andy Green0d338332011-02-12 11:57:43 +0000483 break;
484 }
485
Andy Green07034092011-02-13 08:37:12 +0000486 /*
487 * look at who we connected to and give user code a chance
488 * to reject based on client IP. There's no protocol selected
489 * yet so we issue this to protocols[0]
490 */
491
Peter Hinz56885f32011-03-02 22:03:47 +0000492 if ((context->protocols[0].callback)(context, wsi,
Andy Green07034092011-02-13 08:37:12 +0000493 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
494 (void*)(long)accept_fd, NULL, 0)) {
495 fprintf(stderr, "Callback denied network connection\n");
Peter Hinz56885f32011-03-02 22:03:47 +0000496#ifdef WIN32
497 closesocket(accept_fd);
498#else
Andy Green07034092011-02-13 08:37:12 +0000499 close(accept_fd);
Peter Hinz56885f32011-03-02 22:03:47 +0000500#endif
Andy Green07034092011-02-13 08:37:12 +0000501 break;
502 }
503
Andy Green0d338332011-02-12 11:57:43 +0000504 /* accepting connection to main listener */
505
506 new_wsi = malloc(sizeof(struct libwebsocket));
507 if (new_wsi == NULL) {
508 fprintf(stderr, "Out of memory for new connection\n");
509 break;
510 }
511
512 memset(new_wsi, 0, sizeof (struct libwebsocket));
513 new_wsi->sock = accept_fd;
Andy Greena71eafc2011-02-14 17:59:43 +0000514 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
Andy Green0d338332011-02-12 11:57:43 +0000515
516#ifdef LWS_OPENSSL_SUPPORT
517 new_wsi->ssl = NULL;
Andy Green0d338332011-02-12 11:57:43 +0000518
Peter Hinz56885f32011-03-02 22:03:47 +0000519 if (context->use_ssl) {
Andy Green0d338332011-02-12 11:57:43 +0000520
Peter Hinz56885f32011-03-02 22:03:47 +0000521 new_wsi->ssl = SSL_new(context->ssl_ctx);
Andy Green0d338332011-02-12 11:57:43 +0000522 if (new_wsi->ssl == NULL) {
523 fprintf(stderr, "SSL_new failed: %s\n",
524 ERR_error_string(SSL_get_error(
525 new_wsi->ssl, 0), NULL));
Andy Green1f9bf522011-02-14 21:14:37 +0000526 libwebsockets_decode_ssl_error();
Andy Green0d338332011-02-12 11:57:43 +0000527 free(new_wsi);
528 break;
529 }
530
531 SSL_set_fd(new_wsi->ssl, accept_fd);
532
533 n = SSL_accept(new_wsi->ssl);
534 if (n != 1) {
535 /*
536 * browsers seem to probe with various
537 * ssl params which fail then retry
538 * and succeed
539 */
540 debug("SSL_accept failed skt %u: %s\n",
541 pollfd->fd,
542 ERR_error_string(SSL_get_error(
543 new_wsi->ssl, n), NULL));
544 SSL_free(
545 new_wsi->ssl);
546 free(new_wsi);
547 break;
548 }
Andy Greenc6bf2c22011-02-20 11:10:47 +0000549
Andy Green0d338332011-02-12 11:57:43 +0000550 debug("accepted new SSL conn "
551 "port %u on fd=%d SSL ver %s\n",
552 ntohs(cli_addr.sin_port), accept_fd,
553 SSL_get_version(new_wsi->ssl));
554
555 } else
556#endif
557 debug("accepted new conn port %u on fd=%d\n",
558 ntohs(cli_addr.sin_port), accept_fd);
559
560 /* intialize the instance struct */
561
562 new_wsi->state = WSI_STATE_HTTP;
563 new_wsi->name_buffer_pos = 0;
564 new_wsi->mode = LWS_CONNMODE_WS_SERVING;
565
566 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
567 new_wsi->utf8_token[n].token = NULL;
568 new_wsi->utf8_token[n].token_len = 0;
569 }
570
571 /*
572 * these can only be set once the protocol is known
573 * we set an unestablished connection's protocol pointer
574 * to the start of the supported list, so it can look
575 * for matching ones during the handshake
576 */
Peter Hinz56885f32011-03-02 22:03:47 +0000577 new_wsi->protocol = context->protocols;
Andy Green0d338332011-02-12 11:57:43 +0000578 new_wsi->user_space = NULL;
579
580 /*
581 * Default protocol is 76 / 00
582 * After 76, there's a header specified to inform which
583 * draft the client wants, when that's seen we modify
584 * the individual connection's spec revision accordingly
585 */
586 new_wsi->ietf_spec_revision = 0;
587
Peter Hinz56885f32011-03-02 22:03:47 +0000588 insert_wsi(context, new_wsi);
Andy Green0d338332011-02-12 11:57:43 +0000589
Andy Green0d338332011-02-12 11:57:43 +0000590 /*
591 * make sure NO events are seen yet on this new socket
592 * (otherwise we inherit old fds[client].revents from
593 * previous socket there and die mysteriously! )
594 */
Peter Hinz56885f32011-03-02 22:03:47 +0000595 context->fds[context->fds_count].revents = 0;
Andy Green0d338332011-02-12 11:57:43 +0000596
Peter Hinz56885f32011-03-02 22:03:47 +0000597 context->fds[context->fds_count].events = POLLIN;
598 context->fds[context->fds_count++].fd = accept_fd;
Andy Green0d338332011-02-12 11:57:43 +0000599
Andy Green3221f922011-02-12 13:14:11 +0000600 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +0000601 context->protocols[0].callback(context, new_wsi,
Andy Green3221f922011-02-12 13:14:11 +0000602 LWS_CALLBACK_ADD_POLL_FD,
603 (void *)(long)accept_fd, NULL, POLLIN);
604
Andy Green0d338332011-02-12 11:57:43 +0000605 break;
606
607 case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
608
609 /* as we are listening, POLLIN means accept() is needed */
610
611 if (!pollfd->revents & POLLIN)
612 break;
613
614 /* listen socket got an unencrypted connection... */
615
616 clilen = sizeof(cli_addr);
617 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
618 &clilen);
619 if (accept_fd < 0) {
620 fprintf(stderr, "ERROR on accept");
621 break;
622 }
623
Peter Hinz56885f32011-03-02 22:03:47 +0000624 if (context->fds_count >= MAX_CLIENTS) {
Andy Green3221f922011-02-12 13:14:11 +0000625 fprintf(stderr, "too busy to accept new broadcast "
626 "proxy client\n");
Peter Hinz56885f32011-03-02 22:03:47 +0000627#ifdef WIN32
628 closesocket(accept_fd);
629#else
Andy Green0d338332011-02-12 11:57:43 +0000630 close(accept_fd);
Peter Hinz56885f32011-03-02 22:03:47 +0000631#endif
Andy Green0d338332011-02-12 11:57:43 +0000632 break;
633 }
634
635 /* create a dummy wsi for the connection and add it */
636
637 new_wsi = malloc(sizeof(struct libwebsocket));
638 memset(new_wsi, 0, sizeof (struct libwebsocket));
639 new_wsi->sock = accept_fd;
640 new_wsi->mode = LWS_CONNMODE_BROADCAST_PROXY;
641 new_wsi->state = WSI_STATE_ESTABLISHED;
642 /* note which protocol we are proxying */
643 new_wsi->protocol_index_for_broadcast_proxy =
644 wsi->protocol_index_for_broadcast_proxy;
Peter Hinz56885f32011-03-02 22:03:47 +0000645 insert_wsi(context, new_wsi);
Andy Green0d338332011-02-12 11:57:43 +0000646
647 /* add connected socket to internal poll array */
648
Peter Hinz56885f32011-03-02 22:03:47 +0000649 context->fds[context->fds_count].revents = 0;
650 context->fds[context->fds_count].events = POLLIN;
651 context->fds[context->fds_count++].fd = accept_fd;
Andy Green0d338332011-02-12 11:57:43 +0000652
Andy Green3221f922011-02-12 13:14:11 +0000653 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +0000654 context->protocols[0].callback(context, new_wsi,
Andy Green3221f922011-02-12 13:14:11 +0000655 LWS_CALLBACK_ADD_POLL_FD,
656 (void *)(long)accept_fd, NULL, POLLIN);
657
Andy Green0d338332011-02-12 11:57:43 +0000658 break;
659
660 case LWS_CONNMODE_BROADCAST_PROXY:
Andy Green8f037e42010-12-19 22:13:26 +0000661
Andy Greenb45993c2010-12-18 15:13:50 +0000662 /* handle session socket closed */
Andy Green8f037e42010-12-19 22:13:26 +0000663
Andy Green0d338332011-02-12 11:57:43 +0000664 if (pollfd->revents & (POLLERR | POLLHUP)) {
Andy Green8f037e42010-12-19 22:13:26 +0000665
Andy Green0d338332011-02-12 11:57:43 +0000666 debug("Session Socket %p (fd=%d) dead\n",
Timothy J Fontaineb86d64e2011-02-14 17:55:27 +0000667 (void *)wsi, pollfd->fd);
Andy Greenb45993c2010-12-18 15:13:50 +0000668
Peter Hinz56885f32011-03-02 22:03:47 +0000669 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +0000670 LWS_CLOSE_STATUS_NORMAL);
Andy Green4b6fbe12011-02-14 08:03:48 +0000671 return 1;
Andy Greenb45993c2010-12-18 15:13:50 +0000672 }
Andy Green8f037e42010-12-19 22:13:26 +0000673
Andy Green90c7cbc2011-01-27 06:26:52 +0000674 /* the guy requested a callback when it was OK to write */
675
Andy Green0d338332011-02-12 11:57:43 +0000676 if (pollfd->revents & POLLOUT) {
Andy Green90c7cbc2011-01-27 06:26:52 +0000677
Andy Green0d338332011-02-12 11:57:43 +0000678 /* one shot */
Andy Green90c7cbc2011-01-27 06:26:52 +0000679
Andy Green0d338332011-02-12 11:57:43 +0000680 pollfd->events &= ~POLLOUT;
681
Andy Green3221f922011-02-12 13:14:11 +0000682 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +0000683 context->protocols[0].callback(context, wsi,
Andy Green3221f922011-02-12 13:14:11 +0000684 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
685 (void *)(long)wsi->sock, NULL, POLLOUT);
686
Peter Hinz56885f32011-03-02 22:03:47 +0000687 wsi->protocol->callback(context, wsi,
Andy Green90c7cbc2011-01-27 06:26:52 +0000688 LWS_CALLBACK_CLIENT_WRITEABLE,
Andy Green0d338332011-02-12 11:57:43 +0000689 wsi->user_space,
Andy Green90c7cbc2011-01-27 06:26:52 +0000690 NULL, 0);
691 }
692
Andy Greenb45993c2010-12-18 15:13:50 +0000693 /* any incoming data ready? */
694
Andy Green0d338332011-02-12 11:57:43 +0000695 if (!(pollfd->revents & POLLIN))
696 break;
Andy Greenb45993c2010-12-18 15:13:50 +0000697
Andy Green0d338332011-02-12 11:57:43 +0000698 /* get the issued broadcast payload from the socket */
Andy Greenb45993c2010-12-18 15:13:50 +0000699
Andy Green0d338332011-02-12 11:57:43 +0000700 len = read(pollfd->fd, buf + LWS_SEND_BUFFER_PRE_PADDING,
701 MAX_BROADCAST_PAYLOAD);
702 if (len < 0) {
703 fprintf(stderr, "Error reading broadcast payload\n");
Andy Green4b6fbe12011-02-14 08:03:48 +0000704 break;
Andy Green0d338332011-02-12 11:57:43 +0000705 }
Andy Greenb45993c2010-12-18 15:13:50 +0000706
Andy Green0d338332011-02-12 11:57:43 +0000707 /* broadcast it to all guys with this protocol index */
Andy Green8f037e42010-12-19 22:13:26 +0000708
Andy Green0d338332011-02-12 11:57:43 +0000709 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
Andy Green8f037e42010-12-19 22:13:26 +0000710
Peter Hinz56885f32011-03-02 22:03:47 +0000711 for (m = 0; m < context->fd_hashtable[n].length; m++) {
Andy Greenb45993c2010-12-18 15:13:50 +0000712
Peter Hinz56885f32011-03-02 22:03:47 +0000713 new_wsi = context->fd_hashtable[n].wsi[m];
Andy Greenb45993c2010-12-18 15:13:50 +0000714
Andy Green0d338332011-02-12 11:57:43 +0000715 /* only to clients we are serving to */
Andy Greenb45993c2010-12-18 15:13:50 +0000716
Andy Green0d338332011-02-12 11:57:43 +0000717 if (new_wsi->mode != LWS_CONNMODE_WS_SERVING)
Andy Greenb45993c2010-12-18 15:13:50 +0000718 continue;
719
720 /*
721 * never broadcast to non-established
722 * connection
723 */
724
Andy Green0d338332011-02-12 11:57:43 +0000725 if (new_wsi->state != WSI_STATE_ESTABLISHED)
Andy Green4739e5c2011-01-22 12:51:57 +0000726 continue;
727
Andy Greenb45993c2010-12-18 15:13:50 +0000728 /*
729 * only broadcast to connections using
730 * the requested protocol
731 */
732
Andy Green0d338332011-02-12 11:57:43 +0000733 if (new_wsi->protocol->protocol_index !=
734 wsi->protocol_index_for_broadcast_proxy)
Andy Greenb45993c2010-12-18 15:13:50 +0000735 continue;
736
Andy Green8f037e42010-12-19 22:13:26 +0000737 /* broadcast it to this connection */
738
Peter Hinz56885f32011-03-02 22:03:47 +0000739 new_wsi->protocol->callback(context, new_wsi,
Andy Green8f037e42010-12-19 22:13:26 +0000740 LWS_CALLBACK_BROADCAST,
Andy Green0d338332011-02-12 11:57:43 +0000741 new_wsi->user_space,
Andy Green0ca6a172010-12-19 20:50:01 +0000742 buf + LWS_SEND_BUFFER_PRE_PADDING, len);
Andy Greenb45993c2010-12-18 15:13:50 +0000743 }
Andy Green0d338332011-02-12 11:57:43 +0000744 }
745 break;
Andy Greenb45993c2010-12-18 15:13:50 +0000746
Andy Greenbe93fef2011-02-14 20:25:43 +0000747 case LWS_CONNMODE_WS_CLIENT_WAITING_PROXY_REPLY:
748
749 /* handle proxy hung up on us */
750
751 if (pollfd->revents & (POLLERR | POLLHUP)) {
752
753 fprintf(stderr, "Proxy connection %p (fd=%d) dead\n",
754 (void *)wsi, pollfd->fd);
755
Peter Hinz56885f32011-03-02 22:03:47 +0000756 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +0000757 LWS_CLOSE_STATUS_NOSTATUS);
Andy Greenbe93fef2011-02-14 20:25:43 +0000758 return 1;
759 }
760
761 n = recv(wsi->sock, pkt, sizeof pkt, 0);
762 if (n < 0) {
Peter Hinz56885f32011-03-02 22:03:47 +0000763 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +0000764 LWS_CLOSE_STATUS_NOSTATUS);
Andy Greenbe93fef2011-02-14 20:25:43 +0000765 fprintf(stderr, "ERROR reading from proxy socket\n");
766 return 1;
767 }
768
769 pkt[13] = '\0';
770 if (strcmp(pkt, "HTTP/1.0 200 ") != 0) {
Peter Hinz56885f32011-03-02 22:03:47 +0000771 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +0000772 LWS_CLOSE_STATUS_NOSTATUS);
Andy Greenbe93fef2011-02-14 20:25:43 +0000773 fprintf(stderr, "ERROR from proxy: %s\n", pkt);
774 return 1;
775 }
776
777 /* clear his proxy connection timeout */
778
779 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
780
781 /* fallthru */
782
783 case LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE:
784
785 #ifdef LWS_OPENSSL_SUPPORT
786 if (wsi->use_ssl) {
787
Peter Hinz56885f32011-03-02 22:03:47 +0000788 wsi->ssl = SSL_new(context->ssl_client_ctx);
789 wsi->client_bio = BIO_new_socket(wsi->sock,
790 BIO_NOCLOSE);
Andy Greenbe93fef2011-02-14 20:25:43 +0000791 SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
792
Andy Green6901cb32011-02-21 08:06:47 +0000793 SSL_set_ex_data(wsi->ssl,
Peter Hinz56885f32011-03-02 22:03:47 +0000794 context->openssl_websocket_private_data_index,
795 context);
Andy Green6901cb32011-02-21 08:06:47 +0000796
Andy Greenbe93fef2011-02-14 20:25:43 +0000797 if (SSL_connect(wsi->ssl) <= 0) {
798 fprintf(stderr, "SSL connect error %s\n",
Andy Green687b0182011-02-26 11:04:01 +0000799 ERR_error_string(ERR_get_error(),
800 ssl_err_buf));
Peter Hinz56885f32011-03-02 22:03:47 +0000801 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +0000802 LWS_CLOSE_STATUS_NOSTATUS);
Andy Greenbe93fef2011-02-14 20:25:43 +0000803 return 1;
804 }
805
806 n = SSL_get_verify_result(wsi->ssl);
Andy Green687b0182011-02-26 11:04:01 +0000807 if (n != X509_V_OK) && (
808 n != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
809 wsi->use_ssl != 2)) {
Andy Greenbe93fef2011-02-14 20:25:43 +0000810
Andy Green687b0182011-02-26 11:04:01 +0000811 fprintf(stderr, "server's cert didn't "
812 "look good %d\n", n);
Peter Hinz56885f32011-03-02 22:03:47 +0000813 libwebsocket_close_and_free_session(context,
814 wsi, LWS_CLOSE_STATUS_NOSTATUS);
Andy Green687b0182011-02-26 11:04:01 +0000815 return 1;
Andy Greenbe93fef2011-02-14 20:25:43 +0000816 }
817 } else {
818 wsi->ssl = NULL;
819 #endif
820
821
822 #ifdef LWS_OPENSSL_SUPPORT
823 }
824 #endif
825
826 /*
827 * create the random key
828 */
829
Peter Hinz56885f32011-03-02 22:03:47 +0000830 n = libwebsockets_get_random(context, hash, 16);
Andy Greenbe93fef2011-02-14 20:25:43 +0000831 if (n != 16) {
832 fprintf(stderr, "Unable to read from random dev %s\n",
833 SYSTEM_RANDOM_FILEPATH);
834 free(wsi->c_path);
835 free(wsi->c_host);
Andy Green08d33922011-02-26 10:22:49 +0000836 if (wsi->c_origin)
837 free(wsi->c_origin);
Andy Greenbe93fef2011-02-14 20:25:43 +0000838 if (wsi->c_protocol)
839 free(wsi->c_protocol);
Peter Hinz56885f32011-03-02 22:03:47 +0000840 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +0000841 LWS_CLOSE_STATUS_NOSTATUS);
Andy Greenbe93fef2011-02-14 20:25:43 +0000842 return 1;
843 }
844
845 lws_b64_encode_string(hash, 16, wsi->key_b64,
846 sizeof wsi->key_b64);
847
848 /*
Andy Greeneeaacb32011-03-01 20:44:24 +0000849 * 00 example client handshake
850 *
851 * GET /socket.io/websocket HTTP/1.1
852 * Upgrade: WebSocket
853 * Connection: Upgrade
854 * Host: 127.0.0.1:9999
855 * Origin: http://127.0.0.1
856 * Sec-WebSocket-Key1: 1 0 2#0W 9 89 7 92 ^
857 * Sec-WebSocket-Key2: 7 7Y 4328 B2v[8(z1
858 * Cookie: socketio=websocket
859 *
860 * (Á®Ä0¶†≥
861 *
Andy Greenbe93fef2011-02-14 20:25:43 +0000862 * 04 example client handshake
863 *
864 * GET /chat HTTP/1.1
865 * Host: server.example.com
866 * Upgrade: websocket
867 * Connection: Upgrade
868 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
869 * Sec-WebSocket-Origin: http://example.com
870 * Sec-WebSocket-Protocol: chat, superchat
871 * Sec-WebSocket-Version: 4
872 */
873
Andy Green08d33922011-02-26 10:22:49 +0000874 p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a", wsi->c_path);
Andy Greeneeaacb32011-03-01 20:44:24 +0000875
876 if (wsi->ietf_spec_revision == 0) {
877 unsigned char spaces_1, spaces_2;
878 unsigned int max_1, max_2;
879 unsigned int num_1, num_2;
880 unsigned long product_1, product_2;
881 char key_1[40];
882 char key_2[40];
883 unsigned int seed;
884 unsigned int count;
885 char challenge[16];
886
Peter Hinz56885f32011-03-02 22:03:47 +0000887 libwebsockets_get_random(context, &spaces_1,
888 sizeof(char));
889 libwebsockets_get_random(context, &spaces_2,
890 sizeof(char));
891
Andy Greeneeaacb32011-03-01 20:44:24 +0000892 spaces_1 = (spaces_1 % 12) + 1;
893 spaces_2 = (spaces_2 % 12) + 1;
Peter Hinz56885f32011-03-02 22:03:47 +0000894
Andy Greeneeaacb32011-03-01 20:44:24 +0000895 max_1 = 4294967295 / spaces_1;
896 max_2 = 4294967295 / spaces_2;
897
Peter Hinz56885f32011-03-02 22:03:47 +0000898 libwebsockets_get_random(context, &num_1, sizeof(int));
899 libwebsockets_get_random(context, &num_2, sizeof(int));
900
Andy Greeneeaacb32011-03-01 20:44:24 +0000901 num_1 = (num_1 % max_1);
902 num_2 = (num_2 % max_2);
Peter Hinz56885f32011-03-02 22:03:47 +0000903
Andy Greeneeaacb32011-03-01 20:44:24 +0000904 challenge[0] = num_1 >> 24;
905 challenge[1] = num_1 >> 16;
906 challenge[2] = num_1 >> 8;
907 challenge[3] = num_1;
908 challenge[4] = num_2 >> 24;
909 challenge[5] = num_2 >> 16;
910 challenge[6] = num_2 >> 8;
911 challenge[7] = num_2;
Peter Hinz56885f32011-03-02 22:03:47 +0000912
Andy Greeneeaacb32011-03-01 20:44:24 +0000913 product_1 = num_1 * spaces_1;
914 product_2 = num_2 * spaces_2;
Peter Hinz56885f32011-03-02 22:03:47 +0000915
Andy Greeneeaacb32011-03-01 20:44:24 +0000916 sprintf(key_1, "%lu", product_1);
917 sprintf(key_2, "%lu", product_2);
918
Peter Hinz56885f32011-03-02 22:03:47 +0000919 libwebsockets_get_random(context, &seed, sizeof(int));
920 libwebsockets_get_random(context, &count, sizeof(int));
921
Andy Greeneeaacb32011-03-01 20:44:24 +0000922 libwebsockets_00_spam(key_1, (count % 12) + 1, seed);
Peter Hinz56885f32011-03-02 22:03:47 +0000923
924 libwebsockets_get_random(context, &seed, sizeof(int));
925 libwebsockets_get_random(context, &count, sizeof(int));
926
Andy Greeneeaacb32011-03-01 20:44:24 +0000927 libwebsockets_00_spam(key_2, (count % 12) + 1, seed);
Peter Hinz56885f32011-03-02 22:03:47 +0000928
929 libwebsockets_get_random(context, &seed, sizeof(int));
930
Andy Greeneeaacb32011-03-01 20:44:24 +0000931 libwebsockets_00_spaceout(key_1, spaces_1, seed);
932 libwebsockets_00_spaceout(key_2, spaces_2, seed >> 16);
Peter Hinz56885f32011-03-02 22:03:47 +0000933
Andy Greeneeaacb32011-03-01 20:44:24 +0000934 p += sprintf(p, "Upgrade: websocket\x0d\x0a"
935 "Connection: Upgrade\x0d\x0aHost: %s\x0d\x0a",
Peter Hinz56885f32011-03-02 22:03:47 +0000936 wsi->c_host);
Andy Greeneeaacb32011-03-01 20:44:24 +0000937 if (wsi->c_origin)
938 p += sprintf(p, "Origin: %s\x0d\x0a",
Peter Hinz56885f32011-03-02 22:03:47 +0000939 wsi->c_origin);
940
Andy Greeneeaacb32011-03-01 20:44:24 +0000941 if (wsi->c_protocol)
Peter Hinz56885f32011-03-02 22:03:47 +0000942 p += sprintf(p, "Sec-WebSocket-Protocol: %s"
943 "\x0d\x0a", wsi->c_protocol);
944
Andy Greeneeaacb32011-03-01 20:44:24 +0000945 p += sprintf(p, "Sec-WebSocket-Key1: %s\x0d\x0a",
Peter Hinz56885f32011-03-02 22:03:47 +0000946 key_1);
Andy Greeneeaacb32011-03-01 20:44:24 +0000947 p += sprintf(p, "Sec-WebSocket-Key2: %s\x0d\x0a",
Peter Hinz56885f32011-03-02 22:03:47 +0000948 key_2);
Andy Greeneeaacb32011-03-01 20:44:24 +0000949
Andy Green385e7ad2011-03-01 21:06:02 +0000950 /* give userland a chance to append, eg, cookies */
Peter Hinz56885f32011-03-02 22:03:47 +0000951
952 context->protocols[0].callback(context, wsi,
953 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
Andy Green385e7ad2011-03-01 21:06:02 +0000954 NULL, &p, (pkt + sizeof(pkt)) - p - 12);
955
Andy Greeneeaacb32011-03-01 20:44:24 +0000956 p += sprintf(p, "\x0d\x0a");
Peter Hinz56885f32011-03-02 22:03:47 +0000957
958 read(context->fd_random, p, 8);
Andy Greeneeaacb32011-03-01 20:44:24 +0000959 memcpy(&challenge[8], p, 8);
960 p += 8;
Peter Hinz56885f32011-03-02 22:03:47 +0000961
Andy Greeneeaacb32011-03-01 20:44:24 +0000962 /* precompute what we want to see from the server */
Peter Hinz56885f32011-03-02 22:03:47 +0000963
Andy Greeneeaacb32011-03-01 20:44:24 +0000964 MD5((unsigned char *)challenge, 16,
965 (unsigned char *)wsi->initial_handshake_hash_base64);
Peter Hinz56885f32011-03-02 22:03:47 +0000966
Andy Greeneeaacb32011-03-01 20:44:24 +0000967 goto issue_hdr;
968 }
969
Andy Green08d33922011-02-26 10:22:49 +0000970 p += sprintf(p, "Host: %s\x0d\x0a", wsi->c_host);
971 p += sprintf(p, "Upgrade: websocket\x0d\x0a");
972 p += sprintf(p, "Connection: Upgrade\x0d\x0a"
Andy Greenbe93fef2011-02-14 20:25:43 +0000973 "Sec-WebSocket-Key: ");
Andy Green08d33922011-02-26 10:22:49 +0000974 strcpy(p, wsi->key_b64);
975 p += strlen(wsi->key_b64);
976 p += sprintf(p, "\x0d\x0a");
977 if (wsi->c_origin)
978 p += sprintf(p, "Sec-WebSocket-Origin: %s\x0d\x0a",
Andy Greenbe93fef2011-02-14 20:25:43 +0000979 wsi->c_origin);
Andy Green08d33922011-02-26 10:22:49 +0000980 if (wsi->c_protocol)
Andy Greenbe93fef2011-02-14 20:25:43 +0000981 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
982 wsi->c_protocol);
Andy Green385e7ad2011-03-01 21:06:02 +0000983 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a",
Peter Hinz56885f32011-03-02 22:03:47 +0000984 wsi->ietf_spec_revision);
Andy Green385e7ad2011-03-01 21:06:02 +0000985 /* give userland a chance to append, eg, cookies */
Peter Hinz56885f32011-03-02 22:03:47 +0000986
987 context->protocols[0].callback(context, wsi,
988 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
989 NULL, &p, (pkt + sizeof(pkt)) - p - 12);
990
Andy Green385e7ad2011-03-01 21:06:02 +0000991 p += sprintf(p, "\x0d\x0a");
992
Andy Greenbe93fef2011-02-14 20:25:43 +0000993 /* prepare the expected server accept response */
994
995 strcpy((char *)buf, wsi->key_b64);
996 strcpy((char *)&buf[strlen((char *)buf)], magic_websocket_guid);
997
998 SHA1(buf, strlen((char *)buf), (unsigned char *)hash);
999
1000 lws_b64_encode_string(hash, 20,
1001 wsi->initial_handshake_hash_base64,
1002 sizeof wsi->initial_handshake_hash_base64);
Peter Hinz56885f32011-03-02 22:03:47 +00001003
Andy Greeneeaacb32011-03-01 20:44:24 +00001004issue_hdr:
Peter Hinz56885f32011-03-02 22:03:47 +00001005
Andy Greeneeaacb32011-03-01 20:44:24 +00001006 /* done with these now */
Peter Hinz56885f32011-03-02 22:03:47 +00001007
Andy Greeneeaacb32011-03-01 20:44:24 +00001008 free(wsi->c_path);
1009 free(wsi->c_host);
1010 if (wsi->c_origin)
1011 free(wsi->c_origin);
1012
Andy Greenbe93fef2011-02-14 20:25:43 +00001013 /* send our request to the server */
1014
1015 #ifdef LWS_OPENSSL_SUPPORT
1016 if (wsi->use_ssl)
1017 n = SSL_write(wsi->ssl, pkt, p - pkt);
1018 else
1019 #endif
1020 n = send(wsi->sock, pkt, p - pkt, 0);
1021
1022 if (n < 0) {
1023 fprintf(stderr, "ERROR writing to client socket\n");
Peter Hinz56885f32011-03-02 22:03:47 +00001024 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +00001025 LWS_CLOSE_STATUS_NOSTATUS);
Andy Greenbe93fef2011-02-14 20:25:43 +00001026 return 1;
1027 }
1028
1029 wsi->parser_state = WSI_TOKEN_NAME_PART;
1030 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY;
1031 libwebsocket_set_timeout(wsi,
1032 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, 5);
1033
1034 break;
1035
1036 case LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY:
1037
1038 /* handle server hung up on us */
1039
1040 if (pollfd->revents & (POLLERR | POLLHUP)) {
1041
1042 fprintf(stderr, "Server connection %p (fd=%d) dead\n",
1043 (void *)wsi, pollfd->fd);
1044
1045 goto bail3;
1046 }
1047
1048
1049 /* interpret the server response */
1050
1051 /*
1052 * HTTP/1.1 101 Switching Protocols
1053 * Upgrade: websocket
1054 * Connection: Upgrade
1055 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
1056 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
1057 * Sec-WebSocket-Protocol: chat
1058 */
1059
1060 #ifdef LWS_OPENSSL_SUPPORT
1061 if (wsi->use_ssl)
1062 len = SSL_read(wsi->ssl, pkt, sizeof pkt);
1063 else
1064 #endif
1065 len = recv(wsi->sock, pkt, sizeof pkt, 0);
1066
1067 if (len < 0) {
1068 fprintf(stderr,
1069 "libwebsocket_client_handshake read error\n");
1070 goto bail3;
1071 }
1072
1073 p = pkt;
1074 for (n = 0; n < len; n++)
1075 libwebsocket_parse(wsi, *p++);
1076
1077 if (wsi->parser_state != WSI_PARSING_COMPLETE) {
1078 fprintf(stderr, "libwebsocket_client_handshake "
Peter Hinz56885f32011-03-02 22:03:47 +00001079 "server response failed parsing\n");
Andy Greenbe93fef2011-02-14 20:25:43 +00001080 goto bail3;
1081 }
1082
1083 /*
Andy Greeneeaacb32011-03-01 20:44:24 +00001084 * 00 / 76 -->
1085 *
1086 * HTTP/1.1 101 WebSocket Protocol Handshake
1087 * Upgrade: WebSocket
1088 * Connection: Upgrade
1089 * Sec-WebSocket-Origin: http://127.0.0.1
1090 * Sec-WebSocket-Location: ws://127.0.0.1:9999/socket.io/websocket
1091 *
1092 * xxxxxxxxxxxxxxxx
1093 */
Peter Hinz56885f32011-03-02 22:03:47 +00001094
Andy Greeneeaacb32011-03-01 20:44:24 +00001095 if (wsi->ietf_spec_revision == 0) {
1096 if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
Peter Hinz56885f32011-03-02 22:03:47 +00001097 !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
1098 !wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len ||
1099 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
1100 (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
1101 wsi->c_protocol != NULL)) {
Andy Greeneeaacb32011-03-01 20:44:24 +00001102 fprintf(stderr, "libwebsocket_client_handshake "
Peter Hinz56885f32011-03-02 22:03:47 +00001103 "missing required header(s)\n");
Andy Greeneeaacb32011-03-01 20:44:24 +00001104 pkt[len] = '\0';
1105 fprintf(stderr, "%s", pkt);
1106 goto bail3;
1107 }
Andy Greeneeaacb32011-03-01 20:44:24 +00001108
Peter Hinz56885f32011-03-02 22:03:47 +00001109 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
1110 if (strcmp(wsi->utf8_token[WSI_TOKEN_HTTP].token,
1111 "101 websocket protocol handshake")) {
Andy Greeneeaacb32011-03-01 20:44:24 +00001112 fprintf(stderr, "libwebsocket_client_handshake "
Peter Hinz56885f32011-03-02 22:03:47 +00001113 "server sent bad HTTP response '%s'\n",
1114 wsi->utf8_token[WSI_TOKEN_HTTP].token);
1115 goto bail3;
1116 }
1117
1118 if (wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len <
1119 16) {
1120 fprintf(stderr, "libwebsocket_client_handshake "
1121 "challenge reply too short %d\n",
1122 wsi->utf8_token[
1123 WSI_TOKEN_CHALLENGE].token_len);
Andy Greeneeaacb32011-03-01 20:44:24 +00001124 pkt[len] = '\0';
1125 fprintf(stderr, "%s", pkt);
1126 goto bail3;
Peter Hinz56885f32011-03-02 22:03:47 +00001127
Andy Greeneeaacb32011-03-01 20:44:24 +00001128 }
Peter Hinz56885f32011-03-02 22:03:47 +00001129
Andy Greeneeaacb32011-03-01 20:44:24 +00001130 goto select_protocol;
1131 }
Peter Hinz56885f32011-03-02 22:03:47 +00001132
Andy Greeneeaacb32011-03-01 20:44:24 +00001133 /*
Andy Greenbe93fef2011-02-14 20:25:43 +00001134 * well, what the server sent looked reasonable for syntax.
1135 * Now let's confirm it sent all the necessary headers
1136 */
1137
1138 if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
1139 !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
1140 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
1141 !wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len ||
Andy Green4eaa86b2011-02-26 11:17:48 +00001142 (!wsi->utf8_token[WSI_TOKEN_NONCE].token_len &&
1143 wsi->ietf_spec_revision == 4) ||
Andy Greenbe93fef2011-02-14 20:25:43 +00001144 (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
1145 wsi->c_protocol != NULL)) {
1146 fprintf(stderr, "libwebsocket_client_handshake "
Andy Green687b0182011-02-26 11:04:01 +00001147 "missing required header(s)\n");
Andy Greenbe93fef2011-02-14 20:25:43 +00001148 pkt[len] = '\0';
1149 fprintf(stderr, "%s", pkt);
1150 goto bail3;
1151 }
1152
1153 /*
1154 * Everything seems to be there, now take a closer look at what
1155 * is in each header
1156 */
1157
1158 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
1159 if (strcmp(wsi->utf8_token[WSI_TOKEN_HTTP].token,
1160 "101 switching protocols")) {
1161 fprintf(stderr, "libwebsocket_client_handshake "
1162 "server sent bad HTTP response '%s'\n",
1163 wsi->utf8_token[WSI_TOKEN_HTTP].token);
1164 goto bail3;
1165 }
1166
1167 strtolower(wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
1168 if (strcmp(wsi->utf8_token[WSI_TOKEN_UPGRADE].token,
1169 "websocket")) {
1170 fprintf(stderr, "libwebsocket_client_handshake server "
1171 "sent bad Upgrade header '%s'\n",
1172 wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
1173 goto bail3;
1174 }
1175
1176 strtolower(wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
1177 if (strcmp(wsi->utf8_token[WSI_TOKEN_CONNECTION].token,
1178 "upgrade")) {
1179 fprintf(stderr, "libwebsocket_client_handshake server "
1180 "sent bad Connection hdr '%s'\n",
1181 wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
1182 goto bail3;
1183 }
1184
Andy Greeneeaacb32011-03-01 20:44:24 +00001185select_protocol:
Andy Greenbe93fef2011-02-14 20:25:43 +00001186 pc = wsi->c_protocol;
1187
1188 /*
1189 * confirm the protocol the server wants to talk was in the list
1190 * of protocols we offered
1191 */
1192
1193 if (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len) {
1194
1195 /*
1196 * no protocol name to work from,
1197 * default to first protocol
1198 */
Peter Hinz56885f32011-03-02 22:03:47 +00001199 wsi->protocol = &context->protocols[0];
Andy Greenbe93fef2011-02-14 20:25:43 +00001200
1201 free(wsi->c_protocol);
1202
1203 goto check_accept;
1204 }
1205
1206 while (*pc && !okay) {
1207 if ((!strncmp(pc,
1208 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
1209 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len)) &&
1210 (pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == ',' ||
1211 pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == '\0')) {
1212 okay = 1;
1213 continue;
1214 }
1215 while (*pc && *pc != ',')
1216 pc++;
1217 while (*pc && *pc != ' ')
1218 pc++;
1219 }
1220
1221 /* done with him now */
1222
1223 if (wsi->c_protocol)
1224 free(wsi->c_protocol);
1225
1226
1227 if (!okay) {
1228 fprintf(stderr, "libwebsocket_client_handshake server "
1229 "sent bad protocol '%s'\n",
1230 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
1231 goto bail2;
1232 }
1233
1234 /*
1235 * identify the selected protocol struct and set it
1236 */
1237 n = 0;
1238 wsi->protocol = NULL;
Peter Hinz56885f32011-03-02 22:03:47 +00001239 while (context->protocols[n].callback) {
Andy Greenbe93fef2011-02-14 20:25:43 +00001240 if (strcmp(wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
Peter Hinz56885f32011-03-02 22:03:47 +00001241 context->protocols[n].name) == 0)
1242 wsi->protocol = &context->protocols[n];
Andy Greenbe93fef2011-02-14 20:25:43 +00001243 n++;
1244 }
1245
1246 if (wsi->protocol == NULL) {
1247 fprintf(stderr, "libwebsocket_client_handshake server "
1248 "requested protocol '%s', which we "
1249 "said we supported but we don't!\n",
1250 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
1251 goto bail2;
1252 }
1253
1254 check_accept:
Andy Greeneeaacb32011-03-01 20:44:24 +00001255
1256 if (wsi->ietf_spec_revision == 0) {
Peter Hinz56885f32011-03-02 22:03:47 +00001257
Andy Greeneeaacb32011-03-01 20:44:24 +00001258 if (memcmp(wsi->initial_handshake_hash_base64,
Peter Hinz56885f32011-03-02 22:03:47 +00001259 wsi->utf8_token[WSI_TOKEN_CHALLENGE].token, 16)) {
Andy Greeneeaacb32011-03-01 20:44:24 +00001260 fprintf(stderr, "libwebsocket_client_handshake "
Peter Hinz56885f32011-03-02 22:03:47 +00001261 "failed 00 challenge compare\n");
1262 pkt[len] = '\0';
1263 fprintf(stderr, "%s", pkt);
1264 goto bail2;
Andy Greeneeaacb32011-03-01 20:44:24 +00001265 }
Peter Hinz56885f32011-03-02 22:03:47 +00001266
Andy Greeneeaacb32011-03-01 20:44:24 +00001267 goto accept_ok;
1268 }
Peter Hinz56885f32011-03-02 22:03:47 +00001269
Andy Greenbe93fef2011-02-14 20:25:43 +00001270 /*
1271 * Confirm his accept token is the one we precomputed
1272 */
1273
1274 if (strcmp(wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
1275 wsi->initial_handshake_hash_base64)) {
1276 fprintf(stderr, "libwebsocket_client_handshake server "
1277 "sent bad ACCEPT '%s' vs computed '%s'\n",
1278 wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
1279 wsi->initial_handshake_hash_base64);
1280 goto bail2;
1281 }
1282
Andy Green4eaa86b2011-02-26 11:17:48 +00001283 if (wsi->ietf_spec_revision == 4) {
1284 /*
1285 * Calculate the 04 masking key to use when
1286 * sending data to server
1287 */
Andy Greenbe93fef2011-02-14 20:25:43 +00001288
Andy Green4eaa86b2011-02-26 11:17:48 +00001289 strcpy((char *)buf, wsi->key_b64);
1290 p = (char *)buf + strlen(wsi->key_b64);
1291 strcpy(p, wsi->utf8_token[WSI_TOKEN_NONCE].token);
1292 p += wsi->utf8_token[WSI_TOKEN_NONCE].token_len;
1293 strcpy(p, magic_websocket_04_masking_guid);
1294 SHA1(buf, strlen((char *)buf), wsi->masking_key_04);
1295 }
Andy Greeneeaacb32011-03-01 20:44:24 +00001296accept_ok:
1297
Andy Greenbe93fef2011-02-14 20:25:43 +00001298 /* allocate the per-connection user memory (if any) */
1299
1300 if (wsi->protocol->per_session_data_size) {
1301 wsi->user_space = malloc(
1302 wsi->protocol->per_session_data_size);
1303 if (wsi->user_space == NULL) {
1304 fprintf(stderr, "Out of memory for "
1305 "conn user space\n");
1306 goto bail2;
1307 }
1308 } else
1309 wsi->user_space = NULL;
1310
1311 /* clear his proxy connection timeout */
1312
1313 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1314
1315 /* mark him as being alive */
1316
1317 wsi->state = WSI_STATE_ESTABLISHED;
1318 wsi->mode = LWS_CONNMODE_WS_CLIENT;
1319
1320 fprintf(stderr, "handshake OK for protocol %s\n",
1321 wsi->protocol->name);
1322
1323 /* call him back to inform him he is up */
1324
Peter Hinz56885f32011-03-02 22:03:47 +00001325 wsi->protocol->callback(context, wsi,
Andy Greenbe93fef2011-02-14 20:25:43 +00001326 LWS_CALLBACK_CLIENT_ESTABLISHED,
1327 wsi->user_space,
1328 NULL, 0);
1329
1330 break;
1331
1332bail3:
1333 if (wsi->c_protocol)
1334 free(wsi->c_protocol);
1335
1336bail2:
Peter Hinz56885f32011-03-02 22:03:47 +00001337 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +00001338 LWS_CLOSE_STATUS_NOSTATUS);
Andy Greenbe93fef2011-02-14 20:25:43 +00001339 return 1;
1340
1341
Andy Green0d338332011-02-12 11:57:43 +00001342 case LWS_CONNMODE_WS_SERVING:
1343 case LWS_CONNMODE_WS_CLIENT:
1344
1345 /* handle session socket closed */
1346
1347 if (pollfd->revents & (POLLERR | POLLHUP)) {
1348
Andy Green62c54d22011-02-14 09:14:25 +00001349 fprintf(stderr, "Session Socket %p (fd=%d) dead\n",
Andy Green0d338332011-02-12 11:57:43 +00001350 (void *)wsi, pollfd->fd);
1351
Peter Hinz56885f32011-03-02 22:03:47 +00001352 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +00001353 LWS_CLOSE_STATUS_NOSTATUS);
Andy Green4b6fbe12011-02-14 08:03:48 +00001354 return 1;
Andy Greenb45993c2010-12-18 15:13:50 +00001355 }
1356
Andy Green0d338332011-02-12 11:57:43 +00001357 /* the guy requested a callback when it was OK to write */
1358
1359 if (pollfd->revents & POLLOUT) {
1360
1361 pollfd->events &= ~POLLOUT;
1362
Andy Green3221f922011-02-12 13:14:11 +00001363 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00001364 context->protocols[0].callback(context, wsi,
Andy Green3221f922011-02-12 13:14:11 +00001365 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1366 (void *)(long)wsi->sock, NULL, POLLOUT);
1367
Peter Hinz56885f32011-03-02 22:03:47 +00001368 wsi->protocol->callback(context, wsi,
Andy Green0d338332011-02-12 11:57:43 +00001369 LWS_CALLBACK_CLIENT_WRITEABLE,
1370 wsi->user_space,
1371 NULL, 0);
1372 }
1373
1374 /* any incoming data ready? */
1375
1376 if (!(pollfd->revents & POLLIN))
1377 break;
1378
Andy Greenb45993c2010-12-18 15:13:50 +00001379#ifdef LWS_OPENSSL_SUPPORT
Andy Green0d338332011-02-12 11:57:43 +00001380 if (wsi->ssl)
1381 n = SSL_read(wsi->ssl, buf, sizeof buf);
Andy Greenb45993c2010-12-18 15:13:50 +00001382 else
1383#endif
Andy Green0d338332011-02-12 11:57:43 +00001384 n = recv(pollfd->fd, buf, sizeof buf, 0);
Andy Greenb45993c2010-12-18 15:13:50 +00001385
1386 if (n < 0) {
1387 fprintf(stderr, "Socket read returned %d\n", n);
Andy Green4b6fbe12011-02-14 08:03:48 +00001388 break;
Andy Greenb45993c2010-12-18 15:13:50 +00001389 }
1390 if (!n) {
Peter Hinz56885f32011-03-02 22:03:47 +00001391 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +00001392 LWS_CLOSE_STATUS_NOSTATUS);
Andy Green4b6fbe12011-02-14 08:03:48 +00001393 return 1;
Andy Greenb45993c2010-12-18 15:13:50 +00001394 }
1395
Andy Greenb45993c2010-12-18 15:13:50 +00001396 /* service incoming data */
1397
Peter Hinz56885f32011-03-02 22:03:47 +00001398 n = libwebsocket_read(context, wsi, buf, n);
Andy Green6964bb52011-01-23 16:50:33 +00001399 if (n >= 0)
Andy Green4b6fbe12011-02-14 08:03:48 +00001400 break;
Andy Greenb45993c2010-12-18 15:13:50 +00001401
Andy Green4b6fbe12011-02-14 08:03:48 +00001402 /* we closed wsi */
Andy Green0d338332011-02-12 11:57:43 +00001403
Andy Green4b6fbe12011-02-14 08:03:48 +00001404 return 1;
Andy Greenb45993c2010-12-18 15:13:50 +00001405 }
1406
1407 return 0;
1408}
1409
Andy Green0d338332011-02-12 11:57:43 +00001410
Andy Green6964bb52011-01-23 16:50:33 +00001411/**
1412 * libwebsocket_context_destroy() - Destroy the websocket context
Peter Hinz56885f32011-03-02 22:03:47 +00001413 * @context: Websocket context
Andy Green6964bb52011-01-23 16:50:33 +00001414 *
1415 * This function closes any active connections and then frees the
1416 * context. After calling this, any further use of the context is
1417 * undefined.
1418 */
1419void
Peter Hinz56885f32011-03-02 22:03:47 +00001420libwebsocket_context_destroy(struct libwebsocket_context *context)
Andy Green6964bb52011-01-23 16:50:33 +00001421{
Andy Green0d338332011-02-12 11:57:43 +00001422 int n;
1423 int m;
1424 struct libwebsocket *wsi;
Andy Green6964bb52011-01-23 16:50:33 +00001425
Andy Green4b6fbe12011-02-14 08:03:48 +00001426 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
Peter Hinz56885f32011-03-02 22:03:47 +00001427 for (m = 0; m < context->fd_hashtable[n].length; m++) {
1428 wsi = context->fd_hashtable[n].wsi[m];
1429 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +00001430 LWS_CLOSE_STATUS_GOINGAWAY);
Andy Greenf3d3b402011-02-09 07:16:34 +00001431 }
Andy Green6964bb52011-01-23 16:50:33 +00001432
Peter Hinz56885f32011-03-02 22:03:47 +00001433#ifdef WIN32
1434#else
1435 close(context->fd_random);
Andy Green6964bb52011-01-23 16:50:33 +00001436#endif
1437
Peter Hinz56885f32011-03-02 22:03:47 +00001438#ifdef LWS_OPENSSL_SUPPORT
1439 if (context->ssl_ctx)
1440 SSL_CTX_free(context->ssl_ctx);
1441 if (context->ssl_client_ctx)
1442 SSL_CTX_free(context->ssl_client_ctx);
1443#endif
1444
1445 free(context);
1446
1447#ifdef WIN32
1448 WSACleanup();
1449#endif
Andy Green6964bb52011-01-23 16:50:33 +00001450}
1451
1452/**
1453 * libwebsocket_service() - Service any pending websocket activity
Peter Hinz56885f32011-03-02 22:03:47 +00001454 * @context: Websocket context
Andy Green6964bb52011-01-23 16:50:33 +00001455 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
1456 * service otherwise block and service immediately, returning
1457 * after the timeout if nothing needed service.
1458 *
1459 * This function deals with any pending websocket traffic, for three
1460 * kinds of event. It handles these events on both server and client
1461 * types of connection the same.
1462 *
1463 * 1) Accept new connections to our context's server
1464 *
1465 * 2) Perform pending broadcast writes initiated from other forked
1466 * processes (effectively serializing asynchronous broadcasts)
1467 *
1468 * 3) Call the receive callback for incoming frame data received by
1469 * server or client connections.
1470 *
1471 * You need to call this service function periodically to all the above
1472 * functions to happen; if your application is single-threaded you can
1473 * just call it in your main event loop.
1474 *
1475 * Alternatively you can fork a new process that asynchronously handles
1476 * calling this service in a loop. In that case you are happy if this
1477 * call blocks your thread until it needs to take care of something and
1478 * would call it with a large nonzero timeout. Your loop then takes no
1479 * CPU while there is nothing happening.
1480 *
1481 * If you are calling it in a single-threaded app, you don't want it to
1482 * wait around blocking other things in your loop from happening, so you
1483 * would call it with a timeout_ms of 0, so it returns immediately if
1484 * nothing is pending, or as soon as it services whatever was pending.
1485 */
1486
Andy Greenb45993c2010-12-18 15:13:50 +00001487
Andy Greene92cd172011-01-19 13:11:55 +00001488int
Peter Hinz56885f32011-03-02 22:03:47 +00001489libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
Andy Greene92cd172011-01-19 13:11:55 +00001490{
1491 int n;
Andy Greene92cd172011-01-19 13:11:55 +00001492
1493 /* stay dead once we are dead */
1494
Peter Hinz56885f32011-03-02 22:03:47 +00001495 if (context == NULL)
Andy Greene92cd172011-01-19 13:11:55 +00001496 return 1;
1497
Andy Green0d338332011-02-12 11:57:43 +00001498 /* wait for something to need service */
Andy Green4739e5c2011-01-22 12:51:57 +00001499
Peter Hinz56885f32011-03-02 22:03:47 +00001500 n = poll(context->fds, context->fds_count, timeout_ms);
Andy Green3221f922011-02-12 13:14:11 +00001501 if (n == 0) /* poll timeout */
1502 return 0;
Andy Greene92cd172011-01-19 13:11:55 +00001503
Andy Green62c54d22011-02-14 09:14:25 +00001504 if (n < 0) {
Andy Green5e1fa172011-02-10 09:07:05 +00001505 /*
Andy Greene92cd172011-01-19 13:11:55 +00001506 fprintf(stderr, "Listen Socket dead\n");
Andy Green5e1fa172011-02-10 09:07:05 +00001507 */
Andy Green0d338332011-02-12 11:57:43 +00001508 return 1;
Andy Greene92cd172011-01-19 13:11:55 +00001509 }
Andy Greene92cd172011-01-19 13:11:55 +00001510
1511 /* handle accept on listening socket? */
1512
Peter Hinz56885f32011-03-02 22:03:47 +00001513 for (n = 0; n < context->fds_count; n++)
1514 if (context->fds[n].revents)
1515 libwebsocket_service_fd(context, &context->fds[n]);
Andy Greene92cd172011-01-19 13:11:55 +00001516
1517 return 0;
Andy Greene92cd172011-01-19 13:11:55 +00001518}
1519
Andy Green90c7cbc2011-01-27 06:26:52 +00001520/**
1521 * libwebsocket_callback_on_writable() - Request a callback when this socket
1522 * becomes able to be written to without
1523 * blocking
Andy Green32375b72011-02-19 08:32:53 +00001524 *
Peter Hinz56885f32011-03-02 22:03:47 +00001525 * @context: libwebsockets context
Andy Green90c7cbc2011-01-27 06:26:52 +00001526 * @wsi: Websocket connection instance to get callback for
1527 */
1528
1529int
Peter Hinz56885f32011-03-02 22:03:47 +00001530libwebsocket_callback_on_writable(struct libwebsocket_context *context,
Andy Green62c54d22011-02-14 09:14:25 +00001531 struct libwebsocket *wsi)
Andy Green90c7cbc2011-01-27 06:26:52 +00001532{
Andy Green90c7cbc2011-01-27 06:26:52 +00001533 int n;
1534
Peter Hinz56885f32011-03-02 22:03:47 +00001535 for (n = 0; n < context->fds_count; n++)
1536 if (context->fds[n].fd == wsi->sock) {
1537 context->fds[n].events |= POLLOUT;
1538 n = context->fds_count;
Andy Green90c7cbc2011-01-27 06:26:52 +00001539 }
1540
Andy Green3221f922011-02-12 13:14:11 +00001541 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00001542 context->protocols[0].callback(context, wsi,
Andy Green3221f922011-02-12 13:14:11 +00001543 LWS_CALLBACK_SET_MODE_POLL_FD,
1544 (void *)(long)wsi->sock, NULL, POLLOUT);
1545
Andy Green90c7cbc2011-01-27 06:26:52 +00001546 return 1;
1547}
1548
1549/**
1550 * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
1551 * all connections using the given protocol when it
1552 * becomes possible to write to each socket without
1553 * blocking in turn.
1554 *
1555 * @protocol: Protocol whose connections will get callbacks
1556 */
1557
1558int
1559libwebsocket_callback_on_writable_all_protocol(
1560 const struct libwebsocket_protocols *protocol)
1561{
Peter Hinz56885f32011-03-02 22:03:47 +00001562 struct libwebsocket_context *context = protocol->owning_server;
Andy Green90c7cbc2011-01-27 06:26:52 +00001563 int n;
Andy Green0d338332011-02-12 11:57:43 +00001564 int m;
1565 struct libwebsocket *wsi;
Andy Green90c7cbc2011-01-27 06:26:52 +00001566
Andy Green0d338332011-02-12 11:57:43 +00001567 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
1568
Peter Hinz56885f32011-03-02 22:03:47 +00001569 for (m = 0; m < context->fd_hashtable[n].length; m++) {
Andy Green0d338332011-02-12 11:57:43 +00001570
Peter Hinz56885f32011-03-02 22:03:47 +00001571 wsi = context->fd_hashtable[n].wsi[m];
Andy Green0d338332011-02-12 11:57:43 +00001572
1573 if (wsi->protocol == protocol)
Peter Hinz56885f32011-03-02 22:03:47 +00001574 libwebsocket_callback_on_writable(context, wsi);
Andy Green0d338332011-02-12 11:57:43 +00001575 }
1576 }
Andy Green90c7cbc2011-01-27 06:26:52 +00001577
1578 return 0;
1579}
1580
Andy Greenbe93fef2011-02-14 20:25:43 +00001581/**
1582 * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
1583 *
1584 * You will not need this unless you are doing something special
1585 *
1586 * @wsi: Websocket connection instance
1587 * @reason: timeout reason
1588 * @secs: how many seconds
1589 */
1590
1591void
1592libwebsocket_set_timeout(struct libwebsocket *wsi,
1593 enum pending_timeout reason, int secs)
1594{
1595 struct timeval tv;
1596
1597 gettimeofday(&tv, NULL);
1598
1599 wsi->pending_timeout_limit = tv.tv_sec + secs;
1600 wsi->pending_timeout = reason;
1601}
1602
Andy Greena6cbece2011-01-27 20:06:03 +00001603
1604/**
1605 * libwebsocket_get_socket_fd() - returns the socket file descriptor
1606 *
1607 * You will not need this unless you are doing something special
1608 *
1609 * @wsi: Websocket connection instance
1610 */
1611
1612int
1613libwebsocket_get_socket_fd(struct libwebsocket *wsi)
1614{
1615 return wsi->sock;
1616}
1617
Andy Green90c7cbc2011-01-27 06:26:52 +00001618/**
1619 * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
1620 * receieved packets.
1621 *
1622 * If the output side of a server process becomes choked, this allows flow
1623 * control for the input side.
1624 *
1625 * @wsi: Websocket connection instance to get callback for
1626 * @enable: 0 = disable read servicing for this connection, 1 = enable
1627 */
1628
1629int
1630libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
1631{
Peter Hinz56885f32011-03-02 22:03:47 +00001632 struct libwebsocket_context *context = wsi->protocol->owning_server;
Andy Green90c7cbc2011-01-27 06:26:52 +00001633 int n;
1634
Peter Hinz56885f32011-03-02 22:03:47 +00001635 for (n = 0; n < context->fds_count; n++)
1636 if (context->fds[n].fd == wsi->sock) {
Andy Green90c7cbc2011-01-27 06:26:52 +00001637 if (enable)
Peter Hinz56885f32011-03-02 22:03:47 +00001638 context->fds[n].events |= POLLIN;
Andy Green90c7cbc2011-01-27 06:26:52 +00001639 else
Peter Hinz56885f32011-03-02 22:03:47 +00001640 context->fds[n].events &= ~POLLIN;
Andy Green90c7cbc2011-01-27 06:26:52 +00001641
1642 return 0;
1643 }
1644
Andy Green3221f922011-02-12 13:14:11 +00001645 if (enable)
1646 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00001647 context->protocols[0].callback(context, wsi,
Andy Green3221f922011-02-12 13:14:11 +00001648 LWS_CALLBACK_SET_MODE_POLL_FD,
1649 (void *)(long)wsi->sock, NULL, POLLIN);
1650 else
1651 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00001652 context->protocols[0].callback(context, wsi,
Andy Green3221f922011-02-12 13:14:11 +00001653 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1654 (void *)(long)wsi->sock, NULL, POLLIN);
1655
1656
Andy Green90c7cbc2011-01-27 06:26:52 +00001657 fprintf(stderr, "libwebsocket_callback_on_writable "
1658 "unable to find socket\n");
1659 return 1;
1660}
1661
Andy Green2ac5a6f2011-01-28 10:00:18 +00001662/**
1663 * libwebsocket_canonical_hostname() - returns this host's hostname
1664 *
1665 * This is typically used by client code to fill in the host parameter
1666 * when making a client connection. You can only call it after the context
1667 * has been created.
1668 *
Peter Hinz56885f32011-03-02 22:03:47 +00001669 * @context: Websocket context
Andy Green2ac5a6f2011-01-28 10:00:18 +00001670 */
1671
1672
1673extern const char *
Peter Hinz56885f32011-03-02 22:03:47 +00001674libwebsocket_canonical_hostname(struct libwebsocket_context *context)
Andy Green2ac5a6f2011-01-28 10:00:18 +00001675{
Peter Hinz56885f32011-03-02 22:03:47 +00001676 return (const char *)context->canonical_hostname;
Andy Green2ac5a6f2011-01-28 10:00:18 +00001677}
1678
1679
Andy Green90c7cbc2011-01-27 06:26:52 +00001680static void sigpipe_handler(int x)
1681{
1682}
1683
Andy Green6901cb32011-02-21 08:06:47 +00001684#ifdef LWS_OPENSSL_SUPPORT
1685static int
1686OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
1687{
1688
1689 SSL *ssl;
1690 int n;
Peter Hinz56885f32011-03-02 22:03:47 +00001691// struct libwebsocket_context *context;
Andy Green6901cb32011-02-21 08:06:47 +00001692
1693 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1694 SSL_get_ex_data_X509_STORE_CTX_idx());
1695
1696 /*
Peter Hinz56885f32011-03-02 22:03:47 +00001697 * !!! can't get context->openssl_websocket_private_data_index
Andy Green6901cb32011-02-21 08:06:47 +00001698 * can't store as a static either
1699 */
Peter Hinz56885f32011-03-02 22:03:47 +00001700// context = SSL_get_ex_data(ssl,
1701// context->openssl_websocket_private_data_index);
Andy Green6901cb32011-02-21 08:06:47 +00001702
Peter Hinz56885f32011-03-02 22:03:47 +00001703 n = context->protocols[0].callback(NULL, NULL,
Andy Green6901cb32011-02-21 08:06:47 +00001704 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
1705 x509_ctx, ssl, preverify_ok);
1706
1707 /* convert return code from 0 = OK to 1 = OK */
1708
1709 if (!n)
1710 n = 1;
1711 else
1712 n = 0;
1713
1714 return n;
1715}
1716#endif
1717
Andy Greenb45993c2010-12-18 15:13:50 +00001718
Andy Greenab990e42010-10-31 12:42:52 +00001719/**
Andy Green4739e5c2011-01-22 12:51:57 +00001720 * libwebsocket_create_context() - Create the websocket handler
1721 * @port: Port to listen on... you can use 0 to suppress listening on
Andy Green6964bb52011-01-23 16:50:33 +00001722 * any port, that's what you want if you are not running a
1723 * websocket server at all but just using it as a client
Peter Hinz56885f32011-03-02 22:03:47 +00001724 * @interf: NULL to bind the listen socket to all interfaces, or the
Andy Green32375b72011-02-19 08:32:53 +00001725 * interface name, eg, "eth2"
Andy Green4f3943a2010-11-12 10:44:16 +00001726 * @protocols: Array of structures listing supported protocols and a protocol-
Andy Green8f037e42010-12-19 22:13:26 +00001727 * specific callback for each one. The list is ended with an
1728 * entry that has a NULL callback pointer.
Andy Green6964bb52011-01-23 16:50:33 +00001729 * It's not const because we write the owning_server member
Andy Green3faa9c72010-11-08 17:03:03 +00001730 * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want
Andy Green8f037e42010-12-19 22:13:26 +00001731 * to listen using SSL, set to the filepath to fetch the
1732 * server cert from, otherwise NULL for unencrypted
Andy Green3faa9c72010-11-08 17:03:03 +00001733 * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
Andy Green8f037e42010-12-19 22:13:26 +00001734 * else ignored
Andy Green3faa9c72010-11-08 17:03:03 +00001735 * @gid: group id to change to after setting listen socket, or -1.
1736 * @uid: user id to change to after setting listen socket, or -1.
Andy Greenbfb051f2011-02-09 08:49:14 +00001737 * @options: 0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
Andy Green05464c62010-11-12 10:44:18 +00001738 *
Andy Green8f037e42010-12-19 22:13:26 +00001739 * This function creates the listening socket and takes care
1740 * of all initialization in one step.
1741 *
Andy Greene92cd172011-01-19 13:11:55 +00001742 * After initialization, it returns a struct libwebsocket_context * that
1743 * represents this server. After calling, user code needs to take care
1744 * of calling libwebsocket_service() with the context pointer to get the
1745 * server's sockets serviced. This can be done in the same process context
1746 * or a forked process, or another thread,
Andy Green05464c62010-11-12 10:44:18 +00001747 *
Andy Green8f037e42010-12-19 22:13:26 +00001748 * The protocol callback functions are called for a handful of events
1749 * including http requests coming in, websocket connections becoming
1750 * established, and data arriving; it's also called periodically to allow
1751 * async transmission.
1752 *
1753 * HTTP requests are sent always to the FIRST protocol in @protocol, since
1754 * at that time websocket protocol has not been negotiated. Other
1755 * protocols after the first one never see any HTTP callack activity.
1756 *
1757 * The server created is a simple http server by default; part of the
1758 * websocket standard is upgrading this http connection to a websocket one.
1759 *
1760 * This allows the same server to provide files like scripts and favicon /
1761 * images or whatever over http and dynamic data over websockets all in
1762 * one place; they're all handled in the user callback.
Andy Greenab990e42010-10-31 12:42:52 +00001763 */
Andy Green4ea60062010-10-30 12:15:07 +01001764
Andy Greene92cd172011-01-19 13:11:55 +00001765struct libwebsocket_context *
Peter Hinz56885f32011-03-02 22:03:47 +00001766libwebsocket_create_context(int port, const char *interf,
Andy Greenb45993c2010-12-18 15:13:50 +00001767 struct libwebsocket_protocols *protocols,
Andy Green8f037e42010-12-19 22:13:26 +00001768 const char *ssl_cert_filepath,
1769 const char *ssl_private_key_filepath,
Andy Green8014b292011-01-30 20:57:25 +00001770 int gid, int uid, unsigned int options)
Andy Greenff95d7a2010-10-28 22:36:01 +01001771{
1772 int n;
Andy Green4739e5c2011-01-22 12:51:57 +00001773 int sockfd = 0;
Andy Green251f6fa2010-11-03 11:13:06 +00001774 int fd;
Andy Greenff95d7a2010-10-28 22:36:01 +01001775 struct sockaddr_in serv_addr, cli_addr;
Andy Green251f6fa2010-11-03 11:13:06 +00001776 int opt = 1;
Peter Hinz56885f32011-03-02 22:03:47 +00001777 struct libwebsocket_context *context = NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00001778 unsigned int slen;
Andy Green9659f372011-01-27 22:01:43 +00001779 char *p;
Andy Green2ac5a6f2011-01-28 10:00:18 +00001780 char hostname[1024];
Andy Green42f69142011-01-30 08:10:02 +00001781 struct hostent *he;
Andy Green0d338332011-02-12 11:57:43 +00001782 struct libwebsocket *wsi;
Andy Greenff95d7a2010-10-28 22:36:01 +01001783
Andy Green3faa9c72010-11-08 17:03:03 +00001784#ifdef LWS_OPENSSL_SUPPORT
Andy Greenf2f54d52010-11-15 22:08:00 +00001785 SSL_METHOD *method;
Andy Green3faa9c72010-11-08 17:03:03 +00001786 char ssl_err_buf[512];
Andy Green3faa9c72010-11-08 17:03:03 +00001787#endif
1788
Peter Hinz56885f32011-03-02 22:03:47 +00001789#ifdef _WIN32
1790 {
1791 WORD wVersionRequested;
1792 WSADATA wsaData;
1793 int err;
1794
1795 /* Use the MAKEWORD(lowbyte, highbyte) macro from Windef.h */
1796 wVersionRequested = MAKEWORD(2, 2);
1797
1798 err = WSAStartup(wVersionRequested, &wsaData);
1799 if (err != 0) {
1800 /* Tell the user that we could not find a usable */
1801 /* Winsock DLL. */
1802 fprintf(stderr, "WSAStartup failed with error: %d\n",
1803 err);
1804 return NULL;
1805 }
1806 }
1807#endif
1808
1809
1810 context = malloc(sizeof(struct libwebsocket_context));
1811 if (!context) {
Andy Green90c7cbc2011-01-27 06:26:52 +00001812 fprintf(stderr, "No memory for websocket context\n");
1813 return NULL;
1814 }
Peter Hinz56885f32011-03-02 22:03:47 +00001815 context->protocols = protocols;
1816 context->listen_port = port;
1817 context->http_proxy_port = 0;
1818 context->http_proxy_address[0] = '\0';
1819 context->options = options;
1820 context->fds_count = 0;
Andy Green9659f372011-01-27 22:01:43 +00001821
Peter Hinz56885f32011-03-02 22:03:47 +00001822#ifdef WIN32
1823 context->fd_random = 0;
1824#else
1825 context->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
1826 if (context->fd_random < 0) {
Andy Green44eee682011-02-10 09:32:24 +00001827 fprintf(stderr, "Unable to open random device %s %d\n",
Peter Hinz56885f32011-03-02 22:03:47 +00001828 SYSTEM_RANDOM_FILEPATH, context->fd_random);
Andy Green44eee682011-02-10 09:32:24 +00001829 return NULL;
1830 }
Peter Hinz56885f32011-03-02 22:03:47 +00001831#endif
Andy Green44eee682011-02-10 09:32:24 +00001832
Peter Hinz56885f32011-03-02 22:03:47 +00001833#ifdef LWS_OPENSSL_SUPPORT
1834 context->use_ssl = 0;
1835 context->ssl_ctx = NULL;
1836 context->ssl_client_ctx = NULL;
1837 context->openssl_websocket_private_data_index = 0;
1838#endif
Andy Green2ac5a6f2011-01-28 10:00:18 +00001839 /* find canonical hostname */
1840
1841 hostname[(sizeof hostname) - 1] = '\0';
1842 gethostname(hostname, (sizeof hostname) - 1);
1843 he = gethostbyname(hostname);
Darin Willitsc19456f2011-02-14 17:52:39 +00001844 if (he) {
Peter Hinz56885f32011-03-02 22:03:47 +00001845 strncpy(context->canonical_hostname, he->h_name,
1846 sizeof context->canonical_hostname - 1);
1847 context->canonical_hostname[
1848 sizeof context->canonical_hostname - 1] = '\0';
Darin Willitsc19456f2011-02-14 17:52:39 +00001849 } else
Peter Hinz56885f32011-03-02 22:03:47 +00001850 strncpy(context->canonical_hostname, hostname,
1851 sizeof context->canonical_hostname - 1);
Andy Green2ac5a6f2011-01-28 10:00:18 +00001852
Andy Green9659f372011-01-27 22:01:43 +00001853 /* split the proxy ads:port if given */
1854
1855 p = getenv("http_proxy");
1856 if (p) {
Peter Hinz56885f32011-03-02 22:03:47 +00001857 strncpy(context->http_proxy_address, p,
1858 sizeof context->http_proxy_address - 1);
1859 context->http_proxy_address[
1860 sizeof context->http_proxy_address - 1] = '\0';
Andy Green9659f372011-01-27 22:01:43 +00001861
Peter Hinz56885f32011-03-02 22:03:47 +00001862 p = strchr(context->http_proxy_address, ':');
Andy Green9659f372011-01-27 22:01:43 +00001863 if (p == NULL) {
1864 fprintf(stderr, "http_proxy needs to be ads:port\n");
1865 return NULL;
1866 }
1867 *p = '\0';
Peter Hinz56885f32011-03-02 22:03:47 +00001868 context->http_proxy_port = atoi(p + 1);
Andy Green9659f372011-01-27 22:01:43 +00001869
1870 fprintf(stderr, "Using proxy %s:%u\n",
Peter Hinz56885f32011-03-02 22:03:47 +00001871 context->http_proxy_address,
1872 context->http_proxy_port);
Andy Green9659f372011-01-27 22:01:43 +00001873 }
Andy Green90c7cbc2011-01-27 06:26:52 +00001874
1875 if (port) {
1876
Andy Green3faa9c72010-11-08 17:03:03 +00001877#ifdef LWS_OPENSSL_SUPPORT
Peter Hinz56885f32011-03-02 22:03:47 +00001878 context->use_ssl = ssl_cert_filepath != NULL &&
Andy Green90c7cbc2011-01-27 06:26:52 +00001879 ssl_private_key_filepath != NULL;
Peter Hinz56885f32011-03-02 22:03:47 +00001880 if (context->use_ssl)
Andy Green90c7cbc2011-01-27 06:26:52 +00001881 fprintf(stderr, " Compiled with SSL support, "
1882 "using it\n");
1883 else
1884 fprintf(stderr, " Compiled with SSL support, "
1885 "not using it\n");
Andy Green3faa9c72010-11-08 17:03:03 +00001886
Andy Green90c7cbc2011-01-27 06:26:52 +00001887#else
1888 if (ssl_cert_filepath != NULL &&
1889 ssl_private_key_filepath != NULL) {
1890 fprintf(stderr, " Not compiled for OpenSSl support!\n");
Andy Greene92cd172011-01-19 13:11:55 +00001891 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00001892 }
Andy Green90c7cbc2011-01-27 06:26:52 +00001893 fprintf(stderr, " Compiled without SSL support, "
1894 "serving unencrypted\n");
1895#endif
1896 }
1897
1898 /* ignore SIGPIPE */
Peter Hinz56885f32011-03-02 22:03:47 +00001899#ifdef WIN32
1900#else
Andy Green90c7cbc2011-01-27 06:26:52 +00001901 signal(SIGPIPE, sigpipe_handler);
Peter Hinz56885f32011-03-02 22:03:47 +00001902#endif
Andy Green90c7cbc2011-01-27 06:26:52 +00001903
1904
1905#ifdef LWS_OPENSSL_SUPPORT
1906
1907 /* basic openssl init */
1908
1909 SSL_library_init();
1910
1911 OpenSSL_add_all_algorithms();
1912 SSL_load_error_strings();
1913
Peter Hinz56885f32011-03-02 22:03:47 +00001914 context->openssl_websocket_private_data_index =
Andy Green6901cb32011-02-21 08:06:47 +00001915 SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
1916
Andy Green90c7cbc2011-01-27 06:26:52 +00001917 /*
1918 * Firefox insists on SSLv23 not SSLv3
1919 * Konq disables SSLv2 by default now, SSLv23 works
1920 */
1921
1922 method = (SSL_METHOD *)SSLv23_server_method();
1923 if (!method) {
1924 fprintf(stderr, "problem creating ssl method: %s\n",
1925 ERR_error_string(ERR_get_error(), ssl_err_buf));
1926 return NULL;
1927 }
Peter Hinz56885f32011-03-02 22:03:47 +00001928 context->ssl_ctx = SSL_CTX_new(method); /* create context */
1929 if (!context->ssl_ctx) {
Andy Green90c7cbc2011-01-27 06:26:52 +00001930 fprintf(stderr, "problem creating ssl context: %s\n",
1931 ERR_error_string(ERR_get_error(), ssl_err_buf));
1932 return NULL;
1933 }
1934
1935 /* client context */
Peter Hinz56885f32011-03-02 22:03:47 +00001936 if (port == CONTEXT_PORT_NO_LISTEN)
1937 {
1938 method = (SSL_METHOD *)SSLv23_client_method();
1939 if (!method) {
1940 fprintf(stderr, "problem creating ssl method: %s\n",
1941 ERR_error_string(ERR_get_error(), ssl_err_buf));
1942 return NULL;
1943 }
1944 /* create context */
1945 context->ssl_client_ctx = SSL_CTX_new(method);
1946 if (!context->ssl_client_ctx) {
1947 fprintf(stderr, "problem creating ssl context: %s\n",
1948 ERR_error_string(ERR_get_error(), ssl_err_buf));
1949 return NULL;
1950 }
Andy Green90c7cbc2011-01-27 06:26:52 +00001951
Peter Hinz56885f32011-03-02 22:03:47 +00001952 /* openssl init for cert verification (for client sockets) */
Andy Green90c7cbc2011-01-27 06:26:52 +00001953
Peter Hinz56885f32011-03-02 22:03:47 +00001954 if (!SSL_CTX_load_verify_locations(
1955 context->ssl_client_ctx, NULL,
1956 LWS_OPENSSL_CLIENT_CERTS))
1957 fprintf(stderr,
1958 "Unable to load SSL Client certs from %s "
1959 "(set by --with-client-cert-dir= in configure) -- "
1960 " client ssl isn't going to work",
Andy Green90c7cbc2011-01-27 06:26:52 +00001961 LWS_OPENSSL_CLIENT_CERTS);
Peter Hinz56885f32011-03-02 22:03:47 +00001962
1963 /*
1964 * callback allowing user code to load extra verification certs
1965 * helping the client to verify server identity
1966 */
1967
1968 context->protocols[0].callback(context, NULL,
1969 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
1970 context->ssl_client_ctx, NULL, 0);
Andy Green90c7cbc2011-01-27 06:26:52 +00001971 }
Andy Greenc6bf2c22011-02-20 11:10:47 +00001972 /* as a server, are we requiring clients to identify themselves? */
1973
1974 if (options & LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
1975
1976 /* absolutely require the client cert */
1977
Peter Hinz56885f32011-03-02 22:03:47 +00001978 SSL_CTX_set_verify(context->ssl_ctx,
Andy Green6901cb32011-02-21 08:06:47 +00001979 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1980 OpenSSL_verify_callback);
Andy Greenc6bf2c22011-02-20 11:10:47 +00001981
1982 /*
1983 * give user code a chance to load certs into the server
1984 * allowing it to verify incoming client certs
1985 */
1986
Peter Hinz56885f32011-03-02 22:03:47 +00001987 context->protocols[0].callback(context, NULL,
Andy Greenc6bf2c22011-02-20 11:10:47 +00001988 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
Peter Hinz56885f32011-03-02 22:03:47 +00001989 context->ssl_ctx, NULL, 0);
Andy Greenc6bf2c22011-02-20 11:10:47 +00001990 }
1991
Peter Hinz56885f32011-03-02 22:03:47 +00001992 if (context->use_ssl) {
Andy Green90c7cbc2011-01-27 06:26:52 +00001993
1994 /* openssl init for server sockets */
1995
Andy Green3faa9c72010-11-08 17:03:03 +00001996 /* set the local certificate from CertFile */
Peter Hinz56885f32011-03-02 22:03:47 +00001997 n = SSL_CTX_use_certificate_file(context->ssl_ctx,
Andy Green3faa9c72010-11-08 17:03:03 +00001998 ssl_cert_filepath, SSL_FILETYPE_PEM);
1999 if (n != 1) {
2000 fprintf(stderr, "problem getting cert '%s': %s\n",
2001 ssl_cert_filepath,
2002 ERR_error_string(ERR_get_error(), ssl_err_buf));
Andy Greene92cd172011-01-19 13:11:55 +00002003 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00002004 }
2005 /* set the private key from KeyFile */
Peter Hinz56885f32011-03-02 22:03:47 +00002006 if (SSL_CTX_use_PrivateKey_file(context->ssl_ctx,
2007 ssl_private_key_filepath, SSL_FILETYPE_PEM) != 1) {
Andy Green018d8eb2010-11-08 21:04:23 +00002008 fprintf(stderr, "ssl problem getting key '%s': %s\n",
2009 ssl_private_key_filepath,
2010 ERR_error_string(ERR_get_error(), ssl_err_buf));
Andy Greene92cd172011-01-19 13:11:55 +00002011 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00002012 }
2013 /* verify private key */
Peter Hinz56885f32011-03-02 22:03:47 +00002014 if (!SSL_CTX_check_private_key(context->ssl_ctx)) {
Andy Green018d8eb2010-11-08 21:04:23 +00002015 fprintf(stderr, "Private SSL key doesn't match cert\n");
Andy Greene92cd172011-01-19 13:11:55 +00002016 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00002017 }
2018
2019 /* SSL is happy and has a cert it's content with */
2020 }
2021#endif
Andy Greenb45993c2010-12-18 15:13:50 +00002022
Andy Greendf736162011-01-18 15:39:02 +00002023 /* selftest */
2024
2025 if (lws_b64_selftest())
Andy Greene92cd172011-01-19 13:11:55 +00002026 return NULL;
Andy Greendf736162011-01-18 15:39:02 +00002027
Andy Green0d338332011-02-12 11:57:43 +00002028 /* fd hashtable init */
2029
2030 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
Peter Hinz56885f32011-03-02 22:03:47 +00002031 context->fd_hashtable[n].length = 0;
Andy Green0d338332011-02-12 11:57:43 +00002032
Andy Greenb45993c2010-12-18 15:13:50 +00002033 /* set up our external listening socket we serve on */
Andy Green8f037e42010-12-19 22:13:26 +00002034
Andy Green4739e5c2011-01-22 12:51:57 +00002035 if (port) {
Andy Green8f037e42010-12-19 22:13:26 +00002036
Andy Green4739e5c2011-01-22 12:51:57 +00002037 sockfd = socket(AF_INET, SOCK_STREAM, 0);
2038 if (sockfd < 0) {
2039 fprintf(stderr, "ERROR opening socket");
2040 return NULL;
2041 }
Andy Green775c0dd2010-10-29 14:15:22 +01002042
Andy Green4739e5c2011-01-22 12:51:57 +00002043 /* allow us to restart even if old sockets in TIME_WAIT */
2044 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
Andy Greene77ddd82010-11-13 10:03:47 +00002045
Andy Green4739e5c2011-01-22 12:51:57 +00002046 bzero((char *) &serv_addr, sizeof(serv_addr));
2047 serv_addr.sin_family = AF_INET;
Peter Hinz56885f32011-03-02 22:03:47 +00002048 if (interf == NULL)
Andy Green32375b72011-02-19 08:32:53 +00002049 serv_addr.sin_addr.s_addr = INADDR_ANY;
2050 else
Peter Hinz56885f32011-03-02 22:03:47 +00002051 interface_to_sa(interf, &serv_addr,
Andy Green32375b72011-02-19 08:32:53 +00002052 sizeof(serv_addr));
Andy Green4739e5c2011-01-22 12:51:57 +00002053 serv_addr.sin_port = htons(port);
2054
2055 n = bind(sockfd, (struct sockaddr *) &serv_addr,
2056 sizeof(serv_addr));
2057 if (n < 0) {
2058 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
Andy Green8f037e42010-12-19 22:13:26 +00002059 port, n, errno);
Andy Green4739e5c2011-01-22 12:51:57 +00002060 return NULL;
2061 }
Andy Green0d338332011-02-12 11:57:43 +00002062
2063 wsi = malloc(sizeof(struct libwebsocket));
2064 memset(wsi, 0, sizeof (struct libwebsocket));
2065 wsi->sock = sockfd;
2066 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
Peter Hinz56885f32011-03-02 22:03:47 +00002067 insert_wsi(context, wsi);
Andy Green0d338332011-02-12 11:57:43 +00002068
2069 listen(sockfd, 5);
2070 fprintf(stderr, " Listening on port %d\n", port);
2071
2072 /* list in the internal poll array */
2073
Peter Hinz56885f32011-03-02 22:03:47 +00002074 context->fds[context->fds_count].fd = sockfd;
2075 context->fds[context->fds_count++].events = POLLIN;
Andy Green3221f922011-02-12 13:14:11 +00002076
2077 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00002078 context->protocols[0].callback(context, wsi,
Andy Green3221f922011-02-12 13:14:11 +00002079 LWS_CALLBACK_ADD_POLL_FD,
2080 (void *)(long)sockfd, NULL, POLLIN);
2081
Andy Green8f037e42010-12-19 22:13:26 +00002082 }
Andy Greenb45993c2010-12-18 15:13:50 +00002083
Andy Greene77ddd82010-11-13 10:03:47 +00002084 /* drop any root privs for this process */
Peter Hinz56885f32011-03-02 22:03:47 +00002085#ifdef WIN32
2086#else
Andy Green3faa9c72010-11-08 17:03:03 +00002087 if (gid != -1)
2088 if (setgid(gid))
2089 fprintf(stderr, "setgid: %s\n", strerror(errno));
2090 if (uid != -1)
2091 if (setuid(uid))
2092 fprintf(stderr, "setuid: %s\n", strerror(errno));
Peter Hinz56885f32011-03-02 22:03:47 +00002093#endif
Andy Greenb45993c2010-12-18 15:13:50 +00002094
2095 /* set up our internal broadcast trigger sockets per-protocol */
2096
Peter Hinz56885f32011-03-02 22:03:47 +00002097 for (context->count_protocols = 0;
2098 protocols[context->count_protocols].callback;
2099 context->count_protocols++) {
2100 protocols[context->count_protocols].owning_server = context;
2101 protocols[context->count_protocols].protocol_index =
2102 context->count_protocols;
Andy Greenb45993c2010-12-18 15:13:50 +00002103
2104 fd = socket(AF_INET, SOCK_STREAM, 0);
2105 if (fd < 0) {
2106 fprintf(stderr, "ERROR opening socket");
Andy Greene92cd172011-01-19 13:11:55 +00002107 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00002108 }
Andy Green8f037e42010-12-19 22:13:26 +00002109
Andy Greenb45993c2010-12-18 15:13:50 +00002110 /* allow us to restart even if old sockets in TIME_WAIT */
2111 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
2112
2113 bzero((char *) &serv_addr, sizeof(serv_addr));
2114 serv_addr.sin_family = AF_INET;
2115 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2116 serv_addr.sin_port = 0; /* pick the port for us */
2117
2118 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
2119 if (n < 0) {
Andy Green8f037e42010-12-19 22:13:26 +00002120 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
Andy Greenb45993c2010-12-18 15:13:50 +00002121 port, n, errno);
Andy Greene92cd172011-01-19 13:11:55 +00002122 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00002123 }
2124
2125 slen = sizeof cli_addr;
2126 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
2127 if (n < 0) {
2128 fprintf(stderr, "getsockname failed\n");
Andy Greene92cd172011-01-19 13:11:55 +00002129 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00002130 }
Peter Hinz56885f32011-03-02 22:03:47 +00002131 protocols[context->count_protocols].broadcast_socket_port =
Andy Greenb45993c2010-12-18 15:13:50 +00002132 ntohs(cli_addr.sin_port);
2133 listen(fd, 5);
2134
2135 debug(" Protocol %s broadcast socket %d\n",
Peter Hinz56885f32011-03-02 22:03:47 +00002136 protocols[context->count_protocols].name,
Andy Greenb45993c2010-12-18 15:13:50 +00002137 ntohs(cli_addr.sin_port));
2138
Andy Green0d338332011-02-12 11:57:43 +00002139 /* dummy wsi per broadcast proxy socket */
2140
2141 wsi = malloc(sizeof(struct libwebsocket));
2142 memset(wsi, 0, sizeof (struct libwebsocket));
2143 wsi->sock = fd;
2144 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
2145 /* note which protocol we are proxying */
Peter Hinz56885f32011-03-02 22:03:47 +00002146 wsi->protocol_index_for_broadcast_proxy =
2147 context->count_protocols;
2148 insert_wsi(context, wsi);
Andy Green0d338332011-02-12 11:57:43 +00002149
2150 /* list in internal poll array */
2151
Peter Hinz56885f32011-03-02 22:03:47 +00002152 context->fds[context->fds_count].fd = fd;
2153 context->fds[context->fds_count].events = POLLIN;
2154 context->fds[context->fds_count].revents = 0;
2155 context->fds_count++;
Andy Green3221f922011-02-12 13:14:11 +00002156
2157 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00002158 context->protocols[0].callback(context, wsi,
Andy Green3221f922011-02-12 13:14:11 +00002159 LWS_CALLBACK_ADD_POLL_FD,
2160 (void *)(long)fd, NULL, POLLIN);
Andy Greenb45993c2010-12-18 15:13:50 +00002161 }
2162
Peter Hinz56885f32011-03-02 22:03:47 +00002163 return context;
Andy Greene92cd172011-01-19 13:11:55 +00002164}
Andy Greenb45993c2010-12-18 15:13:50 +00002165
Andy Green4739e5c2011-01-22 12:51:57 +00002166
Andy Greened11a022011-01-20 10:23:50 +00002167#ifndef LWS_NO_FORK
2168
Andy Greene92cd172011-01-19 13:11:55 +00002169/**
2170 * libwebsockets_fork_service_loop() - Optional helper function forks off
2171 * a process for the websocket server loop.
Andy Green6964bb52011-01-23 16:50:33 +00002172 * You don't have to use this but if not, you
2173 * have to make sure you are calling
2174 * libwebsocket_service periodically to service
2175 * the websocket traffic
Peter Hinz56885f32011-03-02 22:03:47 +00002176 * @context: server context returned by creation function
Andy Greene92cd172011-01-19 13:11:55 +00002177 */
Andy Greenb45993c2010-12-18 15:13:50 +00002178
Andy Greene92cd172011-01-19 13:11:55 +00002179int
Peter Hinz56885f32011-03-02 22:03:47 +00002180libwebsockets_fork_service_loop(struct libwebsocket_context *context)
Andy Greene92cd172011-01-19 13:11:55 +00002181{
Andy Greene92cd172011-01-19 13:11:55 +00002182 int fd;
2183 struct sockaddr_in cli_addr;
2184 int n;
Andy Green3221f922011-02-12 13:14:11 +00002185 int p;
Andy Greenb45993c2010-12-18 15:13:50 +00002186
Andy Greened11a022011-01-20 10:23:50 +00002187 n = fork();
2188 if (n < 0)
2189 return n;
2190
2191 if (!n) {
2192
2193 /* main process context */
2194
Andy Green3221f922011-02-12 13:14:11 +00002195 /*
2196 * set up the proxy sockets to allow broadcast from
2197 * service process context
2198 */
2199
Peter Hinz56885f32011-03-02 22:03:47 +00002200 for (p = 0; p < context->count_protocols; p++) {
Andy Greened11a022011-01-20 10:23:50 +00002201 fd = socket(AF_INET, SOCK_STREAM, 0);
2202 if (fd < 0) {
2203 fprintf(stderr, "Unable to create socket\n");
2204 return -1;
2205 }
2206 cli_addr.sin_family = AF_INET;
2207 cli_addr.sin_port = htons(
Peter Hinz56885f32011-03-02 22:03:47 +00002208 context->protocols[p].broadcast_socket_port);
Andy Greened11a022011-01-20 10:23:50 +00002209 cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2210 n = connect(fd, (struct sockaddr *)&cli_addr,
2211 sizeof cli_addr);
2212 if (n < 0) {
2213 fprintf(stderr, "Unable to connect to "
2214 "broadcast socket %d, %s\n",
Andy Green3221f922011-02-12 13:14:11 +00002215 n, strerror(errno));
Andy Greened11a022011-01-20 10:23:50 +00002216 return -1;
2217 }
2218
Peter Hinz56885f32011-03-02 22:03:47 +00002219 context->protocols[p].broadcast_socket_user_fd = fd;
Andy Greened11a022011-01-20 10:23:50 +00002220 }
2221
Andy Greene92cd172011-01-19 13:11:55 +00002222 return 0;
Andy Greenb45993c2010-12-18 15:13:50 +00002223 }
2224
2225 /* we want a SIGHUP when our parent goes down */
2226 prctl(PR_SET_PDEATHSIG, SIGHUP);
2227
2228 /* in this forked process, sit and service websocket connections */
Andy Green8f037e42010-12-19 22:13:26 +00002229
Andy Greene92cd172011-01-19 13:11:55 +00002230 while (1)
Peter Hinz56885f32011-03-02 22:03:47 +00002231 if (libwebsocket_service(context, 1000))
Andy Greene92cd172011-01-19 13:11:55 +00002232 return -1;
Andy Green8f037e42010-12-19 22:13:26 +00002233
Andy Green251f6fa2010-11-03 11:13:06 +00002234 return 0;
Andy Greenff95d7a2010-10-28 22:36:01 +01002235}
2236
Andy Greened11a022011-01-20 10:23:50 +00002237#endif
2238
Andy Greenb45993c2010-12-18 15:13:50 +00002239/**
2240 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
Andy Green8f037e42010-12-19 22:13:26 +00002241 * connection.
Andy Greenb45993c2010-12-18 15:13:50 +00002242 * @wsi: pointer to struct websocket you want to know the protocol of
2243 *
Andy Green8f037e42010-12-19 22:13:26 +00002244 *
2245 * This is useful to get the protocol to broadcast back to from inside
Andy Greenb45993c2010-12-18 15:13:50 +00002246 * the callback.
2247 */
Andy Greenab990e42010-10-31 12:42:52 +00002248
Andy Greenb45993c2010-12-18 15:13:50 +00002249const struct libwebsocket_protocols *
2250libwebsockets_get_protocol(struct libwebsocket *wsi)
2251{
2252 return wsi->protocol;
2253}
2254
2255/**
Andy Greene92cd172011-01-19 13:11:55 +00002256 * libwebsockets_broadcast() - Sends a buffer to the callback for all active
Andy Green8f037e42010-12-19 22:13:26 +00002257 * connections of the given protocol.
Andy Greenb45993c2010-12-18 15:13:50 +00002258 * @protocol: pointer to the protocol you will broadcast to all members of
2259 * @buf: buffer containing the data to be broadcase. NOTE: this has to be
Andy Green8f037e42010-12-19 22:13:26 +00002260 * allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
2261 * the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
2262 * case you are calling this function from callback context.
Andy Greenb45993c2010-12-18 15:13:50 +00002263 * @len: length of payload data in buf, starting from buf.
Andy Green8f037e42010-12-19 22:13:26 +00002264 *
2265 * This function allows bulk sending of a packet to every connection using
Andy Greenb45993c2010-12-18 15:13:50 +00002266 * the given protocol. It does not send the data directly; instead it calls
2267 * the callback with a reason type of LWS_CALLBACK_BROADCAST. If the callback
2268 * wants to actually send the data for that connection, the callback itself
2269 * should call libwebsocket_write().
2270 *
2271 * libwebsockets_broadcast() can be called from another fork context without
2272 * having to take any care about data visibility between the processes, it'll
2273 * "just work".
2274 */
2275
2276
2277int
Andy Green8f037e42010-12-19 22:13:26 +00002278libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
Andy Greenb45993c2010-12-18 15:13:50 +00002279 unsigned char *buf, size_t len)
2280{
Peter Hinz56885f32011-03-02 22:03:47 +00002281 struct libwebsocket_context *context = protocol->owning_server;
Andy Greenb45993c2010-12-18 15:13:50 +00002282 int n;
Andy Green0d338332011-02-12 11:57:43 +00002283 int m;
2284 struct libwebsocket * wsi;
Andy Greenb45993c2010-12-18 15:13:50 +00002285
2286 if (!protocol->broadcast_socket_user_fd) {
2287 /*
Andy Greene92cd172011-01-19 13:11:55 +00002288 * We are either running unforked / flat, or we are being
2289 * called from poll thread context
Andy Greenb45993c2010-12-18 15:13:50 +00002290 * eg, from a callback. In that case don't use sockets for
2291 * broadcast IPC (since we can't open a socket connection to
2292 * a socket listening on our own thread) but directly do the
2293 * send action.
2294 *
2295 * Locking is not needed because we are by definition being
2296 * called in the poll thread context and are serialized.
2297 */
2298
Andy Green0d338332011-02-12 11:57:43 +00002299 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
Andy Greenb45993c2010-12-18 15:13:50 +00002300
Peter Hinz56885f32011-03-02 22:03:47 +00002301 for (m = 0; m < context->fd_hashtable[n].length; m++) {
Andy Greenb45993c2010-12-18 15:13:50 +00002302
Peter Hinz56885f32011-03-02 22:03:47 +00002303 wsi = context->fd_hashtable[n].wsi[m];
Andy Greenb45993c2010-12-18 15:13:50 +00002304
Andy Green0d338332011-02-12 11:57:43 +00002305 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
2306 continue;
Andy Greenb45993c2010-12-18 15:13:50 +00002307
Andy Green0d338332011-02-12 11:57:43 +00002308 /*
2309 * never broadcast to
2310 * non-established connections
2311 */
2312 if (wsi->state != WSI_STATE_ESTABLISHED)
2313 continue;
2314
2315 /* only broadcast to guys using
2316 * requested protocol
2317 */
2318 if (wsi->protocol != protocol)
2319 continue;
2320
Peter Hinz56885f32011-03-02 22:03:47 +00002321 wsi->protocol->callback(context, wsi,
Andy Green8f037e42010-12-19 22:13:26 +00002322 LWS_CALLBACK_BROADCAST,
Andy Green0d338332011-02-12 11:57:43 +00002323 wsi->user_space,
Andy Greenb45993c2010-12-18 15:13:50 +00002324 buf, len);
Andy Green0d338332011-02-12 11:57:43 +00002325 }
Andy Greenb45993c2010-12-18 15:13:50 +00002326 }
2327
2328 return 0;
2329 }
2330
Andy Green0ca6a172010-12-19 20:50:01 +00002331 /*
2332 * We're being called from a different process context than the server
2333 * loop. Instead of broadcasting directly, we send our
2334 * payload on a socket to do the IPC; the server process will serialize
2335 * the broadcast action in its main poll() loop.
2336 *
2337 * There's one broadcast socket listening for each protocol supported
2338 * set up when the websocket server initializes
2339 */
2340
Andy Green6964bb52011-01-23 16:50:33 +00002341 n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);
Andy Greenb45993c2010-12-18 15:13:50 +00002342
2343 return n;
2344}