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