introduce struct libwebsocket_extension
[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
26 #else
27 #include <ifaddrs.h>
28 #endif
29
30 #ifdef LWS_OPENSSL_SUPPORT
31 int openssl_websocket_private_data_index;
32 #endif
33
34 /*
35  * In-place str to lower case
36  */
37
38 static void
39 strtolower(char *s)
40 {
41         while (*s) {
42                 *s = tolower(*s);
43                 s++;
44         }
45 }
46
47 /* file descriptor hash management */
48
49 struct libwebsocket *
50 wsi_from_fd(struct libwebsocket_context *context, int fd)
51 {
52         int h = LWS_FD_HASH(fd);
53         int n = 0;
54
55         for (n = 0; n < context->fd_hashtable[h].length; n++)
56                 if (context->fd_hashtable[h].wsi[n]->sock == fd)
57                         return context->fd_hashtable[h].wsi[n];
58
59         return NULL;
60 }
61
62 int
63 insert_wsi(struct libwebsocket_context *context, struct libwebsocket *wsi)
64 {
65         int h = LWS_FD_HASH(wsi->sock);
66
67         if (context->fd_hashtable[h].length == MAX_CLIENTS - 1) {
68                 fprintf(stderr, "hash table overflow\n");
69                 return 1;
70         }
71
72         context->fd_hashtable[h].wsi[context->fd_hashtable[h].length++] = wsi;
73
74         return 0;
75 }
76
77 int
78 delete_from_fd(struct libwebsocket_context *context, int fd)
79 {
80         int h = LWS_FD_HASH(fd);
81         int n = 0;
82
83         for (n = 0; n < context->fd_hashtable[h].length; n++)
84                 if (context->fd_hashtable[h].wsi[n]->sock == fd) {
85                         while (n < context->fd_hashtable[h].length) {
86                                 context->fd_hashtable[h].wsi[n] =
87                                             context->fd_hashtable[h].wsi[n + 1];
88                                 n++;
89                         }
90                         context->fd_hashtable[h].length--;
91
92                         return 0;
93                 }
94
95         fprintf(stderr, "Failed to find fd %d requested for "
96                                                    "delete in hashtable\n", fd);
97         return 1;
98 }
99
100 #ifdef LWS_OPENSSL_SUPPORT
101 static void
102 libwebsockets_decode_ssl_error(void)
103 {
104         char buf[256];
105         u_long err;
106
107         while ((err = ERR_get_error()) != 0) {
108                 ERR_error_string_n(err, buf, sizeof(buf));
109                 fprintf(stderr, "*** %s\n", buf);
110         }
111 }
112 #endif
113
114
115 static int
116 interface_to_sa(const char* ifname, struct sockaddr_in *addr, size_t addrlen)
117 {
118         int rc = -1;
119 #ifdef WIN32
120         // TODO
121 #else
122         struct ifaddrs *ifr;
123         struct ifaddrs *ifc;
124         struct sockaddr_in *sin;
125
126         getifaddrs(&ifr);
127         for (ifc = ifr; ifc != NULL; ifc = ifc->ifa_next) {
128                 if (strcmp(ifc->ifa_name, ifname))
129                         continue;
130                 if (ifc->ifa_addr == NULL)
131                         continue;
132                 sin = (struct sockaddr_in *)ifc->ifa_addr;
133                 if (sin->sin_family != AF_INET)
134                         continue;
135                 memcpy(addr, sin, addrlen);
136                 rc = 0; 
137         }
138
139         freeifaddrs(ifr);
140 #endif
141         return rc;
142 }
143
144 void
145 libwebsocket_close_and_free_session(struct libwebsocket_context *context,
146                          struct libwebsocket *wsi, enum lws_close_status reason)
147 {
148         int n;
149         int old_state;
150         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
151                                                   LWS_SEND_BUFFER_POST_PADDING];
152
153         if (!wsi)
154                 return;
155
156         old_state = wsi->state;
157
158         if (old_state == WSI_STATE_DEAD_SOCKET)
159                 return;
160
161         /* remove this fd from wsi mapping hashtable */
162
163         delete_from_fd(context, wsi->sock);
164
165         /* delete it from the internal poll list if still present */
166
167         for (n = 0; n < context->fds_count; n++) {
168                 if (context->fds[n].fd != wsi->sock)
169                         continue;
170                 while (n < context->fds_count - 1) {
171                         context->fds[n] = context->fds[n + 1];
172                         n++;
173                 }
174                 context->fds_count--;
175                 /* we only have to deal with one */
176                 n = context->fds_count;
177         }
178
179         /* remove also from external POLL support via protocol 0 */
180
181         context->protocols[0].callback(context, wsi,
182                     LWS_CALLBACK_DEL_POLL_FD, (void *)(long)wsi->sock, NULL, 0);
183
184         wsi->close_reason = reason;
185
186         /*
187          * signal we are closing, libsocket_write will
188          * add any necessary version-specific stuff.  If the write fails,
189          * no worries we are closing anyway.  If we didn't initiate this
190          * close, then our state has been changed to
191          * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this
192          */
193
194         if (old_state == WSI_STATE_ESTABLISHED)
195                 libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING], 0,
196                                                                LWS_WRITE_CLOSE);
197
198         wsi->state = WSI_STATE_DEAD_SOCKET;
199
200         /* tell the user it's all over for this guy */
201
202         if (wsi->protocol && wsi->protocol->callback &&
203                                              old_state == WSI_STATE_ESTABLISHED)
204                 wsi->protocol->callback(context, wsi, LWS_CALLBACK_CLOSED,
205                                                       wsi->user_space, NULL, 0);
206
207         /* free up his allocations */
208
209         for (n = 0; n < WSI_TOKEN_COUNT; n++)
210                 if (wsi->utf8_token[n].token)
211                         free(wsi->utf8_token[n].token);
212
213 /*      fprintf(stderr, "closing fd=%d\n", wsi->sock); */
214
215 #ifdef LWS_OPENSSL_SUPPORT
216         if (wsi->ssl) {
217                 n = SSL_get_fd(wsi->ssl);
218                 SSL_shutdown(wsi->ssl);
219 #ifdef WIN32
220                 closesocket(n);
221 #else
222                 close(n);
223 #endif
224                 SSL_free(wsi->ssl);
225         } else {
226 #endif
227                 shutdown(wsi->sock, SHUT_RDWR);
228 #ifdef WIN32
229                 closesocket(wsi->sock);
230 #else
231                 close(wsi->sock);
232 #endif
233 #ifdef LWS_OPENSSL_SUPPORT
234         }
235 #endif
236         if (wsi->user_space)
237                 free(wsi->user_space);
238
239         free(wsi);
240 }
241
242 /**
243  * libwebsockets_hangup_on_client() - Server calls to terminate client
244  *                                      connection
245  * @context:    libwebsockets context
246  * @fd:         Connection socket descriptor
247  */
248
249 void
250 libwebsockets_hangup_on_client(struct libwebsocket_context *context, int fd)
251 {
252         struct libwebsocket *wsi = wsi_from_fd(context, fd);
253
254         if (wsi == NULL)
255                 return;
256
257         libwebsocket_close_and_free_session(context, wsi,
258                                                      LWS_CLOSE_STATUS_NOSTATUS);
259 }
260
261
262 /**
263  * libwebsockets_get_peer_addresses() - Get client address information
264  * @fd:         Connection socket descriptor
265  * @name:       Buffer to take client address name
266  * @name_len:   Length of client address name buffer
267  * @rip:        Buffer to take client address IP qotted quad
268  * @rip_len:    Length of client address IP buffer
269  *
270  *      This function fills in @name and @rip with the name and IP of
271  *      the client connected with socket descriptor @fd.  Names may be
272  *      truncated if there is not enough room.  If either cannot be
273  *      determined, they will be returned as valid zero-length strings.
274  */
275
276 void
277 libwebsockets_get_peer_addresses(int fd, char *name, int name_len,
278                                         char *rip, int rip_len)
279 {
280         unsigned int len;
281         struct sockaddr_in sin;
282         struct hostent *host;
283         struct hostent *host1;
284         char ip[128];
285         char *p;
286         int n;
287
288         rip[0] = '\0';
289         name[0] = '\0';
290
291         len = sizeof sin;
292         if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
293                 perror("getpeername");
294                 return;
295         }
296                 
297         host = gethostbyaddr((char *) &sin.sin_addr, sizeof sin.sin_addr,
298                                                                        AF_INET);
299         if (host == NULL) {
300                 perror("gethostbyaddr");
301                 return;
302         }
303
304         strncpy(name, host->h_name, name_len);
305         name[name_len - 1] = '\0';
306
307         host1 = gethostbyname(host->h_name);
308         if (host1 == NULL)
309                 return;
310         p = (char *)host1;
311         n = 0;
312         while (p != NULL) {
313                 p = host1->h_addr_list[n++];
314                 if (p == NULL)
315                         continue;
316                 if (host1->h_addrtype != AF_INET)
317                         continue;
318
319                 sprintf(ip, "%d.%d.%d.%d",
320                                 p[0], p[1], p[2], p[3]);
321                 p = NULL;
322                 strncpy(rip, ip, rip_len);
323                 rip[rip_len - 1] = '\0';
324         }
325 }
326
327 int libwebsockets_get_random(struct libwebsocket_context *context,
328                                                              void *buf, int len)
329 {
330         int n;
331         char *p = buf;
332
333 #ifdef WIN32
334         for (n = 0; n < len; n++)
335                 p[n] = (unsigned char)rand();
336 #else
337         n = read(context->fd_random, p, len);
338 #endif
339
340         return n;
341 }
342
343 void libwebsockets_00_spaceout(char *key, int spaces, int seed)
344 {
345         char *p;
346         
347         key++;
348         while (spaces--) {
349                 if (*key && (seed & 1))
350                         key++;
351                 seed >>= 1;
352                 
353                 p = key + strlen(key);
354                 while (p >= key) {
355                         p[1] = p[0];
356                         p--;
357                 }
358                 *key++ = ' ';
359         }
360 }
361
362 void libwebsockets_00_spam(char *key, int count, int seed)
363 {
364         char *p;
365
366         key++;
367         while (count--) {
368                 
369                 if (*key && (seed & 1))
370                         key++;
371                 seed >>= 1;
372
373                 p = key + strlen(key);
374                 while (p >= key) {
375                         p[1] = p[0];
376                         p--;
377                 }
378                 *key++ = 0x21 + ((seed & 0xffff) % 15);
379                 /* 4 would use it up too fast.. not like it matters */
380                 seed >>= 1;
381         }
382 }
383
384 /**
385  * libwebsocket_service_fd() - Service polled socket with something waiting
386  * @context:    Websocket context
387  * @pollfd:     The pollfd entry describing the socket fd and which events
388  *              happened.
389  *
390  *      This function closes any active connections and then frees the
391  *      context.  After calling this, any further use of the context is
392  *      undefined.
393  */
394
395 int
396 libwebsocket_service_fd(struct libwebsocket_context *context,
397                                                           struct pollfd *pollfd)
398 {
399         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + MAX_BROADCAST_PAYLOAD +
400                                                   LWS_SEND_BUFFER_POST_PADDING];
401         struct libwebsocket *wsi;
402         struct libwebsocket *new_wsi;
403         int n;
404         int m;
405         size_t len;
406         int accept_fd;
407         unsigned int clilen;
408         struct sockaddr_in cli_addr;
409         struct timeval tv;
410         static const char magic_websocket_guid[] =
411                                          "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
412         static const char magic_websocket_04_masking_guid[] =
413                                          "61AC5F19-FBBA-4540-B96F-6561F1AB40A8";
414         char hash[20];
415         char pkt[1024];
416         char *p = &pkt[0];
417         const char *pc;
418         int okay = 0;
419 #ifdef LWS_OPENSSL_SUPPORT
420         char ssl_err_buf[512];
421 #endif
422         /*
423          * you can call us with pollfd = NULL to just allow the once-per-second
424          * global timeout checks; if less than a second since the last check
425          * it returns immediately then.
426          */
427
428         gettimeofday(&tv, NULL);
429
430         if (context->last_timeout_check_s != tv.tv_sec) {
431                 context->last_timeout_check_s = tv.tv_sec;
432
433                 /* global timeout check once per second */
434
435                 for (n = 0; n < context->fds_count; n++) {
436                         wsi = wsi_from_fd(context, context->fds[n].fd);
437                         if (!wsi->pending_timeout)
438                                 continue;
439
440                         /*
441                          * if we went beyond the allowed time, kill the
442                          * connection
443                          */
444
445                         if (tv.tv_sec > wsi->pending_timeout_limit)
446                                 libwebsocket_close_and_free_session(context,
447                                                 wsi, LWS_CLOSE_STATUS_NOSTATUS);
448                 }
449         }
450
451         /* just here for timeout management? */
452
453         if (pollfd == NULL)
454                 return 0;
455
456         /* no, here to service a socket descriptor */
457
458         wsi = wsi_from_fd(context, pollfd->fd);
459
460         if (wsi == NULL)
461                 return 1;
462
463         switch (wsi->mode) {
464         case LWS_CONNMODE_SERVER_LISTENER:
465
466                 /* pollin means a client has connected to us then */
467
468                 if (!pollfd->revents & POLLIN)
469                         break;
470
471                 /* listen socket got an unencrypted connection... */
472
473                 clilen = sizeof(cli_addr);
474                 accept_fd  = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
475                                                                        &clilen);
476                 if (accept_fd < 0) {
477                         fprintf(stderr, "ERROR on accept");
478                         break;
479                 }
480
481                 if (context->fds_count >= MAX_CLIENTS) {
482                         fprintf(stderr, "too busy to accept new client\n");
483 #ifdef WIN32
484                         closesocket(accept_fd);
485 #else
486                         close(accept_fd);
487 #endif
488                         break;
489                 }
490
491                 /*
492                  * look at who we connected to and give user code a chance
493                  * to reject based on client IP.  There's no protocol selected
494                  * yet so we issue this to protocols[0]
495                  */
496
497                 if ((context->protocols[0].callback)(context, wsi,
498                                 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
499                                              (void*)(long)accept_fd, NULL, 0)) {
500                         fprintf(stderr, "Callback denied network connection\n");
501 #ifdef WIN32
502                         closesocket(accept_fd);
503 #else
504                         close(accept_fd);
505 #endif
506                         break;
507                 }
508
509                 /* accepting connection to main listener */
510
511                 new_wsi = malloc(sizeof(struct libwebsocket));
512                 if (new_wsi == NULL) {
513                         fprintf(stderr, "Out of memory for new connection\n");
514                         break;
515                 }
516
517                 memset(new_wsi, 0, sizeof (struct libwebsocket));
518                 new_wsi->sock = accept_fd;
519                 new_wsi->count_active_extensions = 0;
520                 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
521
522 #ifdef LWS_OPENSSL_SUPPORT
523                 new_wsi->ssl = NULL;
524
525                 if (context->use_ssl) {
526
527                         new_wsi->ssl = SSL_new(context->ssl_ctx);
528                         if (new_wsi->ssl == NULL) {
529                                 fprintf(stderr, "SSL_new failed: %s\n",
530                                     ERR_error_string(SSL_get_error(
531                                     new_wsi->ssl, 0), NULL));
532                                     libwebsockets_decode_ssl_error();
533                                 free(new_wsi);
534                                 break;
535                         }
536
537                         SSL_set_fd(new_wsi->ssl, accept_fd);
538
539                         n = SSL_accept(new_wsi->ssl);
540                         if (n != 1) {
541                                 /*
542                                  * browsers seem to probe with various
543                                  * ssl params which fail then retry
544                                  * and succeed
545                                  */
546                                 debug("SSL_accept failed skt %u: %s\n",
547                                       pollfd->fd,
548                                       ERR_error_string(SSL_get_error(
549                                       new_wsi->ssl, n), NULL));
550                                 SSL_free(
551                                        new_wsi->ssl);
552                                 free(new_wsi);
553                                 break;
554                         }
555                         
556                         debug("accepted new SSL conn  "
557                               "port %u on fd=%d SSL ver %s\n",
558                                 ntohs(cli_addr.sin_port), accept_fd,
559                                   SSL_get_version(new_wsi->ssl));
560
561                 } else
562 #endif
563                         debug("accepted new conn  port %u on fd=%d\n",
564                                           ntohs(cli_addr.sin_port), accept_fd);
565
566                 /* intialize the instance struct */
567
568                 new_wsi->state = WSI_STATE_HTTP;
569                 new_wsi->name_buffer_pos = 0;
570                 new_wsi->mode = LWS_CONNMODE_WS_SERVING;
571
572                 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
573                         new_wsi->utf8_token[n].token = NULL;
574                         new_wsi->utf8_token[n].token_len = 0;
575                 }
576
577                 /*
578                  * these can only be set once the protocol is known
579                  * we set an unestablished connection's protocol pointer
580                  * to the start of the supported list, so it can look
581                  * for matching ones during the handshake
582                  */
583                 new_wsi->protocol = context->protocols;
584                 new_wsi->user_space = NULL;
585
586                 /*
587                  * Default protocol is 76 / 00
588                  * After 76, there's a header specified to inform which
589                  * draft the client wants, when that's seen we modify
590                  * the individual connection's spec revision accordingly
591                  */
592                 new_wsi->ietf_spec_revision = 0;
593
594                 insert_wsi(context, new_wsi);
595
596                 /*
597                  * make sure NO events are seen yet on this new socket
598                  * (otherwise we inherit old fds[client].revents from
599                  * previous socket there and die mysteriously! )
600                  */
601                 context->fds[context->fds_count].revents = 0;
602
603                 context->fds[context->fds_count].events = POLLIN;
604                 context->fds[context->fds_count++].fd = accept_fd;
605
606                 /* external POLL support via protocol 0 */
607                 context->protocols[0].callback(context, new_wsi,
608                         LWS_CALLBACK_ADD_POLL_FD,
609                         (void *)(long)accept_fd, NULL, POLLIN);
610
611                 break;
612
613         case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
614
615                 /* as we are listening, POLLIN means accept() is needed */
616         
617                 if (!pollfd->revents & POLLIN)
618                         break;
619
620                 /* listen socket got an unencrypted connection... */
621
622                 clilen = sizeof(cli_addr);
623                 accept_fd  = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
624                                                                        &clilen);
625                 if (accept_fd < 0) {
626                         fprintf(stderr, "ERROR on accept");
627                         break;
628                 }
629
630                 if (context->fds_count >= MAX_CLIENTS) {
631                         fprintf(stderr, "too busy to accept new broadcast "
632                                                               "proxy client\n");
633 #ifdef WIN32
634                         closesocket(accept_fd);
635 #else
636                         close(accept_fd);
637 #endif
638                         break;
639                 }
640
641                 /* create a dummy wsi for the connection and add it */
642
643                 new_wsi = malloc(sizeof(struct libwebsocket));
644                 memset(new_wsi, 0, sizeof (struct libwebsocket));
645                 new_wsi->sock = accept_fd;
646                 new_wsi->mode = LWS_CONNMODE_BROADCAST_PROXY;
647                 new_wsi->state = WSI_STATE_ESTABLISHED;
648                 new_wsi->count_active_extensions = 0;
649                 /* note which protocol we are proxying */
650                 new_wsi->protocol_index_for_broadcast_proxy =
651                                         wsi->protocol_index_for_broadcast_proxy;
652                 insert_wsi(context, new_wsi);
653
654                 /* add connected socket to internal poll array */
655
656                 context->fds[context->fds_count].revents = 0;
657                 context->fds[context->fds_count].events = POLLIN;
658                 context->fds[context->fds_count++].fd = accept_fd;
659
660                 /* external POLL support via protocol 0 */
661                 context->protocols[0].callback(context, new_wsi,
662                         LWS_CALLBACK_ADD_POLL_FD,
663                         (void *)(long)accept_fd, NULL, POLLIN);
664
665                 break;
666
667         case LWS_CONNMODE_BROADCAST_PROXY:
668
669                 /* handle session socket closed */
670
671                 if (pollfd->revents & (POLLERR | POLLHUP)) {
672
673                         debug("Session Socket %p (fd=%d) dead\n",
674                                 (void *)wsi, pollfd->fd);
675
676                         libwebsocket_close_and_free_session(context, wsi,
677                                                        LWS_CLOSE_STATUS_NORMAL);
678                         return 1;
679                 }
680
681                 /* the guy requested a callback when it was OK to write */
682
683                 if (pollfd->revents & POLLOUT) {
684
685                         /* one shot */
686
687                         pollfd->events &= ~POLLOUT;
688
689                         /* external POLL support via protocol 0 */
690                         context->protocols[0].callback(context, wsi,
691                                 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
692                                 (void *)(long)wsi->sock, NULL, POLLOUT);
693
694                         wsi->protocol->callback(context, wsi,
695                                 LWS_CALLBACK_CLIENT_WRITEABLE,
696                                 wsi->user_space,
697                                 NULL, 0);
698                 }
699
700                 /* any incoming data ready? */
701
702                 if (!(pollfd->revents & POLLIN))
703                         break;
704
705                 /* get the issued broadcast payload from the socket */
706
707                 len = read(pollfd->fd, buf + LWS_SEND_BUFFER_PRE_PADDING,
708                                                          MAX_BROADCAST_PAYLOAD);
709                 if (len < 0) {
710                         fprintf(stderr, "Error reading broadcast payload\n");
711                         break;
712                 }
713
714                 /* broadcast it to all guys with this protocol index */
715
716                 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
717
718                         for (m = 0; m < context->fd_hashtable[n].length; m++) {
719
720                                 new_wsi = context->fd_hashtable[n].wsi[m];
721
722                                 /* only to clients we are serving to */
723
724                                 if (new_wsi->mode != LWS_CONNMODE_WS_SERVING)
725                                         continue;
726
727                                 /*
728                                  * never broadcast to non-established
729                                  * connection
730                                  */
731
732                                 if (new_wsi->state != WSI_STATE_ESTABLISHED)
733                                         continue;
734
735                                 /*
736                                  * only broadcast to connections using
737                                  * the requested protocol
738                                  */
739
740                                 if (new_wsi->protocol->protocol_index !=
741                                         wsi->protocol_index_for_broadcast_proxy)
742                                         continue;
743
744                                 /* broadcast it to this connection */
745
746                                 new_wsi->protocol->callback(context, new_wsi,
747                                         LWS_CALLBACK_BROADCAST,
748                                         new_wsi->user_space,
749                                         buf + LWS_SEND_BUFFER_PRE_PADDING, len);
750                         }
751                 }
752                 break;
753
754         case LWS_CONNMODE_WS_CLIENT_WAITING_PROXY_REPLY:
755
756                 /* handle proxy hung up on us */
757
758                 if (pollfd->revents & (POLLERR | POLLHUP)) {
759
760                         fprintf(stderr, "Proxy connection %p (fd=%d) dead\n",
761                                 (void *)wsi, pollfd->fd);
762
763                         libwebsocket_close_and_free_session(context, wsi,
764                                                      LWS_CLOSE_STATUS_NOSTATUS);
765                         return 1;
766                 }
767
768                 n = recv(wsi->sock, pkt, sizeof pkt, 0);
769                 if (n < 0) {
770                         libwebsocket_close_and_free_session(context, wsi,
771                                                      LWS_CLOSE_STATUS_NOSTATUS);
772                         fprintf(stderr, "ERROR reading from proxy socket\n");
773                         return 1;
774                 }
775
776                 pkt[13] = '\0';
777                 if (strcmp(pkt, "HTTP/1.0 200 ") != 0) {
778                         libwebsocket_close_and_free_session(context, wsi,
779                                                      LWS_CLOSE_STATUS_NOSTATUS);
780                         fprintf(stderr, "ERROR from proxy: %s\n", pkt);
781                         return 1;
782                 }
783
784                 /* clear his proxy connection timeout */
785
786                 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
787
788                 /* fallthru */
789
790         case LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE:
791
792         #ifdef LWS_OPENSSL_SUPPORT
793                 if (wsi->use_ssl) {
794
795                         wsi->ssl = SSL_new(context->ssl_client_ctx);
796                         wsi->client_bio = BIO_new_socket(wsi->sock,
797                                                                    BIO_NOCLOSE);
798                         SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
799
800                         SSL_set_ex_data(wsi->ssl,
801                                         openssl_websocket_private_data_index,
802                                                                        context);
803
804                         if (SSL_connect(wsi->ssl) <= 0) {
805                                 fprintf(stderr, "SSL connect error %s\n",
806                                         ERR_error_string(ERR_get_error(),
807                                                                   ssl_err_buf));
808                                 libwebsocket_close_and_free_session(context, wsi,
809                                                      LWS_CLOSE_STATUS_NOSTATUS);
810                                 return 1;
811                         }
812
813                         n = SSL_get_verify_result(wsi->ssl);
814                         if ((n != X509_V_OK) && (
815                                 n != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
816                                                            wsi->use_ssl != 2)) {
817
818                                 fprintf(stderr, "server's cert didn't "
819                                                            "look good %d\n", n);
820                                 libwebsocket_close_and_free_session(context,
821                                                 wsi, LWS_CLOSE_STATUS_NOSTATUS);
822                                 return 1;
823                         }
824                 } else {
825                         wsi->ssl = NULL;
826         #endif
827
828
829         #ifdef LWS_OPENSSL_SUPPORT
830                 }
831         #endif
832
833                 /*
834                  * create the random key
835                  */
836
837                 n = libwebsockets_get_random(context, hash, 16);
838                 if (n != 16) {
839                         fprintf(stderr, "Unable to read from random dev %s\n",
840                                                         SYSTEM_RANDOM_FILEPATH);
841                         free(wsi->c_path);
842                         free(wsi->c_host);
843                         if (wsi->c_origin)
844                                 free(wsi->c_origin);
845                         if (wsi->c_protocol)
846                                 free(wsi->c_protocol);
847                         libwebsocket_close_and_free_session(context, wsi,
848                                                      LWS_CLOSE_STATUS_NOSTATUS);
849                         return 1;
850                 }
851
852                 lws_b64_encode_string(hash, 16, wsi->key_b64,
853                                                            sizeof wsi->key_b64);
854
855                 /*
856                  * 00 example client handshake
857                  *
858                  * GET /socket.io/websocket HTTP/1.1
859                  * Upgrade: WebSocket
860                  * Connection: Upgrade
861                  * Host: 127.0.0.1:9999
862                  * Origin: http://127.0.0.1
863                  * Sec-WebSocket-Key1: 1 0 2#0W 9 89 7  92 ^
864                  * Sec-WebSocket-Key2: 7 7Y 4328 B2v[8(z1
865                  * Cookie: socketio=websocket
866                  * 
867                  * (Á®Ä0¶†≥
868                  * 
869                  * 04 example client handshake
870                  *
871                  * GET /chat HTTP/1.1
872                  * Host: server.example.com
873                  * Upgrade: websocket
874                  * Connection: Upgrade
875                  * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
876                  * Sec-WebSocket-Origin: http://example.com
877                  * Sec-WebSocket-Protocol: chat, superchat
878                  * Sec-WebSocket-Version: 4
879                  */
880
881                 p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a", wsi->c_path);
882
883                 if (wsi->ietf_spec_revision == 0) {
884                         unsigned char spaces_1, spaces_2;
885                         unsigned int max_1, max_2;
886                         unsigned int num_1, num_2;
887                         unsigned long product_1, product_2;
888                         char key_1[40];
889                         char key_2[40];
890                         unsigned int seed;
891                         unsigned int count;
892                         char challenge[16];
893
894                         libwebsockets_get_random(context, &spaces_1,
895                                                                   sizeof(char));
896                         libwebsockets_get_random(context, &spaces_2,
897                                                                   sizeof(char));
898                         
899                         spaces_1 = (spaces_1 % 12) + 1;
900                         spaces_2 = (spaces_2 % 12) + 1;
901                         
902                         max_1 = 4294967295 / spaces_1;
903                         max_2 = 4294967295 / spaces_2;
904
905                         libwebsockets_get_random(context, &num_1, sizeof(int));
906                         libwebsockets_get_random(context, &num_2, sizeof(int));
907                         
908                         num_1 = (num_1 % max_1);
909                         num_2 = (num_2 % max_2);
910                         
911                         challenge[0] = num_1 >> 24;
912                         challenge[1] = num_1 >> 16;
913                         challenge[2] = num_1 >> 8;
914                         challenge[3] = num_1;
915                         challenge[4] = num_2 >> 24;
916                         challenge[5] = num_2 >> 16;
917                         challenge[6] = num_2 >> 8;
918                         challenge[7] = num_2;
919                         
920                         product_1 = num_1 * spaces_1;
921                         product_2 = num_2 * spaces_2;
922                         
923                         sprintf(key_1, "%lu", product_1);
924                         sprintf(key_2, "%lu", product_2);
925
926                         libwebsockets_get_random(context, &seed, sizeof(int));
927                         libwebsockets_get_random(context, &count, sizeof(int));
928                         
929                         libwebsockets_00_spam(key_1, (count % 12) + 1, seed);
930                         
931                         libwebsockets_get_random(context, &seed, sizeof(int));
932                         libwebsockets_get_random(context, &count, sizeof(int));
933                         
934                         libwebsockets_00_spam(key_2, (count % 12) + 1, seed);
935                         
936                         libwebsockets_get_random(context, &seed, sizeof(int));
937                         
938                         libwebsockets_00_spaceout(key_1, spaces_1, seed);
939                         libwebsockets_00_spaceout(key_2, spaces_2, seed >> 16);
940                         
941                         p += sprintf(p, "Upgrade: websocket\x0d\x0a"
942                                 "Connection: Upgrade\x0d\x0aHost: %s\x0d\x0a",
943                                 wsi->c_host);
944                         if (wsi->c_origin)
945                                 p += sprintf(p, "Origin: %s\x0d\x0a",
946                                 wsi->c_origin);
947                         
948                         if (wsi->c_protocol)
949                                 p += sprintf(p, "Sec-WebSocket-Protocol: %s"
950                                                  "\x0d\x0a", wsi->c_protocol);
951                         
952                         p += sprintf(p, "Sec-WebSocket-Key1: %s\x0d\x0a",
953                                 key_1);
954                         p += sprintf(p, "Sec-WebSocket-Key2: %s\x0d\x0a",
955                                 key_2);
956
957                         /* give userland a chance to append, eg, cookies */
958                         
959                         context->protocols[0].callback(context, wsi,
960                                 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
961                                         NULL, &p, (pkt + sizeof(pkt)) - p - 12);
962
963                         p += sprintf(p, "\x0d\x0a");
964                         
965                         read(context->fd_random, p, 8);
966                         memcpy(&challenge[8], p, 8);
967                         p += 8;
968                         
969                         /* precompute what we want to see from the server */
970                         
971                         MD5((unsigned char *)challenge, 16,
972                            (unsigned char *)wsi->initial_handshake_hash_base64);
973                         
974                         goto issue_hdr;
975                 }
976
977                 p += sprintf(p, "Host: %s\x0d\x0a", wsi->c_host);
978                 p += sprintf(p, "Upgrade: websocket\x0d\x0a");
979                 p += sprintf(p, "Connection: Upgrade\x0d\x0a"
980                                         "Sec-WebSocket-Key: ");
981                 strcpy(p, wsi->key_b64);
982                 p += strlen(wsi->key_b64);
983                 p += sprintf(p, "\x0d\x0a");
984                 if (wsi->c_origin)
985                         p += sprintf(p, "Sec-WebSocket-Origin: %s\x0d\x0a",
986                                                                  wsi->c_origin);
987                 if (wsi->c_protocol)
988                         p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
989                                                                wsi->c_protocol);
990                 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a",
991                         wsi->ietf_spec_revision); 
992                 /* give userland a chance to append, eg, cookies */
993                 
994                 context->protocols[0].callback(context, wsi,
995                         LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
996                         NULL, &p, (pkt + sizeof(pkt)) - p - 12);
997                 
998                 p += sprintf(p, "\x0d\x0a");
999
1000                 /* prepare the expected server accept response */
1001
1002                 strcpy((char *)buf, wsi->key_b64);
1003                 strcpy((char *)&buf[strlen((char *)buf)], magic_websocket_guid);
1004
1005                 SHA1(buf, strlen((char *)buf), (unsigned char *)hash);
1006
1007                 lws_b64_encode_string(hash, 20,
1008                                 wsi->initial_handshake_hash_base64,
1009                                      sizeof wsi->initial_handshake_hash_base64);
1010
1011 issue_hdr:
1012                 
1013                 /* done with these now */
1014                 
1015                 free(wsi->c_path);
1016                 free(wsi->c_host);
1017                 if (wsi->c_origin)
1018                         free(wsi->c_origin);
1019
1020                 /* send our request to the server */
1021
1022         #ifdef LWS_OPENSSL_SUPPORT
1023                 if (wsi->use_ssl)
1024                         n = SSL_write(wsi->ssl, pkt, p - pkt);
1025                 else
1026         #endif
1027                         n = send(wsi->sock, pkt, p - pkt, 0);
1028
1029                 if (n < 0) {
1030                         fprintf(stderr, "ERROR writing to client socket\n");
1031                         libwebsocket_close_and_free_session(context, wsi,
1032                                                      LWS_CLOSE_STATUS_NOSTATUS);
1033                         return 1;
1034                 }
1035
1036                 wsi->parser_state = WSI_TOKEN_NAME_PART;
1037                 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY;
1038                 libwebsocket_set_timeout(wsi,
1039                                 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, 5);
1040
1041                 break;
1042
1043         case LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY:
1044
1045                 /* handle server hung up on us */
1046
1047                 if (pollfd->revents & (POLLERR | POLLHUP)) {
1048
1049                         fprintf(stderr, "Server connection %p (fd=%d) dead\n",
1050                                 (void *)wsi, pollfd->fd);
1051
1052                         goto bail3;
1053                 }
1054
1055
1056                 /* interpret the server response */
1057
1058                 /*
1059                  *  HTTP/1.1 101 Switching Protocols
1060                  *  Upgrade: websocket
1061                  *  Connection: Upgrade
1062                  *  Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
1063                  *  Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
1064                  *  Sec-WebSocket-Protocol: chat
1065                  */
1066
1067         #ifdef LWS_OPENSSL_SUPPORT
1068                 if (wsi->use_ssl)
1069                         len = SSL_read(wsi->ssl, pkt, sizeof pkt);
1070                 else
1071         #endif
1072                         len = recv(wsi->sock, pkt, sizeof pkt, 0);
1073
1074                 if (len < 0) {
1075                         fprintf(stderr,
1076                                   "libwebsocket_client_handshake read error\n");
1077                         goto bail3;
1078                 }
1079
1080                 p = pkt;
1081                 for (n = 0; n < len; n++)
1082                         libwebsocket_parse(wsi, *p++);
1083
1084                 if (wsi->parser_state != WSI_PARSING_COMPLETE) {
1085                         fprintf(stderr, "libwebsocket_client_handshake "
1086                                         "server response failed parsing\n");
1087                         goto bail3;
1088                 }
1089
1090                 /*
1091                  * 00 / 76 -->
1092                  *
1093                  * HTTP/1.1 101 WebSocket Protocol Handshake
1094                  * Upgrade: WebSocket
1095                  * Connection: Upgrade
1096                  * Sec-WebSocket-Origin: http://127.0.0.1
1097                  * Sec-WebSocket-Location: ws://127.0.0.1:9999/socket.io/websocket
1098                  *
1099                  * xxxxxxxxxxxxxxxx
1100                  */
1101                 
1102                 if (wsi->ietf_spec_revision == 0) {
1103                         if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
1104                             !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
1105                             !wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len ||
1106                             !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
1107                             (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
1108                             wsi->c_protocol != NULL)) {
1109                                 fprintf(stderr, "libwebsocket_client_handshake "
1110                                                 "missing required header(s)\n");
1111                                 pkt[len] = '\0';
1112                                 fprintf(stderr, "%s", pkt);
1113                                 goto bail3;
1114                         }
1115                         
1116                         strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
1117                         if (strcmp(wsi->utf8_token[WSI_TOKEN_HTTP].token,
1118                                 "101 websocket protocol handshake")) {
1119                                 fprintf(stderr, "libwebsocket_client_handshake "
1120                                         "server sent bad HTTP response '%s'\n",
1121                                         wsi->utf8_token[WSI_TOKEN_HTTP].token);
1122                                 goto bail3;
1123                         }
1124                         
1125                         if (wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len <
1126                                                                            16) {
1127                                 fprintf(stderr, "libwebsocket_client_handshake "
1128                                         "challenge reply too short %d\n",
1129                                         wsi->utf8_token[
1130                                                 WSI_TOKEN_CHALLENGE].token_len);
1131                                 pkt[len] = '\0';
1132                                 fprintf(stderr, "%s", pkt);
1133                                 goto bail3;
1134                                 
1135                         }
1136                         
1137                         goto select_protocol;
1138                 }
1139                 
1140                 /*
1141                  * well, what the server sent looked reasonable for syntax.
1142                  * Now let's confirm it sent all the necessary headers
1143                  */
1144
1145                  if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
1146                         !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
1147                         !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
1148                         !wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len ||
1149                         (!wsi->utf8_token[WSI_TOKEN_NONCE].token_len &&
1150                                            wsi->ietf_spec_revision == 4) ||
1151                         (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
1152                                                      wsi->c_protocol != NULL)) {
1153                         fprintf(stderr, "libwebsocket_client_handshake "
1154                                                 "missing required header(s)\n");
1155                         pkt[len] = '\0';
1156                         fprintf(stderr, "%s", pkt);
1157                         goto bail3;
1158                 }
1159
1160                 /*
1161                  * Everything seems to be there, now take a closer look at what
1162                  * is in each header
1163                  */
1164
1165                 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
1166                 if (strcmp(wsi->utf8_token[WSI_TOKEN_HTTP].token,
1167                                                    "101 switching protocols")) {
1168                         fprintf(stderr, "libwebsocket_client_handshake "
1169                                         "server sent bad HTTP response '%s'\n",
1170                                          wsi->utf8_token[WSI_TOKEN_HTTP].token);
1171                         goto bail3;
1172                 }
1173
1174                 strtolower(wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
1175                 if (strcmp(wsi->utf8_token[WSI_TOKEN_UPGRADE].token,
1176                                                                  "websocket")) {
1177                         fprintf(stderr, "libwebsocket_client_handshake server "
1178                                         "sent bad Upgrade header '%s'\n",
1179                                       wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
1180                         goto bail3;
1181                 }
1182
1183                 strtolower(wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
1184                 if (strcmp(wsi->utf8_token[WSI_TOKEN_CONNECTION].token,
1185                                                                    "upgrade")) {
1186                         fprintf(stderr, "libwebsocket_client_handshake server "
1187                                         "sent bad Connection hdr '%s'\n",
1188                                    wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
1189                         goto bail3;
1190                 }
1191
1192 select_protocol:
1193                 pc = wsi->c_protocol;
1194
1195                 /*
1196                  * confirm the protocol the server wants to talk was in the list
1197                  * of protocols we offered
1198                  */
1199
1200                 if (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len) {
1201
1202                         /*
1203                          * no protocol name to work from,
1204                          * default to first protocol
1205                          */
1206                         wsi->protocol = &context->protocols[0];
1207
1208                         free(wsi->c_protocol);
1209
1210                         goto check_accept;
1211                 }
1212
1213                 while (*pc && !okay) {
1214                         if ((!strncmp(pc,
1215                                 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
1216                            wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len)) &&
1217                  (pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == ',' ||
1218                    pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == '\0')) {
1219                                 okay = 1;
1220                                 continue;
1221                         }
1222                         while (*pc && *pc != ',')
1223                                 pc++;
1224                         while (*pc && *pc != ' ')
1225                                 pc++;
1226                 }
1227
1228                 /* done with him now */
1229
1230                 if (wsi->c_protocol)
1231                         free(wsi->c_protocol);
1232
1233
1234                 if (!okay) {
1235                         fprintf(stderr, "libwebsocket_client_handshake server "
1236                                                 "sent bad protocol '%s'\n",
1237                                      wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
1238                         goto bail2;
1239                 }
1240
1241                 /*
1242                  * identify the selected protocol struct and set it
1243                  */
1244                 n = 0;
1245                 wsi->protocol = NULL;
1246                 while (context->protocols[n].callback) {
1247                         if (strcmp(wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
1248                                                context->protocols[n].name) == 0)
1249                                 wsi->protocol = &context->protocols[n];
1250                         n++;
1251                 }
1252
1253                 if (wsi->protocol == NULL) {
1254                         fprintf(stderr, "libwebsocket_client_handshake server "
1255                                         "requested protocol '%s', which we "
1256                                         "said we supported but we don't!\n",
1257                                      wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
1258                         goto bail2;
1259                 }
1260
1261         check_accept:
1262
1263                 if (wsi->ietf_spec_revision == 0) {
1264                         
1265                         if (memcmp(wsi->initial_handshake_hash_base64,
1266                               wsi->utf8_token[WSI_TOKEN_CHALLENGE].token, 16)) {
1267                                 fprintf(stderr, "libwebsocket_client_handshake "
1268                                                "failed 00 challenge compare\n");        
1269                                         pkt[len] = '\0';
1270                                         fprintf(stderr, "%s", pkt);
1271                                         goto bail2;
1272                         }
1273                         
1274                         goto accept_ok;
1275                 }
1276
1277                 /*
1278                  * Confirm his accept token is the one we precomputed
1279                  */
1280
1281                 if (strcmp(wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
1282                                           wsi->initial_handshake_hash_base64)) {
1283                         fprintf(stderr, "libwebsocket_client_handshake server "
1284                                 "sent bad ACCEPT '%s' vs computed '%s'\n",
1285                                 wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
1286                                             wsi->initial_handshake_hash_base64);
1287                         goto bail2;
1288                 }
1289
1290                 if (wsi->ietf_spec_revision == 4) {
1291                         /*
1292                          * Calculate the 04 masking key to use when
1293                          * sending data to server
1294                          */
1295
1296                         strcpy((char *)buf, wsi->key_b64);
1297                         p = (char *)buf + strlen(wsi->key_b64);
1298                         strcpy(p, wsi->utf8_token[WSI_TOKEN_NONCE].token);
1299                         p += wsi->utf8_token[WSI_TOKEN_NONCE].token_len;
1300                         strcpy(p, magic_websocket_04_masking_guid);
1301                         SHA1(buf, strlen((char *)buf), wsi->masking_key_04);
1302                 }
1303 accept_ok:
1304
1305                 /* allocate the per-connection user memory (if any) */
1306
1307                 if (wsi->protocol->per_session_data_size) {
1308                         wsi->user_space = malloc(
1309                                           wsi->protocol->per_session_data_size);
1310                         if (wsi->user_space  == NULL) {
1311                                 fprintf(stderr, "Out of memory for "
1312                                                            "conn user space\n");
1313                                 goto bail2;
1314                         }
1315                 } else
1316                         wsi->user_space = NULL;
1317
1318                 /* clear his proxy connection timeout */
1319
1320                 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1321
1322                 /* mark him as being alive */
1323
1324                 wsi->state = WSI_STATE_ESTABLISHED;
1325                 wsi->mode = LWS_CONNMODE_WS_CLIENT;
1326
1327                 fprintf(stderr, "handshake OK for protocol %s\n",
1328                                                            wsi->protocol->name);
1329
1330                 /* call him back to inform him he is up */
1331
1332                 wsi->protocol->callback(context, wsi,
1333                                  LWS_CALLBACK_CLIENT_ESTABLISHED,
1334                                  wsi->user_space,
1335                                  NULL, 0);
1336
1337                 break;
1338
1339 bail3:
1340                 if (wsi->c_protocol)
1341                         free(wsi->c_protocol);
1342
1343 bail2:
1344                 libwebsocket_close_and_free_session(context, wsi,
1345                                                      LWS_CLOSE_STATUS_NOSTATUS);
1346                 return 1;
1347                 
1348
1349         case LWS_CONNMODE_WS_SERVING:
1350         case LWS_CONNMODE_WS_CLIENT:
1351
1352                 /* handle session socket closed */
1353
1354                 if (pollfd->revents & (POLLERR | POLLHUP)) {
1355
1356                         fprintf(stderr, "Session Socket %p (fd=%d) dead\n",
1357                                 (void *)wsi, pollfd->fd);
1358
1359                         libwebsocket_close_and_free_session(context, wsi,
1360                                                      LWS_CLOSE_STATUS_NOSTATUS);
1361                         return 1;
1362                 }
1363
1364                 /* the guy requested a callback when it was OK to write */
1365
1366                 if (pollfd->revents & POLLOUT) {
1367
1368                         pollfd->events &= ~POLLOUT;
1369
1370                         /* external POLL support via protocol 0 */
1371                         context->protocols[0].callback(context, wsi,
1372                                 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1373                                 (void *)(long)wsi->sock, NULL, POLLOUT);
1374
1375                         wsi->protocol->callback(context, wsi,
1376                                 LWS_CALLBACK_CLIENT_WRITEABLE,
1377                                 wsi->user_space,
1378                                 NULL, 0);
1379                 }
1380
1381                 /* any incoming data ready? */
1382
1383                 if (!(pollfd->revents & POLLIN))
1384                         break;
1385
1386 #ifdef LWS_OPENSSL_SUPPORT
1387                 if (wsi->ssl)
1388                         n = SSL_read(wsi->ssl, buf, sizeof buf);
1389                 else
1390 #endif
1391                         n = recv(pollfd->fd, buf, sizeof buf, 0);
1392
1393                 if (n < 0) {
1394                         fprintf(stderr, "Socket read returned %d\n", n);
1395                         break;
1396                 }
1397                 if (!n) {
1398                         libwebsocket_close_and_free_session(context, wsi,
1399                                                      LWS_CLOSE_STATUS_NOSTATUS);
1400                         return 1;
1401                 }
1402
1403                 /* service incoming data */
1404
1405                 n = libwebsocket_read(context, wsi, buf, n);
1406                 if (n >= 0)
1407                         break;
1408
1409                 /* we closed wsi */
1410
1411                 return 1;
1412         }
1413
1414         return 0;
1415 }
1416
1417
1418 /**
1419  * libwebsocket_context_destroy() - Destroy the websocket context
1420  * @context:    Websocket context
1421  *
1422  *      This function closes any active connections and then frees the
1423  *      context.  After calling this, any further use of the context is
1424  *      undefined.
1425  */
1426 void
1427 libwebsocket_context_destroy(struct libwebsocket_context *context)
1428 {
1429         int n;
1430         int m;
1431         struct libwebsocket *wsi;
1432
1433         for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
1434                 for (m = 0; m < context->fd_hashtable[n].length; m++) {
1435                         wsi = context->fd_hashtable[n].wsi[m];
1436                         libwebsocket_close_and_free_session(context, wsi,
1437                                                     LWS_CLOSE_STATUS_GOINGAWAY);
1438                 }
1439
1440 #ifdef WIN32
1441 #else
1442         close(context->fd_random);
1443 #endif
1444
1445 #ifdef LWS_OPENSSL_SUPPORT
1446         if (context->ssl_ctx)
1447                 SSL_CTX_free(context->ssl_ctx);
1448         if (context->ssl_client_ctx)
1449                 SSL_CTX_free(context->ssl_client_ctx);
1450 #endif
1451
1452         free(context);
1453
1454 #ifdef WIN32
1455         WSACleanup();
1456 #endif
1457 }
1458
1459 /**
1460  * libwebsocket_service() - Service any pending websocket activity
1461  * @context:    Websocket context
1462  * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
1463  *              service otherwise block and service immediately, returning
1464  *              after the timeout if nothing needed service.
1465  *
1466  *      This function deals with any pending websocket traffic, for three
1467  *      kinds of event.  It handles these events on both server and client
1468  *      types of connection the same.
1469  *
1470  *      1) Accept new connections to our context's server
1471  *
1472  *      2) Perform pending broadcast writes initiated from other forked
1473  *         processes (effectively serializing asynchronous broadcasts)
1474  *
1475  *      3) Call the receive callback for incoming frame data received by
1476  *          server or client connections.
1477  *
1478  *      You need to call this service function periodically to all the above
1479  *      functions to happen; if your application is single-threaded you can
1480  *      just call it in your main event loop.
1481  *
1482  *      Alternatively you can fork a new process that asynchronously handles
1483  *      calling this service in a loop.  In that case you are happy if this
1484  *      call blocks your thread until it needs to take care of something and
1485  *      would call it with a large nonzero timeout.  Your loop then takes no
1486  *      CPU while there is nothing happening.
1487  *
1488  *      If you are calling it in a single-threaded app, you don't want it to
1489  *      wait around blocking other things in your loop from happening, so you
1490  *      would call it with a timeout_ms of 0, so it returns immediately if
1491  *      nothing is pending, or as soon as it services whatever was pending.
1492  */
1493
1494
1495 int
1496 libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
1497 {
1498         int n;
1499
1500         /* stay dead once we are dead */
1501
1502         if (context == NULL)
1503                 return 1;
1504
1505         /* wait for something to need service */
1506
1507         n = poll(context->fds, context->fds_count, timeout_ms);
1508         if (n == 0) /* poll timeout */
1509                 return 0;
1510
1511         if (n < 0) {
1512                 /*
1513                 fprintf(stderr, "Listen Socket dead\n");
1514                 */
1515                 return 1;
1516         }
1517
1518         /* handle accept on listening socket? */
1519
1520         for (n = 0; n < context->fds_count; n++)
1521                 if (context->fds[n].revents)
1522                         libwebsocket_service_fd(context, &context->fds[n]);
1523
1524         return 0;
1525 }
1526
1527 /**
1528  * libwebsocket_callback_on_writable() - Request a callback when this socket
1529  *                                       becomes able to be written to without
1530  *                                       blocking
1531  *
1532  * @context:    libwebsockets context
1533  * @wsi:        Websocket connection instance to get callback for
1534  */
1535
1536 int
1537 libwebsocket_callback_on_writable(struct libwebsocket_context *context,
1538                                                        struct libwebsocket *wsi)
1539 {
1540         int n;
1541
1542         for (n = 0; n < context->fds_count; n++)
1543                 if (context->fds[n].fd == wsi->sock) {
1544                         context->fds[n].events |= POLLOUT;
1545                         n = context->fds_count;
1546                 }
1547
1548         /* external POLL support via protocol 0 */
1549         context->protocols[0].callback(context, wsi,
1550                 LWS_CALLBACK_SET_MODE_POLL_FD,
1551                 (void *)(long)wsi->sock, NULL, POLLOUT);
1552
1553         return 1;
1554 }
1555
1556 /**
1557  * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
1558  *                      all connections using the given protocol when it
1559  *                      becomes possible to write to each socket without
1560  *                      blocking in turn.
1561  *
1562  * @protocol:   Protocol whose connections will get callbacks
1563  */
1564
1565 int
1566 libwebsocket_callback_on_writable_all_protocol(
1567                                   const struct libwebsocket_protocols *protocol)
1568 {
1569         struct libwebsocket_context *context = protocol->owning_server;
1570         int n;
1571         int m;
1572         struct libwebsocket *wsi;
1573
1574         for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
1575
1576                 for (m = 0; m < context->fd_hashtable[n].length; m++) {
1577
1578                         wsi = context->fd_hashtable[n].wsi[m];
1579
1580                         if (wsi->protocol == protocol)
1581                                 libwebsocket_callback_on_writable(context, wsi);
1582                 }
1583         }
1584
1585         return 0;
1586 }
1587
1588 /**
1589  * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
1590  *
1591  * You will not need this unless you are doing something special
1592  *
1593  * @wsi:        Websocket connection instance
1594  * @reason:     timeout reason
1595  * @secs:       how many seconds
1596  */
1597
1598 void
1599 libwebsocket_set_timeout(struct libwebsocket *wsi,
1600                                           enum pending_timeout reason, int secs)
1601 {
1602         struct timeval tv;
1603
1604         gettimeofday(&tv, NULL);
1605
1606         wsi->pending_timeout_limit = tv.tv_sec + secs;
1607         wsi->pending_timeout = reason;
1608 }
1609
1610
1611 /**
1612  * libwebsocket_get_socket_fd() - returns the socket file descriptor
1613  *
1614  * You will not need this unless you are doing something special
1615  *
1616  * @wsi:        Websocket connection instance
1617  */
1618
1619 int
1620 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
1621 {
1622         return wsi->sock;
1623 }
1624
1625 /**
1626  * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
1627  *                              receieved packets.
1628  *
1629  * If the output side of a server process becomes choked, this allows flow
1630  * control for the input side.
1631  *
1632  * @wsi:        Websocket connection instance to get callback for
1633  * @enable:     0 = disable read servicing for this connection, 1 = enable
1634  */
1635
1636 int
1637 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
1638 {
1639         struct libwebsocket_context *context = wsi->protocol->owning_server;
1640         int n;
1641
1642         for (n = 0; n < context->fds_count; n++)
1643                 if (context->fds[n].fd == wsi->sock) {
1644                         if (enable)
1645                                 context->fds[n].events |= POLLIN;
1646                         else
1647                                 context->fds[n].events &= ~POLLIN;
1648
1649                         return 0;
1650                 }
1651
1652         if (enable)
1653                 /* external POLL support via protocol 0 */
1654                 context->protocols[0].callback(context, wsi,
1655                         LWS_CALLBACK_SET_MODE_POLL_FD,
1656                         (void *)(long)wsi->sock, NULL, POLLIN);
1657         else
1658                 /* external POLL support via protocol 0 */
1659                 context->protocols[0].callback(context, wsi,
1660                         LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1661                         (void *)(long)wsi->sock, NULL, POLLIN);
1662
1663
1664         fprintf(stderr, "libwebsocket_callback_on_writable "
1665                                                      "unable to find socket\n");
1666         return 1;
1667 }
1668
1669 /**
1670  * libwebsocket_canonical_hostname() - returns this host's hostname
1671  *
1672  * This is typically used by client code to fill in the host parameter
1673  * when making a client connection.  You can only call it after the context
1674  * has been created.
1675  *
1676  * @context:    Websocket context
1677  */
1678
1679
1680 extern const char *
1681 libwebsocket_canonical_hostname(struct libwebsocket_context *context)
1682 {
1683         return (const char *)context->canonical_hostname;
1684 }
1685
1686
1687 static void sigpipe_handler(int x)
1688 {
1689 }
1690
1691 #ifdef LWS_OPENSSL_SUPPORT
1692 static int
1693 OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
1694 {
1695
1696         SSL *ssl;
1697         int n;
1698         struct libwebsocket_context *context;
1699
1700         ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1701                 SSL_get_ex_data_X509_STORE_CTX_idx());
1702
1703         /*
1704          * !!! nasty openssl requires the index to come as a library-scope
1705          * static
1706          */
1707         context = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
1708         
1709         n = context->protocols[0].callback(NULL, NULL,
1710                 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
1711                                                    x509_ctx, ssl, preverify_ok);
1712
1713         /* convert return code from 0 = OK to 1 = OK */
1714
1715         if (!n)
1716                 n = 1;
1717         else
1718                 n = 0;
1719
1720         return n;
1721 }
1722 #endif
1723
1724
1725 /**
1726  * libwebsocket_create_context() - Create the websocket handler
1727  * @port:       Port to listen on... you can use 0 to suppress listening on
1728  *              any port, that's what you want if you are not running a
1729  *              websocket server at all but just using it as a client
1730  * @interf:  NULL to bind the listen socket to all interfaces, or the
1731  *              interface name, eg, "eth2"
1732  * @protocols:  Array of structures listing supported protocols and a protocol-
1733  *              specific callback for each one.  The list is ended with an
1734  *              entry that has a NULL callback pointer.
1735  *              It's not const because we write the owning_server member
1736  * @ssl_cert_filepath:  If libwebsockets was compiled to use ssl, and you want
1737  *                      to listen using SSL, set to the filepath to fetch the
1738  *                      server cert from, otherwise NULL for unencrypted
1739  * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
1740  *                      else ignored
1741  * @gid:        group id to change to after setting listen socket, or -1.
1742  * @uid:        user id to change to after setting listen socket, or -1.
1743  * @options:    0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
1744  *
1745  *      This function creates the listening socket and takes care
1746  *      of all initialization in one step.
1747  *
1748  *      After initialization, it returns a struct libwebsocket_context * that
1749  *      represents this server.  After calling, user code needs to take care
1750  *      of calling libwebsocket_service() with the context pointer to get the
1751  *      server's sockets serviced.  This can be done in the same process context
1752  *      or a forked process, or another thread,
1753  *
1754  *      The protocol callback functions are called for a handful of events
1755  *      including http requests coming in, websocket connections becoming
1756  *      established, and data arriving; it's also called periodically to allow
1757  *      async transmission.
1758  *
1759  *      HTTP requests are sent always to the FIRST protocol in @protocol, since
1760  *      at that time websocket protocol has not been negotiated.  Other
1761  *      protocols after the first one never see any HTTP callack activity.
1762  *
1763  *      The server created is a simple http server by default; part of the
1764  *      websocket standard is upgrading this http connection to a websocket one.
1765  *
1766  *      This allows the same server to provide files like scripts and favicon /
1767  *      images or whatever over http and dynamic data over websockets all in
1768  *      one place; they're all handled in the user callback.
1769  */
1770
1771 struct libwebsocket_context *
1772 libwebsocket_create_context(int port, const char *interf,
1773                                struct libwebsocket_protocols *protocols,
1774                                struct libwebsocket_extension *extensions,
1775                                const char *ssl_cert_filepath,
1776                                const char *ssl_private_key_filepath,
1777                                int gid, int uid, unsigned int options)
1778 {
1779         int n;
1780         int sockfd = 0;
1781         int fd;
1782         struct sockaddr_in serv_addr, cli_addr;
1783         int opt = 1;
1784         struct libwebsocket_context *context = NULL;
1785         unsigned int slen;
1786         char *p;
1787         char hostname[1024];
1788         struct hostent *he;
1789         struct libwebsocket *wsi;
1790
1791 #ifdef LWS_OPENSSL_SUPPORT
1792         SSL_METHOD *method;
1793         char ssl_err_buf[512];
1794 #endif
1795
1796 #ifdef _WIN32
1797         {
1798                 WORD wVersionRequested;
1799                 WSADATA wsaData;
1800                 int err;
1801
1802                 /* Use the MAKEWORD(lowbyte, highbyte) macro from Windef.h */
1803                 wVersionRequested = MAKEWORD(2, 2);
1804
1805                 err = WSAStartup(wVersionRequested, &wsaData);
1806                 if (err != 0) {
1807                         /* Tell the user that we could not find a usable */
1808                         /* Winsock DLL.                                  */
1809                         fprintf(stderr, "WSAStartup failed with error: %d\n",
1810                                                                            err);
1811                         return NULL;
1812                 }
1813         }
1814 #endif
1815
1816
1817         context = malloc(sizeof(struct libwebsocket_context));
1818         if (!context) {
1819                 fprintf(stderr, "No memory for websocket context\n");
1820                 return NULL;
1821         }
1822         context->protocols = protocols;
1823         context->listen_port = port;
1824         context->http_proxy_port = 0;
1825         context->http_proxy_address[0] = '\0';
1826         context->options = options;
1827         context->fds_count = 0;
1828         context->extensions = extensions;
1829
1830 #ifdef WIN32
1831         context->fd_random = 0;
1832 #else
1833         context->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
1834         if (context->fd_random < 0) {
1835                 fprintf(stderr, "Unable to open random device %s %d\n",
1836                                     SYSTEM_RANDOM_FILEPATH, context->fd_random);
1837                 return NULL;
1838         }
1839 #endif
1840
1841 #ifdef LWS_OPENSSL_SUPPORT
1842         context->use_ssl = 0;
1843         context->ssl_ctx = NULL;
1844         context->ssl_client_ctx = NULL;
1845         openssl_websocket_private_data_index = 0;
1846 #endif
1847         /* find canonical hostname */
1848
1849         hostname[(sizeof hostname) - 1] = '\0';
1850         gethostname(hostname, (sizeof hostname) - 1);
1851         he = gethostbyname(hostname);
1852         if (he) {
1853                 strncpy(context->canonical_hostname, he->h_name,
1854                                         sizeof context->canonical_hostname - 1);
1855                 context->canonical_hostname[
1856                                 sizeof context->canonical_hostname - 1] = '\0';
1857         } else
1858                 strncpy(context->canonical_hostname, hostname,
1859                                         sizeof context->canonical_hostname - 1);
1860
1861         /* split the proxy ads:port if given */
1862
1863         p = getenv("http_proxy");
1864         if (p) {
1865                 strncpy(context->http_proxy_address, p,
1866                                         sizeof context->http_proxy_address - 1);
1867                 context->http_proxy_address[
1868                                  sizeof context->http_proxy_address - 1] = '\0';
1869
1870                 p = strchr(context->http_proxy_address, ':');
1871                 if (p == NULL) {
1872                         fprintf(stderr, "http_proxy needs to be ads:port\n");
1873                         return NULL;
1874                 }
1875                 *p = '\0';
1876                 context->http_proxy_port = atoi(p + 1);
1877
1878                 fprintf(stderr, "Using proxy %s:%u\n",
1879                                 context->http_proxy_address,
1880                                                       context->http_proxy_port);
1881         }
1882
1883         if (port) {
1884
1885 #ifdef LWS_OPENSSL_SUPPORT
1886                 context->use_ssl = ssl_cert_filepath != NULL &&
1887                                                ssl_private_key_filepath != NULL;
1888                 if (context->use_ssl)
1889                         fprintf(stderr, " Compiled with SSL support, "
1890                                                                   "using it\n");
1891                 else
1892                         fprintf(stderr, " Compiled with SSL support, "
1893                                                               "not using it\n");
1894
1895 #else
1896                 if (ssl_cert_filepath != NULL &&
1897                                              ssl_private_key_filepath != NULL) {
1898                         fprintf(stderr, " Not compiled for OpenSSl support!\n");
1899                         return NULL;
1900                 }
1901                 fprintf(stderr, " Compiled without SSL support, "
1902                                                        "serving unencrypted\n");
1903 #endif
1904         }
1905
1906         /* ignore SIGPIPE */
1907 #ifdef WIN32
1908 #else
1909         signal(SIGPIPE, sigpipe_handler);
1910 #endif
1911
1912
1913 #ifdef LWS_OPENSSL_SUPPORT
1914
1915         /* basic openssl init */
1916
1917         SSL_library_init();
1918
1919         OpenSSL_add_all_algorithms();
1920         SSL_load_error_strings();
1921
1922         openssl_websocket_private_data_index =
1923                 SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
1924
1925         /*
1926          * Firefox insists on SSLv23 not SSLv3
1927          * Konq disables SSLv2 by default now, SSLv23 works
1928          */
1929
1930         method = (SSL_METHOD *)SSLv23_server_method();
1931         if (!method) {
1932                 fprintf(stderr, "problem creating ssl method: %s\n",
1933                         ERR_error_string(ERR_get_error(), ssl_err_buf));
1934                 return NULL;
1935         }
1936         context->ssl_ctx = SSL_CTX_new(method); /* create context */
1937         if (!context->ssl_ctx) {
1938                 fprintf(stderr, "problem creating ssl context: %s\n",
1939                         ERR_error_string(ERR_get_error(), ssl_err_buf));
1940                 return NULL;
1941         }
1942
1943         /* client context */
1944         if (port == CONTEXT_PORT_NO_LISTEN)
1945         {
1946                 method = (SSL_METHOD *)SSLv23_client_method();
1947                 if (!method) {
1948                         fprintf(stderr, "problem creating ssl method: %s\n",
1949                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
1950                         return NULL;
1951                 }
1952                 /* create context */
1953                 context->ssl_client_ctx = SSL_CTX_new(method);
1954                 if (!context->ssl_client_ctx) {
1955                         fprintf(stderr, "problem creating ssl context: %s\n",
1956                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
1957                         return NULL;
1958                 }
1959
1960                 /* openssl init for cert verification (for client sockets) */
1961
1962                 if (!SSL_CTX_load_verify_locations(
1963                                         context->ssl_client_ctx, NULL,
1964                                                       LWS_OPENSSL_CLIENT_CERTS))
1965                         fprintf(stderr,
1966                             "Unable to load SSL Client certs from %s "
1967                             "(set by --with-client-cert-dir= in configure) -- "
1968                                 " client ssl isn't going to work",
1969                                                       LWS_OPENSSL_CLIENT_CERTS);
1970
1971                 /*
1972                  * callback allowing user code to load extra verification certs
1973                  * helping the client to verify server identity
1974                  */
1975
1976                 context->protocols[0].callback(context, NULL,
1977                         LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
1978                         context->ssl_client_ctx, NULL, 0);
1979         }
1980         /* as a server, are we requiring clients to identify themselves? */
1981
1982         if (options & LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
1983
1984                 /* absolutely require the client cert */
1985                 
1986                 SSL_CTX_set_verify(context->ssl_ctx,
1987                        SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1988                                                        OpenSSL_verify_callback);
1989
1990                 /*
1991                  * give user code a chance to load certs into the server
1992                  * allowing it to verify incoming client certs
1993                  */
1994
1995                 context->protocols[0].callback(context, NULL,
1996                         LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
1997                                                      context->ssl_ctx, NULL, 0);
1998         }
1999
2000         if (context->use_ssl) {
2001
2002                 /* openssl init for server sockets */
2003
2004                 /* set the local certificate from CertFile */
2005                 n = SSL_CTX_use_certificate_file(context->ssl_ctx,
2006                                         ssl_cert_filepath, SSL_FILETYPE_PEM);
2007                 if (n != 1) {
2008                         fprintf(stderr, "problem getting cert '%s': %s\n",
2009                                 ssl_cert_filepath,
2010                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
2011                         return NULL;
2012                 }
2013                 /* set the private key from KeyFile */
2014                 if (SSL_CTX_use_PrivateKey_file(context->ssl_ctx,
2015                              ssl_private_key_filepath, SSL_FILETYPE_PEM) != 1) {
2016                         fprintf(stderr, "ssl problem getting key '%s': %s\n",
2017                                                 ssl_private_key_filepath,
2018                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
2019                         return NULL;
2020                 }
2021                 /* verify private key */
2022                 if (!SSL_CTX_check_private_key(context->ssl_ctx)) {
2023                         fprintf(stderr, "Private SSL key doesn't match cert\n");
2024                         return NULL;
2025                 }
2026
2027                 /* SSL is happy and has a cert it's content with */
2028         }
2029 #endif
2030
2031         /* selftest */
2032
2033         if (lws_b64_selftest())
2034                 return NULL;
2035
2036         /* fd hashtable init */
2037
2038         for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
2039                 context->fd_hashtable[n].length = 0;
2040
2041         /* set up our external listening socket we serve on */
2042
2043         if (port) {
2044
2045                 sockfd = socket(AF_INET, SOCK_STREAM, 0);
2046                 if (sockfd < 0) {
2047                         fprintf(stderr, "ERROR opening socket");
2048                         return NULL;
2049                 }
2050
2051                 /* allow us to restart even if old sockets in TIME_WAIT */
2052                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
2053
2054                 bzero((char *) &serv_addr, sizeof(serv_addr));
2055                 serv_addr.sin_family = AF_INET;
2056                 if (interf == NULL)
2057                         serv_addr.sin_addr.s_addr = INADDR_ANY;
2058                 else
2059                         interface_to_sa(interf, &serv_addr,
2060                                                 sizeof(serv_addr));
2061                 serv_addr.sin_port = htons(port);
2062
2063                 n = bind(sockfd, (struct sockaddr *) &serv_addr,
2064                                                              sizeof(serv_addr));
2065                 if (n < 0) {
2066                         fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
2067                                                                 port, n, errno);
2068                         return NULL;
2069                 }
2070
2071                 wsi = malloc(sizeof(struct libwebsocket));
2072                 memset(wsi, 0, sizeof (struct libwebsocket));
2073                 wsi->sock = sockfd;
2074                 wsi->count_active_extensions = 0;
2075                 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
2076                 insert_wsi(context, wsi);
2077
2078                 listen(sockfd, 5);
2079                 fprintf(stderr, " Listening on port %d\n", port);
2080
2081                 /* list in the internal poll array */
2082                 
2083                 context->fds[context->fds_count].fd = sockfd;
2084                 context->fds[context->fds_count++].events = POLLIN;
2085
2086                 /* external POLL support via protocol 0 */
2087                 context->protocols[0].callback(context, wsi,
2088                         LWS_CALLBACK_ADD_POLL_FD,
2089                         (void *)(long)sockfd, NULL, POLLIN);
2090
2091         }
2092
2093         /* drop any root privs for this process */
2094 #ifdef WIN32
2095 #else
2096         if (gid != -1)
2097                 if (setgid(gid))
2098                         fprintf(stderr, "setgid: %s\n", strerror(errno));
2099         if (uid != -1)
2100                 if (setuid(uid))
2101                         fprintf(stderr, "setuid: %s\n", strerror(errno));
2102 #endif
2103
2104         /* set up our internal broadcast trigger sockets per-protocol */
2105
2106         for (context->count_protocols = 0;
2107                         protocols[context->count_protocols].callback;
2108                                                    context->count_protocols++) {
2109                 protocols[context->count_protocols].owning_server = context;
2110                 protocols[context->count_protocols].protocol_index =
2111                                                        context->count_protocols;
2112
2113                 fd = socket(AF_INET, SOCK_STREAM, 0);
2114                 if (fd < 0) {
2115                         fprintf(stderr, "ERROR opening socket");
2116                         return NULL;
2117                 }
2118
2119                 /* allow us to restart even if old sockets in TIME_WAIT */
2120                 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
2121
2122                 bzero((char *) &serv_addr, sizeof(serv_addr));
2123                 serv_addr.sin_family = AF_INET;
2124                 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2125                 serv_addr.sin_port = 0; /* pick the port for us */
2126
2127                 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
2128                 if (n < 0) {
2129                         fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
2130                                                                 port, n, errno);
2131                         return NULL;
2132                 }
2133
2134                 slen = sizeof cli_addr;
2135                 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
2136                 if (n < 0) {
2137                         fprintf(stderr, "getsockname failed\n");
2138                         return NULL;
2139                 }
2140                 protocols[context->count_protocols].broadcast_socket_port =
2141                                                        ntohs(cli_addr.sin_port);
2142                 listen(fd, 5);
2143
2144                 debug("  Protocol %s broadcast socket %d\n",
2145                                 protocols[context->count_protocols].name,
2146                                                       ntohs(cli_addr.sin_port));
2147
2148                 /* dummy wsi per broadcast proxy socket */
2149
2150                 wsi = malloc(sizeof(struct libwebsocket));
2151                 memset(wsi, 0, sizeof (struct libwebsocket));
2152                 wsi->sock = fd;
2153                 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
2154                 wsi->count_active_extensions = 0;
2155                 /* note which protocol we are proxying */
2156                 wsi->protocol_index_for_broadcast_proxy =
2157                                                        context->count_protocols;
2158                 insert_wsi(context, wsi);
2159
2160                 /* list in internal poll array */
2161
2162                 context->fds[context->fds_count].fd = fd;
2163                 context->fds[context->fds_count].events = POLLIN;
2164                 context->fds[context->fds_count].revents = 0;
2165                 context->fds_count++;
2166
2167                 /* external POLL support via protocol 0 */
2168                 context->protocols[0].callback(context, wsi,
2169                         LWS_CALLBACK_ADD_POLL_FD,
2170                         (void *)(long)fd, NULL, POLLIN);
2171         }
2172
2173         return context;
2174 }
2175
2176
2177 #ifndef LWS_NO_FORK
2178
2179 /**
2180  * libwebsockets_fork_service_loop() - Optional helper function forks off
2181  *                                a process for the websocket server loop.
2182  *                              You don't have to use this but if not, you
2183  *                              have to make sure you are calling
2184  *                              libwebsocket_service periodically to service
2185  *                              the websocket traffic
2186  * @context:    server context returned by creation function
2187  */
2188
2189 int
2190 libwebsockets_fork_service_loop(struct libwebsocket_context *context)
2191 {
2192         int fd;
2193         struct sockaddr_in cli_addr;
2194         int n;
2195         int p;
2196
2197         n = fork();
2198         if (n < 0)
2199                 return n;
2200
2201         if (!n) {
2202
2203                 /* main process context */
2204
2205                 /*
2206                  * set up the proxy sockets to allow broadcast from
2207                  * service process context
2208                  */
2209
2210                 for (p = 0; p < context->count_protocols; p++) {
2211                         fd = socket(AF_INET, SOCK_STREAM, 0);
2212                         if (fd < 0) {
2213                                 fprintf(stderr, "Unable to create socket\n");
2214                                 return -1;
2215                         }
2216                         cli_addr.sin_family = AF_INET;
2217                         cli_addr.sin_port = htons(
2218                              context->protocols[p].broadcast_socket_port);
2219                         cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2220                         n = connect(fd, (struct sockaddr *)&cli_addr,
2221                                                                sizeof cli_addr);
2222                         if (n < 0) {
2223                                 fprintf(stderr, "Unable to connect to "
2224                                                 "broadcast socket %d, %s\n",
2225                                                 n, strerror(errno));
2226                                 return -1;
2227                         }
2228
2229                         context->protocols[p].broadcast_socket_user_fd = fd;
2230                 }
2231
2232                 return 0;
2233         }
2234
2235         /* we want a SIGHUP when our parent goes down */
2236         prctl(PR_SET_PDEATHSIG, SIGHUP);
2237
2238         /* in this forked process, sit and service websocket connections */
2239
2240         while (1)
2241                 if (libwebsocket_service(context, 1000))
2242                         return -1;
2243
2244         return 0;
2245 }
2246
2247 #endif
2248
2249 /**
2250  * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
2251  *                                connection.
2252  * @wsi:        pointer to struct websocket you want to know the protocol of
2253  *
2254  *
2255  *      This is useful to get the protocol to broadcast back to from inside
2256  * the callback.
2257  */
2258
2259 const struct libwebsocket_protocols *
2260 libwebsockets_get_protocol(struct libwebsocket *wsi)
2261 {
2262         return wsi->protocol;
2263 }
2264
2265 /**
2266  * libwebsockets_broadcast() - Sends a buffer to the callback for all active
2267  *                                connections of the given protocol.
2268  * @protocol:   pointer to the protocol you will broadcast to all members of
2269  * @buf:  buffer containing the data to be broadcase.  NOTE: this has to be
2270  *              allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
2271  *              the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
2272  *              case you are calling this function from callback context.
2273  * @len:        length of payload data in buf, starting from buf.
2274  *
2275  *      This function allows bulk sending of a packet to every connection using
2276  * the given protocol.  It does not send the data directly; instead it calls
2277  * the callback with a reason type of LWS_CALLBACK_BROADCAST.  If the callback
2278  * wants to actually send the data for that connection, the callback itself
2279  * should call libwebsocket_write().
2280  *
2281  * libwebsockets_broadcast() can be called from another fork context without
2282  * having to take any care about data visibility between the processes, it'll
2283  * "just work".
2284  */
2285
2286
2287 int
2288 libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
2289                                                  unsigned char *buf, size_t len)
2290 {
2291         struct libwebsocket_context *context = protocol->owning_server;
2292         int n;
2293         int m;
2294         struct libwebsocket * wsi;
2295
2296         if (!protocol->broadcast_socket_user_fd) {
2297                 /*
2298                  * We are either running unforked / flat, or we are being
2299                  * called from poll thread context
2300                  * eg, from a callback.  In that case don't use sockets for
2301                  * broadcast IPC (since we can't open a socket connection to
2302                  * a socket listening on our own thread) but directly do the
2303                  * send action.
2304                  *
2305                  * Locking is not needed because we are by definition being
2306                  * called in the poll thread context and are serialized.
2307                  */
2308
2309                 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
2310
2311                         for (m = 0; m < context->fd_hashtable[n].length; m++) {
2312
2313                                 wsi = context->fd_hashtable[n].wsi[m];
2314
2315                                 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
2316                                         continue;
2317
2318                                 /*
2319                                  * never broadcast to
2320                                  * non-established connections
2321                                  */
2322                                 if (wsi->state != WSI_STATE_ESTABLISHED)
2323                                         continue;
2324
2325                                 /* only broadcast to guys using
2326                                  * requested protocol
2327                                  */
2328                                 if (wsi->protocol != protocol)
2329                                         continue;
2330
2331                                 wsi->protocol->callback(context, wsi,
2332                                          LWS_CALLBACK_BROADCAST,
2333                                          wsi->user_space,
2334                                          buf, len);
2335                         }
2336                 }
2337
2338                 return 0;
2339         }
2340
2341         /*
2342          * We're being called from a different process context than the server
2343          * loop.  Instead of broadcasting directly, we send our
2344          * payload on a socket to do the IPC; the server process will serialize
2345          * the broadcast action in its main poll() loop.
2346          *
2347          * There's one broadcast socket listening for each protocol supported
2348          * set up when the websocket server initializes
2349          */
2350
2351         n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);
2352
2353         return n;
2354 }