Print error string on accept failure.
[profile/ivi/libwebsockets.git] / lib / libwebsockets.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * 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
20  */
21
22 #include "private-libwebsockets.h"
23
24 #ifdef WIN32
25 #include <tchar.h>
26 #include <io.h>
27 #else
28 #include <ifaddrs.h>
29 #include <sys/un.h>
30 #include <sys/socket.h>
31 #include <netdb.h>
32 #endif
33
34 #ifdef LWS_OPENSSL_SUPPORT
35 int openssl_websocket_private_data_index;
36 #endif
37
38 #ifdef __MINGW32__
39 #include "../win32port/win32helpers/websock-w32.c"
40 #else
41 #ifdef __MINGW64__
42 #include "../win32port/win32helpers/websock-w32.c"
43 #endif
44 #endif
45
46 /*
47  * In-place str to lower case
48  */
49
50 static void
51 strtolower(char *s)
52 {
53         while (*s) {
54                 *s = tolower(*s);
55                 s++;
56         }
57 }
58
59 /* file descriptor hash management */
60
61 struct libwebsocket *
62 wsi_from_fd(struct libwebsocket_context *context, int fd)
63 {
64         int h = LWS_FD_HASH(fd);
65         int n = 0;
66
67         for (n = 0; n < context->fd_hashtable[h].length; n++)
68                 if (context->fd_hashtable[h].wsi[n]->sock == fd)
69                         return context->fd_hashtable[h].wsi[n];
70
71         return NULL;
72 }
73
74 int
75 insert_wsi(struct libwebsocket_context *context, struct libwebsocket *wsi)
76 {
77         int h = LWS_FD_HASH(wsi->sock);
78
79         if (context->fd_hashtable[h].length == MAX_CLIENTS - 1) {
80                 fprintf(stderr, "hash table overflow\n");
81                 return 1;
82         }
83
84         context->fd_hashtable[h].wsi[context->fd_hashtable[h].length++] = wsi;
85
86         return 0;
87 }
88
89 int
90 delete_from_fd(struct libwebsocket_context *context, int fd)
91 {
92         int h = LWS_FD_HASH(fd);
93         int n = 0;
94
95         for (n = 0; n < context->fd_hashtable[h].length; n++)
96                 if (context->fd_hashtable[h].wsi[n]->sock == fd) {
97                         while (n < context->fd_hashtable[h].length) {
98                                 context->fd_hashtable[h].wsi[n] =
99                                             context->fd_hashtable[h].wsi[n + 1];
100                                 n++;
101                         }
102                         context->fd_hashtable[h].length--;
103
104                         return 0;
105                 }
106
107         fprintf(stderr, "Failed to find fd %d requested for "
108                                                    "delete in hashtable\n", fd);
109         return 1;
110 }
111
112 #ifdef LWS_OPENSSL_SUPPORT
113 static void
114 libwebsockets_decode_ssl_error(void)
115 {
116         char buf[256];
117         u_long err;
118
119         while ((err = ERR_get_error()) != 0) {
120                 ERR_error_string_n(err, buf, sizeof(buf));
121                 fprintf(stderr, "*** %s\n", buf);
122         }
123 }
124 #endif
125
126
127 static int
128 interface_to_sa(const char *ifname, struct sockaddr_in *addr, size_t addrlen)
129 {
130         int rc = -1;
131 #ifdef WIN32
132         /* TODO */
133 #else
134         struct ifaddrs *ifr;
135         struct ifaddrs *ifc;
136         struct sockaddr_in *sin;
137
138         getifaddrs(&ifr);
139         for (ifc = ifr; ifc != NULL; ifc = ifc->ifa_next) {
140                 if (strcmp(ifc->ifa_name, ifname))
141                         continue;
142                 if (ifc->ifa_addr == NULL)
143                         continue;
144                 sin = (struct sockaddr_in *)ifc->ifa_addr;
145                 if (sin->sin_family != AF_INET)
146                         continue;
147                 memcpy(addr, sin, addrlen);
148                 rc = 0;
149         }
150
151         freeifaddrs(ifr);
152 #endif
153         return rc;
154 }
155
156 void
157 libwebsocket_close_and_free_session(struct libwebsocket_context *context,
158                          struct libwebsocket *wsi, enum lws_close_status reason)
159 {
160         int n;
161         int old_state;
162         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
163                                                   LWS_SEND_BUFFER_POST_PADDING];
164         int ret;
165         int m;
166         struct lws_tokens eff_buf;
167         struct libwebsocket_extension *ext;
168
169         if (!wsi)
170                 return;
171
172         old_state = wsi->state;
173
174         if (old_state == WSI_STATE_DEAD_SOCKET)
175                 return;
176
177         wsi->close_reason = reason;
178
179         /*
180          * are his extensions okay with him closing?  Eg he might be a mux
181          * parent and just his ch1 aspect is closing?
182          */
183
184
185         for (n = 0; n < wsi->count_active_extensions; n++) {
186                 if (!wsi->active_extensions[n]->callback)
187                         continue;
188
189                 m = wsi->active_extensions[n]->callback(context,
190                         wsi->active_extensions[n], wsi,
191                         LWS_EXT_CALLBACK_CHECK_OK_TO_REALLY_CLOSE,
192                                        wsi->active_extensions_user[n], NULL, 0);
193
194                 /*
195                  * if somebody vetoed actually closing him at this time....
196                  * up to the extension to track the attempted close, let's
197                  * just bail
198                  */
199
200                 if (m) {
201                         debug("extension vetoed close\n");
202                         return;
203                 }
204         }
205
206
207
208         /*
209          * flush any tx pending from extensions, since we may send close packet
210          * if there are problems with send, just nuke the connection
211          */
212
213         ret = 1;
214         while (ret == 1) {
215
216                 /* default to nobody has more to spill */
217
218                 ret = 0;
219                 eff_buf.token = NULL;
220                 eff_buf.token_len = 0;
221
222                 /* show every extension the new incoming data */
223
224                 for (n = 0; n < wsi->count_active_extensions; n++) {
225                         m = wsi->active_extensions[n]->callback(
226                                         wsi->protocol->owning_server,
227                                         wsi->active_extensions[n], wsi,
228                                         LWS_EXT_CALLBACK_FLUSH_PENDING_TX,
229                                    wsi->active_extensions_user[n], &eff_buf, 0);
230                         if (m < 0) {
231                                 fprintf(stderr, "Extension reports "
232                                                                "fatal error\n");
233                                 goto just_kill_connection;
234                         }
235                         if (m)
236                                 /*
237                                  * at least one extension told us he has more
238                                  * to spill, so we will go around again after
239                                  */
240                                 ret = 1;
241                 }
242
243                 /* assuming they left us something to send, send it */
244
245                 if (eff_buf.token_len)
246                         if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
247                                                              eff_buf.token_len))
248                                 goto just_kill_connection;
249         }
250
251         /*
252          * signal we are closing, libsocket_write will
253          * add any necessary version-specific stuff.  If the write fails,
254          * no worries we are closing anyway.  If we didn't initiate this
255          * close, then our state has been changed to
256          * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this.
257          *
258          * Likewise if it's a second call to close this connection after we
259          * sent the close indication to the peer already, we are in state
260          * WSI_STATE_AWAITING_CLOSE_ACK and will skip doing this a second time.
261          */
262
263         if (old_state == WSI_STATE_ESTABLISHED &&
264                                           reason != LWS_CLOSE_STATUS_NOSTATUS) {
265
266                 debug("sending close indication...\n");
267
268                 n = libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING],
269                                                             0, LWS_WRITE_CLOSE);
270                 if (!n) {
271                         /*
272                          * we have sent a nice protocol level indication we
273                          * now wish to close, we should not send anything more
274                          */
275
276                         wsi->state = WSI_STATE_AWAITING_CLOSE_ACK;
277
278                         /* and we should wait for a reply for a bit */
279
280                         libwebsocket_set_timeout(wsi,
281                                                   PENDING_TIMEOUT_CLOSE_ACK, AWAITING_TIMEOUT);
282
283                         debug("sent close indication, awaiting ack\n");
284
285                         return;
286                 }
287
288                 /* else, the send failed and we should just hang up */
289         }
290
291 just_kill_connection:
292
293         debug("libwebsocket_close_and_free_session: just_kill_connection\n");
294
295         /*
296          * we won't be servicing or receiving anything further from this guy
297          * remove this fd from wsi mapping hashtable
298          */
299
300         if (wsi->sock)
301                 delete_from_fd(context, wsi->sock);
302
303         /* delete it from the internal poll list if still present */
304
305         for (n = 0; n < context->fds_count; n++) {
306                 if (context->fds[n].fd != wsi->sock)
307                         continue;
308                 while (n < context->fds_count - 1) {
309                         context->fds[n] = context->fds[n + 1];
310                         n++;
311                 }
312                 context->fds_count--;
313                 /* we only have to deal with one */
314                 n = context->fds_count;
315         }
316
317         /* remove also from external POLL support via protocol 0 */
318         if (wsi->sock)
319                 context->protocols[0].callback(context, wsi,
320                     LWS_CALLBACK_DEL_POLL_FD, (void *)(long)wsi->sock, NULL, 0);
321
322         wsi->state = WSI_STATE_DEAD_SOCKET;
323
324         /* tell the user it's all over for this guy */
325
326         if (wsi->protocol && wsi->protocol->callback &&
327                         ((old_state == WSI_STATE_ESTABLISHED) ||
328                          (old_state == WSI_STATE_RETURNED_CLOSE_ALREADY) ||
329                          (old_state == WSI_STATE_AWAITING_CLOSE_ACK))) {
330                 debug("calling back CLOSED\n");
331                 wsi->protocol->callback(context, wsi, LWS_CALLBACK_CLOSED,
332                                                       wsi->user_space, NULL, 0);
333         } else
334                 debug("not calling back closed, old_state=%d\n", old_state);
335
336         /* deallocate any active extension contexts */
337
338         for (n = 0; n < wsi->count_active_extensions; n++) {
339                 if (!wsi->active_extensions[n]->callback)
340                         continue;
341
342                 wsi->active_extensions[n]->callback(context,
343                         wsi->active_extensions[n], wsi,
344                                 LWS_EXT_CALLBACK_DESTROY,
345                                        wsi->active_extensions_user[n], NULL, 0);
346
347                 free(wsi->active_extensions_user[n]);
348         }
349
350         /*
351          * inform all extensions in case they tracked this guy out of band
352          * even though not active on him specifically
353          */
354
355         ext = context->extensions;
356         while (ext && ext->callback) {
357                 ext->callback(context, ext, wsi,
358                                 LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING,
359                                        NULL, NULL, 0);
360                 ext++;
361         }
362
363         /* free up his parsing allocations */
364
365         for (n = 0; n < WSI_TOKEN_COUNT; n++)
366                 if (wsi->utf8_token[n].token)
367                         free(wsi->utf8_token[n].token);
368
369         if (wsi->c_address)
370                 free(wsi->c_address);
371
372 /*      fprintf(stderr, "closing fd=%d\n", wsi->sock); */
373
374 #ifdef LWS_OPENSSL_SUPPORT
375         if (wsi->ssl) {
376                 n = SSL_get_fd(wsi->ssl);
377                 SSL_shutdown(wsi->ssl);
378 #ifdef WIN32
379                 closesocket(n);
380 #else
381                 close(n);
382 #endif
383                 SSL_free(wsi->ssl);
384         } else {
385 #endif
386                 shutdown(wsi->sock, SHUT_RDWR);
387 #ifdef WIN32
388                 if (wsi->sock)
389                         closesocket(wsi->sock);
390 #else
391                 if (wsi->sock)
392                         close(wsi->sock);
393 #endif
394 #ifdef LWS_OPENSSL_SUPPORT
395         }
396 #endif
397         if (wsi->protocol && wsi->protocol->per_session_data_size && wsi->user_space) /* user code may own */
398                 free(wsi->user_space);
399
400         free(wsi);
401 }
402
403 /**
404  * libwebsockets_hangup_on_client() - Server calls to terminate client
405  *                                      connection
406  * @context:    libwebsockets context
407  * @fd:         Connection socket descriptor
408  */
409
410 void
411 libwebsockets_hangup_on_client(struct libwebsocket_context *context, int fd)
412 {
413         struct libwebsocket *wsi = wsi_from_fd(context, fd);
414
415         if (wsi == NULL)
416                 return;
417
418         libwebsocket_close_and_free_session(context, wsi,
419                                                      LWS_CLOSE_STATUS_NOSTATUS);
420 }
421
422
423 /**
424  * libwebsockets_get_peer_addresses() - Get client address information
425  * @fd:         Connection socket descriptor
426  * @name:       Buffer to take client address name
427  * @name_len:   Length of client address name buffer
428  * @rip:        Buffer to take client address IP qotted quad
429  * @rip_len:    Length of client address IP buffer
430  *
431  *      This function fills in @name and @rip with the name and IP of
432  *      the client connected with socket descriptor @fd.  Names may be
433  *      truncated if there is not enough room.  If either cannot be
434  *      determined, they will be returned as valid zero-length strings.
435  */
436
437 void
438 libwebsockets_get_peer_addresses(int fd, char *name, int name_len,
439                                         char *rip, int rip_len)
440 {
441         unsigned int len;
442         struct sockaddr_in sin;
443         struct hostent *host;
444         struct hostent *host1;
445         char ip[128];
446         unsigned char *p;
447         int n;
448 #ifdef AF_LOCAL
449     struct sockaddr_un *un;
450 #endif
451
452         rip[0] = '\0';
453         name[0] = '\0';
454
455         len = sizeof sin;
456         if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
457                 perror("getpeername");
458                 return;
459         }
460
461         host = gethostbyaddr((char *) &sin.sin_addr, sizeof sin.sin_addr,
462                                                                        AF_INET);
463         if (host == NULL) {
464                 perror("gethostbyaddr");
465                 return;
466         }
467
468         strncpy(name, host->h_name, name_len);
469         name[name_len - 1] = '\0';
470
471         host1 = gethostbyname(host->h_name);
472         if (host1 == NULL)
473                 return;
474         p = (unsigned char *)host1;
475         n = 0;
476         while (p != NULL) {
477                 p = (unsigned char *)host1->h_addr_list[n++];
478                 if (p == NULL)
479                         continue;
480                 if ((host1->h_addrtype != AF_INET)
481 #ifdef AF_LOCAL
482                         && (host1->h_addrtype != AF_LOCAL)
483 #endif
484                         )
485                         continue;
486
487                 if (host1->h_addrtype == AF_INET)
488                         sprintf(ip, "%u.%u.%u.%u", p[0], p[1], p[2], p[3]);
489 #ifdef AF_LOCAL
490                 else {
491                         un = (struct sockaddr_un *)p;
492                         strncpy(ip, un->sun_path, sizeof(ip) - 1);
493                         ip[sizeof(ip) - 1] = '\0';
494                 }
495 #endif
496                 p = NULL;
497                 strncpy(rip, ip, rip_len);
498                 rip[rip_len - 1] = '\0';
499         }
500 }
501
502 int libwebsockets_get_random(struct libwebsocket_context *context,
503                                                              void *buf, int len)
504 {
505         int n;
506         char *p = buf;
507
508 #ifdef WIN32
509         for (n = 0; n < len; n++)
510                 p[n] = (unsigned char)rand();
511 #else
512         n = read(context->fd_random, p, len);
513 #endif
514
515         return n;
516 }
517
518 unsigned char *
519 libwebsockets_SHA1(const unsigned char *d, size_t n, unsigned char *md)
520 {
521         return SHA1(d, n, md);
522 }
523
524 void libwebsockets_00_spaceout(char *key, int spaces, int seed)
525 {
526         char *p;
527
528         key++;
529         while (spaces--) {
530                 if (*key && (seed & 1))
531                         key++;
532                 seed >>= 1;
533
534                 p = key + strlen(key);
535                 while (p >= key) {
536                         p[1] = p[0];
537                         p--;
538                 }
539                 *key++ = ' ';
540         }
541 }
542
543 void libwebsockets_00_spam(char *key, int count, int seed)
544 {
545         char *p;
546
547         key++;
548         while (count--) {
549
550                 if (*key && (seed & 1))
551                         key++;
552                 seed >>= 1;
553
554                 p = key + strlen(key);
555                 while (p >= key) {
556                         p[1] = p[0];
557                         p--;
558                 }
559                 *key++ = 0x21 + ((seed & 0xffff) % 15);
560                 /* 4 would use it up too fast.. not like it matters */
561                 seed >>= 1;
562         }
563 }
564
565 int lws_send_pipe_choked(struct libwebsocket *wsi)
566 {
567         struct pollfd fds;
568
569         fds.fd = wsi->sock;
570         fds.events = POLLOUT;
571         fds.revents = 0;
572
573         if (poll(&fds, 1, 0) != 1)
574                 return 1;
575
576         if ((fds.revents & POLLOUT) == 0)
577                 return 1;
578
579         /* okay to send another packet without blocking */
580
581         return 0;
582 }
583
584 int
585 lws_handle_POLLOUT_event(struct libwebsocket_context *context,
586                                 struct libwebsocket *wsi, struct pollfd *pollfd)
587 {
588         struct lws_tokens eff_buf;
589         int n;
590         int ret;
591         int m;
592         int handled = 0;
593
594         for (n = 0; n < wsi->count_active_extensions; n++) {
595                 if (!wsi->active_extensions[n]->callback)
596                         continue;
597
598                 m = wsi->active_extensions[n]->callback(context,
599                         wsi->active_extensions[n], wsi,
600                         LWS_EXT_CALLBACK_IS_WRITEABLE,
601                                        wsi->active_extensions_user[n], NULL, 0);
602                 if (m > handled)
603                         handled = m;
604         }
605
606         if (handled == 1)
607                 goto notify_action;
608
609         if (!wsi->extension_data_pending || handled == 2)
610                 goto user_service;
611
612         /*
613          * check in on the active extensions, see if they
614          * had pending stuff to spill... they need to get the
615          * first look-in otherwise sequence will be disordered
616          *
617          * NULL, zero-length eff_buf means just spill pending
618          */
619
620         ret = 1;
621         while (ret == 1) {
622
623                 /* default to nobody has more to spill */
624
625                 ret = 0;
626                 eff_buf.token = NULL;
627                 eff_buf.token_len = 0;
628
629                 /* give every extension a chance to spill */
630
631                 for (n = 0; n < wsi->count_active_extensions; n++) {
632                         m = wsi->active_extensions[n]->callback(
633                                 wsi->protocol->owning_server,
634                                 wsi->active_extensions[n], wsi,
635                                         LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
636                                    wsi->active_extensions_user[n], &eff_buf, 0);
637                         if (m < 0) {
638                                 fprintf(stderr, "ext reports fatal error\n");
639                                 return -1;
640                         }
641                         if (m)
642                                 /*
643                                  * at least one extension told us he has more
644                                  * to spill, so we will go around again after
645                                  */
646                                 ret = 1;
647                 }
648
649                 /* assuming they gave us something to send, send it */
650
651                 if (eff_buf.token_len) {
652                         if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
653                                                              eff_buf.token_len))
654                                 return -1;
655                 } else
656                         continue;
657
658                 /* no extension has more to spill */
659
660                 if (!ret)
661                         continue;
662
663                 /*
664                  * There's more to spill from an extension, but we just sent
665                  * something... did that leave the pipe choked?
666                  */
667
668                 if (!lws_send_pipe_choked(wsi))
669                         /* no we could add more */
670                         continue;
671
672                 debug("choked in POLLOUT service\n");
673
674                 /*
675                  * Yes, he's choked.  Leave the POLLOUT masked on so we will
676                  * come back here when he is unchoked.  Don't call the user
677                  * callback to enforce ordering of spilling, he'll get called
678                  * when we come back here and there's nothing more to spill.
679                  */
680
681                 return 0;
682         }
683
684         wsi->extension_data_pending = 0;
685
686 user_service:
687         /* one shot */
688
689         if (pollfd) {
690                 pollfd->events &= ~POLLOUT;
691
692                 /* external POLL support via protocol 0 */
693                 context->protocols[0].callback(context, wsi,
694                         LWS_CALLBACK_CLEAR_MODE_POLL_FD,
695                         (void *)(long)wsi->sock, NULL, POLLOUT);
696         }
697
698 notify_action:
699
700         if (wsi->mode == LWS_CONNMODE_WS_CLIENT)
701                 n = LWS_CALLBACK_CLIENT_WRITEABLE;
702         else
703                 n = LWS_CALLBACK_SERVER_WRITEABLE;
704
705         wsi->protocol->callback(context, wsi, n, wsi->user_space, NULL, 0);
706
707         return 0;
708 }
709
710
711
712 void
713 libwebsocket_service_timeout_check(struct libwebsocket_context *context,
714                                      struct libwebsocket *wsi, unsigned int sec)
715 {
716         int n;
717
718         /*
719          * if extensions want in on it (eg, we are a mux parent)
720          * give them a chance to service child timeouts
721          */
722
723         for (n = 0; n < wsi->count_active_extensions; n++)
724                 wsi->active_extensions[n]->callback(
725                                     context, wsi->active_extensions[n],
726                                     wsi, LWS_EXT_CALLBACK_1HZ,
727                                     wsi->active_extensions_user[n], NULL, sec);
728
729         if (!wsi->pending_timeout)
730                 return;
731
732         /*
733          * if we went beyond the allowed time, kill the
734          * connection
735          */
736
737         if (sec > wsi->pending_timeout_limit) {
738                 debug("TIMEDOUT WAITING\n");
739                 libwebsocket_close_and_free_session(context,
740                                 wsi, LWS_CLOSE_STATUS_NOSTATUS);
741         }
742 }
743
744 struct libwebsocket *
745 libwebsocket_create_new_server_wsi(struct libwebsocket_context *context)
746 {
747         struct libwebsocket *new_wsi;
748         int n;
749
750         new_wsi = malloc(sizeof(struct libwebsocket));
751         if (new_wsi == NULL) {
752                 fprintf(stderr, "Out of memory for new connection\n");
753                 return NULL;
754         }
755
756         memset(new_wsi, 0, sizeof(struct libwebsocket));
757         new_wsi->count_active_extensions = 0;
758         new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
759
760         /* intialize the instance struct */
761
762         new_wsi->state = WSI_STATE_HTTP;
763         new_wsi->name_buffer_pos = 0;
764         new_wsi->mode = LWS_CONNMODE_WS_SERVING;
765
766         for (n = 0; n < WSI_TOKEN_COUNT; n++) {
767                 new_wsi->utf8_token[n].token = NULL;
768                 new_wsi->utf8_token[n].token_len = 0;
769         }
770
771         /*
772          * these can only be set once the protocol is known
773          * we set an unestablished connection's protocol pointer
774          * to the start of the supported list, so it can look
775          * for matching ones during the handshake
776          */
777         new_wsi->protocol = context->protocols;
778         new_wsi->user_space = NULL;
779
780         /*
781          * Default protocol is 76 / 00
782          * After 76, there's a header specified to inform which
783          * draft the client wants, when that's seen we modify
784          * the individual connection's spec revision accordingly
785          */
786         new_wsi->ietf_spec_revision = 0;
787
788         return new_wsi;
789 }
790
791 char *
792 libwebsockets_generate_client_handshake(struct libwebsocket_context *context,
793                 struct libwebsocket *wsi, char *pkt)
794 {
795         char hash[20];
796         char *p = pkt;
797         int n;
798         struct libwebsocket_extension *ext;
799         struct libwebsocket_extension *ext1;
800         int ext_count = 0;
801         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1 +
802                          MAX_BROADCAST_PAYLOAD + LWS_SEND_BUFFER_POST_PADDING];
803         static const char magic_websocket_guid[] =
804                                          "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
805
806         /*
807          * create the random key
808          */
809
810         n = libwebsockets_get_random(context, hash, 16);
811         if (n != 16) {
812                 fprintf(stderr, "Unable to read from random dev %s\n",
813                                                 SYSTEM_RANDOM_FILEPATH);
814                 free(wsi->c_path);
815                 free(wsi->c_host);
816                 if (wsi->c_origin)
817                         free(wsi->c_origin);
818                 if (wsi->c_protocol)
819                         free(wsi->c_protocol);
820                 libwebsocket_close_and_free_session(context, wsi,
821                                              LWS_CLOSE_STATUS_NOSTATUS);
822                 return NULL;
823         }
824
825         lws_b64_encode_string(hash, 16, wsi->key_b64,
826                                                    sizeof wsi->key_b64);
827
828         /*
829          * 00 example client handshake
830          *
831          * GET /socket.io/websocket HTTP/1.1
832          * Upgrade: WebSocket
833          * Connection: Upgrade
834          * Host: 127.0.0.1:9999
835          * Origin: http://127.0.0.1
836          * Sec-WebSocket-Key1: 1 0 2#0W 9 89 7  92 ^
837          * Sec-WebSocket-Key2: 7 7Y 4328 B2v[8(z1
838          * Cookie: socketio=websocket
839          *
840          * (Á®Ä0¶†≥
841          *
842          * 04 example client handshake
843          *
844          * GET /chat HTTP/1.1
845          * Host: server.example.com
846          * Upgrade: websocket
847          * Connection: Upgrade
848          * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
849          * Sec-WebSocket-Origin: http://example.com
850          * Sec-WebSocket-Protocol: chat, superchat
851          * Sec-WebSocket-Version: 4
852          */
853
854         p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a", wsi->c_path);
855
856         p += sprintf(p, "Pragma: no-cache\x0d\x0a"
857                                         "Cache-Control: no-cache\x0d\x0a");
858
859         if (wsi->ietf_spec_revision == 0) {
860                 unsigned char spaces_1, spaces_2;
861                 unsigned int max_1, max_2;
862                 unsigned int num_1, num_2;
863                 unsigned long product_1, product_2;
864                 char key_1[40];
865                 char key_2[40];
866                 unsigned int seed;
867                 unsigned int count;
868                 char challenge[16];
869
870                 libwebsockets_get_random(context, &spaces_1, sizeof(char));
871                 libwebsockets_get_random(context, &spaces_2, sizeof(char));
872
873                 spaces_1 = (spaces_1 % 12) + 1;
874                 spaces_2 = (spaces_2 % 12) + 1;
875
876                 max_1 = 4294967295 / spaces_1;
877                 max_2 = 4294967295 / spaces_2;
878
879                 libwebsockets_get_random(context, &num_1, sizeof(int));
880                 libwebsockets_get_random(context, &num_2, sizeof(int));
881
882                 num_1 = (num_1 % max_1);
883                 num_2 = (num_2 % max_2);
884
885                 challenge[0] = num_1 >> 24;
886                 challenge[1] = num_1 >> 16;
887                 challenge[2] = num_1 >> 8;
888                 challenge[3] = num_1;
889                 challenge[4] = num_2 >> 24;
890                 challenge[5] = num_2 >> 16;
891                 challenge[6] = num_2 >> 8;
892                 challenge[7] = num_2;
893
894                 product_1 = num_1 * spaces_1;
895                 product_2 = num_2 * spaces_2;
896
897                 sprintf(key_1, "%lu", product_1);
898                 sprintf(key_2, "%lu", product_2);
899
900                 libwebsockets_get_random(context, &seed, sizeof(int));
901                 libwebsockets_get_random(context, &count, sizeof(int));
902
903                 libwebsockets_00_spam(key_1, (count % 12) + 1, seed);
904
905                 libwebsockets_get_random(context, &seed, sizeof(int));
906                 libwebsockets_get_random(context, &count, sizeof(int));
907
908                 libwebsockets_00_spam(key_2, (count % 12) + 1, seed);
909
910                 libwebsockets_get_random(context, &seed, sizeof(int));
911
912                 libwebsockets_00_spaceout(key_1, spaces_1, seed);
913                 libwebsockets_00_spaceout(key_2, spaces_2, seed >> 16);
914
915                 p += sprintf(p, "Upgrade: WebSocket\x0d\x0a"
916                         "Connection: Upgrade\x0d\x0aHost: %s\x0d\x0a",
917                         wsi->c_host);
918                 if (wsi->c_origin)
919                         p += sprintf(p, "Origin: %s\x0d\x0a", wsi->c_origin);
920
921                 if (wsi->c_protocol)
922                         p += sprintf(p, "Sec-WebSocket-Protocol: %s"
923                                          "\x0d\x0a", wsi->c_protocol);
924
925                 p += sprintf(p, "Sec-WebSocket-Key1: %s\x0d\x0a", key_1);
926                 p += sprintf(p, "Sec-WebSocket-Key2: %s\x0d\x0a", key_2);
927
928                 /* give userland a chance to append, eg, cookies */
929
930                 context->protocols[0].callback(context, wsi,
931                         LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
932                                 NULL, &p, (pkt + sizeof(pkt)) - p - 12);
933
934                 p += sprintf(p, "\x0d\x0a");
935
936                 if (libwebsockets_get_random(context, p, 8) != 8)
937                         return NULL;
938                 memcpy(&challenge[8], p, 8);
939                 p += 8;
940
941                 /* precompute what we want to see from the server */
942
943                 MD5((unsigned char *)challenge, 16,
944                    (unsigned char *)wsi->initial_handshake_hash_base64);
945
946                 goto issue_hdr;
947         }
948
949         p += sprintf(p, "Host: %s\x0d\x0a", wsi->c_host);
950         p += sprintf(p, "Upgrade: websocket\x0d\x0a"
951                                         "Connection: Upgrade\x0d\x0a"
952                                         "Sec-WebSocket-Key: ");
953         strcpy(p, wsi->key_b64);
954         p += strlen(wsi->key_b64);
955         p += sprintf(p, "\x0d\x0a");
956         if (wsi->c_origin) {
957         if (wsi->ietf_spec_revision == 13) {
958             p += sprintf(p, "Origin: %s\x0d\x0a",
959                                                          wsi->c_origin);
960         }
961         else {
962                     p += sprintf(p, "Sec-WebSocket-Origin: %s\x0d\x0a",
963                                                          wsi->c_origin);
964         }
965     }
966         if (wsi->c_protocol)
967                 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
968                                                        wsi->c_protocol);
969
970         /* tell the server what extensions we could support */
971
972         p += sprintf(p, "Sec-WebSocket-Extensions: ");
973
974         ext = context->extensions;
975         while (ext && ext->callback) {
976
977                 n = 0;
978                 ext1 = context->extensions;
979
980                 while (ext1 && ext1->callback) {
981                         n |= ext1->callback(context, ext1, wsi,
982                                 LWS_EXT_CALLBACK_CHECK_OK_TO_PROPOSE_EXTENSION,
983                                         NULL, (char *)ext->name, 0);
984
985                         ext1++;
986                 }
987
988                 if (n) { /* an extension vetos us */
989                         debug("ext %s vetoed\n", (char *)ext->name);
990                         ext++;
991                         continue;
992                 }
993
994                 n = context->protocols[0].callback(context, wsi,
995                         LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED,
996                                 wsi->user_space, (char *)ext->name, 0);
997
998                 /*
999                  * zero return from callback means
1000                  * go ahead and allow the extension,
1001                  * it's what we get if the callback is
1002                  * unhandled
1003                  */
1004
1005                 if (n) {
1006                         ext++;
1007                         continue;
1008                 }
1009
1010                 /* apply it */
1011
1012                 if (ext_count)
1013                         *p++ = ',';
1014                 p += sprintf(p, "%s", ext->name);
1015                 ext_count++;
1016
1017                 ext++;
1018         }
1019
1020         p += sprintf(p, "\x0d\x0a");
1021
1022         if (wsi->ietf_spec_revision)
1023                 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a",
1024                                                wsi->ietf_spec_revision);
1025
1026         /* give userland a chance to append, eg, cookies */
1027
1028         context->protocols[0].callback(context, wsi,
1029                 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
1030                 NULL, &p, (pkt + sizeof(pkt)) - p - 12);
1031
1032         p += sprintf(p, "\x0d\x0a");
1033
1034         /* prepare the expected server accept response */
1035
1036         strcpy((char *)buf, wsi->key_b64);
1037         strcpy((char *)&buf[strlen((char *)buf)], magic_websocket_guid);
1038
1039         SHA1(buf, strlen((char *)buf), (unsigned char *)hash);
1040
1041         lws_b64_encode_string(hash, 20,
1042                         wsi->initial_handshake_hash_base64,
1043                              sizeof wsi->initial_handshake_hash_base64);
1044
1045 issue_hdr:
1046
1047 #if 0
1048         puts(pkt);
1049 #endif
1050
1051         /* done with these now */
1052
1053         free(wsi->c_path);
1054         free(wsi->c_host);
1055         if (wsi->c_origin)
1056                 free(wsi->c_origin);
1057
1058         return p;
1059 }
1060
1061 int
1062 lws_client_interpret_server_handshake(struct libwebsocket_context *context,
1063                 struct libwebsocket *wsi)
1064 {
1065         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1 +
1066                         MAX_BROADCAST_PAYLOAD + LWS_SEND_BUFFER_POST_PADDING];
1067         char pkt[1024];
1068         char *p = &pkt[0];
1069         const char *pc;
1070         const char *c;
1071         int more = 1;
1072         int okay = 0;
1073         char ext_name[128];
1074         struct libwebsocket_extension *ext;
1075         void *v;
1076         int len = 0;
1077         int n;
1078         static const char magic_websocket_04_masking_guid[] =
1079                                          "61AC5F19-FBBA-4540-B96F-6561F1AB40A8";
1080
1081         /*
1082          * 00 / 76 -->
1083          *
1084          * HTTP/1.1 101 WebSocket Protocol Handshake
1085          * Upgrade: WebSocket
1086          * Connection: Upgrade
1087          * Sec-WebSocket-Origin: http://127.0.0.1
1088          * Sec-WebSocket-Location: ws://127.0.0.1:9999/socket.io/websocket
1089          *
1090          * xxxxxxxxxxxxxxxx
1091          */
1092
1093         if (wsi->ietf_spec_revision == 0) {
1094                 if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
1095                         !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
1096                         !wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len ||
1097                         !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
1098                         (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
1099                         wsi->c_protocol != NULL)) {
1100                         debug("libwebsocket_client_handshake "
1101                                         "missing required header(s)\n");
1102                         pkt[len] = '\0';
1103                         debug("%s", pkt);
1104                         goto bail3;
1105                 }
1106
1107                 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
1108                 if (strncmp(wsi->utf8_token[WSI_TOKEN_HTTP].token, "101", 3)) {
1109                         fprintf(stderr, "libwebsocket_client_handshake "
1110                                 "server sent bad HTTP response '%s'\n",
1111                                 wsi->utf8_token[WSI_TOKEN_HTTP].token);
1112                         goto bail3;
1113                 }
1114
1115                 if (wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len < 16) {
1116                         fprintf(stderr, "libwebsocket_client_handshake "
1117                                 "challenge reply too short %d\n",
1118                                 wsi->utf8_token[
1119                                         WSI_TOKEN_CHALLENGE].token_len);
1120                         pkt[len] = '\0';
1121                         debug("%s", pkt);
1122                         goto bail3;
1123
1124                 }
1125
1126                 goto select_protocol;
1127         }
1128
1129         /*
1130          * well, what the server sent looked reasonable for syntax.
1131          * Now let's confirm it sent all the necessary headers
1132          */
1133 #if 0
1134         fprintf(stderr, "WSI_TOKEN_HTTP: %d\n",
1135                                     wsi->utf8_token[WSI_TOKEN_HTTP].token_len);
1136         fprintf(stderr, "WSI_TOKEN_UPGRADE: %d\n",
1137                                  wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len);
1138         fprintf(stderr, "WSI_TOKEN_CONNECTION: %d\n",
1139                               wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len);
1140         fprintf(stderr, "WSI_TOKEN_ACCEPT: %d\n",
1141                                   wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len);
1142         fprintf(stderr, "WSI_TOKEN_NONCE: %d\n",
1143                                    wsi->utf8_token[WSI_TOKEN_NONCE].token_len);
1144         fprintf(stderr, "WSI_TOKEN_PROTOCOL: %d\n",
1145                                 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len);
1146 #endif
1147         if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
1148             !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
1149             !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
1150             !wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len ||
1151             (!wsi->utf8_token[WSI_TOKEN_NONCE].token_len &&
1152                                    wsi->ietf_spec_revision == 4) ||
1153             (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
1154                                                     wsi->c_protocol != NULL)) {
1155                 debug("libwebsocket_client_handshake "
1156                                         "missing required header(s)\n");
1157                 pkt[len] = '\0';
1158                 debug("%s", pkt);
1159                 goto bail3;
1160         }
1161
1162         /*
1163          * Everything seems to be there, now take a closer look at what
1164          * is in each header
1165          */
1166
1167         strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
1168         if (strncmp(wsi->utf8_token[WSI_TOKEN_HTTP].token, "101", 3)) {
1169                 fprintf(stderr, "libwebsocket_client_handshake "
1170                                 "server sent bad HTTP response '%s'\n",
1171                                  wsi->utf8_token[WSI_TOKEN_HTTP].token);
1172                 goto bail3;
1173         }
1174
1175         strtolower(wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
1176         if (strcmp(wsi->utf8_token[WSI_TOKEN_UPGRADE].token,
1177                                                          "websocket")) {
1178                 fprintf(stderr, "libwebsocket_client_handshake server "
1179                                 "sent bad Upgrade header '%s'\n",
1180                                   wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
1181                 goto bail3;
1182         }
1183
1184         strtolower(wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
1185         if (strcmp(wsi->utf8_token[WSI_TOKEN_CONNECTION].token,
1186                                                            "upgrade")) {
1187                 fprintf(stderr, "libwebsocket_client_handshake server "
1188                                 "sent bad Connection hdr '%s'\n",
1189                            wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
1190                 goto bail3;
1191         }
1192
1193 select_protocol:
1194         pc = wsi->c_protocol;
1195         if (pc == NULL)
1196                 fprintf(stderr, "lws_client_interpret_server_handshake: "
1197                                                           "NULL c_protocol\n");
1198         else
1199                 debug("lws_client_interpret_server_handshake: "
1200                                                       "cPprotocol='%s'\n", pc);
1201
1202         /*
1203          * confirm the protocol the server wants to talk was in the list
1204          * of protocols we offered
1205          */
1206
1207         if (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len) {
1208
1209                 fprintf(stderr, "lws_client_interpret_server_handshake "
1210                                                "WSI_TOKEN_PROTOCOL is null\n");
1211                 /*
1212                  * no protocol name to work from,
1213                  * default to first protocol
1214                  */
1215                 wsi->protocol = &context->protocols[0];
1216                 wsi->c_callback = wsi->protocol->callback;
1217                 free(wsi->c_protocol);
1218
1219                 goto check_extensions;
1220         }
1221
1222         while (*pc && !okay) {
1223                 if ((!strncmp(pc, wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
1224                  wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len)) &&
1225                  (pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == ',' ||
1226                   pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == '\0')) {
1227                         okay = 1;
1228                         continue;
1229                 }
1230                 while (*pc && *pc != ',')
1231                         pc++;
1232                 while (*pc && *pc != ' ')
1233                         pc++;
1234         }
1235
1236         /* done with him now */
1237
1238         if (wsi->c_protocol)
1239                 free(wsi->c_protocol);
1240
1241         if (!okay) {
1242                 fprintf(stderr, "libwebsocket_client_handshake server "
1243                                         "sent bad protocol '%s'\n",
1244                                  wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
1245                 goto bail2;
1246         }
1247
1248         /*
1249          * identify the selected protocol struct and set it
1250          */
1251         n = 0;
1252         wsi->protocol = NULL;
1253         while (context->protocols[n].callback && !wsi->protocol) {  /* Stop after finding first one?? */
1254                 if (strcmp(wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
1255                                            context->protocols[n].name) == 0) {
1256                         wsi->protocol = &context->protocols[n];
1257                         wsi->c_callback = wsi->protocol->callback;
1258                 }
1259                 n++;
1260         }
1261
1262         if (wsi->protocol == NULL) {
1263                 fprintf(stderr, "libwebsocket_client_handshake server "
1264                                 "requested protocol '%s', which we "
1265                                 "said we supported but we don't!\n",
1266                                  wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
1267                 goto bail2;
1268         }
1269
1270
1271 check_extensions:
1272
1273         /* instantiate the accepted extensions */
1274
1275         if (!wsi->utf8_token[WSI_TOKEN_EXTENSIONS].token_len) {
1276                 debug("no client extenstions allowed by server\n");
1277                 goto check_accept;
1278         }
1279
1280         /*
1281          * break down the list of server accepted extensions
1282          * and go through matching them or identifying bogons
1283          */
1284
1285         c = wsi->utf8_token[WSI_TOKEN_EXTENSIONS].token;
1286         n = 0;
1287         while (more) {
1288
1289                 if (*c && (*c != ',' && *c != ' ' && *c != '\t')) {
1290                         ext_name[n] = *c++;
1291                         if (n < sizeof(ext_name) - 1)
1292                                 n++;
1293                         continue;
1294                 }
1295                 ext_name[n] = '\0';
1296                 if (!*c)
1297                         more = 0;
1298                 else {
1299                         c++;
1300                         if (!n)
1301                                 continue;
1302                 }
1303
1304                 /* check we actually support it */
1305
1306                 debug("checking client ext %s\n", ext_name);
1307
1308                 n = 0;
1309                 ext = wsi->protocol->owning_server->extensions;
1310                 while (ext && ext->callback) {
1311
1312                         if (strcmp(ext_name, ext->name)) {
1313                                 ext++;
1314                                 continue;
1315                         }
1316
1317                         n = 1;
1318
1319                         debug("instantiating client ext %s\n", ext_name);
1320
1321                         /* instantiate the extension on this conn */
1322
1323                         wsi->active_extensions_user[
1324                                 wsi->count_active_extensions] =
1325                                          malloc(ext->per_session_data_size);
1326                         memset(wsi->active_extensions_user[
1327                                 wsi->count_active_extensions], 0,
1328                                                     ext->per_session_data_size);
1329                         wsi->active_extensions[
1330                                   wsi->count_active_extensions] = ext;
1331
1332                         /* allow him to construct his context */
1333
1334                         ext->callback(wsi->protocol->owning_server,
1335                                 ext, wsi,
1336                                    LWS_EXT_CALLBACK_CLIENT_CONSTRUCT,
1337                                         wsi->active_extensions_user[
1338                                          wsi->count_active_extensions],
1339                                                                    NULL, 0);
1340
1341                         wsi->count_active_extensions++;
1342
1343                         ext++;
1344                 }
1345
1346                 if (n == 0) {
1347                         fprintf(stderr, "Server said we should use"
1348                                   "an unknown extension '%s'!\n", ext_name);
1349                         goto bail2;
1350                 }
1351
1352                 n = 0;
1353         }
1354
1355
1356 check_accept:
1357
1358         if (wsi->ietf_spec_revision == 0) {
1359
1360                 if (memcmp(wsi->initial_handshake_hash_base64,
1361                           wsi->utf8_token[WSI_TOKEN_CHALLENGE].token, 16)) {
1362                         fprintf(stderr, "libwebsocket_client_handshake "
1363                                            "failed 00 challenge compare\n");
1364                                 pkt[len] = '\0';
1365                                 fprintf(stderr, "%s", pkt);
1366                                 goto bail2;
1367                 }
1368
1369                 goto accept_ok;
1370         }
1371
1372         /*
1373          * Confirm his accept token is the one we precomputed
1374          */
1375
1376         if (strcmp(wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
1377                                   wsi->initial_handshake_hash_base64)) {
1378                 fprintf(stderr, "libwebsocket_client_handshake server "
1379                         "sent bad ACCEPT '%s' vs computed '%s'\n",
1380                         wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
1381                                         wsi->initial_handshake_hash_base64);
1382                 goto bail2;
1383         }
1384
1385         if (wsi->ietf_spec_revision == 4) {
1386                 /*
1387                  * Calculate the 04 masking key to use when
1388                  * sending data to server
1389                  */
1390
1391                 strcpy((char *)buf, wsi->key_b64);
1392                 p = (char *)buf + strlen(wsi->key_b64);
1393                 strcpy(p, wsi->utf8_token[WSI_TOKEN_NONCE].token);
1394                 p += wsi->utf8_token[WSI_TOKEN_NONCE].token_len;
1395                 strcpy(p, magic_websocket_04_masking_guid);
1396                 SHA1(buf, strlen((char *)buf), wsi->masking_key_04);
1397         }
1398 accept_ok:
1399
1400         /* allocate the per-connection user memory (if any) */
1401         if (wsi->protocol->per_session_data_size &&
1402                                           !libwebsocket_ensure_user_space(wsi))
1403                 goto bail2;
1404
1405         /* clear his proxy connection timeout */
1406
1407         libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1408
1409         /* mark him as being alive */
1410
1411         wsi->state = WSI_STATE_ESTABLISHED;
1412         wsi->mode = LWS_CONNMODE_WS_CLIENT;
1413
1414         debug("handshake OK for protocol %s\n", wsi->protocol->name);
1415
1416         /* call him back to inform him he is up */
1417
1418         wsi->protocol->callback(context, wsi,
1419                                 LWS_CALLBACK_CLIENT_ESTABLISHED,
1420                                                      wsi->user_space, NULL, 0);
1421
1422         /*
1423          * inform all extensions, not just active ones since they
1424          * already know
1425          */
1426
1427         ext = context->extensions;
1428
1429         while (ext && ext->callback) {
1430                 v = NULL;
1431                 for (n = 0; n < wsi->count_active_extensions; n++)
1432                         if (wsi->active_extensions[n] == ext)
1433                                 v = wsi->active_extensions_user[n];
1434
1435                 ext->callback(context, ext, wsi,
1436                           LWS_EXT_CALLBACK_ANY_WSI_ESTABLISHED, v, NULL, 0);
1437                 ext++;
1438         }
1439
1440         return 0;
1441
1442 bail3:
1443         if (wsi->c_protocol)
1444                 free(wsi->c_protocol);
1445
1446 bail2:
1447         if (wsi->c_callback) wsi->c_callback(context, wsi,
1448        LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
1449                          wsi->user_space,
1450                          NULL, 0);
1451         libwebsocket_close_and_free_session(context, wsi,
1452                                                  LWS_CLOSE_STATUS_NOSTATUS);  // But this should be LWS_CLOSE_STATUS_PROTOCOL_ERR
1453
1454         return 1;
1455 }
1456
1457
1458
1459 /**
1460  * libwebsocket_service_fd() - Service polled socket with something waiting
1461  * @context:    Websocket context
1462  * @pollfd:     The pollfd entry describing the socket fd and which events
1463  *              happened.
1464  *
1465  *      This function closes any active connections and then frees the
1466  *      context.  After calling this, any further use of the context is
1467  *      undefined.
1468  */
1469
1470 int
1471 libwebsocket_service_fd(struct libwebsocket_context *context,
1472                                                           struct pollfd *pollfd)
1473 {
1474         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1 +
1475                          MAX_BROADCAST_PAYLOAD + LWS_SEND_BUFFER_POST_PADDING];
1476         struct libwebsocket *wsi;
1477         struct libwebsocket *new_wsi;
1478         int n;
1479         int m;
1480         ssize_t len;
1481         int accept_fd;
1482         unsigned int clilen;
1483         struct sockaddr_in cli_addr;
1484         struct timeval tv;
1485         char pkt[1024];
1486         char *p = &pkt[0];
1487         int more = 1;
1488         struct lws_tokens eff_buf;
1489         int opt = 1;
1490         char c;
1491
1492 #ifdef LWS_OPENSSL_SUPPORT
1493         char ssl_err_buf[512];
1494 #endif
1495         /*
1496          * you can call us with pollfd = NULL to just allow the once-per-second
1497          * global timeout checks; if less than a second since the last check
1498          * it returns immediately then.
1499          */
1500
1501         gettimeofday(&tv, NULL);
1502
1503         if (context->last_timeout_check_s != tv.tv_sec) {
1504                 context->last_timeout_check_s = tv.tv_sec;
1505
1506                 /* global timeout check once per second */
1507
1508                 for (n = 0; n < context->fds_count; n++) {
1509                         wsi = wsi_from_fd(context, context->fds[n].fd);
1510
1511                         libwebsocket_service_timeout_check(context, wsi,
1512                                                                      tv.tv_sec);
1513                 }
1514         }
1515
1516         /* just here for timeout management? */
1517
1518         if (pollfd == NULL)
1519                 return 0;
1520
1521         /* no, here to service a socket descriptor */
1522
1523         wsi = wsi_from_fd(context, pollfd->fd);
1524
1525         if (wsi == NULL)
1526                 return 0;
1527
1528         switch (wsi->mode) {
1529         case LWS_CONNMODE_SERVER_LISTENER:
1530
1531                 /* pollin means a client has connected to us then */
1532
1533                 if (!(pollfd->revents & POLLIN))
1534                         break;
1535
1536                 if (context->fds_count >= MAX_CLIENTS) {
1537                         fprintf(stderr, "too busy to accept new client\n");
1538                         break;
1539                 }
1540
1541                 /* listen socket got an unencrypted connection... */
1542
1543                 clilen = sizeof(cli_addr);
1544                 accept_fd  = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
1545                                                                        &clilen);
1546                 if (accept_fd < 0) {
1547                         debug("ERROR on accept: %d\n", strerror(errno));
1548                         return -1;
1549                 }
1550
1551                 /* Disable Nagle */
1552                 opt = 1;
1553                 setsockopt(accept_fd, IPPROTO_TCP, TCP_NODELAY,
1554                                               (const void *)&opt, sizeof(opt));
1555
1556                 /*
1557                  * look at who we connected to and give user code a chance
1558                  * to reject based on client IP.  There's no protocol selected
1559                  * yet so we issue this to protocols[0]
1560                  */
1561
1562                 if ((context->protocols[0].callback)(context, wsi,
1563                                 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
1564                                            (void *)(long)accept_fd, NULL, 0)) {
1565                         debug("Callback denied network connection\n");
1566 #ifdef WIN32
1567                         closesocket(accept_fd);
1568 #else
1569                         close(accept_fd);
1570 #endif
1571                         break;
1572                 }
1573
1574                 /* accepting connection to main listener */
1575
1576                 new_wsi = libwebsocket_create_new_server_wsi(context);
1577                 if (new_wsi == NULL)
1578                         break;
1579
1580                 new_wsi->sock = accept_fd;
1581
1582
1583 #ifdef LWS_OPENSSL_SUPPORT
1584                 new_wsi->ssl = NULL;
1585
1586                 if (context->use_ssl) {
1587
1588                         new_wsi->ssl = SSL_new(context->ssl_ctx);
1589                         if (new_wsi->ssl == NULL) {
1590                                 fprintf(stderr, "SSL_new failed: %s\n",
1591                                     ERR_error_string(SSL_get_error(
1592                                     new_wsi->ssl, 0), NULL));
1593                                     libwebsockets_decode_ssl_error();
1594                                 free(new_wsi);
1595                                 break;
1596                         }
1597
1598                         SSL_set_fd(new_wsi->ssl, accept_fd);
1599
1600                         n = SSL_accept(new_wsi->ssl);
1601                         if (n != 1) {
1602                                 /*
1603                                  * browsers seem to probe with various
1604                                  * ssl params which fail then retry
1605                                  * and succeed
1606                                  */
1607                                 debug("SSL_accept failed skt %u: %s\n",
1608                                       pollfd->fd,
1609                                       ERR_error_string(SSL_get_error(
1610                                       new_wsi->ssl, n), NULL));
1611                                 SSL_free(
1612                                        new_wsi->ssl);
1613                                 free(new_wsi);
1614                                 break;
1615                         }
1616
1617                         debug("accepted new SSL conn  "
1618                               "port %u on fd=%d SSL ver %s\n",
1619                                 ntohs(cli_addr.sin_port), accept_fd,
1620                                   SSL_get_version(new_wsi->ssl));
1621
1622                 } else
1623 #endif
1624                         debug("accepted new conn  port %u on fd=%d\n",
1625                                           ntohs(cli_addr.sin_port), accept_fd);
1626
1627                 insert_wsi(context, new_wsi);
1628
1629                 /*
1630                  * make sure NO events are seen yet on this new socket
1631                  * (otherwise we inherit old fds[client].revents from
1632                  * previous socket there and die mysteriously! )
1633                  */
1634                 context->fds[context->fds_count].revents = 0;
1635
1636                 context->fds[context->fds_count].events = POLLIN;
1637                 context->fds[context->fds_count++].fd = accept_fd;
1638
1639                 /* external POLL support via protocol 0 */
1640                 context->protocols[0].callback(context, new_wsi,
1641                         LWS_CALLBACK_ADD_POLL_FD,
1642                         (void *)(long)accept_fd, NULL, POLLIN);
1643
1644                 break;
1645
1646         case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
1647
1648                 /* as we are listening, POLLIN means accept() is needed */
1649
1650                 if (!(pollfd->revents & POLLIN))
1651                         break;
1652
1653                 /* listen socket got an unencrypted connection... */
1654
1655                 clilen = sizeof(cli_addr);
1656                 accept_fd  = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
1657                                                                        &clilen);
1658                 if (accept_fd < 0) {
1659                         debug("ERROR on accept\n");
1660                         return -1;
1661                 }
1662
1663                 if (context->fds_count >= MAX_CLIENTS) {
1664                         fprintf(stderr, "too busy to accept new broadcast "
1665                                                               "proxy client\n");
1666 #ifdef WIN32
1667                         closesocket(accept_fd);
1668 #else
1669                         close(accept_fd);
1670 #endif
1671                         break;
1672                 }
1673
1674                 /* create a dummy wsi for the connection and add it */
1675
1676                 new_wsi = malloc(sizeof(struct libwebsocket));
1677                 memset(new_wsi, 0, sizeof(struct libwebsocket));
1678                 new_wsi->sock = accept_fd;
1679                 new_wsi->mode = LWS_CONNMODE_BROADCAST_PROXY;
1680                 new_wsi->state = WSI_STATE_ESTABLISHED;
1681                 new_wsi->count_active_extensions = 0;
1682                 /* note which protocol we are proxying */
1683                 new_wsi->protocol_index_for_broadcast_proxy =
1684                                         wsi->protocol_index_for_broadcast_proxy;
1685                 insert_wsi(context, new_wsi);
1686
1687                 /* add connected socket to internal poll array */
1688
1689                 context->fds[context->fds_count].revents = 0;
1690                 context->fds[context->fds_count].events = POLLIN;
1691                 context->fds[context->fds_count++].fd = accept_fd;
1692
1693                 /* external POLL support via protocol 0 */
1694                 context->protocols[0].callback(context, new_wsi,
1695                         LWS_CALLBACK_ADD_POLL_FD,
1696                         (void *)(long)accept_fd, NULL, POLLIN);
1697
1698                 break;
1699
1700         case LWS_CONNMODE_BROADCAST_PROXY:
1701
1702                 /* handle session socket closed */
1703
1704                 if (pollfd->revents & (POLLERR | POLLHUP)) {
1705
1706                         debug("Session Socket %p (fd=%d) dead\n",
1707                                 (void *)wsi, pollfd->fd);
1708
1709                         libwebsocket_close_and_free_session(context, wsi,
1710                                                        LWS_CLOSE_STATUS_NORMAL);
1711                         return 1;
1712                 }
1713
1714                 /*
1715                  * either extension code with stuff to spill, or the user code,
1716                  * requested a callback when it was OK to write
1717                  */
1718
1719                 if (pollfd->revents & POLLOUT)
1720                         if (lws_handle_POLLOUT_event(context, wsi,
1721                                                                  pollfd) < 0) {
1722                                 libwebsocket_close_and_free_session(
1723                                         context, wsi, LWS_CLOSE_STATUS_NORMAL);
1724                                 return 1;
1725                         }
1726
1727                 /* any incoming data ready? */
1728
1729                 if (!(pollfd->revents & POLLIN))
1730                         break;
1731
1732                 /* get the issued broadcast payload from the socket */
1733
1734                 len = read(pollfd->fd, buf + LWS_SEND_BUFFER_PRE_PADDING,
1735                                                          MAX_BROADCAST_PAYLOAD);
1736                 if (len < 0) {
1737                         fprintf(stderr, "Error reading broadcast payload\n");
1738                         break;
1739                 }
1740
1741                 /* broadcast it to all guys with this protocol index */
1742
1743                 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
1744
1745                         for (m = 0; m < context->fd_hashtable[n].length; m++) {
1746
1747                                 new_wsi = context->fd_hashtable[n].wsi[m];
1748
1749                                 /* only to clients we are serving to */
1750
1751                                 if (new_wsi->mode != LWS_CONNMODE_WS_SERVING)
1752                                         continue;
1753
1754                                 /*
1755                                  * never broadcast to non-established
1756                                  * connection
1757                                  */
1758
1759                                 if (new_wsi->state != WSI_STATE_ESTABLISHED)
1760                                         continue;
1761
1762                                 /*
1763                                  * only broadcast to connections using
1764                                  * the requested protocol
1765                                  */
1766
1767                                 if (new_wsi->protocol->protocol_index !=
1768                                         wsi->protocol_index_for_broadcast_proxy)
1769                                         continue;
1770
1771                                 /* broadcast it to this connection */
1772
1773                                 new_wsi->protocol->callback(context, new_wsi,
1774                                         LWS_CALLBACK_BROADCAST,
1775                                         new_wsi->user_space,
1776                                         buf + LWS_SEND_BUFFER_PRE_PADDING, len);
1777                         }
1778                 }
1779                 break;
1780
1781         case LWS_CONNMODE_WS_CLIENT_WAITING_PROXY_REPLY:
1782
1783                 /* handle proxy hung up on us */
1784
1785                 if (pollfd->revents & (POLLERR | POLLHUP)) {
1786
1787                         fprintf(stderr, "Proxy connection %p (fd=%d) dead\n",
1788                                 (void *)wsi, pollfd->fd);
1789
1790                         libwebsocket_close_and_free_session(context, wsi,
1791                                                      LWS_CLOSE_STATUS_NOSTATUS);
1792                         return 1;
1793                 }
1794
1795                 n = recv(wsi->sock, pkt, sizeof pkt, 0);
1796                 if (n < 0) {
1797                         libwebsocket_close_and_free_session(context, wsi,
1798                                                      LWS_CLOSE_STATUS_NOSTATUS);
1799                         fprintf(stderr, "ERROR reading from proxy socket\n");
1800                         return 1;
1801                 }
1802
1803                 pkt[13] = '\0';
1804                 if (strcmp(pkt, "HTTP/1.0 200 ") != 0) {
1805                         libwebsocket_close_and_free_session(context, wsi,
1806                                                      LWS_CLOSE_STATUS_NOSTATUS);
1807                         fprintf(stderr, "ERROR from proxy: %s\n", pkt);
1808                         return 1;
1809                 }
1810
1811                 /* clear his proxy connection timeout */
1812
1813                 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1814
1815                 /* fallthru */
1816
1817         case LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE:
1818
1819         #ifdef LWS_OPENSSL_SUPPORT
1820                 if (wsi->use_ssl && !wsi->ssl) {
1821
1822                         wsi->ssl = SSL_new(context->ssl_client_ctx);
1823                         wsi->client_bio = BIO_new_socket(wsi->sock,
1824                                                                    BIO_NOCLOSE);
1825                         SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
1826
1827                         SSL_set_ex_data(wsi->ssl,
1828                                         openssl_websocket_private_data_index,
1829                                                                        context);
1830                 }               
1831
1832                 if (wsi->use_ssl) {
1833                         if (SSL_connect(wsi->ssl) <= 0) {
1834
1835                                 /*
1836                                  * retry if new data comes until we
1837                                  * run into the connection timeout or win
1838                                  */
1839
1840                                 fprintf(stderr, "SSL connect error %s\n",
1841                                         ERR_error_string(ERR_get_error(),
1842                                                                   ssl_err_buf));
1843                                 return 0;
1844                         }
1845
1846                         n = SSL_get_verify_result(wsi->ssl);
1847                         if ((n != X509_V_OK) && (
1848                                 n != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
1849                                                            wsi->use_ssl != 2)) {
1850
1851                                 fprintf(stderr, "server's cert didn't "
1852                                                            "look good %d\n", n);
1853                                 libwebsocket_close_and_free_session(context,
1854                                                 wsi, LWS_CLOSE_STATUS_NOSTATUS);
1855                                 return 1;
1856                         }
1857                 } else
1858                         wsi->ssl = NULL;
1859         #endif
1860
1861                 p = libwebsockets_generate_client_handshake(context, wsi, p);
1862                 if (p == NULL)
1863                         return 1;
1864
1865                 /* send our request to the server */
1866
1867         #ifdef LWS_OPENSSL_SUPPORT
1868                 if (wsi->use_ssl)
1869                         n = SSL_write(wsi->ssl, pkt, p - pkt);
1870                 else
1871         #endif
1872                         n = send(wsi->sock, pkt, p - pkt, 0);
1873
1874                 if (n < 0) {
1875                         fprintf(stderr, "ERROR writing to client socket\n");
1876                         libwebsocket_close_and_free_session(context, wsi,
1877                                                      LWS_CLOSE_STATUS_NOSTATUS);
1878                         return 1;
1879                 }
1880
1881                 wsi->parser_state = WSI_TOKEN_NAME_PART;
1882                 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY;
1883                 libwebsocket_set_timeout(wsi,
1884                                 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, AWAITING_TIMEOUT);
1885
1886                 break;
1887
1888         case LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY:
1889
1890                 /* handle server hung up on us */
1891
1892                 if (pollfd->revents & (POLLERR | POLLHUP)) {
1893
1894                         fprintf(stderr, "Server connection %p (fd=%d) dead\n",
1895                                 (void *)wsi, pollfd->fd);
1896
1897                         goto bail3;
1898                 }
1899
1900
1901                 /* interpret the server response */
1902
1903                 /*
1904                  *  HTTP/1.1 101 Switching Protocols
1905                  *  Upgrade: websocket
1906                  *  Connection: Upgrade
1907                  *  Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
1908                  *  Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
1909                  *  Sec-WebSocket-Protocol: chat
1910                  */
1911
1912                 /*
1913                  * we have to take some care here to only take from the
1914                  * socket bytewise.  The browser may (and has been seen to
1915                  * in the case that onopen() performs websocket traffic)
1916                  * coalesce both handshake response and websocket traffic
1917                  * in one packet, since at that point the connection is
1918                  * definitively ready from browser pov.
1919                  */
1920
1921                 len = 1;
1922                 while (wsi->parser_state != WSI_PARSING_COMPLETE && len > 0) {
1923 #ifdef LWS_OPENSSL_SUPPORT
1924                         if (wsi->use_ssl)
1925                                 len = SSL_read(wsi->ssl, &c, 1);
1926                          else
1927 #endif
1928                                 len = recv(wsi->sock, &c, 1, 0);
1929
1930                         libwebsocket_parse(wsi, c);
1931                 }
1932
1933                 /*
1934                  * hs may also be coming in multiple packets, there is a 5-sec
1935                  * libwebsocket timeout still active here too, so if parsing did
1936                  * not complete just wait for next packet coming in this state
1937                  */
1938
1939                 if (wsi->parser_state != WSI_PARSING_COMPLETE)
1940                         break;
1941
1942                 /*
1943                  * otherwise deal with the handshake.  If there's any
1944                  * packet traffic already arrived we'll trigger poll() again
1945                  * right away and deal with it that way
1946                  */
1947
1948                 return lws_client_interpret_server_handshake(context, wsi);
1949
1950 bail3:
1951                 if (wsi->c_protocol)
1952                         free(wsi->c_protocol);
1953                 libwebsocket_close_and_free_session(context, wsi,
1954                                                     LWS_CLOSE_STATUS_NOSTATUS);
1955                 return 1;
1956
1957         case LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT:
1958                 fprintf(stderr,
1959                          "LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT\n");
1960                 break;
1961
1962         case LWS_CONNMODE_WS_CLIENT_PENDING_CANDIDATE_CHILD:
1963                 fprintf(stderr,
1964                            "LWS_CONNMODE_WS_CLIENT_PENDING_CANDIDATE_CHILD\n");
1965                 break;
1966
1967
1968         case LWS_CONNMODE_WS_SERVING:
1969         case LWS_CONNMODE_WS_CLIENT:
1970
1971                 /* handle session socket closed */
1972
1973                 if (pollfd->revents & (POLLERR | POLLHUP)) {
1974
1975                         fprintf(stderr, "Session Socket %p (fd=%d) dead\n",
1976                                 (void *)wsi, pollfd->fd);
1977
1978                         libwebsocket_close_and_free_session(context, wsi,
1979                                                      LWS_CLOSE_STATUS_NOSTATUS);
1980                         return 1;
1981                 }
1982
1983                 /* the guy requested a callback when it was OK to write */
1984
1985                 if ((pollfd->revents & POLLOUT) &&
1986                                             wsi->state == WSI_STATE_ESTABLISHED)
1987                         if (lws_handle_POLLOUT_event(context, wsi,
1988                                                                   pollfd) < 0) {
1989                                 libwebsocket_close_and_free_session(
1990                                          context, wsi, LWS_CLOSE_STATUS_NORMAL);
1991                                 return 1;
1992                         }
1993
1994
1995                 /* any incoming data ready? */
1996
1997                 if (!(pollfd->revents & POLLIN))
1998                         break;
1999
2000 #ifdef LWS_OPENSSL_SUPPORT
2001 read_pending:
2002                 if (wsi->ssl)
2003                         eff_buf.token_len = SSL_read(wsi->ssl, buf, sizeof buf);
2004                 else
2005 #endif
2006                         eff_buf.token_len =
2007                                            recv(pollfd->fd, buf, sizeof buf, 0);
2008
2009                 if (eff_buf.token_len < 0) {
2010                         fprintf(stderr, "Socket read returned %d\n",
2011                                                             eff_buf.token_len);
2012                         if (errno != EINTR && errno != EAGAIN)
2013                                 libwebsocket_close_and_free_session(context,
2014                                                wsi, LWS_CLOSE_STATUS_NOSTATUS);
2015                         return 1;
2016                 }
2017                 if (!eff_buf.token_len) {
2018                         libwebsocket_close_and_free_session(context, wsi,
2019                                                     LWS_CLOSE_STATUS_NOSTATUS);
2020                         return 0;
2021                 }
2022
2023                 /*
2024                  * give any active extensions a chance to munge the buffer
2025                  * before parse.  We pass in a pointer to an lws_tokens struct
2026                  * prepared with the default buffer and content length that's in
2027                  * there.  Rather than rewrite the default buffer, extensions
2028                  * that expect to grow the buffer can adapt .token to
2029                  * point to their own per-connection buffer in the extension
2030                  * user allocation.  By default with no extensions or no
2031                  * extension callback handling, just the normal input buffer is
2032                  * used then so it is efficient.
2033                  */
2034
2035                 eff_buf.token = (char *)buf;
2036
2037                 more = 1;
2038                 while (more) {
2039
2040                         more = 0;
2041
2042                         for (n = 0; n < wsi->count_active_extensions; n++) {
2043                                 m = wsi->active_extensions[n]->callback(context,
2044                                         wsi->active_extensions[n], wsi,
2045                                         LWS_EXT_CALLBACK_PACKET_RX_PREPARSE,
2046                                         wsi->active_extensions_user[n],
2047                                                                    &eff_buf, 0);
2048                                 if (m < 0) {
2049                                         fprintf(stderr,
2050                                             "Extension reports fatal error\n");
2051                                         libwebsocket_close_and_free_session(
2052                                                 context, wsi,
2053                                                     LWS_CLOSE_STATUS_NOSTATUS);
2054                                         return 1;
2055                                 }
2056                                 if (m)
2057                                         more = 1;
2058                         }
2059
2060                         /* service incoming data */
2061
2062                         if (eff_buf.token_len) {
2063                                 n = libwebsocket_read(context, wsi,
2064                                         (unsigned char *)eff_buf.token,
2065                                                             eff_buf.token_len);
2066                                 if (n < 0)
2067                                         /* we closed wsi */
2068                                         return 1;
2069                         }
2070
2071                         eff_buf.token = NULL;
2072                         eff_buf.token_len = 0;
2073                 }
2074
2075 #ifdef LWS_OPENSSL_SUPPORT
2076                 if (wsi->ssl && SSL_pending(wsi->ssl))
2077                         goto read_pending;
2078 #endif
2079                 break;
2080         }
2081
2082         return 0;
2083 }
2084
2085
2086 /**
2087  * libwebsocket_context_destroy() - Destroy the websocket context
2088  * @context:    Websocket context
2089  *
2090  *      This function closes any active connections and then frees the
2091  *      context.  After calling this, any further use of the context is
2092  *      undefined.
2093  */
2094 void
2095 libwebsocket_context_destroy(struct libwebsocket_context *context)
2096 {
2097         int n;
2098         int m;
2099         struct libwebsocket *wsi;
2100         struct libwebsocket_extension *ext;
2101
2102         for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
2103                 for (m = 0; m < context->fd_hashtable[n].length; m++) {
2104                         wsi = context->fd_hashtable[n].wsi[m];
2105                         libwebsocket_close_and_free_session(context, wsi,
2106                                                     LWS_CLOSE_STATUS_GOINGAWAY);
2107                 }
2108
2109         /*
2110          * give all extensions a chance to clean up any per-context
2111          * allocations they might have made
2112          */
2113
2114         ext = context->extensions;
2115         m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_DESTRUCT;
2116         if (context->listen_port)
2117                 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_DESTRUCT;
2118         while (ext && ext->callback) {
2119                 ext->callback(context, ext, NULL, m, NULL, NULL, 0);
2120                 ext++;
2121         }
2122
2123 #ifdef WIN32
2124 #else
2125         close(context->fd_random);
2126 #endif
2127
2128 #ifdef LWS_OPENSSL_SUPPORT
2129         if (context->ssl_ctx)
2130                 SSL_CTX_free(context->ssl_ctx);
2131         if (context->ssl_client_ctx)
2132                 SSL_CTX_free(context->ssl_client_ctx);
2133 #endif
2134
2135         free(context);
2136
2137 #ifdef WIN32
2138         WSACleanup();
2139 #endif
2140 }
2141
2142 LWS_EXTERN void *
2143 libwebsocket_context_user(struct libwebsocket_context *context)
2144 {
2145     return context->user_space;
2146 }
2147
2148 /**
2149  * libwebsocket_service() - Service any pending websocket activity
2150  * @context:    Websocket context
2151  * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
2152  *              service otherwise block and service immediately, returning
2153  *              after the timeout if nothing needed service.
2154  *
2155  *      This function deals with any pending websocket traffic, for three
2156  *      kinds of event.  It handles these events on both server and client
2157  *      types of connection the same.
2158  *
2159  *      1) Accept new connections to our context's server
2160  *
2161  *      2) Perform pending broadcast writes initiated from other forked
2162  *         processes (effectively serializing asynchronous broadcasts)
2163  *
2164  *      3) Call the receive callback for incoming frame data received by
2165  *          server or client connections.
2166  *
2167  *      You need to call this service function periodically to all the above
2168  *      functions to happen; if your application is single-threaded you can
2169  *      just call it in your main event loop.
2170  *
2171  *      Alternatively you can fork a new process that asynchronously handles
2172  *      calling this service in a loop.  In that case you are happy if this
2173  *      call blocks your thread until it needs to take care of something and
2174  *      would call it with a large nonzero timeout.  Your loop then takes no
2175  *      CPU while there is nothing happening.
2176  *
2177  *      If you are calling it in a single-threaded app, you don't want it to
2178  *      wait around blocking other things in your loop from happening, so you
2179  *      would call it with a timeout_ms of 0, so it returns immediately if
2180  *      nothing is pending, or as soon as it services whatever was pending.
2181  */
2182
2183
2184 int
2185 libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
2186 {
2187         int n;
2188
2189         /* stay dead once we are dead */
2190
2191         if (context == NULL)
2192                 return 1;
2193
2194         /* wait for something to need service */
2195
2196         n = poll(context->fds, context->fds_count, timeout_ms);
2197         if (n == 0) /* poll timeout */
2198                 return 0;
2199
2200         if (n < 0) {
2201                 /*
2202                 fprintf(stderr, "Listen Socket dead\n");
2203                 */
2204                 return -1;
2205         }
2206
2207         /* handle accept on listening socket? */
2208
2209         for (n = 0; n < context->fds_count; n++)
2210                 if (context->fds[n].revents)
2211                         if (libwebsocket_service_fd(context,
2212                                                         &context->fds[n]) < 0)
2213                                 return -1;
2214         return 0;
2215 }
2216
2217 int
2218 lws_any_extension_handled(struct libwebsocket_context *context,
2219                           struct libwebsocket *wsi,
2220                           enum libwebsocket_extension_callback_reasons r,
2221                                                        void *v, size_t len)
2222 {
2223         int n;
2224         int handled = 0;
2225
2226         /* maybe an extension will take care of it for us */
2227
2228         for (n = 0; n < wsi->count_active_extensions && !handled; n++) {
2229                 if (!wsi->active_extensions[n]->callback)
2230                         continue;
2231
2232                 handled |= wsi->active_extensions[n]->callback(context,
2233                         wsi->active_extensions[n], wsi,
2234                         r, wsi->active_extensions_user[n], v, len);
2235         }
2236
2237         return handled;
2238 }
2239
2240
2241 void *
2242 lws_get_extension_user_matching_ext(struct libwebsocket *wsi,
2243                                            struct libwebsocket_extension *ext)
2244 {
2245         int n = 0;
2246
2247         if (wsi == NULL)
2248                 return NULL;
2249
2250         while (n < wsi->count_active_extensions) {
2251                 if (wsi->active_extensions[n] != ext) {
2252                         n++;
2253                         continue;
2254                 }
2255                 return wsi->active_extensions_user[n];
2256         }
2257
2258         return NULL;
2259 }
2260
2261 /**
2262  * libwebsocket_callback_on_writable() - Request a callback when this socket
2263  *                                       becomes able to be written to without
2264  *                                       blocking
2265  *
2266  * @context:    libwebsockets context
2267  * @wsi:        Websocket connection instance to get callback for
2268  */
2269
2270 int
2271 libwebsocket_callback_on_writable(struct libwebsocket_context *context,
2272                                                       struct libwebsocket *wsi)
2273 {
2274         int n;
2275         int handled = 0;
2276
2277         /* maybe an extension will take care of it for us */
2278
2279         for (n = 0; n < wsi->count_active_extensions; n++) {
2280                 if (!wsi->active_extensions[n]->callback)
2281                         continue;
2282
2283                 handled |= wsi->active_extensions[n]->callback(context,
2284                         wsi->active_extensions[n], wsi,
2285                         LWS_EXT_CALLBACK_REQUEST_ON_WRITEABLE,
2286                                        wsi->active_extensions_user[n], NULL, 0);
2287         }
2288
2289         if (handled)
2290                 return 1;
2291
2292         for (n = 0; n < context->fds_count; n++)
2293                 if (context->fds[n].fd == wsi->sock) {
2294                         context->fds[n].events |= POLLOUT;
2295                         n = context->fds_count + 1;
2296                 }
2297
2298         if (n == context->fds_count)
2299                 fprintf(stderr, "libwebsocket_callback_on_writable: "
2300                                       "failed to find socket %d\n", wsi->sock);
2301
2302         /* external POLL support via protocol 0 */
2303         context->protocols[0].callback(context, wsi,
2304                 LWS_CALLBACK_SET_MODE_POLL_FD,
2305                 (void *)(long)wsi->sock, NULL, POLLOUT);
2306
2307         return 1;
2308 }
2309
2310 /**
2311  * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
2312  *                      all connections using the given protocol when it
2313  *                      becomes possible to write to each socket without
2314  *                      blocking in turn.
2315  *
2316  * @protocol:   Protocol whose connections will get callbacks
2317  */
2318
2319 int
2320 libwebsocket_callback_on_writable_all_protocol(
2321                                   const struct libwebsocket_protocols *protocol)
2322 {
2323         struct libwebsocket_context *context = protocol->owning_server;
2324         int n;
2325         int m;
2326         struct libwebsocket *wsi;
2327
2328         for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
2329
2330                 for (m = 0; m < context->fd_hashtable[n].length; m++) {
2331
2332                         wsi = context->fd_hashtable[n].wsi[m];
2333
2334                         if (wsi->protocol == protocol)
2335                                 libwebsocket_callback_on_writable(context, wsi);
2336                 }
2337         }
2338
2339         return 0;
2340 }
2341
2342 /**
2343  * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
2344  *
2345  * You will not need this unless you are doing something special
2346  *
2347  * @wsi:        Websocket connection instance
2348  * @reason:     timeout reason
2349  * @secs:       how many seconds
2350  */
2351
2352 void
2353 libwebsocket_set_timeout(struct libwebsocket *wsi,
2354                                           enum pending_timeout reason, int secs)
2355 {
2356         struct timeval tv;
2357
2358         gettimeofday(&tv, NULL);
2359
2360         wsi->pending_timeout_limit = tv.tv_sec + secs;
2361         wsi->pending_timeout = reason;
2362 }
2363
2364
2365 /**
2366  * libwebsocket_get_socket_fd() - returns the socket file descriptor
2367  *
2368  * You will not need this unless you are doing something special
2369  *
2370  * @wsi:        Websocket connection instance
2371  */
2372
2373 int
2374 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
2375 {
2376         return wsi->sock;
2377 }
2378
2379 /**
2380  * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
2381  *                              receieved packets.
2382  *
2383  * If the output side of a server process becomes choked, this allows flow
2384  * control for the input side.
2385  *
2386  * @wsi:        Websocket connection instance to get callback for
2387  * @enable:     0 = disable read servicing for this connection, 1 = enable
2388  */
2389
2390 int
2391 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
2392 {
2393         struct libwebsocket_context *context = wsi->protocol->owning_server;
2394         int n;
2395
2396         for (n = 0; n < context->fds_count; n++)
2397                 if (context->fds[n].fd == wsi->sock) {
2398                         if (enable)
2399                                 context->fds[n].events |= POLLIN;
2400                         else
2401                                 context->fds[n].events &= ~POLLIN;
2402
2403                         return 0;
2404                 }
2405
2406         if (enable)
2407                 /* external POLL support via protocol 0 */
2408                 context->protocols[0].callback(context, wsi,
2409                         LWS_CALLBACK_SET_MODE_POLL_FD,
2410                         (void *)(long)wsi->sock, NULL, POLLIN);
2411         else
2412                 /* external POLL support via protocol 0 */
2413                 context->protocols[0].callback(context, wsi,
2414                         LWS_CALLBACK_CLEAR_MODE_POLL_FD,
2415                         (void *)(long)wsi->sock, NULL, POLLIN);
2416
2417 #if 0
2418         fprintf(stderr, "libwebsocket_rx_flow_control "
2419                                                      "unable to find socket\n");
2420 #endif
2421         return 1;
2422 }
2423
2424 /**
2425  * libwebsocket_canonical_hostname() - returns this host's hostname
2426  *
2427  * This is typically used by client code to fill in the host parameter
2428  * when making a client connection.  You can only call it after the context
2429  * has been created.
2430  *
2431  * @context:    Websocket context
2432  */
2433
2434
2435 extern const char *
2436 libwebsocket_canonical_hostname(struct libwebsocket_context *context)
2437 {
2438         return (const char *)context->canonical_hostname;
2439 }
2440
2441
2442 static void sigpipe_handler(int x)
2443 {
2444 }
2445
2446 #ifdef LWS_OPENSSL_SUPPORT
2447 static int
2448 OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
2449 {
2450
2451         SSL *ssl;
2452         int n;
2453         struct libwebsocket_context *context;
2454
2455         ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
2456                 SSL_get_ex_data_X509_STORE_CTX_idx());
2457
2458         /*
2459          * !!! nasty openssl requires the index to come as a library-scope
2460          * static
2461          */
2462         context = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
2463
2464         n = context->protocols[0].callback(NULL, NULL,
2465                 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
2466                                                    x509_ctx, ssl, preverify_ok);
2467
2468         /* convert return code from 0 = OK to 1 = OK */
2469
2470         if (!n)
2471                 n = 1;
2472         else
2473                 n = 0;
2474
2475         return n;
2476 }
2477 #endif
2478
2479
2480 /**
2481  * libwebsocket_create_context() - Create the websocket handler
2482  * @port:       Port to listen on... you can use 0 to suppress listening on
2483  *              any port, that's what you want if you are not running a
2484  *              websocket server at all but just using it as a client
2485  * @interf:  NULL to bind the listen socket to all interfaces, or the
2486  *              interface name, eg, "eth2"
2487  * @protocols:  Array of structures listing supported protocols and a protocol-
2488  *              specific callback for each one.  The list is ended with an
2489  *              entry that has a NULL callback pointer.
2490  *              It's not const because we write the owning_server member
2491  * @extensions: NULL or array of libwebsocket_extension structs listing the
2492  *              extensions this context supports
2493  * @ssl_cert_filepath:  If libwebsockets was compiled to use ssl, and you want
2494  *                      to listen using SSL, set to the filepath to fetch the
2495  *                      server cert from, otherwise NULL for unencrypted
2496  * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
2497  *                      else ignored
2498  * @ssl_ca_filepath: CA certificate filepath or NULL
2499  * @gid:        group id to change to after setting listen socket, or -1.
2500  * @uid:        user id to change to after setting listen socket, or -1.
2501  * @options:    0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
2502  * @user:       optional user pointer that can be recovered via the context
2503  *              pointer using libwebsocket_context_user 
2504  *
2505  *      This function creates the listening socket and takes care
2506  *      of all initialization in one step.
2507  *
2508  *      After initialization, it returns a struct libwebsocket_context * that
2509  *      represents this server.  After calling, user code needs to take care
2510  *      of calling libwebsocket_service() with the context pointer to get the
2511  *      server's sockets serviced.  This can be done in the same process context
2512  *      or a forked process, or another thread,
2513  *
2514  *      The protocol callback functions are called for a handful of events
2515  *      including http requests coming in, websocket connections becoming
2516  *      established, and data arriving; it's also called periodically to allow
2517  *      async transmission.
2518  *
2519  *      HTTP requests are sent always to the FIRST protocol in @protocol, since
2520  *      at that time websocket protocol has not been negotiated.  Other
2521  *      protocols after the first one never see any HTTP callack activity.
2522  *
2523  *      The server created is a simple http server by default; part of the
2524  *      websocket standard is upgrading this http connection to a websocket one.
2525  *
2526  *      This allows the same server to provide files like scripts and favicon /
2527  *      images or whatever over http and dynamic data over websockets all in
2528  *      one place; they're all handled in the user callback.
2529  */
2530
2531 struct libwebsocket_context *
2532 libwebsocket_create_context(int port, const char *interf,
2533                                struct libwebsocket_protocols *protocols,
2534                                struct libwebsocket_extension *extensions,
2535                                const char *ssl_cert_filepath,
2536                                const char *ssl_private_key_filepath,
2537                                const char *ssl_ca_filepath,
2538                                int gid, int uid, unsigned int options,
2539                                void *user)
2540 {
2541         int n;
2542         int m;
2543         int sockfd = 0;
2544         int fd;
2545         struct sockaddr_in serv_addr, cli_addr;
2546         int opt = 1;
2547         struct libwebsocket_context *context = NULL;
2548         unsigned int slen;
2549         char *p;
2550         char hostname[1024] = "";
2551 //      struct hostent *he;
2552         struct libwebsocket *wsi;
2553         struct sockaddr sa;
2554
2555 #ifdef LWS_OPENSSL_SUPPORT
2556         SSL_METHOD *method;
2557         char ssl_err_buf[512];
2558 #endif
2559
2560 #ifdef _WIN32
2561         {
2562                 WORD wVersionRequested;
2563                 WSADATA wsaData;
2564                 int err;
2565                 HMODULE wsdll;
2566
2567                 /* Use the MAKEWORD(lowbyte, highbyte) macro from Windef.h */
2568                 wVersionRequested = MAKEWORD(2, 2);
2569
2570                 err = WSAStartup(wVersionRequested, &wsaData);
2571                 if (err != 0) {
2572                         /* Tell the user that we could not find a usable */
2573                         /* Winsock DLL.                                  */
2574                         fprintf(stderr, "WSAStartup failed with error: %d\n",
2575                                                                            err);
2576                         return NULL;
2577                 }
2578
2579                 /* default to a poll() made out of select() */
2580                 poll = emulated_poll;
2581
2582                 /* if windows socket lib available, use his WSAPoll */
2583                 wsdll = GetModuleHandle(_T("Ws2_32.dll"));
2584                 if (wsdll)
2585                         poll = (PFNWSAPOLL)GetProcAddress(wsdll, "WSAPoll");
2586         }
2587 #endif
2588
2589
2590         context = malloc(sizeof(struct libwebsocket_context));
2591         if (!context) {
2592                 fprintf(stderr, "No memory for websocket context\n");
2593                 return NULL;
2594         }
2595         context->protocols = protocols;
2596         context->listen_port = port;
2597         context->http_proxy_port = 0;
2598         context->http_proxy_address[0] = '\0';
2599         context->options = options;
2600         context->fds_count = 0;
2601         context->extensions = extensions;
2602         context->last_timeout_check_s = 0;
2603     context->user_space = user;
2604
2605 #ifdef WIN32
2606         context->fd_random = 0;
2607 #else
2608         context->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
2609         if (context->fd_random < 0) {
2610                 fprintf(stderr, "Unable to open random device %s %d\n",
2611                                     SYSTEM_RANDOM_FILEPATH, context->fd_random);
2612                 return NULL;
2613         }
2614 #endif
2615
2616 #ifdef LWS_OPENSSL_SUPPORT
2617         context->use_ssl = 0;
2618         context->ssl_ctx = NULL;
2619         context->ssl_client_ctx = NULL;
2620         openssl_websocket_private_data_index = 0;
2621 #endif
2622
2623         if (options & LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME) {
2624
2625                 strcpy(context->canonical_hostname, "unknown");
2626
2627         } else {
2628
2629                 /* find canonical hostname */
2630
2631                 hostname[(sizeof hostname) - 1] = '\0';
2632                 memset(&sa, 0, sizeof(sa));
2633                 sa.sa_family = AF_INET;
2634                 sa.sa_data[(sizeof sa.sa_data) - 1] = '\0';
2635                 gethostname(hostname, (sizeof hostname) - 1);
2636
2637                 n = 0;
2638
2639                 if (strlen(hostname) < sizeof(sa.sa_data) - 1) {        
2640                         strcpy(sa.sa_data, hostname);
2641         //              fprintf(stderr, "my host name is %s\n", sa.sa_data);
2642                         n = getnameinfo(&sa, sizeof(sa), hostname,
2643                                 (sizeof hostname) - 1, NULL, 0, 0);
2644                 }
2645
2646                 if (!n) {
2647                         strncpy(context->canonical_hostname, hostname,
2648                                                 sizeof context->canonical_hostname - 1);
2649                         context->canonical_hostname[
2650                                         sizeof context->canonical_hostname - 1] = '\0';
2651                 } else
2652                         strncpy(context->canonical_hostname, hostname,
2653                                                 sizeof context->canonical_hostname - 1);
2654
2655         //      fprintf(stderr, "context->canonical_hostname = %s\n",
2656         //                                              context->canonical_hostname);
2657         }
2658
2659         /* split the proxy ads:port if given */
2660
2661         p = getenv("http_proxy");
2662         if (p) {
2663                 strncpy(context->http_proxy_address, p,
2664                                        sizeof context->http_proxy_address - 1);
2665                 context->http_proxy_address[
2666                                  sizeof context->http_proxy_address - 1] = '\0';
2667
2668                 p = strchr(context->http_proxy_address, ':');
2669                 if (p == NULL) {
2670                         fprintf(stderr, "http_proxy needs to be ads:port\n");
2671                         return NULL;
2672                 }
2673                 *p = '\0';
2674                 context->http_proxy_port = atoi(p + 1);
2675
2676                 fprintf(stderr, "Using proxy %s:%u\n",
2677                                 context->http_proxy_address,
2678                                                       context->http_proxy_port);
2679         }
2680
2681         if (port) {
2682
2683 #ifdef LWS_OPENSSL_SUPPORT
2684                 context->use_ssl = ssl_cert_filepath != NULL &&
2685                                                ssl_private_key_filepath != NULL;
2686                 if (context->use_ssl)
2687                         fprintf(stderr, " Compiled with SSL support, "
2688                                                                   "using it\n");
2689                 else
2690                         fprintf(stderr, " Compiled with SSL support, "
2691                                                               "not using it\n");
2692
2693 #else
2694                 if (ssl_cert_filepath != NULL &&
2695                                              ssl_private_key_filepath != NULL) {
2696                         fprintf(stderr, " Not compiled for OpenSSl support!\n");
2697                         return NULL;
2698                 }
2699                 fprintf(stderr, " Compiled without SSL support, "
2700                                                        "serving unencrypted\n");
2701 #endif
2702         }
2703
2704         /* ignore SIGPIPE */
2705 #ifdef WIN32
2706 #else
2707         signal(SIGPIPE, sigpipe_handler);
2708 #endif
2709
2710
2711 #ifdef LWS_OPENSSL_SUPPORT
2712
2713         /* basic openssl init */
2714
2715         SSL_library_init();
2716
2717         OpenSSL_add_all_algorithms();
2718         SSL_load_error_strings();
2719
2720         openssl_websocket_private_data_index =
2721                 SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
2722
2723         /*
2724          * Firefox insists on SSLv23 not SSLv3
2725          * Konq disables SSLv2 by default now, SSLv23 works
2726          */
2727
2728         method = (SSL_METHOD *)SSLv23_server_method();
2729         if (!method) {
2730                 fprintf(stderr, "problem creating ssl method: %s\n",
2731                         ERR_error_string(ERR_get_error(), ssl_err_buf));
2732                 return NULL;
2733         }
2734         context->ssl_ctx = SSL_CTX_new(method); /* create context */
2735         if (!context->ssl_ctx) {
2736                 fprintf(stderr, "problem creating ssl context: %s\n",
2737                         ERR_error_string(ERR_get_error(), ssl_err_buf));
2738                 return NULL;
2739         }
2740
2741 #ifdef SSL_OP_NO_COMPRESSION
2742         SSL_CTX_set_options(context->ssl_ctx, SSL_OP_NO_COMPRESSION);
2743 #endif
2744         SSL_CTX_set_options(context->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
2745         SSL_CTX_set_cipher_list(context->ssl_ctx, CIPHERS_LIST_STRING);
2746
2747         /* client context */
2748
2749         if (port == CONTEXT_PORT_NO_LISTEN) {
2750                 method = (SSL_METHOD *)SSLv23_client_method();
2751                 if (!method) {
2752                         fprintf(stderr, "problem creating ssl method: %s\n",
2753                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
2754                         return NULL;
2755                 }
2756                 /* create context */
2757                 context->ssl_client_ctx = SSL_CTX_new(method);
2758                 if (!context->ssl_client_ctx) {
2759                         fprintf(stderr, "problem creating ssl context: %s\n",
2760                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
2761                         return NULL;
2762                 }
2763
2764 #ifdef SSL_OP_NO_COMPRESSION
2765                 SSL_CTX_set_options(context->ssl_client_ctx, SSL_OP_NO_COMPRESSION);
2766 #endif
2767                 SSL_CTX_set_options(context->ssl_client_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
2768                 SSL_CTX_set_cipher_list(context->ssl_client_ctx, CIPHERS_LIST_STRING);
2769
2770                 /* openssl init for cert verification (for client sockets) */
2771                 if (!ssl_ca_filepath) {
2772                         if (!SSL_CTX_load_verify_locations(
2773                                 context->ssl_client_ctx, NULL,
2774                                                      LWS_OPENSSL_CLIENT_CERTS))
2775                                 fprintf(stderr,
2776                                         "Unable to load SSL Client certs from %s "
2777                                         "(set by --with-client-cert-dir= in configure) -- "
2778                                         " client ssl isn't going to work",
2779                                                      LWS_OPENSSL_CLIENT_CERTS);
2780                 } else
2781                         if (!SSL_CTX_load_verify_locations(
2782                                 context->ssl_client_ctx, ssl_ca_filepath,
2783                                                                   NULL))
2784                                 fprintf(stderr,
2785                                         "Unable to load SSL Client certs "
2786                                         "file from %s -- client ssl isn't "
2787                                         "going to work", ssl_ca_filepath);
2788
2789                 /*
2790                  * callback allowing user code to load extra verification certs
2791                  * helping the client to verify server identity
2792                  */
2793
2794                 context->protocols[0].callback(context, NULL,
2795                         LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
2796                         context->ssl_client_ctx, NULL, 0);
2797         }
2798
2799         /* as a server, are we requiring clients to identify themselves? */
2800
2801         if (options & LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
2802
2803                 /* absolutely require the client cert */
2804
2805                 SSL_CTX_set_verify(context->ssl_ctx,
2806                        SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2807                                                        OpenSSL_verify_callback);
2808
2809                 /*
2810                  * give user code a chance to load certs into the server
2811                  * allowing it to verify incoming client certs
2812                  */
2813
2814                 context->protocols[0].callback(context, NULL,
2815                         LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
2816                                                      context->ssl_ctx, NULL, 0);
2817         }
2818
2819         if (context->use_ssl) {
2820
2821                 /* openssl init for server sockets */
2822
2823                 /* set the local certificate from CertFile */
2824                 n = SSL_CTX_use_certificate_chain_file(context->ssl_ctx,
2825                                         ssl_cert_filepath);
2826                 if (n != 1) {
2827                         fprintf(stderr, "problem getting cert '%s': %s\n",
2828                                 ssl_cert_filepath,
2829                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
2830                         return NULL;
2831                 }
2832                 /* set the private key from KeyFile */
2833                 if (SSL_CTX_use_PrivateKey_file(context->ssl_ctx,
2834                              ssl_private_key_filepath, SSL_FILETYPE_PEM) != 1) {
2835                         fprintf(stderr, "ssl problem getting key '%s': %s\n",
2836                                                 ssl_private_key_filepath,
2837                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
2838                         return NULL;
2839                 }
2840                 /* verify private key */
2841                 if (!SSL_CTX_check_private_key(context->ssl_ctx)) {
2842                         fprintf(stderr, "Private SSL key doesn't match cert\n");
2843                         return NULL;
2844                 }
2845
2846                 /* SSL is happy and has a cert it's content with */
2847         }
2848 #endif
2849
2850         /* selftest */
2851
2852         if (lws_b64_selftest())
2853                 return NULL;
2854
2855         /* fd hashtable init */
2856
2857         for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
2858                 context->fd_hashtable[n].length = 0;
2859
2860         /* set up our external listening socket we serve on */
2861
2862         if (port) {
2863
2864                 sockfd = socket(AF_INET, SOCK_STREAM, 0);
2865                 if (sockfd < 0) {
2866                         fprintf(stderr, "ERROR opening socket");
2867                         return NULL;
2868                 }
2869
2870                 /* allow us to restart even if old sockets in TIME_WAIT */
2871                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
2872                                               (const void *)&opt, sizeof(opt));
2873
2874                 /* Disable Nagle */
2875                 opt = 1;
2876                 setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY,
2877                                               (const void *)&opt, sizeof(opt));
2878
2879                 bzero((char *) &serv_addr, sizeof(serv_addr));
2880                 serv_addr.sin_family = AF_INET;
2881                 if (interf == NULL)
2882                         serv_addr.sin_addr.s_addr = INADDR_ANY;
2883                 else
2884                         interface_to_sa(interf, &serv_addr,
2885                                                 sizeof(serv_addr));
2886                 serv_addr.sin_port = htons(port);
2887
2888                 n = bind(sockfd, (struct sockaddr *) &serv_addr,
2889                                                              sizeof(serv_addr));
2890                 if (n < 0) {
2891                         fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
2892                                                                 port, n, errno);
2893                         return NULL;
2894                 }
2895
2896                 wsi = malloc(sizeof(struct libwebsocket));
2897                 memset(wsi, 0, sizeof(struct libwebsocket));
2898                 wsi->sock = sockfd;
2899                 wsi->count_active_extensions = 0;
2900                 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
2901                 insert_wsi(context, wsi);
2902
2903                 listen(sockfd, SOMAXCONN);
2904                 fprintf(stderr, " Listening on port %d\n", port);
2905
2906                 /* list in the internal poll array */
2907
2908                 context->fds[context->fds_count].fd = sockfd;
2909                 context->fds[context->fds_count++].events = POLLIN;
2910
2911                 /* external POLL support via protocol 0 */
2912                 context->protocols[0].callback(context, wsi,
2913                         LWS_CALLBACK_ADD_POLL_FD,
2914                         (void *)(long)sockfd, NULL, POLLIN);
2915
2916         }
2917
2918         /*
2919          * drop any root privs for this process
2920          * to listen on port < 1023 we would have needed root, but now we are
2921          * listening, we don't want the power for anything else
2922          */
2923 #ifdef WIN32
2924 #else
2925         if (gid != -1)
2926                 if (setgid(gid))
2927                         fprintf(stderr, "setgid: %s\n", strerror(errno));
2928         if (uid != -1)
2929                 if (setuid(uid))
2930                         fprintf(stderr, "setuid: %s\n", strerror(errno));
2931 #endif
2932
2933         /* set up our internal broadcast trigger sockets per-protocol */
2934
2935         for (context->count_protocols = 0;
2936                         protocols[context->count_protocols].callback;
2937                                                    context->count_protocols++) {
2938
2939                 debug("  Protocol: %s\n", protocols[context->count_protocols].name);
2940
2941                 protocols[context->count_protocols].owning_server = context;
2942                 protocols[context->count_protocols].protocol_index =
2943                                                        context->count_protocols;
2944
2945                 fd = socket(AF_INET, SOCK_STREAM, 0);
2946                 if (fd < 0) {
2947                         fprintf(stderr, "ERROR opening socket");
2948                         return NULL;
2949                 }
2950
2951                 /* allow us to restart even if old sockets in TIME_WAIT */
2952                 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&opt,
2953                                                                   sizeof(opt));
2954
2955                 bzero((char *) &serv_addr, sizeof(serv_addr));
2956                 serv_addr.sin_family = AF_INET;
2957                 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2958                 serv_addr.sin_port = 0; /* pick the port for us */
2959
2960                 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
2961                 if (n < 0) {
2962                         fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
2963                                                                 port, n, errno);
2964                         return NULL;
2965                 }
2966
2967                 slen = sizeof cli_addr;
2968                 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
2969                 if (n < 0) {
2970                         fprintf(stderr, "getsockname failed\n");
2971                         return NULL;
2972                 }
2973                 protocols[context->count_protocols].broadcast_socket_port =
2974                                                        ntohs(cli_addr.sin_port);
2975                 listen(fd, 5);
2976
2977                 debug("  Protocol %s broadcast socket %d\n",
2978                                 protocols[context->count_protocols].name,
2979                                                       ntohs(cli_addr.sin_port));
2980
2981                 /* dummy wsi per broadcast proxy socket */
2982
2983                 wsi = malloc(sizeof(struct libwebsocket));
2984                 memset(wsi, 0, sizeof(struct libwebsocket));
2985                 wsi->sock = fd;
2986                 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
2987                 wsi->count_active_extensions = 0;
2988                 /* note which protocol we are proxying */
2989                 wsi->protocol_index_for_broadcast_proxy =
2990                                                        context->count_protocols;
2991                 insert_wsi(context, wsi);
2992
2993                 /* list in internal poll array */
2994
2995                 context->fds[context->fds_count].fd = fd;
2996                 context->fds[context->fds_count].events = POLLIN;
2997                 context->fds[context->fds_count].revents = 0;
2998                 context->fds_count++;
2999
3000                 /* external POLL support via protocol 0 */
3001                 context->protocols[0].callback(context, wsi,
3002                         LWS_CALLBACK_ADD_POLL_FD,
3003                         (void *)(long)fd, NULL, POLLIN);
3004         }
3005
3006         /*
3007          * give all extensions a chance to create any per-context
3008          * allocations they need
3009          */
3010
3011         m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_CONSTRUCT;
3012         if (port)
3013                 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_CONSTRUCT;
3014         
3015         if (extensions) {
3016             while (extensions->callback) {
3017                     debug("  Extension: %s\n", extensions->name);
3018                     extensions->callback(context, extensions,
3019                                                 NULL, m, NULL, NULL, 0);
3020                     extensions++;
3021             }
3022         }
3023
3024         return context;
3025 }
3026
3027
3028 #ifndef LWS_NO_FORK
3029
3030 /**
3031  * libwebsockets_fork_service_loop() - Optional helper function forks off
3032  *                                a process for the websocket server loop.
3033  *                              You don't have to use this but if not, you
3034  *                              have to make sure you are calling
3035  *                              libwebsocket_service periodically to service
3036  *                              the websocket traffic
3037  * @context:    server context returned by creation function
3038  */
3039
3040 int
3041 libwebsockets_fork_service_loop(struct libwebsocket_context *context)
3042 {
3043         int fd;
3044         struct sockaddr_in cli_addr;
3045         int n;
3046         int p;
3047
3048         n = fork();
3049         if (n < 0)
3050                 return n;
3051
3052         if (!n) {
3053
3054                 /* main process context */
3055
3056                 /*
3057                  * set up the proxy sockets to allow broadcast from
3058                  * service process context
3059                  */
3060
3061                 for (p = 0; p < context->count_protocols; p++) {
3062                         fd = socket(AF_INET, SOCK_STREAM, 0);
3063                         if (fd < 0) {
3064                                 fprintf(stderr, "Unable to create socket\n");
3065                                 return -1;
3066                         }
3067                         cli_addr.sin_family = AF_INET;
3068                         cli_addr.sin_port = htons(
3069                              context->protocols[p].broadcast_socket_port);
3070                         cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
3071                         n = connect(fd, (struct sockaddr *)&cli_addr,
3072                                                                sizeof cli_addr);
3073                         if (n < 0) {
3074                                 fprintf(stderr, "Unable to connect to "
3075                                                 "broadcast socket %d, %s\n",
3076                                                 n, strerror(errno));
3077                                 return -1;
3078                         }
3079
3080                         context->protocols[p].broadcast_socket_user_fd = fd;
3081                 }
3082
3083                 return 0;
3084         }
3085
3086 #ifdef HAVE_SYS_PRCTL_H
3087         /* we want a SIGHUP when our parent goes down */
3088         prctl(PR_SET_PDEATHSIG, SIGHUP);
3089 #endif
3090
3091         /* in this forked process, sit and service websocket connections */
3092
3093         while (1) {
3094                 if (libwebsocket_service(context, 1000))
3095                         break;
3096 //#ifndef HAVE_SYS_PRCTL_H
3097 /*
3098  * on systems without prctl() (i.e. anything but linux) we can notice that our
3099  * parent is dead if getppid() returns 1. FIXME apparently this is not true for
3100  * solaris, could remember ppid right after fork and wait for it to change.
3101  */
3102
3103         if (getppid() == 1)
3104             break;
3105 //#endif
3106     }
3107
3108
3109         return 1;
3110 }
3111
3112 #endif
3113
3114 /**
3115  * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
3116  *                                connection.
3117  * @wsi:        pointer to struct websocket you want to know the protocol of
3118  *
3119  *
3120  *      This is useful to get the protocol to broadcast back to from inside
3121  * the callback.
3122  */
3123
3124 const struct libwebsocket_protocols *
3125 libwebsockets_get_protocol(struct libwebsocket *wsi)
3126 {
3127         return wsi->protocol;
3128 }
3129
3130 /**
3131  * libwebsockets_broadcast() - Sends a buffer to the callback for all active
3132  *                                connections of the given protocol.
3133  * @protocol:   pointer to the protocol you will broadcast to all members of
3134  * @buf:  buffer containing the data to be broadcase.  NOTE: this has to be
3135  *              allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
3136  *              the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
3137  *              case you are calling this function from callback context.
3138  * @len:        length of payload data in buf, starting from buf.
3139  *
3140  *      This function allows bulk sending of a packet to every connection using
3141  * the given protocol.  It does not send the data directly; instead it calls
3142  * the callback with a reason type of LWS_CALLBACK_BROADCAST.  If the callback
3143  * wants to actually send the data for that connection, the callback itself
3144  * should call libwebsocket_write().
3145  *
3146  * libwebsockets_broadcast() can be called from another fork context without
3147  * having to take any care about data visibility between the processes, it'll
3148  * "just work".
3149  */
3150
3151
3152 int
3153 libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
3154                                                  unsigned char *buf, size_t len)
3155 {
3156         struct libwebsocket_context *context = protocol->owning_server;
3157         int n;
3158         int m;
3159         struct libwebsocket *wsi;
3160
3161         if (!protocol->broadcast_socket_user_fd) {
3162                 /*
3163                  * We are either running unforked / flat, or we are being
3164                  * called from poll thread context
3165                  * eg, from a callback.  In that case don't use sockets for
3166                  * broadcast IPC (since we can't open a socket connection to
3167                  * a socket listening on our own thread) but directly do the
3168                  * send action.
3169                  *
3170                  * Locking is not needed because we are by definition being
3171                  * called in the poll thread context and are serialized.
3172                  */
3173
3174                 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
3175
3176                         for (m = 0; m < context->fd_hashtable[n].length; m++) {
3177
3178                                 wsi = context->fd_hashtable[n].wsi[m];
3179
3180                                 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
3181                                         continue;
3182
3183                                 /*
3184                                  * never broadcast to
3185                                  * non-established connections
3186                                  */
3187                                 if (wsi->state != WSI_STATE_ESTABLISHED)
3188                                         continue;
3189
3190                                 /* only broadcast to guys using
3191                                  * requested protocol
3192                                  */
3193                                 if (wsi->protocol != protocol)
3194                                         continue;
3195
3196                                 wsi->protocol->callback(context, wsi,
3197                                          LWS_CALLBACK_BROADCAST,
3198                                          wsi->user_space,
3199                                          buf, len);
3200                         }
3201                 }
3202
3203                 return 0;
3204         }
3205
3206         /*
3207          * We're being called from a different process context than the server
3208          * loop.  Instead of broadcasting directly, we send our
3209          * payload on a socket to do the IPC; the server process will serialize
3210          * the broadcast action in its main poll() loop.
3211          *
3212          * There's one broadcast socket listening for each protocol supported
3213          * set up when the websocket server initializes
3214          */
3215
3216         n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);
3217
3218         return n;
3219 }
3220
3221 int
3222 libwebsocket_is_final_fragment(struct libwebsocket *wsi)
3223 {
3224         return wsi->final;
3225 }
3226
3227 unsigned char
3228 libwebsocket_get_reserved_bits(struct libwebsocket *wsi)
3229 {
3230         return wsi->rsv;
3231 }
3232
3233 void *
3234 libwebsocket_ensure_user_space(struct libwebsocket *wsi)
3235 {
3236         /* allocate the per-connection user memory (if any) */
3237
3238         if (wsi->protocol->per_session_data_size && !wsi->user_space) {
3239                 wsi->user_space = malloc(
3240                                   wsi->protocol->per_session_data_size);
3241                 if (wsi->user_space  == NULL) {
3242                         fprintf(stderr, "Out of memory for "
3243                                                    "conn user space\n");
3244                         return NULL;
3245                 }
3246                 memset(wsi->user_space, 0,
3247                                          wsi->protocol->per_session_data_size);
3248         }
3249         return wsi->user_space;
3250 }