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