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