blob: 9e22a160331f4ec897a7267c84b4dbb1f6c535a6 [file] [log] [blame]
Andy Green58eaa742011-03-07 17:54:06 +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>
Andy Green7627af52011-03-09 15:13:52 +000028#include <sys/un.h>
Peter Hinz56885f32011-03-02 22:03:47 +000029#endif
Andy Green2e24da02011-03-05 16:12:04 +000030
31#ifdef LWS_OPENSSL_SUPPORT
32int openssl_websocket_private_data_index;
33#endif
34
Andy Greenaa6fc442012-04-12 13:26:49 +080035#ifdef __MINGW32__
36#include "../win32port/win32helpers/websock-w32.c"
37#else
38#ifdef __MINGW64__
39#include "../win32port/win32helpers/websock-w32.c"
40#endif
41#endif
42
Andy Greenbe93fef2011-02-14 20:25:43 +000043/*
44 * In-place str to lower case
45 */
46
47static void
48strtolower(char *s)
49{
50 while (*s) {
51 *s = tolower(*s);
52 s++;
53 }
54}
55
Andy Green0d338332011-02-12 11:57:43 +000056/* file descriptor hash management */
57
58struct libwebsocket *
Peter Hinz56885f32011-03-02 22:03:47 +000059wsi_from_fd(struct libwebsocket_context *context, int fd)
Andy Green0d338332011-02-12 11:57:43 +000060{
61 int h = LWS_FD_HASH(fd);
62 int n = 0;
63
Peter Hinz56885f32011-03-02 22:03:47 +000064 for (n = 0; n < context->fd_hashtable[h].length; n++)
65 if (context->fd_hashtable[h].wsi[n]->sock == fd)
66 return context->fd_hashtable[h].wsi[n];
Andy Green0d338332011-02-12 11:57:43 +000067
68 return NULL;
69}
70
71int
Peter Hinz56885f32011-03-02 22:03:47 +000072insert_wsi(struct libwebsocket_context *context, struct libwebsocket *wsi)
Andy Green0d338332011-02-12 11:57:43 +000073{
74 int h = LWS_FD_HASH(wsi->sock);
75
Peter Hinz56885f32011-03-02 22:03:47 +000076 if (context->fd_hashtable[h].length == MAX_CLIENTS - 1) {
Andy Green0d338332011-02-12 11:57:43 +000077 fprintf(stderr, "hash table overflow\n");
78 return 1;
79 }
80
Peter Hinz56885f32011-03-02 22:03:47 +000081 context->fd_hashtable[h].wsi[context->fd_hashtable[h].length++] = wsi;
Andy Green0d338332011-02-12 11:57:43 +000082
83 return 0;
84}
85
86int
Peter Hinz56885f32011-03-02 22:03:47 +000087delete_from_fd(struct libwebsocket_context *context, int fd)
Andy Green0d338332011-02-12 11:57:43 +000088{
89 int h = LWS_FD_HASH(fd);
90 int n = 0;
91
Peter Hinz56885f32011-03-02 22:03:47 +000092 for (n = 0; n < context->fd_hashtable[h].length; n++)
93 if (context->fd_hashtable[h].wsi[n]->sock == fd) {
94 while (n < context->fd_hashtable[h].length) {
95 context->fd_hashtable[h].wsi[n] =
96 context->fd_hashtable[h].wsi[n + 1];
Andy Green0d338332011-02-12 11:57:43 +000097 n++;
98 }
Peter Hinz56885f32011-03-02 22:03:47 +000099 context->fd_hashtable[h].length--;
Andy Green0d338332011-02-12 11:57:43 +0000100
101 return 0;
102 }
103
104 fprintf(stderr, "Failed to find fd %d requested for "
105 "delete in hashtable\n", fd);
106 return 1;
107}
108
Andy Green1f9bf522011-02-14 21:14:37 +0000109#ifdef LWS_OPENSSL_SUPPORT
110static void
111libwebsockets_decode_ssl_error(void)
112{
113 char buf[256];
114 u_long err;
115
116 while ((err = ERR_get_error()) != 0) {
117 ERR_error_string_n(err, buf, sizeof(buf));
118 fprintf(stderr, "*** %s\n", buf);
119 }
120}
121#endif
Andy Green0d338332011-02-12 11:57:43 +0000122
Andy Green32375b72011-02-19 08:32:53 +0000123
124static int
Andy Green6ee372f2012-04-09 15:09:01 +0800125interface_to_sa(const char *ifname, struct sockaddr_in *addr, size_t addrlen)
Andy Green32375b72011-02-19 08:32:53 +0000126{
127 int rc = -1;
Peter Hinz56885f32011-03-02 22:03:47 +0000128#ifdef WIN32
Andy Green6ee372f2012-04-09 15:09:01 +0800129 /* TODO */
Peter Hinz56885f32011-03-02 22:03:47 +0000130#else
Andy Green32375b72011-02-19 08:32:53 +0000131 struct ifaddrs *ifr;
132 struct ifaddrs *ifc;
133 struct sockaddr_in *sin;
134
135 getifaddrs(&ifr);
136 for (ifc = ifr; ifc != NULL; ifc = ifc->ifa_next) {
137 if (strcmp(ifc->ifa_name, ifname))
138 continue;
139 if (ifc->ifa_addr == NULL)
140 continue;
141 sin = (struct sockaddr_in *)ifc->ifa_addr;
142 if (sin->sin_family != AF_INET)
143 continue;
144 memcpy(addr, sin, addrlen);
Andy Green6ee372f2012-04-09 15:09:01 +0800145 rc = 0;
Andy Green32375b72011-02-19 08:32:53 +0000146 }
147
148 freeifaddrs(ifr);
Peter Hinz56885f32011-03-02 22:03:47 +0000149#endif
Andy Green32375b72011-02-19 08:32:53 +0000150 return rc;
151}
152
Andy Green8f037e42010-12-19 22:13:26 +0000153void
Peter Hinz56885f32011-03-02 22:03:47 +0000154libwebsocket_close_and_free_session(struct libwebsocket_context *context,
Andy Green687b0182011-02-26 11:04:01 +0000155 struct libwebsocket *wsi, enum lws_close_status reason)
Andy Green251f6fa2010-11-03 11:13:06 +0000156{
Andy Greenb45993c2010-12-18 15:13:50 +0000157 int n;
Andy Green62c54d22011-02-14 09:14:25 +0000158 int old_state;
Andy Green5e1fa172011-02-10 09:07:05 +0000159 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
160 LWS_SEND_BUFFER_POST_PADDING];
Andy Greenc44159f2011-03-07 07:08:18 +0000161 int ret;
162 int m;
163 struct lws_tokens eff_buf;
Andy Greena41314f2011-05-23 10:00:03 +0100164 struct libwebsocket_extension *ext;
Andy Greenb45993c2010-12-18 15:13:50 +0000165
Andy Green4b6fbe12011-02-14 08:03:48 +0000166 if (!wsi)
Andy Greenb45993c2010-12-18 15:13:50 +0000167 return;
168
Andy Green62c54d22011-02-14 09:14:25 +0000169 old_state = wsi->state;
Andy Green251f6fa2010-11-03 11:13:06 +0000170
Andy Green62c54d22011-02-14 09:14:25 +0000171 if (old_state == WSI_STATE_DEAD_SOCKET)
Andy Green5e1fa172011-02-10 09:07:05 +0000172 return;
173
Andy Greenda527df2011-03-07 07:08:12 +0000174 wsi->close_reason = reason;
175
176 /*
Andy Green68b45042011-05-25 21:41:57 +0100177 * are his extensions okay with him closing? Eg he might be a mux
178 * parent and just his ch1 aspect is closing?
179 */
180
181
182 for (n = 0; n < wsi->count_active_extensions; n++) {
183 if (!wsi->active_extensions[n]->callback)
184 continue;
185
186 m = wsi->active_extensions[n]->callback(context,
187 wsi->active_extensions[n], wsi,
188 LWS_EXT_CALLBACK_CHECK_OK_TO_REALLY_CLOSE,
189 wsi->active_extensions_user[n], NULL, 0);
190
191 /*
192 * if somebody vetoed actually closing him at this time....
193 * up to the extension to track the attempted close, let's
194 * just bail
195 */
196
197 if (m) {
Andy Greencc012472011-11-07 19:53:23 +0800198 debug("extension vetoed close\n");
Andy Green68b45042011-05-25 21:41:57 +0100199 return;
200 }
201 }
202
203
204
205 /*
Andy Greenc44159f2011-03-07 07:08:18 +0000206 * flush any tx pending from extensions, since we may send close packet
207 * if there are problems with send, just nuke the connection
208 */
209
210 ret = 1;
211 while (ret == 1) {
212
213 /* default to nobody has more to spill */
214
215 ret = 0;
216 eff_buf.token = NULL;
217 eff_buf.token_len = 0;
218
219 /* show every extension the new incoming data */
220
221 for (n = 0; n < wsi->count_active_extensions; n++) {
222 m = wsi->active_extensions[n]->callback(
Andy Green46c2ea02011-03-22 09:04:01 +0000223 wsi->protocol->owning_server,
224 wsi->active_extensions[n], wsi,
Andy Greenc44159f2011-03-07 07:08:18 +0000225 LWS_EXT_CALLBACK_FLUSH_PENDING_TX,
226 wsi->active_extensions_user[n], &eff_buf, 0);
227 if (m < 0) {
228 fprintf(stderr, "Extension reports "
229 "fatal error\n");
230 goto just_kill_connection;
231 }
232 if (m)
233 /*
234 * at least one extension told us he has more
235 * to spill, so we will go around again after
236 */
237 ret = 1;
238 }
239
240 /* assuming they left us something to send, send it */
241
242 if (eff_buf.token_len)
243 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
244 eff_buf.token_len))
245 goto just_kill_connection;
246 }
247
248 /*
Andy Greenda527df2011-03-07 07:08:12 +0000249 * signal we are closing, libsocket_write will
250 * add any necessary version-specific stuff. If the write fails,
251 * no worries we are closing anyway. If we didn't initiate this
252 * close, then our state has been changed to
253 * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this.
254 *
255 * Likewise if it's a second call to close this connection after we
256 * sent the close indication to the peer already, we are in state
257 * WSI_STATE_AWAITING_CLOSE_ACK and will skip doing this a second time.
258 */
259
260 if (old_state == WSI_STATE_ESTABLISHED &&
261 reason != LWS_CLOSE_STATUS_NOSTATUS) {
Andy Green66a16f32011-05-24 22:07:45 +0100262
Andy Greencc012472011-11-07 19:53:23 +0800263 debug("sending close indication...\n");
Andy Green66a16f32011-05-24 22:07:45 +0100264
Andy Greenda527df2011-03-07 07:08:12 +0000265 n = libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING],
266 0, LWS_WRITE_CLOSE);
267 if (!n) {
268 /*
269 * we have sent a nice protocol level indication we
270 * now wish to close, we should not send anything more
271 */
272
273 wsi->state = WSI_STATE_AWAITING_CLOSE_ACK;
274
275 /* and we should wait for a reply for a bit */
276
277 libwebsocket_set_timeout(wsi,
278 PENDING_TIMEOUT_CLOSE_ACK, 5);
279
Andy Greencc012472011-11-07 19:53:23 +0800280 debug("sent close indication, awaiting ack\n");
Andy Greenda527df2011-03-07 07:08:12 +0000281
282 return;
283 }
284
285 /* else, the send failed and we should just hang up */
286 }
287
Andy Greenc44159f2011-03-07 07:08:18 +0000288just_kill_connection:
Andy Green66a16f32011-05-24 22:07:45 +0100289
Andy Greencc012472011-11-07 19:53:23 +0800290 debug("libwebsocket_close_and_free_session: just_kill_connection\n");
Andy Green66a16f32011-05-24 22:07:45 +0100291
Andy Greenda527df2011-03-07 07:08:12 +0000292 /*
293 * we won't be servicing or receiving anything further from this guy
294 * remove this fd from wsi mapping hashtable
295 */
Andy Green4b6fbe12011-02-14 08:03:48 +0000296
Andy Greena41314f2011-05-23 10:00:03 +0100297 if (wsi->sock)
298 delete_from_fd(context, wsi->sock);
Andy Green4b6fbe12011-02-14 08:03:48 +0000299
300 /* delete it from the internal poll list if still present */
301
Peter Hinz56885f32011-03-02 22:03:47 +0000302 for (n = 0; n < context->fds_count; n++) {
303 if (context->fds[n].fd != wsi->sock)
Andy Green4b6fbe12011-02-14 08:03:48 +0000304 continue;
Peter Hinz56885f32011-03-02 22:03:47 +0000305 while (n < context->fds_count - 1) {
306 context->fds[n] = context->fds[n + 1];
Andy Green4b6fbe12011-02-14 08:03:48 +0000307 n++;
308 }
Peter Hinz56885f32011-03-02 22:03:47 +0000309 context->fds_count--;
Andy Green4b6fbe12011-02-14 08:03:48 +0000310 /* we only have to deal with one */
Peter Hinz56885f32011-03-02 22:03:47 +0000311 n = context->fds_count;
Andy Green4b6fbe12011-02-14 08:03:48 +0000312 }
313
314 /* remove also from external POLL support via protocol 0 */
Andy Greena41314f2011-05-23 10:00:03 +0100315 if (wsi->sock)
316 context->protocols[0].callback(context, wsi,
Andy Green4b6fbe12011-02-14 08:03:48 +0000317 LWS_CALLBACK_DEL_POLL_FD, (void *)(long)wsi->sock, NULL, 0);
318
Andy Green251f6fa2010-11-03 11:13:06 +0000319 wsi->state = WSI_STATE_DEAD_SOCKET;
320
Andy Green4b6fbe12011-02-14 08:03:48 +0000321 /* tell the user it's all over for this guy */
322
Andy Greend4302732011-02-28 07:45:29 +0000323 if (wsi->protocol && wsi->protocol->callback &&
Andy Green6ee372f2012-04-09 15:09:01 +0800324 ((old_state == WSI_STATE_ESTABLISHED) ||
325 (old_state == WSI_STATE_RETURNED_CLOSE_ALREADY) ||
326 (old_state == WSI_STATE_AWAITING_CLOSE_ACK))) {
Andy Greencc012472011-11-07 19:53:23 +0800327 debug("calling back CLOSED\n");
Peter Hinz56885f32011-03-02 22:03:47 +0000328 wsi->protocol->callback(context, wsi, LWS_CALLBACK_CLOSED,
Andy Greene77ddd82010-11-13 10:03:47 +0000329 wsi->user_space, NULL, 0);
Andy Greencc012472011-11-07 19:53:23 +0800330 } else
Andy Green6ee372f2012-04-09 15:09:01 +0800331 debug("not calling back closed, old_state=%d\n", old_state);
Andy Green251f6fa2010-11-03 11:13:06 +0000332
Andy Greenef660a92011-03-06 10:29:38 +0000333 /* deallocate any active extension contexts */
334
335 for (n = 0; n < wsi->count_active_extensions; n++) {
336 if (!wsi->active_extensions[n]->callback)
337 continue;
338
Andy Green46c2ea02011-03-22 09:04:01 +0000339 wsi->active_extensions[n]->callback(context,
340 wsi->active_extensions[n], wsi,
341 LWS_EXT_CALLBACK_DESTROY,
342 wsi->active_extensions_user[n], NULL, 0);
Andy Greenef660a92011-03-06 10:29:38 +0000343
344 free(wsi->active_extensions_user[n]);
345 }
346
Andy Greena41314f2011-05-23 10:00:03 +0100347 /*
348 * inform all extensions in case they tracked this guy out of band
349 * even though not active on him specifically
350 */
351
352 ext = context->extensions;
353 while (ext && ext->callback) {
354 ext->callback(context, ext, wsi,
355 LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING,
356 NULL, NULL, 0);
357 ext++;
358 }
359
Andy Greenef660a92011-03-06 10:29:38 +0000360 /* free up his parsing allocations */
Andy Green4b6fbe12011-02-14 08:03:48 +0000361
Andy Green251f6fa2010-11-03 11:13:06 +0000362 for (n = 0; n < WSI_TOKEN_COUNT; n++)
363 if (wsi->utf8_token[n].token)
364 free(wsi->utf8_token[n].token);
365
Andy Greena41314f2011-05-23 10:00:03 +0100366 if (wsi->c_address)
367 free(wsi->c_address);
368
Andy Green0ca6a172010-12-19 20:50:01 +0000369/* fprintf(stderr, "closing fd=%d\n", wsi->sock); */
Andy Green251f6fa2010-11-03 11:13:06 +0000370
Andy Green3faa9c72010-11-08 17:03:03 +0000371#ifdef LWS_OPENSSL_SUPPORT
Andy Green90c7cbc2011-01-27 06:26:52 +0000372 if (wsi->ssl) {
Andy Green3faa9c72010-11-08 17:03:03 +0000373 n = SSL_get_fd(wsi->ssl);
374 SSL_shutdown(wsi->ssl);
Peter Hinz56885f32011-03-02 22:03:47 +0000375#ifdef WIN32
376 closesocket(n);
377#else
Andy Green3faa9c72010-11-08 17:03:03 +0000378 close(n);
Peter Hinz56885f32011-03-02 22:03:47 +0000379#endif
Andy Green3faa9c72010-11-08 17:03:03 +0000380 SSL_free(wsi->ssl);
381 } else {
382#endif
383 shutdown(wsi->sock, SHUT_RDWR);
Peter Hinz56885f32011-03-02 22:03:47 +0000384#ifdef WIN32
Andy Green66a16f32011-05-24 22:07:45 +0100385 if (wsi->sock)
386 closesocket(wsi->sock);
Peter Hinz56885f32011-03-02 22:03:47 +0000387#else
Andy Green66a16f32011-05-24 22:07:45 +0100388 if (wsi->sock)
389 close(wsi->sock);
Peter Hinz56885f32011-03-02 22:03:47 +0000390#endif
Andy Green3faa9c72010-11-08 17:03:03 +0000391#ifdef LWS_OPENSSL_SUPPORT
392 }
393#endif
Andy Green4f3943a2010-11-12 10:44:16 +0000394 if (wsi->user_space)
395 free(wsi->user_space);
396
Andy Green251f6fa2010-11-03 11:13:06 +0000397 free(wsi);
398}
399
Andy Green07034092011-02-13 08:37:12 +0000400/**
Andy Greenf7ee5492011-02-13 09:04:21 +0000401 * libwebsockets_hangup_on_client() - Server calls to terminate client
Andy Green6ee372f2012-04-09 15:09:01 +0800402 * connection
Peter Hinz56885f32011-03-02 22:03:47 +0000403 * @context: libwebsockets context
Andy Greenf7ee5492011-02-13 09:04:21 +0000404 * @fd: Connection socket descriptor
405 */
406
407void
Peter Hinz56885f32011-03-02 22:03:47 +0000408libwebsockets_hangup_on_client(struct libwebsocket_context *context, int fd)
Andy Greenf7ee5492011-02-13 09:04:21 +0000409{
Peter Hinz56885f32011-03-02 22:03:47 +0000410 struct libwebsocket *wsi = wsi_from_fd(context, fd);
Andy Greenf7ee5492011-02-13 09:04:21 +0000411
412 if (wsi == NULL)
413 return;
414
Peter Hinz56885f32011-03-02 22:03:47 +0000415 libwebsocket_close_and_free_session(context, wsi,
Andy Green6da560c2011-02-26 11:06:27 +0000416 LWS_CLOSE_STATUS_NOSTATUS);
Andy Greenf7ee5492011-02-13 09:04:21 +0000417}
418
419
420/**
Andy Green07034092011-02-13 08:37:12 +0000421 * libwebsockets_get_peer_addresses() - Get client address information
422 * @fd: Connection socket descriptor
423 * @name: Buffer to take client address name
424 * @name_len: Length of client address name buffer
425 * @rip: Buffer to take client address IP qotted quad
426 * @rip_len: Length of client address IP buffer
427 *
428 * This function fills in @name and @rip with the name and IP of
Andy Green6ee372f2012-04-09 15:09:01 +0800429 * the client connected with socket descriptor @fd. Names may be
430 * truncated if there is not enough room. If either cannot be
431 * determined, they will be returned as valid zero-length strings.
Andy Green07034092011-02-13 08:37:12 +0000432 */
433
434void
435libwebsockets_get_peer_addresses(int fd, char *name, int name_len,
436 char *rip, int rip_len)
437{
438 unsigned int len;
439 struct sockaddr_in sin;
440 struct hostent *host;
441 struct hostent *host1;
442 char ip[128];
Andy Greenf92def72011-03-09 15:02:20 +0000443 unsigned char *p;
Andy Green07034092011-02-13 08:37:12 +0000444 int n;
Andy Green7627af52011-03-09 15:13:52 +0000445 struct sockaddr_un *un;
Andy Green07034092011-02-13 08:37:12 +0000446
447 rip[0] = '\0';
448 name[0] = '\0';
449
450 len = sizeof sin;
451 if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
452 perror("getpeername");
453 return;
454 }
Andy Green6ee372f2012-04-09 15:09:01 +0800455
Andy Green07034092011-02-13 08:37:12 +0000456 host = gethostbyaddr((char *) &sin.sin_addr, sizeof sin.sin_addr,
457 AF_INET);
458 if (host == NULL) {
459 perror("gethostbyaddr");
460 return;
461 }
462
463 strncpy(name, host->h_name, name_len);
464 name[name_len - 1] = '\0';
465
466 host1 = gethostbyname(host->h_name);
467 if (host1 == NULL)
468 return;
Andy Greenf92def72011-03-09 15:02:20 +0000469 p = (unsigned char *)host1;
Andy Green07034092011-02-13 08:37:12 +0000470 n = 0;
471 while (p != NULL) {
Andy Greenf92def72011-03-09 15:02:20 +0000472 p = (unsigned char *)host1->h_addr_list[n++];
Andy Green07034092011-02-13 08:37:12 +0000473 if (p == NULL)
474 continue;
Peter Hinzbb45a902011-03-10 18:14:01 +0000475 if ((host1->h_addrtype != AF_INET)
476#ifdef AF_LOCAL
477 && (host1->h_addrtype != AF_LOCAL)
478#endif
479 )
Andy Green07034092011-02-13 08:37:12 +0000480 continue;
481
Andy Green7627af52011-03-09 15:13:52 +0000482 if (host1->h_addrtype == AF_INET)
483 sprintf(ip, "%u.%u.%u.%u", p[0], p[1], p[2], p[3]);
Peter Hinzbb45a902011-03-10 18:14:01 +0000484#ifdef AF_LOCAL
Andy Green7627af52011-03-09 15:13:52 +0000485 else {
486 un = (struct sockaddr_un *)p;
Andy Green6ee372f2012-04-09 15:09:01 +0800487 strncpy(ip, un->sun_path, sizeof(ip) - 1);
Andy Green7627af52011-03-09 15:13:52 +0000488 ip[sizeof(ip) - 1] = '\0';
489 }
Peter Hinzbb45a902011-03-10 18:14:01 +0000490#endif
Andy Green07034092011-02-13 08:37:12 +0000491 p = NULL;
492 strncpy(rip, ip, rip_len);
493 rip[rip_len - 1] = '\0';
494 }
495}
Andy Green9f990342011-02-12 11:57:45 +0000496
Peter Hinz56885f32011-03-02 22:03:47 +0000497int libwebsockets_get_random(struct libwebsocket_context *context,
498 void *buf, int len)
499{
500 int n;
501 char *p = buf;
502
503#ifdef WIN32
504 for (n = 0; n < len; n++)
505 p[n] = (unsigned char)rand();
506#else
507 n = read(context->fd_random, p, len);
508#endif
509
510 return n;
511}
512
Andy Green2836c642011-03-07 20:47:41 +0000513unsigned char *
514libwebsockets_SHA1(const unsigned char *d, size_t n, unsigned char *md)
515{
516 return SHA1(d, n, md);
517}
518
Andy Greeneeaacb32011-03-01 20:44:24 +0000519void libwebsockets_00_spaceout(char *key, int spaces, int seed)
520{
521 char *p;
Andy Green6ee372f2012-04-09 15:09:01 +0800522
Andy Greeneeaacb32011-03-01 20:44:24 +0000523 key++;
524 while (spaces--) {
525 if (*key && (seed & 1))
526 key++;
527 seed >>= 1;
Andy Green6ee372f2012-04-09 15:09:01 +0800528
Andy Greeneeaacb32011-03-01 20:44:24 +0000529 p = key + strlen(key);
530 while (p >= key) {
531 p[1] = p[0];
532 p--;
533 }
534 *key++ = ' ';
535 }
536}
537
538void libwebsockets_00_spam(char *key, int count, int seed)
539{
540 char *p;
541
542 key++;
543 while (count--) {
Andy Green6ee372f2012-04-09 15:09:01 +0800544
Andy Greeneeaacb32011-03-01 20:44:24 +0000545 if (*key && (seed & 1))
546 key++;
547 seed >>= 1;
548
549 p = key + strlen(key);
550 while (p >= key) {
551 p[1] = p[0];
552 p--;
553 }
554 *key++ = 0x21 + ((seed & 0xffff) % 15);
555 /* 4 would use it up too fast.. not like it matters */
556 seed >>= 1;
557 }
558}
559
Andy Green95a7b5d2011-03-06 10:29:39 +0000560int lws_send_pipe_choked(struct libwebsocket *wsi)
561{
562 struct pollfd fds;
563
564 fds.fd = wsi->sock;
565 fds.events = POLLOUT;
566 fds.revents = 0;
567
568 if (poll(&fds, 1, 0) != 1)
569 return 1;
570
571 if ((fds.revents & POLLOUT) == 0)
572 return 1;
573
574 /* okay to send another packet without blocking */
575
576 return 0;
577}
578
Andy Greena41314f2011-05-23 10:00:03 +0100579int
Andy Green3b84c002011-03-06 13:14:42 +0000580lws_handle_POLLOUT_event(struct libwebsocket_context *context,
581 struct libwebsocket *wsi, struct pollfd *pollfd)
582{
583 struct lws_tokens eff_buf;
584 int n;
585 int ret;
586 int m;
Andy Greena41314f2011-05-23 10:00:03 +0100587 int handled = 0;
Andy Green3b84c002011-03-06 13:14:42 +0000588
Andy Greena41314f2011-05-23 10:00:03 +0100589 for (n = 0; n < wsi->count_active_extensions; n++) {
590 if (!wsi->active_extensions[n]->callback)
591 continue;
592
593 m = wsi->active_extensions[n]->callback(context,
594 wsi->active_extensions[n], wsi,
595 LWS_EXT_CALLBACK_IS_WRITEABLE,
596 wsi->active_extensions_user[n], NULL, 0);
597 if (m > handled)
598 handled = m;
599 }
600
601 if (handled == 1)
602 goto notify_action;
603
604 if (!wsi->extension_data_pending || handled == 2)
Andy Green3b84c002011-03-06 13:14:42 +0000605 goto user_service;
606
607 /*
608 * check in on the active extensions, see if they
609 * had pending stuff to spill... they need to get the
610 * first look-in otherwise sequence will be disordered
611 *
612 * NULL, zero-length eff_buf means just spill pending
613 */
614
615 ret = 1;
616 while (ret == 1) {
617
618 /* default to nobody has more to spill */
619
620 ret = 0;
621 eff_buf.token = NULL;
622 eff_buf.token_len = 0;
623
624 /* give every extension a chance to spill */
625
626 for (n = 0; n < wsi->count_active_extensions; n++) {
627 m = wsi->active_extensions[n]->callback(
Andy Green46c2ea02011-03-22 09:04:01 +0000628 wsi->protocol->owning_server,
629 wsi->active_extensions[n], wsi,
Andy Green3b84c002011-03-06 13:14:42 +0000630 LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
631 wsi->active_extensions_user[n], &eff_buf, 0);
632 if (m < 0) {
Andy Green6ee372f2012-04-09 15:09:01 +0800633 fprintf(stderr, "ext reports fatal error\n");
Andy Green3b84c002011-03-06 13:14:42 +0000634 return -1;
635 }
636 if (m)
637 /*
638 * at least one extension told us he has more
639 * to spill, so we will go around again after
640 */
641 ret = 1;
642 }
643
644 /* assuming they gave us something to send, send it */
645
646 if (eff_buf.token_len) {
647 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
648 eff_buf.token_len))
649 return -1;
650 } else
651 continue;
652
653 /* no extension has more to spill */
654
655 if (!ret)
656 continue;
657
658 /*
659 * There's more to spill from an extension, but we just sent
660 * something... did that leave the pipe choked?
661 */
662
663 if (!lws_send_pipe_choked(wsi))
664 /* no we could add more */
665 continue;
666
Andy Greencc012472011-11-07 19:53:23 +0800667 debug("choked in POLLOUT service\n");
Andy Green3b84c002011-03-06 13:14:42 +0000668
669 /*
670 * Yes, he's choked. Leave the POLLOUT masked on so we will
671 * come back here when he is unchoked. Don't call the user
672 * callback to enforce ordering of spilling, he'll get called
673 * when we come back here and there's nothing more to spill.
674 */
675
676 return 0;
677 }
678
679 wsi->extension_data_pending = 0;
680
681user_service:
682 /* one shot */
683
Andy Greena41314f2011-05-23 10:00:03 +0100684 if (pollfd) {
685 pollfd->events &= ~POLLOUT;
Andy Green3b84c002011-03-06 13:14:42 +0000686
Andy Greena41314f2011-05-23 10:00:03 +0100687 /* external POLL support via protocol 0 */
688 context->protocols[0].callback(context, wsi,
689 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
690 (void *)(long)wsi->sock, NULL, POLLOUT);
691 }
692
693notify_action:
Andy Green3b84c002011-03-06 13:14:42 +0000694
Andy Green9e4c2b62011-03-07 20:47:39 +0000695 if (wsi->mode == LWS_CONNMODE_WS_CLIENT)
696 n = LWS_CALLBACK_CLIENT_WRITEABLE;
697 else
698 n = LWS_CALLBACK_SERVER_WRITEABLE;
699
700 wsi->protocol->callback(context, wsi, n, wsi->user_space, NULL, 0);
Andy Green3b84c002011-03-06 13:14:42 +0000701
702 return 0;
703}
704
705
706
Andy Greena41314f2011-05-23 10:00:03 +0100707void
708libwebsocket_service_timeout_check(struct libwebsocket_context *context,
709 struct libwebsocket *wsi, unsigned int sec)
710{
711 int n;
712
713 /*
714 * if extensions want in on it (eg, we are a mux parent)
715 * give them a chance to service child timeouts
716 */
717
718 for (n = 0; n < wsi->count_active_extensions; n++)
719 wsi->active_extensions[n]->callback(
720 context, wsi->active_extensions[n],
721 wsi, LWS_EXT_CALLBACK_1HZ,
722 wsi->active_extensions_user[n], NULL, sec);
723
724 if (!wsi->pending_timeout)
725 return;
Andy Green6ee372f2012-04-09 15:09:01 +0800726
Andy Greena41314f2011-05-23 10:00:03 +0100727 /*
728 * if we went beyond the allowed time, kill the
729 * connection
730 */
731
732 if (sec > wsi->pending_timeout_limit) {
Andy Greencc012472011-11-07 19:53:23 +0800733 debug("TIMEDOUT WAITING\n");
Andy Greena41314f2011-05-23 10:00:03 +0100734 libwebsocket_close_and_free_session(context,
735 wsi, LWS_CLOSE_STATUS_NOSTATUS);
736 }
737}
738
739struct libwebsocket *
740libwebsocket_create_new_server_wsi(struct libwebsocket_context *context)
741{
742 struct libwebsocket *new_wsi;
743 int n;
744
745 new_wsi = malloc(sizeof(struct libwebsocket));
746 if (new_wsi == NULL) {
747 fprintf(stderr, "Out of memory for new connection\n");
748 return NULL;
749 }
750
Andy Green6ee372f2012-04-09 15:09:01 +0800751 memset(new_wsi, 0, sizeof(struct libwebsocket));
Andy Greena41314f2011-05-23 10:00:03 +0100752 new_wsi->count_active_extensions = 0;
753 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
754
755 /* intialize the instance struct */
756
757 new_wsi->state = WSI_STATE_HTTP;
758 new_wsi->name_buffer_pos = 0;
759 new_wsi->mode = LWS_CONNMODE_WS_SERVING;
760
761 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
762 new_wsi->utf8_token[n].token = NULL;
763 new_wsi->utf8_token[n].token_len = 0;
764 }
765
766 /*
767 * these can only be set once the protocol is known
768 * we set an unestablished connection's protocol pointer
769 * to the start of the supported list, so it can look
770 * for matching ones during the handshake
771 */
772 new_wsi->protocol = context->protocols;
773 new_wsi->user_space = NULL;
774
775 /*
776 * Default protocol is 76 / 00
777 * After 76, there's a header specified to inform which
778 * draft the client wants, when that's seen we modify
779 * the individual connection's spec revision accordingly
780 */
781 new_wsi->ietf_spec_revision = 0;
782
783 return new_wsi;
784}
785
786char *
787libwebsockets_generate_client_handshake(struct libwebsocket_context *context,
788 struct libwebsocket *wsi, char *pkt)
789{
790 char hash[20];
791 char *p = pkt;
792 int n;
793 struct libwebsocket_extension *ext;
Andy Green09226502011-05-28 10:19:19 +0100794 struct libwebsocket_extension *ext1;
Andy Greena41314f2011-05-23 10:00:03 +0100795 int ext_count = 0;
Andy Green6ee372f2012-04-09 15:09:01 +0800796 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1 +
797 MAX_BROADCAST_PAYLOAD + LWS_SEND_BUFFER_POST_PADDING];
Andy Greena41314f2011-05-23 10:00:03 +0100798 static const char magic_websocket_guid[] =
799 "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
800
801 /*
802 * create the random key
803 */
804
805 n = libwebsockets_get_random(context, hash, 16);
806 if (n != 16) {
807 fprintf(stderr, "Unable to read from random dev %s\n",
808 SYSTEM_RANDOM_FILEPATH);
809 free(wsi->c_path);
810 free(wsi->c_host);
811 if (wsi->c_origin)
812 free(wsi->c_origin);
813 if (wsi->c_protocol)
814 free(wsi->c_protocol);
815 libwebsocket_close_and_free_session(context, wsi,
816 LWS_CLOSE_STATUS_NOSTATUS);
817 return NULL;
818 }
819
820 lws_b64_encode_string(hash, 16, wsi->key_b64,
821 sizeof wsi->key_b64);
822
823 /*
824 * 00 example client handshake
825 *
826 * GET /socket.io/websocket HTTP/1.1
827 * Upgrade: WebSocket
828 * Connection: Upgrade
829 * Host: 127.0.0.1:9999
830 * Origin: http://127.0.0.1
831 * Sec-WebSocket-Key1: 1 0 2#0W 9 89 7 92 ^
832 * Sec-WebSocket-Key2: 7 7Y 4328 B2v[8(z1
833 * Cookie: socketio=websocket
834 *
835 * (Á®Ä0¶†≥
836 *
837 * 04 example client handshake
838 *
839 * GET /chat HTTP/1.1
840 * Host: server.example.com
841 * Upgrade: websocket
842 * Connection: Upgrade
843 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
844 * Sec-WebSocket-Origin: http://example.com
845 * Sec-WebSocket-Protocol: chat, superchat
846 * Sec-WebSocket-Version: 4
847 */
848
849 p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a", wsi->c_path);
850
851 if (wsi->ietf_spec_revision == 0) {
852 unsigned char spaces_1, spaces_2;
853 unsigned int max_1, max_2;
854 unsigned int num_1, num_2;
855 unsigned long product_1, product_2;
856 char key_1[40];
857 char key_2[40];
858 unsigned int seed;
859 unsigned int count;
860 char challenge[16];
861
Andy Green6ee372f2012-04-09 15:09:01 +0800862 libwebsockets_get_random(context, &spaces_1, sizeof(char));
863 libwebsockets_get_random(context, &spaces_2, sizeof(char));
Andy Greena41314f2011-05-23 10:00:03 +0100864
865 spaces_1 = (spaces_1 % 12) + 1;
866 spaces_2 = (spaces_2 % 12) + 1;
867
868 max_1 = 4294967295 / spaces_1;
869 max_2 = 4294967295 / spaces_2;
870
871 libwebsockets_get_random(context, &num_1, sizeof(int));
872 libwebsockets_get_random(context, &num_2, sizeof(int));
873
874 num_1 = (num_1 % max_1);
875 num_2 = (num_2 % max_2);
876
877 challenge[0] = num_1 >> 24;
878 challenge[1] = num_1 >> 16;
879 challenge[2] = num_1 >> 8;
880 challenge[3] = num_1;
881 challenge[4] = num_2 >> 24;
882 challenge[5] = num_2 >> 16;
883 challenge[6] = num_2 >> 8;
884 challenge[7] = num_2;
885
886 product_1 = num_1 * spaces_1;
887 product_2 = num_2 * spaces_2;
888
889 sprintf(key_1, "%lu", product_1);
890 sprintf(key_2, "%lu", product_2);
891
892 libwebsockets_get_random(context, &seed, sizeof(int));
893 libwebsockets_get_random(context, &count, sizeof(int));
894
895 libwebsockets_00_spam(key_1, (count % 12) + 1, seed);
896
897 libwebsockets_get_random(context, &seed, sizeof(int));
898 libwebsockets_get_random(context, &count, sizeof(int));
899
900 libwebsockets_00_spam(key_2, (count % 12) + 1, seed);
901
902 libwebsockets_get_random(context, &seed, sizeof(int));
903
904 libwebsockets_00_spaceout(key_1, spaces_1, seed);
905 libwebsockets_00_spaceout(key_2, spaces_2, seed >> 16);
906
907 p += sprintf(p, "Upgrade: WebSocket\x0d\x0a"
908 "Connection: Upgrade\x0d\x0aHost: %s\x0d\x0a",
909 wsi->c_host);
910 if (wsi->c_origin)
Andy Green6ee372f2012-04-09 15:09:01 +0800911 p += sprintf(p, "Origin: %s\x0d\x0a", wsi->c_origin);
Andy Greena41314f2011-05-23 10:00:03 +0100912
913 if (wsi->c_protocol)
914 p += sprintf(p, "Sec-WebSocket-Protocol: %s"
915 "\x0d\x0a", wsi->c_protocol);
916
Andy Green6ee372f2012-04-09 15:09:01 +0800917 p += sprintf(p, "Sec-WebSocket-Key1: %s\x0d\x0a", key_1);
918 p += sprintf(p, "Sec-WebSocket-Key2: %s\x0d\x0a", key_2);
Andy Greena41314f2011-05-23 10:00:03 +0100919
920 /* give userland a chance to append, eg, cookies */
921
922 context->protocols[0].callback(context, wsi,
923 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
924 NULL, &p, (pkt + sizeof(pkt)) - p - 12);
925
926 p += sprintf(p, "\x0d\x0a");
927
928 if (libwebsockets_get_random(context, p, 8) != 8)
929 return NULL;
930 memcpy(&challenge[8], p, 8);
931 p += 8;
932
933 /* precompute what we want to see from the server */
934
935 MD5((unsigned char *)challenge, 16,
936 (unsigned char *)wsi->initial_handshake_hash_base64);
937
938 goto issue_hdr;
939 }
940
941 p += sprintf(p, "Host: %s\x0d\x0a", wsi->c_host);
942 p += sprintf(p, "Upgrade: websocket\x0d\x0a");
943 p += sprintf(p, "Connection: Upgrade\x0d\x0a"
944 "Sec-WebSocket-Key: ");
945 strcpy(p, wsi->key_b64);
946 p += strlen(wsi->key_b64);
947 p += sprintf(p, "\x0d\x0a");
948 if (wsi->c_origin)
949 p += sprintf(p, "Sec-WebSocket-Origin: %s\x0d\x0a",
950 wsi->c_origin);
951 if (wsi->c_protocol)
952 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
953 wsi->c_protocol);
954
955 /* tell the server what extensions we could support */
956
957 p += sprintf(p, "Sec-WebSocket-Extensions: ");
958
Andy Green6ee372f2012-04-09 15:09:01 +0800959 ext = context->extensions;
Andy Greena41314f2011-05-23 10:00:03 +0100960 while (ext && ext->callback) {
961
962 n = 0;
Andy Green09226502011-05-28 10:19:19 +0100963 ext1 = context->extensions;
Andy Green09226502011-05-28 10:19:19 +0100964
Andy Green6ee372f2012-04-09 15:09:01 +0800965 while (ext1 && ext1->callback) {
Andy Green09226502011-05-28 10:19:19 +0100966 n |= ext1->callback(context, ext1, wsi,
967 LWS_EXT_CALLBACK_CHECK_OK_TO_PROPOSE_EXTENSION,
968 NULL, (char *)ext->name, 0);
969
970 ext1++;
971 }
972
Andy Green6ee372f2012-04-09 15:09:01 +0800973 if (n) { /* an extension vetos us */
Andy Greencc012472011-11-07 19:53:23 +0800974 debug("ext %s vetoed\n", (char *)ext->name);
Andy Green09226502011-05-28 10:19:19 +0100975 ext++;
976 continue;
977 }
978
Andy Greena41314f2011-05-23 10:00:03 +0100979 n = context->protocols[0].callback(context, wsi,
980 LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED,
981 wsi->user_space, (char *)ext->name, 0);
982
983 /*
984 * zero return from callback means
985 * go ahead and allow the extension,
986 * it's what we get if the callback is
987 * unhandled
988 */
989
990 if (n) {
991 ext++;
992 continue;
993 }
994
995 /* apply it */
996
997 if (ext_count)
998 *p++ = ',';
999 p += sprintf(p, "%s", ext->name);
1000 ext_count++;
1001
1002 ext++;
1003 }
1004
1005 p += sprintf(p, "\x0d\x0a");
1006
1007 if (wsi->ietf_spec_revision)
1008 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a",
1009 wsi->ietf_spec_revision);
1010
1011 /* give userland a chance to append, eg, cookies */
1012
1013 context->protocols[0].callback(context, wsi,
1014 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
1015 NULL, &p, (pkt + sizeof(pkt)) - p - 12);
1016
1017 p += sprintf(p, "\x0d\x0a");
1018
1019 /* prepare the expected server accept response */
1020
1021 strcpy((char *)buf, wsi->key_b64);
1022 strcpy((char *)&buf[strlen((char *)buf)], magic_websocket_guid);
1023
1024 SHA1(buf, strlen((char *)buf), (unsigned char *)hash);
1025
1026 lws_b64_encode_string(hash, 20,
1027 wsi->initial_handshake_hash_base64,
1028 sizeof wsi->initial_handshake_hash_base64);
1029
1030issue_hdr:
1031
Andy Green6ee372f2012-04-09 15:09:01 +08001032#if 0
1033 puts(pkt);
1034#endif
Andy Green09226502011-05-28 10:19:19 +01001035
Andy Greena41314f2011-05-23 10:00:03 +01001036 /* done with these now */
1037
1038 free(wsi->c_path);
1039 free(wsi->c_host);
1040 if (wsi->c_origin)
1041 free(wsi->c_origin);
1042
1043 return p;
1044}
1045
1046int
1047lws_client_interpret_server_handshake(struct libwebsocket_context *context,
1048 struct libwebsocket *wsi)
1049{
Andy Green6ee372f2012-04-09 15:09:01 +08001050 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1 +
1051 MAX_BROADCAST_PAYLOAD + LWS_SEND_BUFFER_POST_PADDING];
Andy Greena41314f2011-05-23 10:00:03 +01001052 char pkt[1024];
1053 char *p = &pkt[0];
1054 const char *pc;
1055 const char *c;
1056 int more = 1;
1057 int okay = 0;
1058 char ext_name[128];
1059 struct libwebsocket_extension *ext;
1060 void *v;
Andy Greenc15cb382011-06-26 10:27:28 +01001061 int len = 0;
Andy Greena41314f2011-05-23 10:00:03 +01001062 int n;
1063 static const char magic_websocket_04_masking_guid[] =
1064 "61AC5F19-FBBA-4540-B96F-6561F1AB40A8";
1065
1066 /*
1067 * 00 / 76 -->
1068 *
1069 * HTTP/1.1 101 WebSocket Protocol Handshake
1070 * Upgrade: WebSocket
1071 * Connection: Upgrade
1072 * Sec-WebSocket-Origin: http://127.0.0.1
1073 * Sec-WebSocket-Location: ws://127.0.0.1:9999/socket.io/websocket
1074 *
1075 * xxxxxxxxxxxxxxxx
1076 */
1077
1078 if (wsi->ietf_spec_revision == 0) {
1079 if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
1080 !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
1081 !wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len ||
1082 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
1083 (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
1084 wsi->c_protocol != NULL)) {
Andy Greencc012472011-11-07 19:53:23 +08001085 debug("libwebsocket_client_handshake "
Andy Greena41314f2011-05-23 10:00:03 +01001086 "missing required header(s)\n");
1087 pkt[len] = '\0';
Andy Greencc012472011-11-07 19:53:23 +08001088 debug("%s", pkt);
Andy Greena41314f2011-05-23 10:00:03 +01001089 goto bail3;
1090 }
1091
1092 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
Andy Green6ee372f2012-04-09 15:09:01 +08001093 if (strncmp(wsi->utf8_token[WSI_TOKEN_HTTP].token, "101", 3)) {
Andy Greena41314f2011-05-23 10:00:03 +01001094 fprintf(stderr, "libwebsocket_client_handshake "
1095 "server sent bad HTTP response '%s'\n",
1096 wsi->utf8_token[WSI_TOKEN_HTTP].token);
1097 goto bail3;
1098 }
1099
Andy Green6ee372f2012-04-09 15:09:01 +08001100 if (wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len < 16) {
Andy Greena41314f2011-05-23 10:00:03 +01001101 fprintf(stderr, "libwebsocket_client_handshake "
1102 "challenge reply too short %d\n",
1103 wsi->utf8_token[
1104 WSI_TOKEN_CHALLENGE].token_len);
1105 pkt[len] = '\0';
Andy Greencc012472011-11-07 19:53:23 +08001106 debug("%s", pkt);
Andy Greena41314f2011-05-23 10:00:03 +01001107 goto bail3;
1108
1109 }
1110
1111 goto select_protocol;
1112 }
1113
1114 /*
1115 * well, what the server sent looked reasonable for syntax.
1116 * Now let's confirm it sent all the necessary headers
1117 */
1118#if 0
Andy Green6ee372f2012-04-09 15:09:01 +08001119 fprintf(stderr, "WSI_TOKEN_HTTP: %d\n",
1120 wsi->utf8_token[WSI_TOKEN_HTTP].token_len);
1121 fprintf(stderr, "WSI_TOKEN_UPGRADE: %d\n",
1122 wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len);
1123 fprintf(stderr, "WSI_TOKEN_CONNECTION: %d\n",
1124 wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len);
1125 fprintf(stderr, "WSI_TOKEN_ACCEPT: %d\n",
1126 wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len);
1127 fprintf(stderr, "WSI_TOKEN_NONCE: %d\n",
1128 wsi->utf8_token[WSI_TOKEN_NONCE].token_len);
1129 fprintf(stderr, "WSI_TOKEN_PROTOCOL: %d\n",
1130 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len);
Andy Greena41314f2011-05-23 10:00:03 +01001131#endif
Andy Green6ee372f2012-04-09 15:09:01 +08001132 if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
1133 !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
1134 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
1135 !wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len ||
1136 (!wsi->utf8_token[WSI_TOKEN_NONCE].token_len &&
Andy Greena41314f2011-05-23 10:00:03 +01001137 wsi->ietf_spec_revision == 4) ||
Andy Green6ee372f2012-04-09 15:09:01 +08001138 (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
1139 wsi->c_protocol != NULL)) {
1140 debug("libwebsocket_client_handshake "
Andy Greena41314f2011-05-23 10:00:03 +01001141 "missing required header(s)\n");
1142 pkt[len] = '\0';
Andy Greencc012472011-11-07 19:53:23 +08001143 debug("%s", pkt);
Andy Greena41314f2011-05-23 10:00:03 +01001144 goto bail3;
1145 }
1146
1147 /*
1148 * Everything seems to be there, now take a closer look at what
1149 * is in each header
1150 */
1151
1152 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
Artem Egorkined515ddd2011-11-23 10:46:24 +02001153 if (strncmp(wsi->utf8_token[WSI_TOKEN_HTTP].token, "101", 3)) {
Andy Greena41314f2011-05-23 10:00:03 +01001154 fprintf(stderr, "libwebsocket_client_handshake "
1155 "server sent bad HTTP response '%s'\n",
1156 wsi->utf8_token[WSI_TOKEN_HTTP].token);
1157 goto bail3;
1158 }
1159
1160 strtolower(wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
1161 if (strcmp(wsi->utf8_token[WSI_TOKEN_UPGRADE].token,
1162 "websocket")) {
1163 fprintf(stderr, "libwebsocket_client_handshake server "
1164 "sent bad Upgrade header '%s'\n",
1165 wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
1166 goto bail3;
1167 }
1168
1169 strtolower(wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
1170 if (strcmp(wsi->utf8_token[WSI_TOKEN_CONNECTION].token,
1171 "upgrade")) {
1172 fprintf(stderr, "libwebsocket_client_handshake server "
1173 "sent bad Connection hdr '%s'\n",
1174 wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
1175 goto bail3;
1176 }
1177
1178select_protocol:
1179 pc = wsi->c_protocol;
1180 if (pc == NULL)
Andy Green6ee372f2012-04-09 15:09:01 +08001181 fprintf(stderr, "lws_client_interpret_server_handshake: "
1182 "NULL c_protocol\n");
Andy Greena41314f2011-05-23 10:00:03 +01001183 else
Andy Green6ee372f2012-04-09 15:09:01 +08001184 debug("lws_client_interpret_server_handshake: "
1185 "cPprotocol='%s'\n", pc);
Andy Greena41314f2011-05-23 10:00:03 +01001186
1187 /*
1188 * confirm the protocol the server wants to talk was in the list
1189 * of protocols we offered
1190 */
1191
1192 if (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len) {
1193
Andy Green6ee372f2012-04-09 15:09:01 +08001194 fprintf(stderr, "lws_client_interpret_server_handshake "
1195 "WSI_TOKEN_PROTOCOL is null\n");
Andy Greena41314f2011-05-23 10:00:03 +01001196 /*
1197 * no protocol name to work from,
1198 * default to first protocol
1199 */
1200 wsi->protocol = &context->protocols[0];
1201
1202 free(wsi->c_protocol);
1203
1204 goto check_accept;
1205 }
1206
1207 while (*pc && !okay) {
Andy Green6ee372f2012-04-09 15:09:01 +08001208 if ((!strncmp(pc, 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')) {
Andy Greena41314f2011-05-23 10:00:03 +01001212 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
Andy Greena41314f2011-05-23 10:00:03 +01001226 if (!okay) {
1227 fprintf(stderr, "libwebsocket_client_handshake server "
1228 "sent bad protocol '%s'\n",
1229 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
1230 goto bail2;
1231 }
1232
1233 /*
1234 * identify the selected protocol struct and set it
1235 */
1236 n = 0;
1237 wsi->protocol = NULL;
1238 while (context->protocols[n].callback) {
1239 if (strcmp(wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
1240 context->protocols[n].name) == 0)
1241 wsi->protocol = &context->protocols[n];
1242 n++;
1243 }
1244
1245 if (wsi->protocol == NULL) {
1246 fprintf(stderr, "libwebsocket_client_handshake server "
1247 "requested protocol '%s', which we "
1248 "said we supported but we don't!\n",
1249 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
1250 goto bail2;
1251 }
1252
1253
1254 /* instantiate the accepted extensions */
1255
1256 if (!wsi->utf8_token[WSI_TOKEN_EXTENSIONS].token_len) {
Andy Green6ee372f2012-04-09 15:09:01 +08001257 debug("no client extenstions allowed by server\n");
Andy Greena41314f2011-05-23 10:00:03 +01001258 goto check_accept;
1259 }
1260
1261 /*
1262 * break down the list of server accepted extensions
1263 * and go through matching them or identifying bogons
1264 */
1265
1266 c = wsi->utf8_token[WSI_TOKEN_EXTENSIONS].token;
1267 n = 0;
1268 while (more) {
1269
1270 if (*c && (*c != ',' && *c != ' ' && *c != '\t')) {
1271 ext_name[n] = *c++;
1272 if (n < sizeof(ext_name) - 1)
1273 n++;
1274 continue;
1275 }
1276 ext_name[n] = '\0';
1277 if (!*c)
1278 more = 0;
1279 else {
1280 c++;
1281 if (!n)
1282 continue;
1283 }
1284
1285 /* check we actually support it */
1286
Andy Greencc012472011-11-07 19:53:23 +08001287 debug("checking client ext %s\n", ext_name);
Andy Greena41314f2011-05-23 10:00:03 +01001288
1289 n = 0;
1290 ext = wsi->protocol->owning_server->extensions;
1291 while (ext && ext->callback) {
1292
1293 if (strcmp(ext_name, ext->name)) {
1294 ext++;
1295 continue;
1296 }
1297
1298 n = 1;
1299
Andy Greencc012472011-11-07 19:53:23 +08001300 debug("instantiating client ext %s\n", ext_name);
Andy Greena41314f2011-05-23 10:00:03 +01001301
1302 /* instantiate the extension on this conn */
1303
1304 wsi->active_extensions_user[
1305 wsi->count_active_extensions] =
1306 malloc(ext->per_session_data_size);
Andy Greenf6652412011-05-25 20:46:18 +01001307 memset(wsi->active_extensions_user[
1308 wsi->count_active_extensions], 0,
1309 ext->per_session_data_size);
Andy Greena41314f2011-05-23 10:00:03 +01001310 wsi->active_extensions[
1311 wsi->count_active_extensions] = ext;
1312
1313 /* allow him to construct his context */
1314
1315 ext->callback(wsi->protocol->owning_server,
1316 ext, wsi,
1317 LWS_EXT_CALLBACK_CLIENT_CONSTRUCT,
1318 wsi->active_extensions_user[
1319 wsi->count_active_extensions],
1320 NULL, 0);
1321
1322 wsi->count_active_extensions++;
1323
1324 ext++;
1325 }
1326
1327 if (n == 0) {
1328 fprintf(stderr, "Server said we should use"
1329 "an unknown extension '%s'!\n", ext_name);
1330 goto bail2;
1331 }
1332
1333 n = 0;
1334 }
1335
1336
1337check_accept:
1338
1339 if (wsi->ietf_spec_revision == 0) {
1340
1341 if (memcmp(wsi->initial_handshake_hash_base64,
1342 wsi->utf8_token[WSI_TOKEN_CHALLENGE].token, 16)) {
1343 fprintf(stderr, "libwebsocket_client_handshake "
1344 "failed 00 challenge compare\n");
1345 pkt[len] = '\0';
1346 fprintf(stderr, "%s", pkt);
1347 goto bail2;
1348 }
1349
1350 goto accept_ok;
1351 }
1352
1353 /*
1354 * Confirm his accept token is the one we precomputed
1355 */
1356
1357 if (strcmp(wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
1358 wsi->initial_handshake_hash_base64)) {
1359 fprintf(stderr, "libwebsocket_client_handshake server "
1360 "sent bad ACCEPT '%s' vs computed '%s'\n",
1361 wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
1362 wsi->initial_handshake_hash_base64);
1363 goto bail2;
1364 }
1365
1366 if (wsi->ietf_spec_revision == 4) {
1367 /*
1368 * Calculate the 04 masking key to use when
1369 * sending data to server
1370 */
1371
1372 strcpy((char *)buf, wsi->key_b64);
1373 p = (char *)buf + strlen(wsi->key_b64);
1374 strcpy(p, wsi->utf8_token[WSI_TOKEN_NONCE].token);
1375 p += wsi->utf8_token[WSI_TOKEN_NONCE].token_len;
1376 strcpy(p, magic_websocket_04_masking_guid);
1377 SHA1(buf, strlen((char *)buf), wsi->masking_key_04);
1378 }
Andy Green6ee372f2012-04-09 15:09:01 +08001379accept_ok:
Andy Greena41314f2011-05-23 10:00:03 +01001380
1381 /* allocate the per-connection user memory (if any) */
Andy Green6ee372f2012-04-09 15:09:01 +08001382 if (wsi->protocol->per_session_data_size &&
1383 !libwebsocket_ensure_user_space(wsi))
1384 goto bail2;
Andy Greena41314f2011-05-23 10:00:03 +01001385
1386 /* clear his proxy connection timeout */
1387
1388 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1389
1390 /* mark him as being alive */
1391
1392 wsi->state = WSI_STATE_ESTABLISHED;
1393 wsi->mode = LWS_CONNMODE_WS_CLIENT;
1394
Andy Green6ee372f2012-04-09 15:09:01 +08001395 fprintf(stderr, "handshake OK for protocol %s\n", wsi->protocol->name);
Andy Greena41314f2011-05-23 10:00:03 +01001396
1397 /* call him back to inform him he is up */
1398
1399 wsi->protocol->callback(context, wsi,
Andy Green6ee372f2012-04-09 15:09:01 +08001400 LWS_CALLBACK_CLIENT_ESTABLISHED,
1401 wsi->user_space, NULL, 0);
Andy Greena41314f2011-05-23 10:00:03 +01001402
1403 /*
1404 * inform all extensions, not just active ones since they
1405 * already know
1406 */
1407
1408 ext = context->extensions;
1409
1410 while (ext && ext->callback) {
1411 v = NULL;
1412 for (n = 0; n < wsi->count_active_extensions; n++)
1413 if (wsi->active_extensions[n] == ext)
1414 v = wsi->active_extensions_user[n];
1415
1416 ext->callback(context, ext, wsi,
1417 LWS_EXT_CALLBACK_ANY_WSI_ESTABLISHED, v, NULL, 0);
1418 ext++;
1419 }
1420
1421 return 0;
1422
1423bail3:
1424 if (wsi->c_protocol)
1425 free(wsi->c_protocol);
1426
1427bail2:
1428 libwebsocket_close_and_free_session(context, wsi,
1429 LWS_CLOSE_STATUS_NOSTATUS);
1430 return 1;
1431}
1432
1433
1434
Andy Green9f990342011-02-12 11:57:45 +00001435/**
1436 * libwebsocket_service_fd() - Service polled socket with something waiting
Peter Hinz56885f32011-03-02 22:03:47 +00001437 * @context: Websocket context
Andy Green9f990342011-02-12 11:57:45 +00001438 * @pollfd: The pollfd entry describing the socket fd and which events
Andy Green6ee372f2012-04-09 15:09:01 +08001439 * happened.
Andy Green9f990342011-02-12 11:57:45 +00001440 *
1441 * This function closes any active connections and then frees the
1442 * context. After calling this, any further use of the context is
1443 * undefined.
1444 */
1445
1446int
Peter Hinz56885f32011-03-02 22:03:47 +00001447libwebsocket_service_fd(struct libwebsocket_context *context,
Andy Green0d338332011-02-12 11:57:43 +00001448 struct pollfd *pollfd)
Andy Greenb45993c2010-12-18 15:13:50 +00001449{
Andy Green6ee372f2012-04-09 15:09:01 +08001450 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1 +
1451 MAX_BROADCAST_PAYLOAD + LWS_SEND_BUFFER_POST_PADDING];
Andy Greena71eafc2011-02-14 17:59:43 +00001452 struct libwebsocket *wsi;
Andy Green0d338332011-02-12 11:57:43 +00001453 struct libwebsocket *new_wsi;
Andy Greenb45993c2010-12-18 15:13:50 +00001454 int n;
Andy Green0d338332011-02-12 11:57:43 +00001455 int m;
Tobias Maiere8c9b562012-04-05 11:57:12 +02001456 ssize_t len;
Andy Green0d338332011-02-12 11:57:43 +00001457 int accept_fd;
1458 unsigned int clilen;
1459 struct sockaddr_in cli_addr;
Andy Greena71eafc2011-02-14 17:59:43 +00001460 struct timeval tv;
Andy Greenbe93fef2011-02-14 20:25:43 +00001461 char pkt[1024];
1462 char *p = &pkt[0];
Andy Green2366b1c2011-03-06 13:15:31 +00001463 int more = 1;
Andy Green98a717c2011-03-06 13:14:15 +00001464 struct lws_tokens eff_buf;
Andy Green6c939552011-03-08 08:56:57 +00001465 int opt = 1;
Yonathan Yusim3ae39ff2012-04-09 06:42:39 +08001466 char c;
Andy Greenc6517fa2011-03-06 13:15:29 +00001467
Andy Greenbe93fef2011-02-14 20:25:43 +00001468#ifdef LWS_OPENSSL_SUPPORT
1469 char ssl_err_buf[512];
1470#endif
Andy Greena71eafc2011-02-14 17:59:43 +00001471 /*
1472 * you can call us with pollfd = NULL to just allow the once-per-second
1473 * global timeout checks; if less than a second since the last check
1474 * it returns immediately then.
1475 */
1476
1477 gettimeofday(&tv, NULL);
1478
Peter Hinz56885f32011-03-02 22:03:47 +00001479 if (context->last_timeout_check_s != tv.tv_sec) {
1480 context->last_timeout_check_s = tv.tv_sec;
Andy Greena71eafc2011-02-14 17:59:43 +00001481
1482 /* global timeout check once per second */
1483
Peter Hinz56885f32011-03-02 22:03:47 +00001484 for (n = 0; n < context->fds_count; n++) {
1485 wsi = wsi_from_fd(context, context->fds[n].fd);
Andy Greena71eafc2011-02-14 17:59:43 +00001486
Andy Greena41314f2011-05-23 10:00:03 +01001487 libwebsocket_service_timeout_check(context, wsi,
1488 tv.tv_sec);
Andy Greena71eafc2011-02-14 17:59:43 +00001489 }
1490 }
1491
1492 /* just here for timeout management? */
1493
1494 if (pollfd == NULL)
1495 return 0;
1496
1497 /* no, here to service a socket descriptor */
1498
Peter Hinz56885f32011-03-02 22:03:47 +00001499 wsi = wsi_from_fd(context, pollfd->fd);
Andy Greenb45993c2010-12-18 15:13:50 +00001500
Andy Green0d338332011-02-12 11:57:43 +00001501 if (wsi == NULL)
1502 return 1;
Andy Green8f037e42010-12-19 22:13:26 +00001503
Andy Green0d338332011-02-12 11:57:43 +00001504 switch (wsi->mode) {
1505 case LWS_CONNMODE_SERVER_LISTENER:
1506
1507 /* pollin means a client has connected to us then */
1508
1509 if (!pollfd->revents & POLLIN)
1510 break;
1511
David Galeanof7009352011-09-26 12:09:54 +01001512 if (context->fds_count >= MAX_CLIENTS) {
1513 fprintf(stderr, "too busy to accept new client\n");
1514 break;
1515 }
1516
Andy Green0d338332011-02-12 11:57:43 +00001517 /* listen socket got an unencrypted connection... */
1518
1519 clilen = sizeof(cli_addr);
1520 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
1521 &clilen);
1522 if (accept_fd < 0) {
1523 fprintf(stderr, "ERROR on accept");
1524 break;
1525 }
1526
Andy Green6c939552011-03-08 08:56:57 +00001527 /* Disable Nagle */
1528 opt = 1;
Andy Green6ee372f2012-04-09 15:09:01 +08001529 setsockopt(accept_fd, IPPROTO_TCP, TCP_NODELAY,
1530 (const void *)&opt, sizeof(opt));
Andy Green6c939552011-03-08 08:56:57 +00001531
Andy Green07034092011-02-13 08:37:12 +00001532 /*
1533 * look at who we connected to and give user code a chance
1534 * to reject based on client IP. There's no protocol selected
1535 * yet so we issue this to protocols[0]
1536 */
1537
Peter Hinz56885f32011-03-02 22:03:47 +00001538 if ((context->protocols[0].callback)(context, wsi,
Andy Green07034092011-02-13 08:37:12 +00001539 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
Andy Green6ee372f2012-04-09 15:09:01 +08001540 (void *)(long)accept_fd, NULL, 0)) {
Andy Greencc012472011-11-07 19:53:23 +08001541 debug("Callback denied network connection\n");
Peter Hinz56885f32011-03-02 22:03:47 +00001542#ifdef WIN32
1543 closesocket(accept_fd);
1544#else
Andy Green07034092011-02-13 08:37:12 +00001545 close(accept_fd);
Peter Hinz56885f32011-03-02 22:03:47 +00001546#endif
Andy Green07034092011-02-13 08:37:12 +00001547 break;
1548 }
1549
Andy Green0d338332011-02-12 11:57:43 +00001550 /* accepting connection to main listener */
1551
Andy Greena41314f2011-05-23 10:00:03 +01001552 new_wsi = libwebsocket_create_new_server_wsi(context);
1553 if (new_wsi == NULL)
Andy Green0d338332011-02-12 11:57:43 +00001554 break;
Andy Green0d338332011-02-12 11:57:43 +00001555
Andy Green0d338332011-02-12 11:57:43 +00001556 new_wsi->sock = accept_fd;
Andy Greena41314f2011-05-23 10:00:03 +01001557
Andy Green0d338332011-02-12 11:57:43 +00001558
1559#ifdef LWS_OPENSSL_SUPPORT
1560 new_wsi->ssl = NULL;
Andy Green0d338332011-02-12 11:57:43 +00001561
Peter Hinz56885f32011-03-02 22:03:47 +00001562 if (context->use_ssl) {
Andy Green0d338332011-02-12 11:57:43 +00001563
Peter Hinz56885f32011-03-02 22:03:47 +00001564 new_wsi->ssl = SSL_new(context->ssl_ctx);
Andy Green0d338332011-02-12 11:57:43 +00001565 if (new_wsi->ssl == NULL) {
1566 fprintf(stderr, "SSL_new failed: %s\n",
1567 ERR_error_string(SSL_get_error(
1568 new_wsi->ssl, 0), NULL));
Andy Green1f9bf522011-02-14 21:14:37 +00001569 libwebsockets_decode_ssl_error();
Andy Green0d338332011-02-12 11:57:43 +00001570 free(new_wsi);
1571 break;
1572 }
1573
1574 SSL_set_fd(new_wsi->ssl, accept_fd);
1575
1576 n = SSL_accept(new_wsi->ssl);
1577 if (n != 1) {
1578 /*
1579 * browsers seem to probe with various
1580 * ssl params which fail then retry
1581 * and succeed
1582 */
1583 debug("SSL_accept failed skt %u: %s\n",
1584 pollfd->fd,
1585 ERR_error_string(SSL_get_error(
1586 new_wsi->ssl, n), NULL));
1587 SSL_free(
1588 new_wsi->ssl);
1589 free(new_wsi);
1590 break;
1591 }
Andy Green6ee372f2012-04-09 15:09:01 +08001592
Andy Green0d338332011-02-12 11:57:43 +00001593 debug("accepted new SSL conn "
1594 "port %u on fd=%d SSL ver %s\n",
1595 ntohs(cli_addr.sin_port), accept_fd,
1596 SSL_get_version(new_wsi->ssl));
1597
1598 } else
1599#endif
1600 debug("accepted new conn port %u on fd=%d\n",
1601 ntohs(cli_addr.sin_port), accept_fd);
1602
Peter Hinz56885f32011-03-02 22:03:47 +00001603 insert_wsi(context, new_wsi);
Andy Green0d338332011-02-12 11:57:43 +00001604
Andy Green0d338332011-02-12 11:57:43 +00001605 /*
1606 * make sure NO events are seen yet on this new socket
1607 * (otherwise we inherit old fds[client].revents from
1608 * previous socket there and die mysteriously! )
1609 */
Peter Hinz56885f32011-03-02 22:03:47 +00001610 context->fds[context->fds_count].revents = 0;
Andy Green0d338332011-02-12 11:57:43 +00001611
Peter Hinz56885f32011-03-02 22:03:47 +00001612 context->fds[context->fds_count].events = POLLIN;
1613 context->fds[context->fds_count++].fd = accept_fd;
Andy Green0d338332011-02-12 11:57:43 +00001614
Andy Green3221f922011-02-12 13:14:11 +00001615 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00001616 context->protocols[0].callback(context, new_wsi,
Andy Green3221f922011-02-12 13:14:11 +00001617 LWS_CALLBACK_ADD_POLL_FD,
1618 (void *)(long)accept_fd, NULL, POLLIN);
1619
Andy Green0d338332011-02-12 11:57:43 +00001620 break;
1621
1622 case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
1623
1624 /* as we are listening, POLLIN means accept() is needed */
Andy Green6ee372f2012-04-09 15:09:01 +08001625
Andy Green0d338332011-02-12 11:57:43 +00001626 if (!pollfd->revents & POLLIN)
1627 break;
1628
1629 /* listen socket got an unencrypted connection... */
1630
1631 clilen = sizeof(cli_addr);
1632 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
1633 &clilen);
1634 if (accept_fd < 0) {
1635 fprintf(stderr, "ERROR on accept");
1636 break;
1637 }
1638
Peter Hinz56885f32011-03-02 22:03:47 +00001639 if (context->fds_count >= MAX_CLIENTS) {
Andy Green3221f922011-02-12 13:14:11 +00001640 fprintf(stderr, "too busy to accept new broadcast "
1641 "proxy client\n");
Peter Hinz56885f32011-03-02 22:03:47 +00001642#ifdef WIN32
1643 closesocket(accept_fd);
1644#else
Andy Green0d338332011-02-12 11:57:43 +00001645 close(accept_fd);
Peter Hinz56885f32011-03-02 22:03:47 +00001646#endif
Andy Green0d338332011-02-12 11:57:43 +00001647 break;
1648 }
1649
1650 /* create a dummy wsi for the connection and add it */
1651
1652 new_wsi = malloc(sizeof(struct libwebsocket));
Andy Green6ee372f2012-04-09 15:09:01 +08001653 memset(new_wsi, 0, sizeof(struct libwebsocket));
Andy Green0d338332011-02-12 11:57:43 +00001654 new_wsi->sock = accept_fd;
1655 new_wsi->mode = LWS_CONNMODE_BROADCAST_PROXY;
1656 new_wsi->state = WSI_STATE_ESTABLISHED;
Andy Greend6e09112011-03-05 16:12:15 +00001657 new_wsi->count_active_extensions = 0;
Andy Green0d338332011-02-12 11:57:43 +00001658 /* note which protocol we are proxying */
1659 new_wsi->protocol_index_for_broadcast_proxy =
1660 wsi->protocol_index_for_broadcast_proxy;
Peter Hinz56885f32011-03-02 22:03:47 +00001661 insert_wsi(context, new_wsi);
Andy Green0d338332011-02-12 11:57:43 +00001662
1663 /* add connected socket to internal poll array */
1664
Peter Hinz56885f32011-03-02 22:03:47 +00001665 context->fds[context->fds_count].revents = 0;
1666 context->fds[context->fds_count].events = POLLIN;
1667 context->fds[context->fds_count++].fd = accept_fd;
Andy Green0d338332011-02-12 11:57:43 +00001668
Andy Green3221f922011-02-12 13:14:11 +00001669 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00001670 context->protocols[0].callback(context, new_wsi,
Andy Green3221f922011-02-12 13:14:11 +00001671 LWS_CALLBACK_ADD_POLL_FD,
1672 (void *)(long)accept_fd, NULL, POLLIN);
1673
Andy Green0d338332011-02-12 11:57:43 +00001674 break;
1675
1676 case LWS_CONNMODE_BROADCAST_PROXY:
Andy Green8f037e42010-12-19 22:13:26 +00001677
Andy Greenb45993c2010-12-18 15:13:50 +00001678 /* handle session socket closed */
Andy Green8f037e42010-12-19 22:13:26 +00001679
Andy Green0d338332011-02-12 11:57:43 +00001680 if (pollfd->revents & (POLLERR | POLLHUP)) {
Andy Green8f037e42010-12-19 22:13:26 +00001681
Andy Green0d338332011-02-12 11:57:43 +00001682 debug("Session Socket %p (fd=%d) dead\n",
Timothy J Fontaineb86d64e2011-02-14 17:55:27 +00001683 (void *)wsi, pollfd->fd);
Andy Greenb45993c2010-12-18 15:13:50 +00001684
Peter Hinz56885f32011-03-02 22:03:47 +00001685 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +00001686 LWS_CLOSE_STATUS_NORMAL);
Andy Green4b6fbe12011-02-14 08:03:48 +00001687 return 1;
Andy Greenb45993c2010-12-18 15:13:50 +00001688 }
Andy Green8f037e42010-12-19 22:13:26 +00001689
Andy Green3b84c002011-03-06 13:14:42 +00001690 /*
1691 * either extension code with stuff to spill, or the user code,
1692 * requested a callback when it was OK to write
1693 */
Andy Green90c7cbc2011-01-27 06:26:52 +00001694
Andy Green3b84c002011-03-06 13:14:42 +00001695 if (pollfd->revents & POLLOUT)
Andy Green6ee372f2012-04-09 15:09:01 +08001696 if (lws_handle_POLLOUT_event(context, wsi,
1697 pollfd) < 0) {
1698 libwebsocket_close_and_free_session(
1699 context, wsi, LWS_CLOSE_STATUS_NORMAL);
Andy Green3b84c002011-03-06 13:14:42 +00001700 return 1;
1701 }
Andy Green90c7cbc2011-01-27 06:26:52 +00001702
Andy Greenb45993c2010-12-18 15:13:50 +00001703 /* any incoming data ready? */
1704
Andy Green0d338332011-02-12 11:57:43 +00001705 if (!(pollfd->revents & POLLIN))
1706 break;
Andy Greenb45993c2010-12-18 15:13:50 +00001707
Andy Green0d338332011-02-12 11:57:43 +00001708 /* get the issued broadcast payload from the socket */
Andy Greenb45993c2010-12-18 15:13:50 +00001709
Andy Green0d338332011-02-12 11:57:43 +00001710 len = read(pollfd->fd, buf + LWS_SEND_BUFFER_PRE_PADDING,
1711 MAX_BROADCAST_PAYLOAD);
1712 if (len < 0) {
1713 fprintf(stderr, "Error reading broadcast payload\n");
Andy Green4b6fbe12011-02-14 08:03:48 +00001714 break;
Andy Green0d338332011-02-12 11:57:43 +00001715 }
Andy Greenb45993c2010-12-18 15:13:50 +00001716
Andy Green0d338332011-02-12 11:57:43 +00001717 /* broadcast it to all guys with this protocol index */
Andy Green8f037e42010-12-19 22:13:26 +00001718
Andy Green0d338332011-02-12 11:57:43 +00001719 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
Andy Green8f037e42010-12-19 22:13:26 +00001720
Peter Hinz56885f32011-03-02 22:03:47 +00001721 for (m = 0; m < context->fd_hashtable[n].length; m++) {
Andy Greenb45993c2010-12-18 15:13:50 +00001722
Peter Hinz56885f32011-03-02 22:03:47 +00001723 new_wsi = context->fd_hashtable[n].wsi[m];
Andy Greenb45993c2010-12-18 15:13:50 +00001724
Andy Green0d338332011-02-12 11:57:43 +00001725 /* only to clients we are serving to */
Andy Greenb45993c2010-12-18 15:13:50 +00001726
Andy Green0d338332011-02-12 11:57:43 +00001727 if (new_wsi->mode != LWS_CONNMODE_WS_SERVING)
Andy Greenb45993c2010-12-18 15:13:50 +00001728 continue;
1729
1730 /*
1731 * never broadcast to non-established
1732 * connection
1733 */
1734
Andy Green0d338332011-02-12 11:57:43 +00001735 if (new_wsi->state != WSI_STATE_ESTABLISHED)
Andy Green4739e5c2011-01-22 12:51:57 +00001736 continue;
1737
Andy Greenb45993c2010-12-18 15:13:50 +00001738 /*
1739 * only broadcast to connections using
1740 * the requested protocol
1741 */
1742
Andy Green0d338332011-02-12 11:57:43 +00001743 if (new_wsi->protocol->protocol_index !=
1744 wsi->protocol_index_for_broadcast_proxy)
Andy Greenb45993c2010-12-18 15:13:50 +00001745 continue;
1746
Andy Green8f037e42010-12-19 22:13:26 +00001747 /* broadcast it to this connection */
1748
Peter Hinz56885f32011-03-02 22:03:47 +00001749 new_wsi->protocol->callback(context, new_wsi,
Andy Green8f037e42010-12-19 22:13:26 +00001750 LWS_CALLBACK_BROADCAST,
Andy Green0d338332011-02-12 11:57:43 +00001751 new_wsi->user_space,
Andy Green0ca6a172010-12-19 20:50:01 +00001752 buf + LWS_SEND_BUFFER_PRE_PADDING, len);
Andy Greenb45993c2010-12-18 15:13:50 +00001753 }
Andy Green0d338332011-02-12 11:57:43 +00001754 }
1755 break;
Andy Greenb45993c2010-12-18 15:13:50 +00001756
Andy Greenbe93fef2011-02-14 20:25:43 +00001757 case LWS_CONNMODE_WS_CLIENT_WAITING_PROXY_REPLY:
1758
1759 /* handle proxy hung up on us */
1760
1761 if (pollfd->revents & (POLLERR | POLLHUP)) {
1762
1763 fprintf(stderr, "Proxy connection %p (fd=%d) dead\n",
1764 (void *)wsi, pollfd->fd);
1765
Peter Hinz56885f32011-03-02 22:03:47 +00001766 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +00001767 LWS_CLOSE_STATUS_NOSTATUS);
Andy Greenbe93fef2011-02-14 20:25:43 +00001768 return 1;
1769 }
1770
Andy Green72c34322011-04-16 10:46:21 +01001771 n = recv(wsi->sock, pkt, sizeof pkt, 0);
Andy Greenbe93fef2011-02-14 20:25:43 +00001772 if (n < 0) {
Peter Hinz56885f32011-03-02 22:03:47 +00001773 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +00001774 LWS_CLOSE_STATUS_NOSTATUS);
Andy Greenbe93fef2011-02-14 20:25:43 +00001775 fprintf(stderr, "ERROR reading from proxy socket\n");
1776 return 1;
1777 }
1778
1779 pkt[13] = '\0';
1780 if (strcmp(pkt, "HTTP/1.0 200 ") != 0) {
Peter Hinz56885f32011-03-02 22:03:47 +00001781 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +00001782 LWS_CLOSE_STATUS_NOSTATUS);
Andy Greenbe93fef2011-02-14 20:25:43 +00001783 fprintf(stderr, "ERROR from proxy: %s\n", pkt);
1784 return 1;
1785 }
1786
1787 /* clear his proxy connection timeout */
1788
1789 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1790
1791 /* fallthru */
1792
1793 case LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE:
1794
1795 #ifdef LWS_OPENSSL_SUPPORT
1796 if (wsi->use_ssl) {
1797
Peter Hinz56885f32011-03-02 22:03:47 +00001798 wsi->ssl = SSL_new(context->ssl_client_ctx);
1799 wsi->client_bio = BIO_new_socket(wsi->sock,
1800 BIO_NOCLOSE);
Andy Greenbe93fef2011-02-14 20:25:43 +00001801 SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
1802
Andy Green6901cb32011-02-21 08:06:47 +00001803 SSL_set_ex_data(wsi->ssl,
Andy Green2e24da02011-03-05 16:12:04 +00001804 openssl_websocket_private_data_index,
Peter Hinz56885f32011-03-02 22:03:47 +00001805 context);
Andy Green6901cb32011-02-21 08:06:47 +00001806
Andy Greenbe93fef2011-02-14 20:25:43 +00001807 if (SSL_connect(wsi->ssl) <= 0) {
1808 fprintf(stderr, "SSL connect error %s\n",
Andy Green687b0182011-02-26 11:04:01 +00001809 ERR_error_string(ERR_get_error(),
1810 ssl_err_buf));
Andy Green6ee372f2012-04-09 15:09:01 +08001811 libwebsocket_close_and_free_session(context,
1812 wsi, LWS_CLOSE_STATUS_NOSTATUS);
Andy Greenbe93fef2011-02-14 20:25:43 +00001813 return 1;
1814 }
1815
1816 n = SSL_get_verify_result(wsi->ssl);
Andy Green2e24da02011-03-05 16:12:04 +00001817 if ((n != X509_V_OK) && (
Andy Green687b0182011-02-26 11:04:01 +00001818 n != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
1819 wsi->use_ssl != 2)) {
Andy Greenbe93fef2011-02-14 20:25:43 +00001820
Andy Green687b0182011-02-26 11:04:01 +00001821 fprintf(stderr, "server's cert didn't "
1822 "look good %d\n", n);
Peter Hinz56885f32011-03-02 22:03:47 +00001823 libwebsocket_close_and_free_session(context,
1824 wsi, LWS_CLOSE_STATUS_NOSTATUS);
Andy Green687b0182011-02-26 11:04:01 +00001825 return 1;
Andy Greenbe93fef2011-02-14 20:25:43 +00001826 }
1827 } else {
1828 wsi->ssl = NULL;
1829 #endif
1830
1831
1832 #ifdef LWS_OPENSSL_SUPPORT
1833 }
1834 #endif
1835
Andy Greena41314f2011-05-23 10:00:03 +01001836 p = libwebsockets_generate_client_handshake(context, wsi, p);
Andy Green6ee372f2012-04-09 15:09:01 +08001837 if (p == NULL)
Andy Greenbe93fef2011-02-14 20:25:43 +00001838 return 1;
Andy Greeneeaacb32011-03-01 20:44:24 +00001839
Andy Greenbe93fef2011-02-14 20:25:43 +00001840 /* send our request to the server */
1841
1842 #ifdef LWS_OPENSSL_SUPPORT
1843 if (wsi->use_ssl)
1844 n = SSL_write(wsi->ssl, pkt, p - pkt);
1845 else
1846 #endif
1847 n = send(wsi->sock, pkt, p - pkt, 0);
1848
1849 if (n < 0) {
1850 fprintf(stderr, "ERROR writing to client socket\n");
Peter Hinz56885f32011-03-02 22:03:47 +00001851 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +00001852 LWS_CLOSE_STATUS_NOSTATUS);
Andy Greenbe93fef2011-02-14 20:25:43 +00001853 return 1;
1854 }
1855
1856 wsi->parser_state = WSI_TOKEN_NAME_PART;
1857 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY;
1858 libwebsocket_set_timeout(wsi,
1859 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, 5);
1860
1861 break;
1862
1863 case LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY:
1864
1865 /* handle server hung up on us */
1866
1867 if (pollfd->revents & (POLLERR | POLLHUP)) {
1868
1869 fprintf(stderr, "Server connection %p (fd=%d) dead\n",
1870 (void *)wsi, pollfd->fd);
1871
1872 goto bail3;
1873 }
1874
1875
1876 /* interpret the server response */
1877
1878 /*
1879 * HTTP/1.1 101 Switching Protocols
1880 * Upgrade: websocket
1881 * Connection: Upgrade
1882 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
1883 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
1884 * Sec-WebSocket-Protocol: chat
1885 */
1886
Yonathan Yusim3ae39ff2012-04-09 06:42:39 +08001887 /*
1888 * we have to take some care here to only take from the
1889 * socket bytewise. The browser may (and has been seen to
1890 * in the case that onopen() performs websocket traffic)
1891 * coalesce both handshake response and websocket traffic
1892 * in one packet, since at that point the connection is
1893 * definitively ready from browser pov.
1894 */
Andy Greenbe93fef2011-02-14 20:25:43 +00001895
Andy Green7b5af9a2012-04-09 15:23:47 +08001896 len = 1;
Yonathan Yusim3ae39ff2012-04-09 06:42:39 +08001897 while (wsi->parser_state != WSI_PARSING_COMPLETE && len > 0) {
1898#ifdef LWS_OPENSSL_SUPPORT
1899 if (wsi->use_ssl)
1900 len = SSL_read(wsi->ssl, &c, 1);
1901 else
1902#endif
1903 len = recv(wsi->sock, &c, 1, 0);
1904
1905 libwebsocket_parse(wsi, c);
Andy Greenbe93fef2011-02-14 20:25:43 +00001906 }
1907
Andy Green27a0b912011-04-16 10:54:28 +01001908 /*
Andy Green6ee372f2012-04-09 15:09:01 +08001909 * hs may also be coming in multiple packets, there is a 5-sec
Andy Green27a0b912011-04-16 10:54:28 +01001910 * libwebsocket timeout still active here too, so if parsing did
1911 * not complete just wait for next packet coming in this state
1912 */
1913
1914 if (wsi->parser_state != WSI_PARSING_COMPLETE)
1915 break;
Andy Greenbe93fef2011-02-14 20:25:43 +00001916
Yonathan Yusim3ae39ff2012-04-09 06:42:39 +08001917 /*
1918 * otherwise deal with the handshake. If there's any
1919 * packet traffic already arrived we'll trigger poll() again
1920 * right away and deal with it that way
1921 */
1922
Andy Greena41314f2011-05-23 10:00:03 +01001923 return lws_client_interpret_server_handshake(context, wsi);
Andy Greenbe93fef2011-02-14 20:25:43 +00001924
1925bail3:
1926 if (wsi->c_protocol)
1927 free(wsi->c_protocol);
Peter Hinz56885f32011-03-02 22:03:47 +00001928 libwebsocket_close_and_free_session(context, wsi,
Andy Green6ee372f2012-04-09 15:09:01 +08001929 LWS_CLOSE_STATUS_NOSTATUS);
Andy Greenbe93fef2011-02-14 20:25:43 +00001930 return 1;
Andy Greena41314f2011-05-23 10:00:03 +01001931
1932 case LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT:
Andy Green6ee372f2012-04-09 15:09:01 +08001933 fprintf(stderr,
1934 "LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT\n");
Andy Greena41314f2011-05-23 10:00:03 +01001935 break;
1936
1937 case LWS_CONNMODE_WS_CLIENT_PENDING_CANDIDATE_CHILD:
Andy Green6ee372f2012-04-09 15:09:01 +08001938 fprintf(stderr,
1939 "LWS_CONNMODE_WS_CLIENT_PENDING_CANDIDATE_CHILD\n");
Andy Greena41314f2011-05-23 10:00:03 +01001940 break;
1941
Andy Greenbe93fef2011-02-14 20:25:43 +00001942
Andy Green0d338332011-02-12 11:57:43 +00001943 case LWS_CONNMODE_WS_SERVING:
1944 case LWS_CONNMODE_WS_CLIENT:
1945
1946 /* handle session socket closed */
1947
1948 if (pollfd->revents & (POLLERR | POLLHUP)) {
1949
Andy Green62c54d22011-02-14 09:14:25 +00001950 fprintf(stderr, "Session Socket %p (fd=%d) dead\n",
Andy Green0d338332011-02-12 11:57:43 +00001951 (void *)wsi, pollfd->fd);
1952
Peter Hinz56885f32011-03-02 22:03:47 +00001953 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +00001954 LWS_CLOSE_STATUS_NOSTATUS);
Andy Green4b6fbe12011-02-14 08:03:48 +00001955 return 1;
Andy Greenb45993c2010-12-18 15:13:50 +00001956 }
1957
Andy Green0d338332011-02-12 11:57:43 +00001958 /* the guy requested a callback when it was OK to write */
1959
Andy Greenda527df2011-03-07 07:08:12 +00001960 if ((pollfd->revents & POLLOUT) &&
1961 wsi->state == WSI_STATE_ESTABLISHED)
1962 if (lws_handle_POLLOUT_event(context, wsi,
1963 pollfd) < 0) {
1964 libwebsocket_close_and_free_session(
1965 context, wsi, LWS_CLOSE_STATUS_NORMAL);
Andy Green3b84c002011-03-06 13:14:42 +00001966 return 1;
1967 }
Andy Green0d338332011-02-12 11:57:43 +00001968
Andy Green0d338332011-02-12 11:57:43 +00001969
1970 /* any incoming data ready? */
1971
1972 if (!(pollfd->revents & POLLIN))
1973 break;
1974
Andy Greenb45993c2010-12-18 15:13:50 +00001975#ifdef LWS_OPENSSL_SUPPORT
Andy Green0d338332011-02-12 11:57:43 +00001976 if (wsi->ssl)
Andy Green98a717c2011-03-06 13:14:15 +00001977 eff_buf.token_len = SSL_read(wsi->ssl, buf, sizeof buf);
Andy Greenb45993c2010-12-18 15:13:50 +00001978 else
1979#endif
Andy Green98a717c2011-03-06 13:14:15 +00001980 eff_buf.token_len =
Andy Green72c34322011-04-16 10:46:21 +01001981 recv(pollfd->fd, buf, sizeof buf, 0);
Andy Greenb45993c2010-12-18 15:13:50 +00001982
Andy Green98a717c2011-03-06 13:14:15 +00001983 if (eff_buf.token_len < 0) {
1984 fprintf(stderr, "Socket read returned %d\n",
1985 eff_buf.token_len);
Nick Dowellc04c1932012-04-05 10:29:39 +08001986 if (errno != EINTR)
Andy Green6ee372f2012-04-09 15:09:01 +08001987 libwebsocket_close_and_free_session(context,
1988 wsi, LWS_CLOSE_STATUS_NOSTATUS);
Nick Dowellc04c1932012-04-05 10:29:39 +08001989 return 1;
Andy Greenb45993c2010-12-18 15:13:50 +00001990 }
Andy Green98a717c2011-03-06 13:14:15 +00001991 if (!eff_buf.token_len) {
Peter Hinz56885f32011-03-02 22:03:47 +00001992 libwebsocket_close_and_free_session(context, wsi,
Andy Green6ee372f2012-04-09 15:09:01 +08001993 LWS_CLOSE_STATUS_NOSTATUS);
Andy Green4b6fbe12011-02-14 08:03:48 +00001994 return 1;
Andy Greenb45993c2010-12-18 15:13:50 +00001995 }
1996
Andy Green98a717c2011-03-06 13:14:15 +00001997 /*
1998 * give any active extensions a chance to munge the buffer
1999 * before parse. We pass in a pointer to an lws_tokens struct
2000 * prepared with the default buffer and content length that's in
2001 * there. Rather than rewrite the default buffer, extensions
2002 * that expect to grow the buffer can adapt .token to
2003 * point to their own per-connection buffer in the extension
2004 * user allocation. By default with no extensions or no
2005 * extension callback handling, just the normal input buffer is
2006 * used then so it is efficient.
2007 */
Andy Greenb45993c2010-12-18 15:13:50 +00002008
Andy Green98a717c2011-03-06 13:14:15 +00002009 eff_buf.token = (char *)buf;
Andy Greenb45993c2010-12-18 15:13:50 +00002010
Andy Green98a717c2011-03-06 13:14:15 +00002011 more = 1;
2012 while (more) {
Andy Green0d338332011-02-12 11:57:43 +00002013
Andy Green98a717c2011-03-06 13:14:15 +00002014 more = 0;
2015
2016 for (n = 0; n < wsi->count_active_extensions; n++) {
Andy Green46c2ea02011-03-22 09:04:01 +00002017 m = wsi->active_extensions[n]->callback(context,
2018 wsi->active_extensions[n], wsi,
Andy Green98a717c2011-03-06 13:14:15 +00002019 LWS_EXT_CALLBACK_PACKET_RX_PREPARSE,
Andy Green46c2ea02011-03-22 09:04:01 +00002020 wsi->active_extensions_user[n],
2021 &eff_buf, 0);
Andy Green98a717c2011-03-06 13:14:15 +00002022 if (m < 0) {
Andy Green6ee372f2012-04-09 15:09:01 +08002023 fprintf(stderr,
2024 "Extension reports fatal error\n");
2025 libwebsocket_close_and_free_session(
2026 context, wsi,
2027 LWS_CLOSE_STATUS_NOSTATUS);
Andy Green98a717c2011-03-06 13:14:15 +00002028 return 1;
2029 }
2030 if (m)
2031 more = 1;
2032 }
2033
2034 /* service incoming data */
2035
2036 if (eff_buf.token_len) {
2037 n = libwebsocket_read(context, wsi,
Andy Green6ee372f2012-04-09 15:09:01 +08002038 (unsigned char *)eff_buf.token,
2039 eff_buf.token_len);
Andy Green98a717c2011-03-06 13:14:15 +00002040 if (n < 0)
2041 /* we closed wsi */
2042 return 1;
2043 }
2044
2045 eff_buf.token = NULL;
2046 eff_buf.token_len = 0;
2047 }
2048 break;
Andy Greenb45993c2010-12-18 15:13:50 +00002049 }
2050
2051 return 0;
2052}
2053
Andy Green0d338332011-02-12 11:57:43 +00002054
Andy Green6964bb52011-01-23 16:50:33 +00002055/**
2056 * libwebsocket_context_destroy() - Destroy the websocket context
Peter Hinz56885f32011-03-02 22:03:47 +00002057 * @context: Websocket context
Andy Green6964bb52011-01-23 16:50:33 +00002058 *
2059 * This function closes any active connections and then frees the
2060 * context. After calling this, any further use of the context is
2061 * undefined.
2062 */
2063void
Peter Hinz56885f32011-03-02 22:03:47 +00002064libwebsocket_context_destroy(struct libwebsocket_context *context)
Andy Green6964bb52011-01-23 16:50:33 +00002065{
Andy Green0d338332011-02-12 11:57:43 +00002066 int n;
2067 int m;
2068 struct libwebsocket *wsi;
Andy Greena41314f2011-05-23 10:00:03 +01002069 struct libwebsocket_extension *ext;
Andy Green6964bb52011-01-23 16:50:33 +00002070
Andy Green4b6fbe12011-02-14 08:03:48 +00002071 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
Peter Hinz56885f32011-03-02 22:03:47 +00002072 for (m = 0; m < context->fd_hashtable[n].length; m++) {
2073 wsi = context->fd_hashtable[n].wsi[m];
2074 libwebsocket_close_and_free_session(context, wsi,
Andy Green687b0182011-02-26 11:04:01 +00002075 LWS_CLOSE_STATUS_GOINGAWAY);
Andy Greenf3d3b402011-02-09 07:16:34 +00002076 }
Andy Green6964bb52011-01-23 16:50:33 +00002077
Andy Greena41314f2011-05-23 10:00:03 +01002078 /*
2079 * give all extensions a chance to clean up any per-context
2080 * allocations they might have made
2081 */
2082
2083 ext = context->extensions;
2084 m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_DESTRUCT;
2085 if (context->listen_port)
2086 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_DESTRUCT;
2087 while (ext->callback) {
2088 ext->callback(context, ext, NULL, m, NULL, NULL, 0);
2089 ext++;
2090 }
2091
Peter Hinz56885f32011-03-02 22:03:47 +00002092#ifdef WIN32
2093#else
2094 close(context->fd_random);
Andy Green6964bb52011-01-23 16:50:33 +00002095#endif
2096
Peter Hinz56885f32011-03-02 22:03:47 +00002097#ifdef LWS_OPENSSL_SUPPORT
2098 if (context->ssl_ctx)
2099 SSL_CTX_free(context->ssl_ctx);
2100 if (context->ssl_client_ctx)
2101 SSL_CTX_free(context->ssl_client_ctx);
2102#endif
2103
2104 free(context);
2105
2106#ifdef WIN32
2107 WSACleanup();
2108#endif
Andy Green6964bb52011-01-23 16:50:33 +00002109}
2110
2111/**
2112 * libwebsocket_service() - Service any pending websocket activity
Peter Hinz56885f32011-03-02 22:03:47 +00002113 * @context: Websocket context
Andy Green6964bb52011-01-23 16:50:33 +00002114 * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
2115 * service otherwise block and service immediately, returning
2116 * after the timeout if nothing needed service.
2117 *
2118 * This function deals with any pending websocket traffic, for three
2119 * kinds of event. It handles these events on both server and client
2120 * types of connection the same.
2121 *
2122 * 1) Accept new connections to our context's server
2123 *
2124 * 2) Perform pending broadcast writes initiated from other forked
2125 * processes (effectively serializing asynchronous broadcasts)
2126 *
2127 * 3) Call the receive callback for incoming frame data received by
2128 * server or client connections.
2129 *
2130 * You need to call this service function periodically to all the above
2131 * functions to happen; if your application is single-threaded you can
2132 * just call it in your main event loop.
2133 *
2134 * Alternatively you can fork a new process that asynchronously handles
2135 * calling this service in a loop. In that case you are happy if this
2136 * call blocks your thread until it needs to take care of something and
2137 * would call it with a large nonzero timeout. Your loop then takes no
2138 * CPU while there is nothing happening.
2139 *
2140 * If you are calling it in a single-threaded app, you don't want it to
2141 * wait around blocking other things in your loop from happening, so you
2142 * would call it with a timeout_ms of 0, so it returns immediately if
2143 * nothing is pending, or as soon as it services whatever was pending.
2144 */
2145
Andy Greenb45993c2010-12-18 15:13:50 +00002146
Andy Greene92cd172011-01-19 13:11:55 +00002147int
Peter Hinz56885f32011-03-02 22:03:47 +00002148libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
Andy Greene92cd172011-01-19 13:11:55 +00002149{
2150 int n;
Andy Greene92cd172011-01-19 13:11:55 +00002151
2152 /* stay dead once we are dead */
2153
Peter Hinz56885f32011-03-02 22:03:47 +00002154 if (context == NULL)
Andy Greene92cd172011-01-19 13:11:55 +00002155 return 1;
2156
Andy Green0d338332011-02-12 11:57:43 +00002157 /* wait for something to need service */
Andy Green4739e5c2011-01-22 12:51:57 +00002158
Peter Hinz56885f32011-03-02 22:03:47 +00002159 n = poll(context->fds, context->fds_count, timeout_ms);
Andy Green3221f922011-02-12 13:14:11 +00002160 if (n == 0) /* poll timeout */
2161 return 0;
Andy Greene92cd172011-01-19 13:11:55 +00002162
Andy Green62c54d22011-02-14 09:14:25 +00002163 if (n < 0) {
Andy Green5e1fa172011-02-10 09:07:05 +00002164 /*
Andy Greene92cd172011-01-19 13:11:55 +00002165 fprintf(stderr, "Listen Socket dead\n");
Andy Green5e1fa172011-02-10 09:07:05 +00002166 */
Andy Green0d338332011-02-12 11:57:43 +00002167 return 1;
Andy Greene92cd172011-01-19 13:11:55 +00002168 }
Andy Greene92cd172011-01-19 13:11:55 +00002169
2170 /* handle accept on listening socket? */
2171
Peter Hinz56885f32011-03-02 22:03:47 +00002172 for (n = 0; n < context->fds_count; n++)
2173 if (context->fds[n].revents)
2174 libwebsocket_service_fd(context, &context->fds[n]);
Andy Greene92cd172011-01-19 13:11:55 +00002175
2176 return 0;
Andy Greene92cd172011-01-19 13:11:55 +00002177}
2178
Andy Greena41314f2011-05-23 10:00:03 +01002179int
2180lws_any_extension_handled(struct libwebsocket_context *context,
Andy Green6ee372f2012-04-09 15:09:01 +08002181 struct libwebsocket *wsi,
2182 enum libwebsocket_extension_callback_reasons r,
Andy Greena41314f2011-05-23 10:00:03 +01002183 void *v, size_t len)
2184{
2185 int n;
2186 int handled = 0;
2187
2188 /* maybe an extension will take care of it for us */
2189
2190 for (n = 0; n < wsi->count_active_extensions && !handled; n++) {
2191 if (!wsi->active_extensions[n]->callback)
2192 continue;
2193
2194 handled |= wsi->active_extensions[n]->callback(context,
2195 wsi->active_extensions[n], wsi,
2196 r, wsi->active_extensions_user[n], v, len);
2197 }
2198
2199 return handled;
2200}
2201
2202
2203void *
2204lws_get_extension_user_matching_ext(struct libwebsocket *wsi,
Andy Green6ee372f2012-04-09 15:09:01 +08002205 struct libwebsocket_extension *ext)
Andy Greena41314f2011-05-23 10:00:03 +01002206{
2207 int n = 0;
2208
Andy Green68b45042011-05-25 21:41:57 +01002209 if (wsi == NULL)
2210 return NULL;
2211
Andy Greena41314f2011-05-23 10:00:03 +01002212 while (n < wsi->count_active_extensions) {
2213 if (wsi->active_extensions[n] != ext) {
2214 n++;
2215 continue;
2216 }
2217 return wsi->active_extensions_user[n];
2218 }
2219
2220 return NULL;
2221}
2222
Andy Green90c7cbc2011-01-27 06:26:52 +00002223/**
2224 * libwebsocket_callback_on_writable() - Request a callback when this socket
2225 * becomes able to be written to without
2226 * blocking
Andy Green32375b72011-02-19 08:32:53 +00002227 *
Peter Hinz56885f32011-03-02 22:03:47 +00002228 * @context: libwebsockets context
Andy Green90c7cbc2011-01-27 06:26:52 +00002229 * @wsi: Websocket connection instance to get callback for
2230 */
2231
2232int
Peter Hinz56885f32011-03-02 22:03:47 +00002233libwebsocket_callback_on_writable(struct libwebsocket_context *context,
Andy Green6ee372f2012-04-09 15:09:01 +08002234 struct libwebsocket *wsi)
Andy Green90c7cbc2011-01-27 06:26:52 +00002235{
Andy Green90c7cbc2011-01-27 06:26:52 +00002236 int n;
Andy Greena41314f2011-05-23 10:00:03 +01002237 int handled = 0;
2238
2239 /* maybe an extension will take care of it for us */
2240
2241 for (n = 0; n < wsi->count_active_extensions; n++) {
2242 if (!wsi->active_extensions[n]->callback)
2243 continue;
2244
2245 handled |= wsi->active_extensions[n]->callback(context,
2246 wsi->active_extensions[n], wsi,
2247 LWS_EXT_CALLBACK_REQUEST_ON_WRITEABLE,
2248 wsi->active_extensions_user[n], NULL, 0);
2249 }
2250
2251 if (handled)
2252 return 1;
Andy Green90c7cbc2011-01-27 06:26:52 +00002253
Peter Hinz56885f32011-03-02 22:03:47 +00002254 for (n = 0; n < context->fds_count; n++)
2255 if (context->fds[n].fd == wsi->sock) {
2256 context->fds[n].events |= POLLOUT;
Andy Greena41314f2011-05-23 10:00:03 +01002257 n = context->fds_count + 1;
Andy Green90c7cbc2011-01-27 06:26:52 +00002258 }
2259
Andy Greena41314f2011-05-23 10:00:03 +01002260 if (n == context->fds_count)
Andy Green6ee372f2012-04-09 15:09:01 +08002261 fprintf(stderr, "libwebsocket_callback_on_writable: "
2262 "failed to find socket %d\n", wsi->sock);
Andy Greena41314f2011-05-23 10:00:03 +01002263
Andy Green3221f922011-02-12 13:14:11 +00002264 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00002265 context->protocols[0].callback(context, wsi,
Andy Green3221f922011-02-12 13:14:11 +00002266 LWS_CALLBACK_SET_MODE_POLL_FD,
2267 (void *)(long)wsi->sock, NULL, POLLOUT);
2268
Andy Green90c7cbc2011-01-27 06:26:52 +00002269 return 1;
2270}
2271
2272/**
2273 * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
2274 * all connections using the given protocol when it
2275 * becomes possible to write to each socket without
2276 * blocking in turn.
2277 *
2278 * @protocol: Protocol whose connections will get callbacks
2279 */
2280
2281int
2282libwebsocket_callback_on_writable_all_protocol(
2283 const struct libwebsocket_protocols *protocol)
2284{
Peter Hinz56885f32011-03-02 22:03:47 +00002285 struct libwebsocket_context *context = protocol->owning_server;
Andy Green90c7cbc2011-01-27 06:26:52 +00002286 int n;
Andy Green0d338332011-02-12 11:57:43 +00002287 int m;
2288 struct libwebsocket *wsi;
Andy Green90c7cbc2011-01-27 06:26:52 +00002289
Andy Green0d338332011-02-12 11:57:43 +00002290 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
2291
Peter Hinz56885f32011-03-02 22:03:47 +00002292 for (m = 0; m < context->fd_hashtable[n].length; m++) {
Andy Green0d338332011-02-12 11:57:43 +00002293
Peter Hinz56885f32011-03-02 22:03:47 +00002294 wsi = context->fd_hashtable[n].wsi[m];
Andy Green0d338332011-02-12 11:57:43 +00002295
2296 if (wsi->protocol == protocol)
Peter Hinz56885f32011-03-02 22:03:47 +00002297 libwebsocket_callback_on_writable(context, wsi);
Andy Green0d338332011-02-12 11:57:43 +00002298 }
2299 }
Andy Green90c7cbc2011-01-27 06:26:52 +00002300
2301 return 0;
2302}
2303
Andy Greenbe93fef2011-02-14 20:25:43 +00002304/**
2305 * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
2306 *
2307 * You will not need this unless you are doing something special
2308 *
2309 * @wsi: Websocket connection instance
2310 * @reason: timeout reason
2311 * @secs: how many seconds
2312 */
2313
2314void
2315libwebsocket_set_timeout(struct libwebsocket *wsi,
2316 enum pending_timeout reason, int secs)
2317{
2318 struct timeval tv;
2319
2320 gettimeofday(&tv, NULL);
2321
2322 wsi->pending_timeout_limit = tv.tv_sec + secs;
2323 wsi->pending_timeout = reason;
2324}
2325
Andy Greena6cbece2011-01-27 20:06:03 +00002326
2327/**
2328 * libwebsocket_get_socket_fd() - returns the socket file descriptor
2329 *
2330 * You will not need this unless you are doing something special
2331 *
2332 * @wsi: Websocket connection instance
2333 */
2334
2335int
2336libwebsocket_get_socket_fd(struct libwebsocket *wsi)
2337{
2338 return wsi->sock;
2339}
2340
Andy Green90c7cbc2011-01-27 06:26:52 +00002341/**
2342 * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
2343 * receieved packets.
2344 *
2345 * If the output side of a server process becomes choked, this allows flow
2346 * control for the input side.
2347 *
2348 * @wsi: Websocket connection instance to get callback for
2349 * @enable: 0 = disable read servicing for this connection, 1 = enable
2350 */
2351
2352int
2353libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
2354{
Peter Hinz56885f32011-03-02 22:03:47 +00002355 struct libwebsocket_context *context = wsi->protocol->owning_server;
Andy Green90c7cbc2011-01-27 06:26:52 +00002356 int n;
2357
Peter Hinz56885f32011-03-02 22:03:47 +00002358 for (n = 0; n < context->fds_count; n++)
2359 if (context->fds[n].fd == wsi->sock) {
Andy Green90c7cbc2011-01-27 06:26:52 +00002360 if (enable)
Peter Hinz56885f32011-03-02 22:03:47 +00002361 context->fds[n].events |= POLLIN;
Andy Green90c7cbc2011-01-27 06:26:52 +00002362 else
Peter Hinz56885f32011-03-02 22:03:47 +00002363 context->fds[n].events &= ~POLLIN;
Andy Green90c7cbc2011-01-27 06:26:52 +00002364
2365 return 0;
2366 }
2367
Andy Green3221f922011-02-12 13:14:11 +00002368 if (enable)
2369 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00002370 context->protocols[0].callback(context, wsi,
Andy Green3221f922011-02-12 13:14:11 +00002371 LWS_CALLBACK_SET_MODE_POLL_FD,
2372 (void *)(long)wsi->sock, NULL, POLLIN);
2373 else
2374 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00002375 context->protocols[0].callback(context, wsi,
Andy Green3221f922011-02-12 13:14:11 +00002376 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
2377 (void *)(long)wsi->sock, NULL, POLLIN);
2378
Andy Greena41314f2011-05-23 10:00:03 +01002379#if 0
2380 fprintf(stderr, "libwebsocket_rx_flow_control "
Andy Green90c7cbc2011-01-27 06:26:52 +00002381 "unable to find socket\n");
Andy Greena41314f2011-05-23 10:00:03 +01002382#endif
Andy Green90c7cbc2011-01-27 06:26:52 +00002383 return 1;
2384}
2385
Andy Green2ac5a6f2011-01-28 10:00:18 +00002386/**
2387 * libwebsocket_canonical_hostname() - returns this host's hostname
2388 *
2389 * This is typically used by client code to fill in the host parameter
2390 * when making a client connection. You can only call it after the context
2391 * has been created.
2392 *
Peter Hinz56885f32011-03-02 22:03:47 +00002393 * @context: Websocket context
Andy Green2ac5a6f2011-01-28 10:00:18 +00002394 */
2395
2396
2397extern const char *
Peter Hinz56885f32011-03-02 22:03:47 +00002398libwebsocket_canonical_hostname(struct libwebsocket_context *context)
Andy Green2ac5a6f2011-01-28 10:00:18 +00002399{
Peter Hinz56885f32011-03-02 22:03:47 +00002400 return (const char *)context->canonical_hostname;
Andy Green2ac5a6f2011-01-28 10:00:18 +00002401}
2402
2403
Andy Green90c7cbc2011-01-27 06:26:52 +00002404static void sigpipe_handler(int x)
2405{
2406}
2407
Andy Green6901cb32011-02-21 08:06:47 +00002408#ifdef LWS_OPENSSL_SUPPORT
2409static int
2410OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
2411{
2412
2413 SSL *ssl;
2414 int n;
Andy Green2e24da02011-03-05 16:12:04 +00002415 struct libwebsocket_context *context;
Andy Green6901cb32011-02-21 08:06:47 +00002416
2417 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
2418 SSL_get_ex_data_X509_STORE_CTX_idx());
2419
2420 /*
Andy Green2e24da02011-03-05 16:12:04 +00002421 * !!! nasty openssl requires the index to come as a library-scope
2422 * static
Andy Green6901cb32011-02-21 08:06:47 +00002423 */
Andy Green2e24da02011-03-05 16:12:04 +00002424 context = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
Andy Green6ee372f2012-04-09 15:09:01 +08002425
Peter Hinz56885f32011-03-02 22:03:47 +00002426 n = context->protocols[0].callback(NULL, NULL,
Andy Green6901cb32011-02-21 08:06:47 +00002427 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
2428 x509_ctx, ssl, preverify_ok);
2429
2430 /* convert return code from 0 = OK to 1 = OK */
2431
2432 if (!n)
2433 n = 1;
2434 else
2435 n = 0;
2436
2437 return n;
2438}
2439#endif
2440
Andy Greenb45993c2010-12-18 15:13:50 +00002441
Andy Greenab990e42010-10-31 12:42:52 +00002442/**
Andy Green4739e5c2011-01-22 12:51:57 +00002443 * libwebsocket_create_context() - Create the websocket handler
2444 * @port: Port to listen on... you can use 0 to suppress listening on
Andy Green6964bb52011-01-23 16:50:33 +00002445 * any port, that's what you want if you are not running a
2446 * websocket server at all but just using it as a client
Peter Hinz56885f32011-03-02 22:03:47 +00002447 * @interf: NULL to bind the listen socket to all interfaces, or the
Andy Green32375b72011-02-19 08:32:53 +00002448 * interface name, eg, "eth2"
Andy Green4f3943a2010-11-12 10:44:16 +00002449 * @protocols: Array of structures listing supported protocols and a protocol-
Andy Green8f037e42010-12-19 22:13:26 +00002450 * specific callback for each one. The list is ended with an
2451 * entry that has a NULL callback pointer.
Andy Green6964bb52011-01-23 16:50:33 +00002452 * It's not const because we write the owning_server member
Andy Greenc5114822011-03-06 10:29:35 +00002453 * @extensions: NULL or array of libwebsocket_extension structs listing the
Andy Green6ee372f2012-04-09 15:09:01 +08002454 * extensions this context supports
Andy Green3faa9c72010-11-08 17:03:03 +00002455 * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want
Andy Green8f037e42010-12-19 22:13:26 +00002456 * to listen using SSL, set to the filepath to fetch the
2457 * server cert from, otherwise NULL for unencrypted
Andy Green3faa9c72010-11-08 17:03:03 +00002458 * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
Andy Green8f037e42010-12-19 22:13:26 +00002459 * else ignored
Andy Green3faa9c72010-11-08 17:03:03 +00002460 * @gid: group id to change to after setting listen socket, or -1.
2461 * @uid: user id to change to after setting listen socket, or -1.
Andy Greenbfb051f2011-02-09 08:49:14 +00002462 * @options: 0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
Andy Green05464c62010-11-12 10:44:18 +00002463 *
Andy Green8f037e42010-12-19 22:13:26 +00002464 * This function creates the listening socket and takes care
2465 * of all initialization in one step.
2466 *
Andy Greene92cd172011-01-19 13:11:55 +00002467 * After initialization, it returns a struct libwebsocket_context * that
2468 * represents this server. After calling, user code needs to take care
2469 * of calling libwebsocket_service() with the context pointer to get the
2470 * server's sockets serviced. This can be done in the same process context
2471 * or a forked process, or another thread,
Andy Green05464c62010-11-12 10:44:18 +00002472 *
Andy Green8f037e42010-12-19 22:13:26 +00002473 * The protocol callback functions are called for a handful of events
2474 * including http requests coming in, websocket connections becoming
2475 * established, and data arriving; it's also called periodically to allow
2476 * async transmission.
2477 *
2478 * HTTP requests are sent always to the FIRST protocol in @protocol, since
2479 * at that time websocket protocol has not been negotiated. Other
2480 * protocols after the first one never see any HTTP callack activity.
2481 *
2482 * The server created is a simple http server by default; part of the
2483 * websocket standard is upgrading this http connection to a websocket one.
2484 *
2485 * This allows the same server to provide files like scripts and favicon /
2486 * images or whatever over http and dynamic data over websockets all in
2487 * one place; they're all handled in the user callback.
Andy Greenab990e42010-10-31 12:42:52 +00002488 */
Andy Green4ea60062010-10-30 12:15:07 +01002489
Andy Greene92cd172011-01-19 13:11:55 +00002490struct libwebsocket_context *
Peter Hinz56885f32011-03-02 22:03:47 +00002491libwebsocket_create_context(int port, const char *interf,
Andy Greenb45993c2010-12-18 15:13:50 +00002492 struct libwebsocket_protocols *protocols,
Andy Greend6e09112011-03-05 16:12:15 +00002493 struct libwebsocket_extension *extensions,
Andy Green8f037e42010-12-19 22:13:26 +00002494 const char *ssl_cert_filepath,
2495 const char *ssl_private_key_filepath,
Andy Green8014b292011-01-30 20:57:25 +00002496 int gid, int uid, unsigned int options)
Andy Greenff95d7a2010-10-28 22:36:01 +01002497{
2498 int n;
Andy Greena41314f2011-05-23 10:00:03 +01002499 int m;
Andy Green4739e5c2011-01-22 12:51:57 +00002500 int sockfd = 0;
Andy Green251f6fa2010-11-03 11:13:06 +00002501 int fd;
Andy Greenff95d7a2010-10-28 22:36:01 +01002502 struct sockaddr_in serv_addr, cli_addr;
Andy Green251f6fa2010-11-03 11:13:06 +00002503 int opt = 1;
Peter Hinz56885f32011-03-02 22:03:47 +00002504 struct libwebsocket_context *context = NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00002505 unsigned int slen;
Andy Green9659f372011-01-27 22:01:43 +00002506 char *p;
Andy Green2ac5a6f2011-01-28 10:00:18 +00002507 char hostname[1024];
Andy Green42f69142011-01-30 08:10:02 +00002508 struct hostent *he;
Andy Green0d338332011-02-12 11:57:43 +00002509 struct libwebsocket *wsi;
Andy Greenff95d7a2010-10-28 22:36:01 +01002510
Andy Green3faa9c72010-11-08 17:03:03 +00002511#ifdef LWS_OPENSSL_SUPPORT
Andy Greenf2f54d52010-11-15 22:08:00 +00002512 SSL_METHOD *method;
Andy Green3faa9c72010-11-08 17:03:03 +00002513 char ssl_err_buf[512];
Andy Green3faa9c72010-11-08 17:03:03 +00002514#endif
2515
Peter Hinz56885f32011-03-02 22:03:47 +00002516#ifdef _WIN32
2517 {
2518 WORD wVersionRequested;
2519 WSADATA wsaData;
2520 int err;
Andy Green6ee372f2012-04-09 15:09:01 +08002521 HMODULE wsdll;
Peter Hinz56885f32011-03-02 22:03:47 +00002522
2523 /* Use the MAKEWORD(lowbyte, highbyte) macro from Windef.h */
2524 wVersionRequested = MAKEWORD(2, 2);
2525
2526 err = WSAStartup(wVersionRequested, &wsaData);
2527 if (err != 0) {
2528 /* Tell the user that we could not find a usable */
2529 /* Winsock DLL. */
2530 fprintf(stderr, "WSAStartup failed with error: %d\n",
2531 err);
2532 return NULL;
2533 }
David Galeano7b11fec2011-10-04 19:55:18 +08002534
Andy Green6ee372f2012-04-09 15:09:01 +08002535 /* default to a poll() made out of select() */
2536 poll = emulated_poll;
David Galeano7b11fec2011-10-04 19:55:18 +08002537
Andy Green6ee372f2012-04-09 15:09:01 +08002538 /* if windows socket lib available, use his WSAPoll */
2539 wsdll = GetModuleHandle("Ws2_32.dll");
2540 if (wsdll)
2541 poll = (PFNWSAPOLL)GetProcAddress(wsdll, "WSAPoll");
Peter Hinz56885f32011-03-02 22:03:47 +00002542 }
2543#endif
2544
2545
2546 context = malloc(sizeof(struct libwebsocket_context));
2547 if (!context) {
Andy Green90c7cbc2011-01-27 06:26:52 +00002548 fprintf(stderr, "No memory for websocket context\n");
2549 return NULL;
2550 }
Peter Hinz56885f32011-03-02 22:03:47 +00002551 context->protocols = protocols;
2552 context->listen_port = port;
2553 context->http_proxy_port = 0;
2554 context->http_proxy_address[0] = '\0';
2555 context->options = options;
2556 context->fds_count = 0;
Andy Greend6e09112011-03-05 16:12:15 +00002557 context->extensions = extensions;
Andy Green9659f372011-01-27 22:01:43 +00002558
Peter Hinz56885f32011-03-02 22:03:47 +00002559#ifdef WIN32
2560 context->fd_random = 0;
2561#else
2562 context->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
2563 if (context->fd_random < 0) {
Andy Green44eee682011-02-10 09:32:24 +00002564 fprintf(stderr, "Unable to open random device %s %d\n",
Peter Hinz56885f32011-03-02 22:03:47 +00002565 SYSTEM_RANDOM_FILEPATH, context->fd_random);
Andy Green44eee682011-02-10 09:32:24 +00002566 return NULL;
2567 }
Peter Hinz56885f32011-03-02 22:03:47 +00002568#endif
Andy Green44eee682011-02-10 09:32:24 +00002569
Peter Hinz56885f32011-03-02 22:03:47 +00002570#ifdef LWS_OPENSSL_SUPPORT
2571 context->use_ssl = 0;
2572 context->ssl_ctx = NULL;
2573 context->ssl_client_ctx = NULL;
Andy Green2e24da02011-03-05 16:12:04 +00002574 openssl_websocket_private_data_index = 0;
Peter Hinz56885f32011-03-02 22:03:47 +00002575#endif
Andy Green2ac5a6f2011-01-28 10:00:18 +00002576 /* find canonical hostname */
2577
2578 hostname[(sizeof hostname) - 1] = '\0';
2579 gethostname(hostname, (sizeof hostname) - 1);
2580 he = gethostbyname(hostname);
Darin Willitsc19456f2011-02-14 17:52:39 +00002581 if (he) {
Peter Hinz56885f32011-03-02 22:03:47 +00002582 strncpy(context->canonical_hostname, he->h_name,
2583 sizeof context->canonical_hostname - 1);
2584 context->canonical_hostname[
2585 sizeof context->canonical_hostname - 1] = '\0';
Darin Willitsc19456f2011-02-14 17:52:39 +00002586 } else
Peter Hinz56885f32011-03-02 22:03:47 +00002587 strncpy(context->canonical_hostname, hostname,
2588 sizeof context->canonical_hostname - 1);
Andy Green2ac5a6f2011-01-28 10:00:18 +00002589
Andy Green9659f372011-01-27 22:01:43 +00002590 /* split the proxy ads:port if given */
2591
2592 p = getenv("http_proxy");
2593 if (p) {
Peter Hinz56885f32011-03-02 22:03:47 +00002594 strncpy(context->http_proxy_address, p,
Andy Green6ee372f2012-04-09 15:09:01 +08002595 sizeof context->http_proxy_address - 1);
Peter Hinz56885f32011-03-02 22:03:47 +00002596 context->http_proxy_address[
2597 sizeof context->http_proxy_address - 1] = '\0';
Andy Green9659f372011-01-27 22:01:43 +00002598
Peter Hinz56885f32011-03-02 22:03:47 +00002599 p = strchr(context->http_proxy_address, ':');
Andy Green9659f372011-01-27 22:01:43 +00002600 if (p == NULL) {
2601 fprintf(stderr, "http_proxy needs to be ads:port\n");
2602 return NULL;
2603 }
2604 *p = '\0';
Peter Hinz56885f32011-03-02 22:03:47 +00002605 context->http_proxy_port = atoi(p + 1);
Andy Green9659f372011-01-27 22:01:43 +00002606
2607 fprintf(stderr, "Using proxy %s:%u\n",
Peter Hinz56885f32011-03-02 22:03:47 +00002608 context->http_proxy_address,
2609 context->http_proxy_port);
Andy Green9659f372011-01-27 22:01:43 +00002610 }
Andy Green90c7cbc2011-01-27 06:26:52 +00002611
2612 if (port) {
2613
Andy Green3faa9c72010-11-08 17:03:03 +00002614#ifdef LWS_OPENSSL_SUPPORT
Peter Hinz56885f32011-03-02 22:03:47 +00002615 context->use_ssl = ssl_cert_filepath != NULL &&
Andy Green90c7cbc2011-01-27 06:26:52 +00002616 ssl_private_key_filepath != NULL;
Peter Hinz56885f32011-03-02 22:03:47 +00002617 if (context->use_ssl)
Andy Green90c7cbc2011-01-27 06:26:52 +00002618 fprintf(stderr, " Compiled with SSL support, "
2619 "using it\n");
2620 else
2621 fprintf(stderr, " Compiled with SSL support, "
2622 "not using it\n");
Andy Green3faa9c72010-11-08 17:03:03 +00002623
Andy Green90c7cbc2011-01-27 06:26:52 +00002624#else
2625 if (ssl_cert_filepath != NULL &&
2626 ssl_private_key_filepath != NULL) {
2627 fprintf(stderr, " Not compiled for OpenSSl support!\n");
Andy Greene92cd172011-01-19 13:11:55 +00002628 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00002629 }
Andy Green90c7cbc2011-01-27 06:26:52 +00002630 fprintf(stderr, " Compiled without SSL support, "
2631 "serving unencrypted\n");
2632#endif
2633 }
2634
2635 /* ignore SIGPIPE */
Peter Hinz56885f32011-03-02 22:03:47 +00002636#ifdef WIN32
2637#else
Andy Green90c7cbc2011-01-27 06:26:52 +00002638 signal(SIGPIPE, sigpipe_handler);
Peter Hinz56885f32011-03-02 22:03:47 +00002639#endif
Andy Green90c7cbc2011-01-27 06:26:52 +00002640
2641
2642#ifdef LWS_OPENSSL_SUPPORT
2643
2644 /* basic openssl init */
2645
2646 SSL_library_init();
2647
2648 OpenSSL_add_all_algorithms();
2649 SSL_load_error_strings();
2650
Andy Green2e24da02011-03-05 16:12:04 +00002651 openssl_websocket_private_data_index =
Andy Green6901cb32011-02-21 08:06:47 +00002652 SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
2653
Andy Green90c7cbc2011-01-27 06:26:52 +00002654 /*
2655 * Firefox insists on SSLv23 not SSLv3
2656 * Konq disables SSLv2 by default now, SSLv23 works
2657 */
2658
2659 method = (SSL_METHOD *)SSLv23_server_method();
2660 if (!method) {
2661 fprintf(stderr, "problem creating ssl method: %s\n",
2662 ERR_error_string(ERR_get_error(), ssl_err_buf));
2663 return NULL;
2664 }
Peter Hinz56885f32011-03-02 22:03:47 +00002665 context->ssl_ctx = SSL_CTX_new(method); /* create context */
2666 if (!context->ssl_ctx) {
Andy Green90c7cbc2011-01-27 06:26:52 +00002667 fprintf(stderr, "problem creating ssl context: %s\n",
2668 ERR_error_string(ERR_get_error(), ssl_err_buf));
2669 return NULL;
2670 }
2671
2672 /* client context */
Andy Green6ee372f2012-04-09 15:09:01 +08002673
2674 if (port == CONTEXT_PORT_NO_LISTEN) {
Peter Hinz56885f32011-03-02 22:03:47 +00002675 method = (SSL_METHOD *)SSLv23_client_method();
2676 if (!method) {
2677 fprintf(stderr, "problem creating ssl method: %s\n",
2678 ERR_error_string(ERR_get_error(), ssl_err_buf));
2679 return NULL;
2680 }
2681 /* create context */
2682 context->ssl_client_ctx = SSL_CTX_new(method);
2683 if (!context->ssl_client_ctx) {
2684 fprintf(stderr, "problem creating ssl context: %s\n",
2685 ERR_error_string(ERR_get_error(), ssl_err_buf));
2686 return NULL;
2687 }
Andy Green90c7cbc2011-01-27 06:26:52 +00002688
Peter Hinz56885f32011-03-02 22:03:47 +00002689 /* openssl init for cert verification (for client sockets) */
Andy Green90c7cbc2011-01-27 06:26:52 +00002690
Peter Hinz56885f32011-03-02 22:03:47 +00002691 if (!SSL_CTX_load_verify_locations(
2692 context->ssl_client_ctx, NULL,
2693 LWS_OPENSSL_CLIENT_CERTS))
2694 fprintf(stderr,
2695 "Unable to load SSL Client certs from %s "
2696 "(set by --with-client-cert-dir= in configure) -- "
2697 " client ssl isn't going to work",
Andy Green90c7cbc2011-01-27 06:26:52 +00002698 LWS_OPENSSL_CLIENT_CERTS);
Peter Hinz56885f32011-03-02 22:03:47 +00002699
2700 /*
2701 * callback allowing user code to load extra verification certs
2702 * helping the client to verify server identity
2703 */
2704
2705 context->protocols[0].callback(context, NULL,
2706 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
2707 context->ssl_client_ctx, NULL, 0);
Andy Green90c7cbc2011-01-27 06:26:52 +00002708 }
Andy Green6ee372f2012-04-09 15:09:01 +08002709
Andy Greenc6bf2c22011-02-20 11:10:47 +00002710 /* as a server, are we requiring clients to identify themselves? */
2711
2712 if (options & LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
2713
2714 /* absolutely require the client cert */
Andy Green6ee372f2012-04-09 15:09:01 +08002715
Peter Hinz56885f32011-03-02 22:03:47 +00002716 SSL_CTX_set_verify(context->ssl_ctx,
Andy Green6901cb32011-02-21 08:06:47 +00002717 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2718 OpenSSL_verify_callback);
Andy Greenc6bf2c22011-02-20 11:10:47 +00002719
2720 /*
2721 * give user code a chance to load certs into the server
2722 * allowing it to verify incoming client certs
2723 */
2724
Peter Hinz56885f32011-03-02 22:03:47 +00002725 context->protocols[0].callback(context, NULL,
Andy Greenc6bf2c22011-02-20 11:10:47 +00002726 LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
Peter Hinz56885f32011-03-02 22:03:47 +00002727 context->ssl_ctx, NULL, 0);
Andy Greenc6bf2c22011-02-20 11:10:47 +00002728 }
2729
Peter Hinz56885f32011-03-02 22:03:47 +00002730 if (context->use_ssl) {
Andy Green90c7cbc2011-01-27 06:26:52 +00002731
2732 /* openssl init for server sockets */
2733
Andy Green3faa9c72010-11-08 17:03:03 +00002734 /* set the local certificate from CertFile */
Peter Hinz56885f32011-03-02 22:03:47 +00002735 n = SSL_CTX_use_certificate_file(context->ssl_ctx,
Andy Green3faa9c72010-11-08 17:03:03 +00002736 ssl_cert_filepath, SSL_FILETYPE_PEM);
2737 if (n != 1) {
2738 fprintf(stderr, "problem getting cert '%s': %s\n",
2739 ssl_cert_filepath,
2740 ERR_error_string(ERR_get_error(), ssl_err_buf));
Andy Greene92cd172011-01-19 13:11:55 +00002741 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00002742 }
2743 /* set the private key from KeyFile */
Peter Hinz56885f32011-03-02 22:03:47 +00002744 if (SSL_CTX_use_PrivateKey_file(context->ssl_ctx,
2745 ssl_private_key_filepath, SSL_FILETYPE_PEM) != 1) {
Andy Green018d8eb2010-11-08 21:04:23 +00002746 fprintf(stderr, "ssl problem getting key '%s': %s\n",
2747 ssl_private_key_filepath,
2748 ERR_error_string(ERR_get_error(), ssl_err_buf));
Andy Greene92cd172011-01-19 13:11:55 +00002749 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00002750 }
2751 /* verify private key */
Peter Hinz56885f32011-03-02 22:03:47 +00002752 if (!SSL_CTX_check_private_key(context->ssl_ctx)) {
Andy Green018d8eb2010-11-08 21:04:23 +00002753 fprintf(stderr, "Private SSL key doesn't match cert\n");
Andy Greene92cd172011-01-19 13:11:55 +00002754 return NULL;
Andy Green3faa9c72010-11-08 17:03:03 +00002755 }
2756
2757 /* SSL is happy and has a cert it's content with */
2758 }
2759#endif
Andy Greenb45993c2010-12-18 15:13:50 +00002760
Andy Greendf736162011-01-18 15:39:02 +00002761 /* selftest */
2762
2763 if (lws_b64_selftest())
Andy Greene92cd172011-01-19 13:11:55 +00002764 return NULL;
Andy Greendf736162011-01-18 15:39:02 +00002765
Andy Green0d338332011-02-12 11:57:43 +00002766 /* fd hashtable init */
2767
2768 for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
Peter Hinz56885f32011-03-02 22:03:47 +00002769 context->fd_hashtable[n].length = 0;
Andy Green0d338332011-02-12 11:57:43 +00002770
Andy Greenb45993c2010-12-18 15:13:50 +00002771 /* set up our external listening socket we serve on */
Andy Green8f037e42010-12-19 22:13:26 +00002772
Andy Green4739e5c2011-01-22 12:51:57 +00002773 if (port) {
Andy Green8f037e42010-12-19 22:13:26 +00002774
Andy Green4739e5c2011-01-22 12:51:57 +00002775 sockfd = socket(AF_INET, SOCK_STREAM, 0);
2776 if (sockfd < 0) {
2777 fprintf(stderr, "ERROR opening socket");
2778 return NULL;
2779 }
Andy Green775c0dd2010-10-29 14:15:22 +01002780
Andy Green4739e5c2011-01-22 12:51:57 +00002781 /* allow us to restart even if old sockets in TIME_WAIT */
Andy Green6ee372f2012-04-09 15:09:01 +08002782 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
2783 (const void *)&opt, sizeof(opt));
Andy Green6c939552011-03-08 08:56:57 +00002784
2785 /* Disable Nagle */
2786 opt = 1;
Andy Green6ee372f2012-04-09 15:09:01 +08002787 setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY,
2788 (const void *)&opt, sizeof(opt));
Andy Green6c939552011-03-08 08:56:57 +00002789
Andy Green4739e5c2011-01-22 12:51:57 +00002790 bzero((char *) &serv_addr, sizeof(serv_addr));
2791 serv_addr.sin_family = AF_INET;
Peter Hinz56885f32011-03-02 22:03:47 +00002792 if (interf == NULL)
Andy Green32375b72011-02-19 08:32:53 +00002793 serv_addr.sin_addr.s_addr = INADDR_ANY;
2794 else
Peter Hinz56885f32011-03-02 22:03:47 +00002795 interface_to_sa(interf, &serv_addr,
Andy Green32375b72011-02-19 08:32:53 +00002796 sizeof(serv_addr));
Andy Green4739e5c2011-01-22 12:51:57 +00002797 serv_addr.sin_port = htons(port);
2798
2799 n = bind(sockfd, (struct sockaddr *) &serv_addr,
2800 sizeof(serv_addr));
2801 if (n < 0) {
2802 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
Andy Green8f037e42010-12-19 22:13:26 +00002803 port, n, errno);
Andy Green4739e5c2011-01-22 12:51:57 +00002804 return NULL;
2805 }
Andy Green0d338332011-02-12 11:57:43 +00002806
2807 wsi = malloc(sizeof(struct libwebsocket));
Andy Green6ee372f2012-04-09 15:09:01 +08002808 memset(wsi, 0, sizeof(struct libwebsocket));
Andy Green0d338332011-02-12 11:57:43 +00002809 wsi->sock = sockfd;
Andy Greend6e09112011-03-05 16:12:15 +00002810 wsi->count_active_extensions = 0;
Andy Green0d338332011-02-12 11:57:43 +00002811 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
Peter Hinz56885f32011-03-02 22:03:47 +00002812 insert_wsi(context, wsi);
Andy Green0d338332011-02-12 11:57:43 +00002813
2814 listen(sockfd, 5);
2815 fprintf(stderr, " Listening on port %d\n", port);
2816
2817 /* list in the internal poll array */
Andy Green6ee372f2012-04-09 15:09:01 +08002818
Peter Hinz56885f32011-03-02 22:03:47 +00002819 context->fds[context->fds_count].fd = sockfd;
2820 context->fds[context->fds_count++].events = POLLIN;
Andy Green3221f922011-02-12 13:14:11 +00002821
2822 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00002823 context->protocols[0].callback(context, wsi,
Andy Green3221f922011-02-12 13:14:11 +00002824 LWS_CALLBACK_ADD_POLL_FD,
2825 (void *)(long)sockfd, NULL, POLLIN);
2826
Andy Green8f037e42010-12-19 22:13:26 +00002827 }
Andy Greenb45993c2010-12-18 15:13:50 +00002828
Andy Green6ee372f2012-04-09 15:09:01 +08002829 /*
2830 * drop any root privs for this process
2831 * to listen on port < 1023 we would have needed root, but now we are
2832 * listening, we don't want the power for anything else
2833 */
Peter Hinz56885f32011-03-02 22:03:47 +00002834#ifdef WIN32
2835#else
Andy Green3faa9c72010-11-08 17:03:03 +00002836 if (gid != -1)
2837 if (setgid(gid))
2838 fprintf(stderr, "setgid: %s\n", strerror(errno));
2839 if (uid != -1)
2840 if (setuid(uid))
2841 fprintf(stderr, "setuid: %s\n", strerror(errno));
Peter Hinz56885f32011-03-02 22:03:47 +00002842#endif
Andy Greenb45993c2010-12-18 15:13:50 +00002843
2844 /* set up our internal broadcast trigger sockets per-protocol */
2845
Peter Hinz56885f32011-03-02 22:03:47 +00002846 for (context->count_protocols = 0;
2847 protocols[context->count_protocols].callback;
2848 context->count_protocols++) {
Andy Green2d1301e2011-05-24 10:14:41 +01002849
Andy Green6ee372f2012-04-09 15:09:01 +08002850 fprintf(stderr, " Protocol: %s\n",
2851 protocols[context->count_protocols].name);
Andy Green2d1301e2011-05-24 10:14:41 +01002852
Peter Hinz56885f32011-03-02 22:03:47 +00002853 protocols[context->count_protocols].owning_server = context;
2854 protocols[context->count_protocols].protocol_index =
2855 context->count_protocols;
Andy Greenb45993c2010-12-18 15:13:50 +00002856
2857 fd = socket(AF_INET, SOCK_STREAM, 0);
2858 if (fd < 0) {
2859 fprintf(stderr, "ERROR opening socket");
Andy Greene92cd172011-01-19 13:11:55 +00002860 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00002861 }
Andy Green8f037e42010-12-19 22:13:26 +00002862
Andy Greenb45993c2010-12-18 15:13:50 +00002863 /* allow us to restart even if old sockets in TIME_WAIT */
Andy Green6ee372f2012-04-09 15:09:01 +08002864 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&opt,
2865 sizeof(opt));
Andy Greenb45993c2010-12-18 15:13:50 +00002866
2867 bzero((char *) &serv_addr, sizeof(serv_addr));
2868 serv_addr.sin_family = AF_INET;
2869 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2870 serv_addr.sin_port = 0; /* pick the port for us */
2871
2872 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
2873 if (n < 0) {
Andy Green8f037e42010-12-19 22:13:26 +00002874 fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
Andy Greenb45993c2010-12-18 15:13:50 +00002875 port, n, errno);
Andy Greene92cd172011-01-19 13:11:55 +00002876 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00002877 }
2878
2879 slen = sizeof cli_addr;
2880 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
2881 if (n < 0) {
2882 fprintf(stderr, "getsockname failed\n");
Andy Greene92cd172011-01-19 13:11:55 +00002883 return NULL;
Andy Greenb45993c2010-12-18 15:13:50 +00002884 }
Peter Hinz56885f32011-03-02 22:03:47 +00002885 protocols[context->count_protocols].broadcast_socket_port =
Andy Greenb45993c2010-12-18 15:13:50 +00002886 ntohs(cli_addr.sin_port);
2887 listen(fd, 5);
2888
2889 debug(" Protocol %s broadcast socket %d\n",
Peter Hinz56885f32011-03-02 22:03:47 +00002890 protocols[context->count_protocols].name,
Andy Greenb45993c2010-12-18 15:13:50 +00002891 ntohs(cli_addr.sin_port));
2892
Andy Green0d338332011-02-12 11:57:43 +00002893 /* dummy wsi per broadcast proxy socket */
2894
2895 wsi = malloc(sizeof(struct libwebsocket));
Andy Green6ee372f2012-04-09 15:09:01 +08002896 memset(wsi, 0, sizeof(struct libwebsocket));
Andy Green0d338332011-02-12 11:57:43 +00002897 wsi->sock = fd;
2898 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
Andy Greend6e09112011-03-05 16:12:15 +00002899 wsi->count_active_extensions = 0;
Andy Green0d338332011-02-12 11:57:43 +00002900 /* note which protocol we are proxying */
Peter Hinz56885f32011-03-02 22:03:47 +00002901 wsi->protocol_index_for_broadcast_proxy =
2902 context->count_protocols;
2903 insert_wsi(context, wsi);
Andy Green0d338332011-02-12 11:57:43 +00002904
2905 /* list in internal poll array */
2906
Peter Hinz56885f32011-03-02 22:03:47 +00002907 context->fds[context->fds_count].fd = fd;
2908 context->fds[context->fds_count].events = POLLIN;
2909 context->fds[context->fds_count].revents = 0;
2910 context->fds_count++;
Andy Green3221f922011-02-12 13:14:11 +00002911
2912 /* external POLL support via protocol 0 */
Peter Hinz56885f32011-03-02 22:03:47 +00002913 context->protocols[0].callback(context, wsi,
Andy Green3221f922011-02-12 13:14:11 +00002914 LWS_CALLBACK_ADD_POLL_FD,
2915 (void *)(long)fd, NULL, POLLIN);
Andy Greenb45993c2010-12-18 15:13:50 +00002916 }
2917
Andy Greena41314f2011-05-23 10:00:03 +01002918 /*
2919 * give all extensions a chance to create any per-context
2920 * allocations they need
2921 */
2922
2923 m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_CONSTRUCT;
2924 if (port)
2925 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_CONSTRUCT;
2926 while (extensions->callback) {
Andy Green2d1301e2011-05-24 10:14:41 +01002927 fprintf(stderr, " Extension: %s\n", extensions->name);
Andy Greena41314f2011-05-23 10:00:03 +01002928 extensions->callback(context, extensions,
2929 NULL, m, NULL, NULL, 0);
2930 extensions++;
2931 }
2932
Peter Hinz56885f32011-03-02 22:03:47 +00002933 return context;
Andy Greene92cd172011-01-19 13:11:55 +00002934}
Andy Greenb45993c2010-12-18 15:13:50 +00002935
Andy Green4739e5c2011-01-22 12:51:57 +00002936
Andy Greened11a022011-01-20 10:23:50 +00002937#ifndef LWS_NO_FORK
2938
Andy Greene92cd172011-01-19 13:11:55 +00002939/**
2940 * libwebsockets_fork_service_loop() - Optional helper function forks off
2941 * a process for the websocket server loop.
Andy Green6964bb52011-01-23 16:50:33 +00002942 * You don't have to use this but if not, you
2943 * have to make sure you are calling
2944 * libwebsocket_service periodically to service
2945 * the websocket traffic
Peter Hinz56885f32011-03-02 22:03:47 +00002946 * @context: server context returned by creation function
Andy Greene92cd172011-01-19 13:11:55 +00002947 */
Andy Greenb45993c2010-12-18 15:13:50 +00002948
Andy Greene92cd172011-01-19 13:11:55 +00002949int
Peter Hinz56885f32011-03-02 22:03:47 +00002950libwebsockets_fork_service_loop(struct libwebsocket_context *context)
Andy Greene92cd172011-01-19 13:11:55 +00002951{
Andy Greene92cd172011-01-19 13:11:55 +00002952 int fd;
2953 struct sockaddr_in cli_addr;
2954 int n;
Andy Green3221f922011-02-12 13:14:11 +00002955 int p;
Andy Greenb45993c2010-12-18 15:13:50 +00002956
Andy Greened11a022011-01-20 10:23:50 +00002957 n = fork();
2958 if (n < 0)
2959 return n;
2960
2961 if (!n) {
2962
2963 /* main process context */
2964
Andy Green3221f922011-02-12 13:14:11 +00002965 /*
2966 * set up the proxy sockets to allow broadcast from
2967 * service process context
2968 */
2969
Peter Hinz56885f32011-03-02 22:03:47 +00002970 for (p = 0; p < context->count_protocols; p++) {
Andy Greened11a022011-01-20 10:23:50 +00002971 fd = socket(AF_INET, SOCK_STREAM, 0);
2972 if (fd < 0) {
2973 fprintf(stderr, "Unable to create socket\n");
2974 return -1;
2975 }
2976 cli_addr.sin_family = AF_INET;
2977 cli_addr.sin_port = htons(
Peter Hinz56885f32011-03-02 22:03:47 +00002978 context->protocols[p].broadcast_socket_port);
Andy Greened11a022011-01-20 10:23:50 +00002979 cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2980 n = connect(fd, (struct sockaddr *)&cli_addr,
2981 sizeof cli_addr);
2982 if (n < 0) {
2983 fprintf(stderr, "Unable to connect to "
2984 "broadcast socket %d, %s\n",
Andy Green3221f922011-02-12 13:14:11 +00002985 n, strerror(errno));
Andy Greened11a022011-01-20 10:23:50 +00002986 return -1;
2987 }
2988
Peter Hinz56885f32011-03-02 22:03:47 +00002989 context->protocols[p].broadcast_socket_user_fd = fd;
Andy Greened11a022011-01-20 10:23:50 +00002990 }
2991
Andy Greene92cd172011-01-19 13:11:55 +00002992 return 0;
Andy Greenb45993c2010-12-18 15:13:50 +00002993 }
2994
2995 /* we want a SIGHUP when our parent goes down */
2996 prctl(PR_SET_PDEATHSIG, SIGHUP);
2997
2998 /* in this forked process, sit and service websocket connections */
Andy Green8f037e42010-12-19 22:13:26 +00002999
Andy Greene92cd172011-01-19 13:11:55 +00003000 while (1)
Peter Hinz56885f32011-03-02 22:03:47 +00003001 if (libwebsocket_service(context, 1000))
Andy Greene92cd172011-01-19 13:11:55 +00003002 return -1;
Andy Green8f037e42010-12-19 22:13:26 +00003003
Andy Green251f6fa2010-11-03 11:13:06 +00003004 return 0;
Andy Greenff95d7a2010-10-28 22:36:01 +01003005}
3006
Andy Greened11a022011-01-20 10:23:50 +00003007#endif
3008
Andy Greenb45993c2010-12-18 15:13:50 +00003009/**
3010 * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
Andy Green8f037e42010-12-19 22:13:26 +00003011 * connection.
Andy Greenb45993c2010-12-18 15:13:50 +00003012 * @wsi: pointer to struct websocket you want to know the protocol of
3013 *
Andy Green8f037e42010-12-19 22:13:26 +00003014 *
3015 * This is useful to get the protocol to broadcast back to from inside
Andy Greenb45993c2010-12-18 15:13:50 +00003016 * the callback.
3017 */
Andy Greenab990e42010-10-31 12:42:52 +00003018
Andy Greenb45993c2010-12-18 15:13:50 +00003019const struct libwebsocket_protocols *
3020libwebsockets_get_protocol(struct libwebsocket *wsi)
3021{
3022 return wsi->protocol;
3023}
3024
3025/**
Andy Greene92cd172011-01-19 13:11:55 +00003026 * libwebsockets_broadcast() - Sends a buffer to the callback for all active
Andy Green8f037e42010-12-19 22:13:26 +00003027 * connections of the given protocol.
Andy Greenb45993c2010-12-18 15:13:50 +00003028 * @protocol: pointer to the protocol you will broadcast to all members of
3029 * @buf: buffer containing the data to be broadcase. NOTE: this has to be
Andy Green8f037e42010-12-19 22:13:26 +00003030 * allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
3031 * the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
3032 * case you are calling this function from callback context.
Andy Greenb45993c2010-12-18 15:13:50 +00003033 * @len: length of payload data in buf, starting from buf.
Andy Green8f037e42010-12-19 22:13:26 +00003034 *
3035 * This function allows bulk sending of a packet to every connection using
Andy Greenb45993c2010-12-18 15:13:50 +00003036 * the given protocol. It does not send the data directly; instead it calls
3037 * the callback with a reason type of LWS_CALLBACK_BROADCAST. If the callback
3038 * wants to actually send the data for that connection, the callback itself
3039 * should call libwebsocket_write().
3040 *
3041 * libwebsockets_broadcast() can be called from another fork context without
3042 * having to take any care about data visibility between the processes, it'll
3043 * "just work".
3044 */
3045
3046
3047int
Andy Green8f037e42010-12-19 22:13:26 +00003048libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
Andy Greenb45993c2010-12-18 15:13:50 +00003049 unsigned char *buf, size_t len)
3050{
Peter Hinz56885f32011-03-02 22:03:47 +00003051 struct libwebsocket_context *context = protocol->owning_server;
Andy Greenb45993c2010-12-18 15:13:50 +00003052 int n;
Andy Green0d338332011-02-12 11:57:43 +00003053 int m;
Andy Green6ee372f2012-04-09 15:09:01 +08003054 struct libwebsocket *wsi;
Andy Greenb45993c2010-12-18 15:13:50 +00003055
3056 if (!protocol->broadcast_socket_user_fd) {
3057 /*
Andy Greene92cd172011-01-19 13:11:55 +00003058 * We are either running unforked / flat, or we are being
3059 * called from poll thread context
Andy Greenb45993c2010-12-18 15:13:50 +00003060 * eg, from a callback. In that case don't use sockets for
3061 * broadcast IPC (since we can't open a socket connection to
3062 * a socket listening on our own thread) but directly do the
3063 * send action.
3064 *
3065 * Locking is not needed because we are by definition being
3066 * called in the poll thread context and are serialized.
3067 */
3068
Andy Green0d338332011-02-12 11:57:43 +00003069 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
Andy Greenb45993c2010-12-18 15:13:50 +00003070
Peter Hinz56885f32011-03-02 22:03:47 +00003071 for (m = 0; m < context->fd_hashtable[n].length; m++) {
Andy Greenb45993c2010-12-18 15:13:50 +00003072
Peter Hinz56885f32011-03-02 22:03:47 +00003073 wsi = context->fd_hashtable[n].wsi[m];
Andy Greenb45993c2010-12-18 15:13:50 +00003074
Andy Green0d338332011-02-12 11:57:43 +00003075 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
3076 continue;
Andy Greenb45993c2010-12-18 15:13:50 +00003077
Andy Green0d338332011-02-12 11:57:43 +00003078 /*
3079 * never broadcast to
3080 * non-established connections
3081 */
3082 if (wsi->state != WSI_STATE_ESTABLISHED)
3083 continue;
3084
3085 /* only broadcast to guys using
3086 * requested protocol
3087 */
3088 if (wsi->protocol != protocol)
3089 continue;
3090
Peter Hinz56885f32011-03-02 22:03:47 +00003091 wsi->protocol->callback(context, wsi,
Andy Green8f037e42010-12-19 22:13:26 +00003092 LWS_CALLBACK_BROADCAST,
Andy Green0d338332011-02-12 11:57:43 +00003093 wsi->user_space,
Andy Greenb45993c2010-12-18 15:13:50 +00003094 buf, len);
Andy Green0d338332011-02-12 11:57:43 +00003095 }
Andy Greenb45993c2010-12-18 15:13:50 +00003096 }
3097
3098 return 0;
3099 }
3100
Andy Green0ca6a172010-12-19 20:50:01 +00003101 /*
3102 * We're being called from a different process context than the server
3103 * loop. Instead of broadcasting directly, we send our
3104 * payload on a socket to do the IPC; the server process will serialize
3105 * the broadcast action in its main poll() loop.
3106 *
3107 * There's one broadcast socket listening for each protocol supported
3108 * set up when the websocket server initializes
3109 */
3110
Andy Green6964bb52011-01-23 16:50:33 +00003111 n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);
Andy Greenb45993c2010-12-18 15:13:50 +00003112
3113 return n;
3114}
Andy Green82c3d542011-03-07 21:16:31 +00003115
3116int
3117libwebsocket_is_final_fragment(struct libwebsocket *wsi)
3118{
3119 return wsi->final;
3120}
Alex Bligh49146db2011-11-07 17:19:25 +08003121
3122void *
3123libwebsocket_ensure_user_space(struct libwebsocket *wsi)
3124{
3125 /* allocate the per-connection user memory (if any) */
3126
3127 if (wsi->protocol->per_session_data_size && !wsi->user_space) {
3128 wsi->user_space = malloc(
3129 wsi->protocol->per_session_data_size);
3130 if (wsi->user_space == NULL) {
3131 fprintf(stderr, "Out of memory for "
3132 "conn user space\n");
3133 return NULL;
3134 }
Andy Green6ee372f2012-04-09 15:09:01 +08003135 memset(wsi->user_space, 0,
3136 wsi->protocol->per_session_data_size);
Alex Bligh49146db2011-11-07 17:19:25 +08003137 }
3138 return wsi->user_space;
3139}