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