decouple-service-from-fd-array-index.patch
[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 /* file descriptor hash management */
25
26 struct libwebsocket *
27 wsi_from_fd(struct libwebsocket_context *this, int fd)
28 {
29         int h = LWS_FD_HASH(fd);
30         int n = 0;
31
32         for (n = 0; n < this->fd_hashtable[h].length; n++)
33                 if (this->fd_hashtable[h].wsi[n]->sock == fd)
34                         return this->fd_hashtable[h].wsi[n];
35
36         return NULL;
37 }
38
39 int
40 insert_wsi(struct libwebsocket_context *this, struct libwebsocket *wsi)
41 {
42         int h = LWS_FD_HASH(wsi->sock);
43
44         if (this->fd_hashtable[h].length == MAX_CLIENTS - 1) {
45                 fprintf(stderr, "hash table overflow\n");
46                 return 1;
47         }
48
49         this->fd_hashtable[h].wsi[this->fd_hashtable[h].length++] = wsi;
50
51         return 0;
52 }
53
54 int
55 delete_from_fd(struct libwebsocket_context *this, int fd)
56 {
57         int h = LWS_FD_HASH(fd);
58         int n = 0;
59
60         for (n = 0; n < this->fd_hashtable[h].length; n++)
61                 if (this->fd_hashtable[h].wsi[n]->sock == fd) {
62                         while (n < this->fd_hashtable[h].length) {
63                                 this->fd_hashtable[h].wsi[n] =
64                                                this->fd_hashtable[h].wsi[n + 1];
65                                 n++;
66                         }
67                         this->fd_hashtable[h].length--;
68
69                         return 0;
70                 }
71
72         fprintf(stderr, "Failed to find fd %d requested for "
73                                                    "delete in hashtable\n", fd);
74         return 1;
75 }
76
77
78 void
79 libwebsocket_close_and_free_session(struct libwebsocket *wsi)
80 {
81         int n;
82         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
83                                                   LWS_SEND_BUFFER_POST_PADDING];
84
85         if ((unsigned long)wsi < LWS_MAX_PROTOCOLS)
86                 return;
87
88         n = wsi->state;
89
90         if (n == WSI_STATE_DEAD_SOCKET)
91                 return;
92
93         /*
94          * signal we are closing, libsocket_write will
95          * add any necessary version-specific stuff.  If the write fails,
96          * no worries we are closing anyway.  If we didn't initiate this
97          * close, then our state has been changed to
98          * WSI_STATE_RETURNED_CLOSE_ALREADY and we can skip this
99          */
100
101         if (n == WSI_STATE_ESTABLISHED)
102                 libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING], 0,
103                                                                LWS_WRITE_CLOSE);
104
105         wsi->state = WSI_STATE_DEAD_SOCKET;
106
107         if (wsi->protocol->callback && n == WSI_STATE_ESTABLISHED)
108                 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
109                                                       wsi->user_space, NULL, 0);
110
111         for (n = 0; n < WSI_TOKEN_COUNT; n++)
112                 if (wsi->utf8_token[n].token)
113                         free(wsi->utf8_token[n].token);
114
115 /*      fprintf(stderr, "closing fd=%d\n", wsi->sock); */
116
117 #ifdef LWS_OPENSSL_SUPPORT
118         if (wsi->ssl) {
119                 n = SSL_get_fd(wsi->ssl);
120                 SSL_shutdown(wsi->ssl);
121                 close(n);
122                 SSL_free(wsi->ssl);
123         } else {
124 #endif
125                 shutdown(wsi->sock, SHUT_RDWR);
126                 close(wsi->sock);
127 #ifdef LWS_OPENSSL_SUPPORT
128         }
129 #endif
130         if (wsi->user_space)
131                 free(wsi->user_space);
132
133         free(wsi);
134 }
135
136 static int
137 libwebsocket_service_fd(struct libwebsocket_context *this,
138                                                           struct pollfd *pollfd)
139 {
140         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + MAX_BROADCAST_PAYLOAD +
141                                                   LWS_SEND_BUFFER_POST_PADDING];
142         struct libwebsocket *wsi = wsi_from_fd(this, pollfd->fd);
143         struct libwebsocket *new_wsi;
144         int n;
145         int m;
146         size_t len;
147         int accept_fd;
148         unsigned int clilen;
149         struct sockaddr_in cli_addr;
150
151         if (wsi == NULL)
152                 return 1;
153
154         switch (wsi->mode) {
155         case LWS_CONNMODE_SERVER_LISTENER:
156
157                 /* pollin means a client has connected to us then */
158
159                 if (!pollfd->revents & POLLIN)
160                         break;
161
162                 /* listen socket got an unencrypted connection... */
163
164                 clilen = sizeof(cli_addr);
165                 accept_fd  = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
166                                                                        &clilen);
167                 if (accept_fd < 0) {
168                         fprintf(stderr, "ERROR on accept");
169                         break;
170                 }
171
172                 if (this->fds_count >= MAX_CLIENTS) {
173                         fprintf(stderr, "too busy");
174                         close(accept_fd);
175                         break;
176                 }
177
178                 /* accepting connection to main listener */
179
180                 new_wsi = malloc(sizeof(struct libwebsocket));
181                 if (new_wsi == NULL) {
182                         fprintf(stderr, "Out of memory for new connection\n");
183                         break;
184                 }
185
186                 memset(new_wsi, 0, sizeof (struct libwebsocket));
187                 new_wsi->sock = accept_fd;
188
189 #ifdef LWS_OPENSSL_SUPPORT
190                 new_wsi->ssl = NULL;
191                 this->ssl_ctx = NULL;
192
193                 if (this->use_ssl) {
194
195                         new_wsi->ssl = SSL_new(this->ssl_ctx);
196                         if (new_wsi->ssl == NULL) {
197                                 fprintf(stderr, "SSL_new failed: %s\n",
198                                     ERR_error_string(SSL_get_error(
199                                     new_wsi->ssl, 0), NULL));
200                                 free(new_wsi);
201                                 break;
202                         }
203
204                         SSL_set_fd(new_wsi->ssl, accept_fd);
205
206                         n = SSL_accept(new_wsi->ssl);
207                         if (n != 1) {
208                                 /*
209                                  * browsers seem to probe with various
210                                  * ssl params which fail then retry
211                                  * and succeed
212                                  */
213                                 debug("SSL_accept failed skt %u: %s\n",
214                                       pollfd->fd,
215                                       ERR_error_string(SSL_get_error(
216                                       new_wsi->ssl, n), NULL));
217                                 SSL_free(
218                                        new_wsi->ssl);
219                                 free(new_wsi);
220                                 break;
221                         }
222                         debug("accepted new SSL conn  "
223                               "port %u on fd=%d SSL ver %s\n",
224                                 ntohs(cli_addr.sin_port), accept_fd,
225                                   SSL_get_version(new_wsi->ssl));
226
227                 } else
228 #endif
229                         debug("accepted new conn  port %u on fd=%d\n",
230                                           ntohs(cli_addr.sin_port), accept_fd);
231
232                 /* intialize the instance struct */
233
234                 new_wsi->state = WSI_STATE_HTTP;
235                 new_wsi->name_buffer_pos = 0;
236                 new_wsi->mode = LWS_CONNMODE_WS_SERVING;
237
238                 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
239                         new_wsi->utf8_token[n].token = NULL;
240                         new_wsi->utf8_token[n].token_len = 0;
241                 }
242
243                 /*
244                  * these can only be set once the protocol is known
245                  * we set an unestablished connection's protocol pointer
246                  * to the start of the supported list, so it can look
247                  * for matching ones during the handshake
248                  */
249                 new_wsi->protocol = this->protocols;
250                 new_wsi->user_space = NULL;
251
252                 /*
253                  * Default protocol is 76 / 00
254                  * After 76, there's a header specified to inform which
255                  * draft the client wants, when that's seen we modify
256                  * the individual connection's spec revision accordingly
257                  */
258                 new_wsi->ietf_spec_revision = 0;
259
260                 insert_wsi(this, new_wsi);
261
262
263                 /*
264                  * make sure NO events are seen yet on this new socket
265                  * (otherwise we inherit old fds[client].revents from
266                  * previous socket there and die mysteriously! )
267                  */
268                 this->fds[this->fds_count].revents = 0;
269
270                 this->fds[this->fds_count].events = POLLIN;
271                 this->fds[this->fds_count++].fd = accept_fd;
272
273                 break;
274
275         case LWS_CONNMODE_BROADCAST_PROXY_LISTENER:
276
277                 /* as we are listening, POLLIN means accept() is needed */
278         
279                 if (!pollfd->revents & POLLIN)
280                         break;
281
282                 /* listen socket got an unencrypted connection... */
283
284                 clilen = sizeof(cli_addr);
285                 accept_fd  = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
286                                                                        &clilen);
287                 if (accept_fd < 0) {
288                         fprintf(stderr, "ERROR on accept");
289                         break;
290                 }
291
292                 if (this->fds_count >= MAX_CLIENTS) {
293                         fprintf(stderr, "too busy");
294                         close(accept_fd);
295                         break;
296                 }
297
298                 /* create a dummy wsi for the connection and add it */
299
300                 new_wsi = malloc(sizeof(struct libwebsocket));
301                 memset(new_wsi, 0, sizeof (struct libwebsocket));
302                 new_wsi->sock = accept_fd;
303                 new_wsi->mode = LWS_CONNMODE_BROADCAST_PROXY;
304                 new_wsi->state = WSI_STATE_ESTABLISHED;
305                 /* note which protocol we are proxying */
306                 new_wsi->protocol_index_for_broadcast_proxy =
307                                         wsi->protocol_index_for_broadcast_proxy;
308                 insert_wsi(this, new_wsi);
309
310                 /* add connected socket to internal poll array */
311
312                 this->fds[this->fds_count].revents = 0;
313                 this->fds[this->fds_count].events = POLLIN;
314                 this->fds[this->fds_count++].fd = accept_fd;
315
316                 break;
317
318         case LWS_CONNMODE_BROADCAST_PROXY:
319
320                 /* handle session socket closed */
321
322                 if (pollfd->revents & (POLLERR | POLLHUP)) {
323
324                         debug("Session Socket %p (fd=%d) dead\n",
325                                 (void *)wsi, accept_fd);
326
327                         libwebsocket_close_and_free_session(wsi);
328                         goto nuke_this;
329                 }
330
331                 /* the guy requested a callback when it was OK to write */
332
333                 if (pollfd->revents & POLLOUT) {
334
335                         /* one shot */
336
337                         pollfd->events &= ~POLLOUT;
338
339                         wsi->protocol->callback(wsi,
340                                 LWS_CALLBACK_CLIENT_WRITEABLE,
341                                 wsi->user_space,
342                                 NULL, 0);
343                 }
344
345                 /* any incoming data ready? */
346
347                 if (!(pollfd->revents & POLLIN))
348                         break;
349
350                 /* get the issued broadcast payload from the socket */
351
352                 len = read(pollfd->fd, buf + LWS_SEND_BUFFER_PRE_PADDING,
353                                                          MAX_BROADCAST_PAYLOAD);
354                 if (len < 0) {
355                         fprintf(stderr, "Error reading broadcast payload\n");
356                         break;;
357                 }
358
359                 /* broadcast it to all guys with this protocol index */
360
361                 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
362
363                         for (m = 0; m < this->fd_hashtable[n].length; m++) {
364
365                                 new_wsi = this->fd_hashtable[n].wsi[m];
366
367                                 /* only to clients we are serving to */
368
369                                 if (new_wsi->mode != LWS_CONNMODE_WS_SERVING)
370                                         continue;
371
372                                 /*
373                                  * never broadcast to non-established
374                                  * connection
375                                  */
376
377                                 if (new_wsi->state != WSI_STATE_ESTABLISHED)
378                                         continue;
379
380                                 /*
381                                  * only broadcast to connections using
382                                  * the requested protocol
383                                  */
384
385                                 if (new_wsi->protocol->protocol_index !=
386                                         wsi->protocol_index_for_broadcast_proxy)
387                                         continue;
388
389                                 /* broadcast it to this connection */
390
391                                 new_wsi->protocol->callback(new_wsi,
392                                         LWS_CALLBACK_BROADCAST,
393                                         new_wsi->user_space,
394                                         buf + LWS_SEND_BUFFER_PRE_PADDING, len);
395                         }
396                 }
397                 break;
398
399         case LWS_CONNMODE_WS_SERVING:
400         case LWS_CONNMODE_WS_CLIENT:
401
402                 /* handle session socket closed */
403
404                 if (pollfd->revents & (POLLERR | POLLHUP)) {
405
406                         debug("Session Socket %p (fd=%d) dead\n",
407                                 (void *)wsi, pollfd->fd);
408
409                         libwebsocket_close_and_free_session(wsi);
410                         goto nuke_this;
411                 }
412
413                 /* the guy requested a callback when it was OK to write */
414
415                 if (pollfd->revents & POLLOUT) {
416
417                         pollfd->events &= ~POLLOUT;
418
419                         wsi->protocol->callback(wsi,
420                                 LWS_CALLBACK_CLIENT_WRITEABLE,
421                                 wsi->user_space,
422                                 NULL, 0);
423                 }
424
425                 /* any incoming data ready? */
426
427                 if (!(pollfd->revents & POLLIN))
428                         break;
429
430 #ifdef LWS_OPENSSL_SUPPORT
431                 if (wsi->ssl)
432                         n = SSL_read(wsi->ssl, buf, sizeof buf);
433                 else
434 #endif
435                         n = recv(pollfd->fd, buf, sizeof buf, 0);
436
437                 if (n < 0) {
438                         fprintf(stderr, "Socket read returned %d\n", n);
439                         break;;
440                 }
441                 if (!n) {
442                         libwebsocket_close_and_free_session(wsi);
443                         goto nuke_this;
444                 }
445
446                 /* service incoming data */
447
448                 n = libwebsocket_read(wsi, buf, n);
449                 if (n >= 0)
450                         break;;
451                 /*
452                  * it closed and nuked wsi[client], so remove the
453                  * socket handle and wsi from our service list
454                  */
455 nuke_this:
456
457                 debug("nuking wsi %p, fsd_count = %d\n",
458                                 (void *)wsi, this->fds_count - 1);
459
460                 delete_from_fd(this, pollfd->fd);
461
462                 this->fds_count--;
463                 for (n = 0; n < this->fds_count; n++)
464                         if (this->fds[n].fd == pollfd->fd) {
465                                 while (n < this->fds_count) {
466                                         this->fds[n] = this->fds[n + 1];
467                                         n++;
468                                 }
469                                 n = this->fds_count;
470                         }
471
472                 break;
473         }
474
475         return 0;
476 }
477
478
479 /**
480  * libwebsocket_context_destroy() - Destroy the websocket context
481  * @this:       Websocket context
482  *
483  *      This function closes any active connections and then frees the
484  *      context.  After calling this, any further use of the context is
485  *      undefined.
486  */
487 void
488 libwebsocket_context_destroy(struct libwebsocket_context *this)
489 {
490         int n;
491         int m;
492         struct libwebsocket *wsi;
493
494         for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
495
496                 for (m = 0; m < this->fd_hashtable[n].length; m++) {
497
498                         wsi = this->fd_hashtable[n].wsi[m];
499
500                         switch (wsi->mode) {
501                         case LWS_CONNMODE_WS_SERVING:
502                                 libwebsocket_close_and_free_session(wsi);
503                                 break;
504                         case LWS_CONNMODE_WS_CLIENT:
505                                 libwebsocket_client_close(wsi);
506                                 break;
507                         default:
508                                 break;
509                         }
510                 }
511         }
512
513         close(this->fd_random);
514
515 #ifdef LWS_OPENSSL_SUPPORT
516         if (this->ssl_ctx)
517                 SSL_CTX_free(this->ssl_ctx);
518         if (this->ssl_client_ctx)
519                 SSL_CTX_free(this->ssl_client_ctx);
520 #endif
521
522         free(this);
523 }
524
525 /**
526  * libwebsocket_service() - Service any pending websocket activity
527  * @this:       Websocket context
528  * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
529  *              service otherwise block and service immediately, returning
530  *              after the timeout if nothing needed service.
531  *
532  *      This function deals with any pending websocket traffic, for three
533  *      kinds of event.  It handles these events on both server and client
534  *      types of connection the same.
535  *
536  *      1) Accept new connections to our context's server
537  *
538  *      2) Perform pending broadcast writes initiated from other forked
539  *         processes (effectively serializing asynchronous broadcasts)
540  *
541  *      3) Call the receive callback for incoming frame data received by
542  *          server or client connections.
543  *
544  *      You need to call this service function periodically to all the above
545  *      functions to happen; if your application is single-threaded you can
546  *      just call it in your main event loop.
547  *
548  *      Alternatively you can fork a new process that asynchronously handles
549  *      calling this service in a loop.  In that case you are happy if this
550  *      call blocks your thread until it needs to take care of something and
551  *      would call it with a large nonzero timeout.  Your loop then takes no
552  *      CPU while there is nothing happening.
553  *
554  *      If you are calling it in a single-threaded app, you don't want it to
555  *      wait around blocking other things in your loop from happening, so you
556  *      would call it with a timeout_ms of 0, so it returns immediately if
557  *      nothing is pending, or as soon as it services whatever was pending.
558  */
559
560
561 int
562 libwebsocket_service(struct libwebsocket_context *this, int timeout_ms)
563 {
564         int n;
565
566         /* stay dead once we are dead */
567
568         if (this == NULL)
569                 return 1;
570
571         /* wait for something to need service */
572
573         n = poll(this->fds, this->fds_count, timeout_ms);
574
575         if (n < 0 || this->fds[0].revents & (POLLERR | POLLHUP)) {
576                 /*
577                 fprintf(stderr, "Listen Socket dead\n");
578                 */
579                 return 1;
580         }
581         if (n == 0) /* poll timeout */
582                 return 0;
583
584         /* handle accept on listening socket? */
585
586         for (n = 0; n < this->fds_count; n++)
587                 if (this->fds[n].revents)
588                         libwebsocket_service_fd(this, &this->fds[n]);
589
590         return 0;
591 }
592
593 /**
594  * libwebsocket_callback_on_writable() - Request a callback when this socket
595  *                                       becomes able to be written to without
596  *                                       blocking
597  *
598  * This only works for internal poll() management, (ie, calling the libwebsocket
599  * service loop, you will have to make your own arrangements if your poll()
600  * loop is managed externally.
601  *
602  * @wsi:        Websocket connection instance to get callback for
603  */
604
605 int
606 libwebsocket_callback_on_writable(struct libwebsocket *wsi)
607 {
608         struct libwebsocket_context *this = wsi->protocol->owning_server;
609         int n;
610
611         for (n = 0; n < this->fds_count; n++)
612                 if (this->fds[n].fd == wsi->sock) {
613                         this->fds[n].events |= POLLOUT;
614                         return 0;
615                 }
616
617         fprintf(stderr, "libwebsocket_callback_on_writable "
618                                                         "didn't find socket\n");
619         return 1;
620 }
621
622 /**
623  * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
624  *                      all connections using the given protocol when it
625  *                      becomes possible to write to each socket without
626  *                      blocking in turn.
627  *
628  * This only works for internal poll() management, (ie, calling the libwebsocket
629  * service loop, you will have to make your own arrangements if your poll()
630  * loop is managed externally.
631  *
632  * @protocol:   Protocol whose connections will get callbacks
633  */
634
635 int
636 libwebsocket_callback_on_writable_all_protocol(
637                                   const struct libwebsocket_protocols *protocol)
638 {
639         struct libwebsocket_context *this = protocol->owning_server;
640         int n;
641         int m;
642         struct libwebsocket *wsi;
643
644         for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
645
646                 for (m = 0; m < this->fd_hashtable[n].length; m++) {
647
648                         wsi = this->fd_hashtable[n].wsi[m];
649
650                         if (wsi->protocol == protocol)
651                                 libwebsocket_callback_on_writable(wsi);
652                 }
653         }
654
655         return 0;
656 }
657
658
659 /**
660  * libwebsocket_get_socket_fd() - returns the socket file descriptor
661  *
662  * You will not need this unless you are doing something special
663  *
664  * @wsi:        Websocket connection instance
665  */
666
667 int
668 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
669 {
670         return wsi->sock;
671 }
672
673 /**
674  * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
675  *                              receieved packets.
676  *
677  * If the output side of a server process becomes choked, this allows flow
678  * control for the input side.
679  *
680  * This only works for internal poll() management, (ie, calling the libwebsocket
681  * service loop, you will have to make your own arrangements if your poll()
682  * loop is managed externally.
683  *
684  * @wsi:        Websocket connection instance to get callback for
685  * @enable:     0 = disable read servicing for this connection, 1 = enable
686  */
687
688 int
689 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
690 {
691         struct libwebsocket_context *this = wsi->protocol->owning_server;
692         int n;
693
694         for (n = 0; n < this->fds_count; n++)
695                 if (this->fds[n].fd == wsi->sock) {
696                         if (enable)
697                                 this->fds[n].events |= POLLIN;
698                         else
699                                 this->fds[n].events &= ~POLLIN;
700
701                         return 0;
702                 }
703
704         fprintf(stderr, "libwebsocket_callback_on_writable "
705                                                      "unable to find socket\n");
706         return 1;
707 }
708
709 /**
710  * libwebsocket_canonical_hostname() - returns this host's hostname
711  *
712  * This is typically used by client code to fill in the host parameter
713  * when making a client connection.  You can only call it after the context
714  * has been created.
715  *
716  * @this:       Websocket context
717  */
718
719
720 extern const char *
721 libwebsocket_canonical_hostname(struct libwebsocket_context *this)
722 {
723         return (const char *)this->canonical_hostname;
724 }
725
726
727 static void sigpipe_handler(int x)
728 {
729 }
730
731
732
733 /**
734  * libwebsocket_create_context() - Create the websocket handler
735  * @port:       Port to listen on... you can use 0 to suppress listening on
736  *              any port, that's what you want if you are not running a
737  *              websocket server at all but just using it as a client
738  * @protocols:  Array of structures listing supported protocols and a protocol-
739  *              specific callback for each one.  The list is ended with an
740  *              entry that has a NULL callback pointer.
741  *              It's not const because we write the owning_server member
742  * @ssl_cert_filepath:  If libwebsockets was compiled to use ssl, and you want
743  *                      to listen using SSL, set to the filepath to fetch the
744  *                      server cert from, otherwise NULL for unencrypted
745  * @ssl_private_key_filepath: filepath to private key if wanting SSL mode,
746  *                      else ignored
747  * @gid:        group id to change to after setting listen socket, or -1.
748  * @uid:        user id to change to after setting listen socket, or -1.
749  * @options:    0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK
750  *
751  *      This function creates the listening socket and takes care
752  *      of all initialization in one step.
753  *
754  *      After initialization, it returns a struct libwebsocket_context * that
755  *      represents this server.  After calling, user code needs to take care
756  *      of calling libwebsocket_service() with the context pointer to get the
757  *      server's sockets serviced.  This can be done in the same process context
758  *      or a forked process, or another thread,
759  *
760  *      The protocol callback functions are called for a handful of events
761  *      including http requests coming in, websocket connections becoming
762  *      established, and data arriving; it's also called periodically to allow
763  *      async transmission.
764  *
765  *      HTTP requests are sent always to the FIRST protocol in @protocol, since
766  *      at that time websocket protocol has not been negotiated.  Other
767  *      protocols after the first one never see any HTTP callack activity.
768  *
769  *      The server created is a simple http server by default; part of the
770  *      websocket standard is upgrading this http connection to a websocket one.
771  *
772  *      This allows the same server to provide files like scripts and favicon /
773  *      images or whatever over http and dynamic data over websockets all in
774  *      one place; they're all handled in the user callback.
775  */
776
777 struct libwebsocket_context *
778 libwebsocket_create_context(int port,
779                                struct libwebsocket_protocols *protocols,
780                                const char *ssl_cert_filepath,
781                                const char *ssl_private_key_filepath,
782                                int gid, int uid, unsigned int options)
783 {
784         int n;
785         int sockfd = 0;
786         int fd;
787         struct sockaddr_in serv_addr, cli_addr;
788         int opt = 1;
789         struct libwebsocket_context *this = NULL;
790         unsigned int slen;
791         char *p;
792         char hostname[1024];
793         struct hostent *he;
794         struct libwebsocket *wsi;
795
796 #ifdef LWS_OPENSSL_SUPPORT
797         SSL_METHOD *method;
798         char ssl_err_buf[512];
799 #endif
800
801         this = malloc(sizeof(struct libwebsocket_context));
802         if (!this) {
803                 fprintf(stderr, "No memory for websocket context\n");
804                 return NULL;
805         }
806         this->protocols = protocols;
807         this->listen_port = port;
808         this->http_proxy_port = 0;
809         this->http_proxy_address[0] = '\0';
810         this->options = options;
811         this->fds_count = 0;
812
813         this->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
814         if (this->fd_random < 0) {
815                 fprintf(stderr, "Unable to open random device %s %d\n",
816                                        SYSTEM_RANDOM_FILEPATH, this->fd_random);
817                 return NULL;
818         }
819
820         /* find canonical hostname */
821
822         hostname[(sizeof hostname) - 1] = '\0';
823         gethostname(hostname, (sizeof hostname) - 1);
824         he = gethostbyname(hostname);
825         strncpy(this->canonical_hostname, he->h_name,
826                                            sizeof this->canonical_hostname - 1);
827         this->canonical_hostname[sizeof this->canonical_hostname - 1] = '\0';
828         fprintf(stderr, "  canonical hostname = '%s'\n",
829                                         this->canonical_hostname);
830
831         /* split the proxy ads:port if given */
832
833         p = getenv("http_proxy");
834         if (p) {
835                 strncpy(this->http_proxy_address, p,
836                                            sizeof this->http_proxy_address - 1);
837                 this->http_proxy_address[
838                                     sizeof this->http_proxy_address - 1] = '\0';
839
840                 p = strchr(this->http_proxy_address, ':');
841                 if (p == NULL) {
842                         fprintf(stderr, "http_proxy needs to be ads:port\n");
843                         return NULL;
844                 }
845                 *p = '\0';
846                 this->http_proxy_port = atoi(p + 1);
847
848                 fprintf(stderr, "Using proxy %s:%u\n",
849                                 this->http_proxy_address,
850                                                         this->http_proxy_port);
851         }
852
853         if (port) {
854
855 #ifdef LWS_OPENSSL_SUPPORT
856                 this->use_ssl = ssl_cert_filepath != NULL &&
857                                                ssl_private_key_filepath != NULL;
858                 if (this->use_ssl)
859                         fprintf(stderr, " Compiled with SSL support, "
860                                                                   "using it\n");
861                 else
862                         fprintf(stderr, " Compiled with SSL support, "
863                                                               "not using it\n");
864
865 #else
866                 if (ssl_cert_filepath != NULL &&
867                                              ssl_private_key_filepath != NULL) {
868                         fprintf(stderr, " Not compiled for OpenSSl support!\n");
869                         return NULL;
870                 }
871                 fprintf(stderr, " Compiled without SSL support, "
872                                                        "serving unencrypted\n");
873 #endif
874         }
875
876         /* ignore SIGPIPE */
877
878         signal(SIGPIPE, sigpipe_handler);
879
880
881 #ifdef LWS_OPENSSL_SUPPORT
882
883         /* basic openssl init */
884
885         SSL_library_init();
886
887         OpenSSL_add_all_algorithms();
888         SSL_load_error_strings();
889
890         /*
891          * Firefox insists on SSLv23 not SSLv3
892          * Konq disables SSLv2 by default now, SSLv23 works
893          */
894
895         method = (SSL_METHOD *)SSLv23_server_method();
896         if (!method) {
897                 fprintf(stderr, "problem creating ssl method: %s\n",
898                         ERR_error_string(ERR_get_error(), ssl_err_buf));
899                 return NULL;
900         }
901         this->ssl_ctx = SSL_CTX_new(method);    /* create context */
902         if (!this->ssl_ctx) {
903                 fprintf(stderr, "problem creating ssl context: %s\n",
904                         ERR_error_string(ERR_get_error(), ssl_err_buf));
905                 return NULL;
906         }
907
908         /* client context */
909
910         method = (SSL_METHOD *)SSLv23_client_method();
911         if (!method) {
912                 fprintf(stderr, "problem creating ssl method: %s\n",
913                         ERR_error_string(ERR_get_error(), ssl_err_buf));
914                 return NULL;
915         }
916         this->ssl_client_ctx = SSL_CTX_new(method);     /* create context */
917         if (!this->ssl_client_ctx) {
918                 fprintf(stderr, "problem creating ssl context: %s\n",
919                         ERR_error_string(ERR_get_error(), ssl_err_buf));
920                 return NULL;
921         }
922
923
924         /* openssl init for cert verification (used with client sockets) */
925
926         if (!SSL_CTX_load_verify_locations(this->ssl_client_ctx, NULL,
927                                                     LWS_OPENSSL_CLIENT_CERTS)) {
928                 fprintf(stderr, "Unable to load SSL Client certs from %s "
929                         "(set by --with-client-cert-dir= in configure) -- "
930                         " client ssl isn't going to work",
931                                                       LWS_OPENSSL_CLIENT_CERTS);
932         }
933
934         if (this->use_ssl) {
935
936                 /* openssl init for server sockets */
937
938                 /* set the local certificate from CertFile */
939                 n = SSL_CTX_use_certificate_file(this->ssl_ctx,
940                                         ssl_cert_filepath, SSL_FILETYPE_PEM);
941                 if (n != 1) {
942                         fprintf(stderr, "problem getting cert '%s': %s\n",
943                                 ssl_cert_filepath,
944                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
945                         return NULL;
946                 }
947                 /* set the private key from KeyFile */
948                 if (SSL_CTX_use_PrivateKey_file(this->ssl_ctx,
949                                                 ssl_private_key_filepath,
950                                                        SSL_FILETYPE_PEM) != 1) {
951                         fprintf(stderr, "ssl problem getting key '%s': %s\n",
952                                                 ssl_private_key_filepath,
953                                 ERR_error_string(ERR_get_error(), ssl_err_buf));
954                         return NULL;
955                 }
956                 /* verify private key */
957                 if (!SSL_CTX_check_private_key(this->ssl_ctx)) {
958                         fprintf(stderr, "Private SSL key doesn't match cert\n");
959                         return NULL;
960                 }
961
962                 /* SSL is happy and has a cert it's content with */
963         }
964 #endif
965
966         /* selftest */
967
968         if (lws_b64_selftest())
969                 return NULL;
970
971         /* fd hashtable init */
972
973         for (n = 0; n < FD_HASHTABLE_MODULUS; n++)
974                 this->fd_hashtable[n].length = 0;
975
976         /* set up our external listening socket we serve on */
977
978         if (port) {
979
980                 sockfd = socket(AF_INET, SOCK_STREAM, 0);
981                 if (sockfd < 0) {
982                         fprintf(stderr, "ERROR opening socket");
983                         return NULL;
984                 }
985
986                 /* allow us to restart even if old sockets in TIME_WAIT */
987                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
988
989                 bzero((char *) &serv_addr, sizeof(serv_addr));
990                 serv_addr.sin_family = AF_INET;
991                 serv_addr.sin_addr.s_addr = INADDR_ANY;
992                 serv_addr.sin_port = htons(port);
993
994                 n = bind(sockfd, (struct sockaddr *) &serv_addr,
995                                                              sizeof(serv_addr));
996                 if (n < 0) {
997                         fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
998                                                                 port, n, errno);
999                         return NULL;
1000                 }
1001
1002                 wsi = malloc(sizeof(struct libwebsocket));
1003                 memset(wsi, 0, sizeof (struct libwebsocket));
1004                 wsi->sock = sockfd;
1005                 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
1006                 insert_wsi(this, wsi);
1007
1008                 listen(sockfd, 5);
1009                 fprintf(stderr, " Listening on port %d\n", port);
1010
1011                 /* list in the internal poll array */
1012                 
1013                 this->fds[this->fds_count].fd = sockfd;
1014                 this->fds[this->fds_count++].events = POLLIN;
1015         }
1016
1017         /* drop any root privs for this process */
1018
1019         if (gid != -1)
1020                 if (setgid(gid))
1021                         fprintf(stderr, "setgid: %s\n", strerror(errno));
1022         if (uid != -1)
1023                 if (setuid(uid))
1024                         fprintf(stderr, "setuid: %s\n", strerror(errno));
1025
1026
1027         /* set up our internal broadcast trigger sockets per-protocol */
1028
1029         for (this->count_protocols = 0;
1030                         protocols[this->count_protocols].callback;
1031                                                       this->count_protocols++) {
1032                 protocols[this->count_protocols].owning_server = this;
1033                 protocols[this->count_protocols].protocol_index =
1034                                                           this->count_protocols;
1035
1036                 fd = socket(AF_INET, SOCK_STREAM, 0);
1037                 if (fd < 0) {
1038                         fprintf(stderr, "ERROR opening socket");
1039                         return NULL;
1040                 }
1041
1042                 /* allow us to restart even if old sockets in TIME_WAIT */
1043                 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
1044
1045                 bzero((char *) &serv_addr, sizeof(serv_addr));
1046                 serv_addr.sin_family = AF_INET;
1047                 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1048                 serv_addr.sin_port = 0; /* pick the port for us */
1049
1050                 n = bind(fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
1051                 if (n < 0) {
1052                         fprintf(stderr, "ERROR on binding to port %d (%d %d)\n",
1053                                                                 port, n, errno);
1054                         return NULL;
1055                 }
1056
1057                 slen = sizeof cli_addr;
1058                 n = getsockname(fd, (struct sockaddr *)&cli_addr, &slen);
1059                 if (n < 0) {
1060                         fprintf(stderr, "getsockname failed\n");
1061                         return NULL;
1062                 }
1063                 protocols[this->count_protocols].broadcast_socket_port =
1064                                                        ntohs(cli_addr.sin_port);
1065                 listen(fd, 5);
1066
1067                 debug("  Protocol %s broadcast socket %d\n",
1068                                 protocols[this->count_protocols].name,
1069                                                       ntohs(cli_addr.sin_port));
1070
1071                 /* dummy wsi per broadcast proxy socket */
1072
1073                 wsi = malloc(sizeof(struct libwebsocket));
1074                 memset(wsi, 0, sizeof (struct libwebsocket));
1075                 wsi->sock = fd;
1076                 wsi->mode = LWS_CONNMODE_BROADCAST_PROXY_LISTENER;
1077                 /* note which protocol we are proxying */
1078                 wsi->protocol_index_for_broadcast_proxy = this->count_protocols;
1079                 insert_wsi(this, wsi);
1080
1081                 /* list in internal poll array */
1082
1083                 this->fds[this->fds_count].fd = fd;
1084                 this->fds[this->fds_count].events = POLLIN;
1085                 this->fds_count++;
1086         }
1087
1088         return this;
1089 }
1090
1091
1092 #ifndef LWS_NO_FORK
1093
1094 /**
1095  * libwebsockets_fork_service_loop() - Optional helper function forks off
1096  *                                a process for the websocket server loop.
1097  *                              You don't have to use this but if not, you
1098  *                              have to make sure you are calling
1099  *                              libwebsocket_service periodically to service
1100  *                              the websocket traffic
1101  * @this:       server context returned by creation function
1102  */
1103
1104 int
1105 libwebsockets_fork_service_loop(struct libwebsocket_context *this)
1106 {
1107         int client;
1108         int fd;
1109         struct sockaddr_in cli_addr;
1110         int n;
1111
1112         n = fork();
1113         if (n < 0)
1114                 return n;
1115
1116         if (!n) {
1117
1118                 /* main process context */
1119
1120                 for (client = 1; client < this->count_protocols + 1; client++) {
1121                         fd = socket(AF_INET, SOCK_STREAM, 0);
1122                         if (fd < 0) {
1123                                 fprintf(stderr, "Unable to create socket\n");
1124                                 return -1;
1125                         }
1126                         cli_addr.sin_family = AF_INET;
1127                         cli_addr.sin_port = htons(
1128                              this->protocols[client - 1].broadcast_socket_port);
1129                         cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1130                         n = connect(fd, (struct sockaddr *)&cli_addr,
1131                                                                sizeof cli_addr);
1132                         if (n < 0) {
1133                                 fprintf(stderr, "Unable to connect to "
1134                                                 "broadcast socket %d, %s\n",
1135                                                 client, strerror(errno));
1136                                 return -1;
1137                         }
1138
1139                         this->protocols[client - 1].broadcast_socket_user_fd =
1140                                                                              fd;
1141                 }
1142
1143
1144                 return 0;
1145         }
1146
1147         /* we want a SIGHUP when our parent goes down */
1148         prctl(PR_SET_PDEATHSIG, SIGHUP);
1149
1150         /* in this forked process, sit and service websocket connections */
1151
1152         while (1)
1153                 if (libwebsocket_service(this, 1000))
1154                         return -1;
1155
1156         return 0;
1157 }
1158
1159 #endif
1160
1161 /**
1162  * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
1163  *                                connection.
1164  * @wsi:        pointer to struct websocket you want to know the protocol of
1165  *
1166  *
1167  *      This is useful to get the protocol to broadcast back to from inside
1168  * the callback.
1169  */
1170
1171 const struct libwebsocket_protocols *
1172 libwebsockets_get_protocol(struct libwebsocket *wsi)
1173 {
1174         return wsi->protocol;
1175 }
1176
1177 /**
1178  * libwebsockets_broadcast() - Sends a buffer to the callback for all active
1179  *                                connections of the given protocol.
1180  * @protocol:   pointer to the protocol you will broadcast to all members of
1181  * @buf:  buffer containing the data to be broadcase.  NOTE: this has to be
1182  *              allocated with LWS_SEND_BUFFER_PRE_PADDING valid bytes before
1183  *              the pointer and LWS_SEND_BUFFER_POST_PADDING afterwards in the
1184  *              case you are calling this function from callback context.
1185  * @len:        length of payload data in buf, starting from buf.
1186  *
1187  *      This function allows bulk sending of a packet to every connection using
1188  * the given protocol.  It does not send the data directly; instead it calls
1189  * the callback with a reason type of LWS_CALLBACK_BROADCAST.  If the callback
1190  * wants to actually send the data for that connection, the callback itself
1191  * should call libwebsocket_write().
1192  *
1193  * libwebsockets_broadcast() can be called from another fork context without
1194  * having to take any care about data visibility between the processes, it'll
1195  * "just work".
1196  */
1197
1198
1199 int
1200 libwebsockets_broadcast(const struct libwebsocket_protocols *protocol,
1201                                                  unsigned char *buf, size_t len)
1202 {
1203         struct libwebsocket_context *this = protocol->owning_server;
1204         int n;
1205         int m;
1206         struct libwebsocket * wsi;
1207
1208         if (!protocol->broadcast_socket_user_fd) {
1209                 /*
1210                  * We are either running unforked / flat, or we are being
1211                  * called from poll thread context
1212                  * eg, from a callback.  In that case don't use sockets for
1213                  * broadcast IPC (since we can't open a socket connection to
1214                  * a socket listening on our own thread) but directly do the
1215                  * send action.
1216                  *
1217                  * Locking is not needed because we are by definition being
1218                  * called in the poll thread context and are serialized.
1219                  */
1220
1221                 for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
1222
1223                         for (m = 0; m < this->fd_hashtable[n].length; m++) {
1224
1225                                 wsi = this->fd_hashtable[n].wsi[m];
1226
1227                                 if (wsi->mode != LWS_CONNMODE_WS_SERVING)
1228                                         continue;
1229
1230                                 /*
1231                                  * never broadcast to
1232                                  * non-established connections
1233                                  */
1234                                 if (wsi->state != WSI_STATE_ESTABLISHED)
1235                                         continue;
1236
1237                                 /* only broadcast to guys using
1238                                  * requested protocol
1239                                  */
1240                                 if (wsi->protocol != protocol)
1241                                         continue;
1242
1243                                 wsi->protocol->callback(wsi,
1244                                          LWS_CALLBACK_BROADCAST,
1245                                          wsi->user_space,
1246                                          buf, len);
1247                         }
1248                 }
1249
1250                 return 0;
1251         }
1252
1253         /*
1254          * We're being called from a different process context than the server
1255          * loop.  Instead of broadcasting directly, we send our
1256          * payload on a socket to do the IPC; the server process will serialize
1257          * the broadcast action in its main poll() loop.
1258          *
1259          * There's one broadcast socket listening for each protocol supported
1260          * set up when the websocket server initializes
1261          */
1262
1263         n = send(protocol->broadcast_socket_user_fd, buf, len, MSG_NOSIGNAL);
1264
1265         return n;
1266 }