Optionally allow non-SSL connections on same port as SSL
[platform/upstream/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 #if defined(WIN32) || defined(_WIN32)
25 #include <tchar.h>
26 #include <io.h>
27 #include <mstcpip.h>
28 #else
29 #ifdef LWS_BUILTIN_GETIFADDRS
30 #include <getifaddrs.h>
31 #else
32 #include <ifaddrs.h>
33 #endif
34 #include <syslog.h>
35 #include <sys/un.h>
36 #include <sys/socket.h>
37 #include <netdb.h>
38 #endif
39
40 #ifdef LWS_OPENSSL_SUPPORT
41 int openssl_websocket_private_data_index;
42 #endif
43
44 #ifdef __MINGW32__
45 #include "../win32port/win32helpers/websock-w32.c"
46 #else
47 #ifdef __MINGW64__
48 #include "../win32port/win32helpers/websock-w32.c"
49 #endif
50 #endif
51
52 #ifndef LWS_BUILD_HASH
53 #define LWS_BUILD_HASH "unknown-build-hash"
54 #endif
55
56 static int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE;
57 static void lwsl_emit_stderr(int level, const char *line);
58 static void (*lwsl_emit)(int level, const char *line) = lwsl_emit_stderr;
59
60 static const char *library_version = LWS_LIBRARY_VERSION " " LWS_BUILD_HASH;
61
62 static const char * const log_level_names[] = {
63         "ERR",
64         "WARN",
65         "NOTICE",
66         "INFO",
67         "DEBUG",
68         "PARSER",
69         "HEADER",
70         "EXTENSION",
71         "CLIENT",
72         "LATENCY",
73 };
74
75 #ifndef LWS_NO_CLIENT
76         extern int lws_client_socket_service(
77                 struct libwebsocket_context *context,
78                 struct libwebsocket *wsi, struct pollfd *pollfd);
79 #endif
80 #ifndef LWS_NO_SERVER
81         extern int lws_server_socket_service(
82                 struct libwebsocket_context *context,
83                 struct libwebsocket *wsi, struct pollfd *pollfd);
84 #endif
85
86 /**
87  * lws_get_library_version: get version and git hash library built from
88  *
89  *      returns a const char * to a string like "1.1 178d78c"
90  *      representing the library version followed by the git head hash it
91  *      was built from
92  */
93
94 LWS_VISIBLE const char *
95 lws_get_library_version(void)
96 {
97         return library_version;
98 }
99
100 int
101 insert_wsi_socket_into_fds(struct libwebsocket_context *context,
102                                                        struct libwebsocket *wsi)
103 {
104         if (context->fds_count >= context->max_fds) {
105                 lwsl_err("Too many fds (%d)\n", context->max_fds);
106                 return 1;
107         }
108
109         if (wsi->sock > context->max_fds) {
110                 lwsl_err("Socket fd %d is too high (%d)\n",
111                                                 wsi->sock, context->max_fds);
112                 return 1;
113         }
114
115         assert(wsi);
116         assert(wsi->sock >= 0);
117
118         lwsl_info("insert_wsi_socket_into_fds: wsi=%p, sock=%d, fds pos=%d\n",
119                                             wsi, wsi->sock, context->fds_count);
120
121         context->lws_lookup[wsi->sock] = wsi;
122         wsi->position_in_fds_table = context->fds_count;
123         context->fds[context->fds_count].fd = wsi->sock;
124         context->fds[context->fds_count].events = POLLIN;
125         context->fds[context->fds_count++].revents = 0;
126
127         /* external POLL support via protocol 0 */
128         context->protocols[0].callback(context, wsi,
129                 LWS_CALLBACK_ADD_POLL_FD,
130                 wsi->user_space, (void *)(long)wsi->sock, POLLIN);
131
132         return 0;
133 }
134
135 static int
136 remove_wsi_socket_from_fds(struct libwebsocket_context *context,
137                                                       struct libwebsocket *wsi)
138 {
139         int m;
140
141         if (!--context->fds_count)
142                 goto do_ext;
143
144         if (wsi->sock > context->max_fds) {
145                 lwsl_err("Socket fd %d too high (%d)\n",
146                                                    wsi->sock, context->max_fds);
147                 return 1;
148         }
149
150         lwsl_info("remove_wsi_socket_from_fds: wsi=%p, sock=%d, fds pos=%d\n",
151                                     wsi, wsi->sock, wsi->position_in_fds_table);
152
153         m = wsi->position_in_fds_table; /* replace the contents for this */
154
155         /* have the last guy take up the vacant slot */
156         context->fds[m] = context->fds[context->fds_count];
157         /*
158          * end guy's fds_lookup entry remains unchanged
159          * (still same fd pointing to same wsi)
160          */
161         /* end guy's "position in fds table" changed */
162         context->lws_lookup[context->fds[context->fds_count].fd]->
163                                                 position_in_fds_table = m;
164         /* deletion guy's lws_lookup entry needs nuking */
165         context->lws_lookup[wsi->sock] = NULL;
166         /* removed wsi has no position any more */
167         wsi->position_in_fds_table = -1;
168
169 do_ext:
170         /* remove also from external POLL support via protocol 0 */
171         if (wsi->sock)
172                 context->protocols[0].callback(context, wsi,
173                     LWS_CALLBACK_DEL_POLL_FD, wsi->user_space,
174                                                     (void *)(long)wsi->sock, 0);
175
176         return 0;
177 }
178
179
180 void
181 libwebsocket_close_and_free_session(struct libwebsocket_context *context,
182                          struct libwebsocket *wsi, enum lws_close_status reason)
183 {
184         int n;
185         int old_state;
186         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
187                                                   LWS_SEND_BUFFER_POST_PADDING];
188 #ifndef LWS_NO_EXTENSIONS
189         int ret;
190         int m;
191         struct lws_tokens eff_buf;
192         struct libwebsocket_extension *ext;
193 #endif
194
195         if (!wsi)
196                 return;
197
198         old_state = wsi->state;
199
200         if (old_state == WSI_STATE_DEAD_SOCKET)
201                 return;
202
203         /* we tried the polite way... */
204         if (old_state == WSI_STATE_AWAITING_CLOSE_ACK)
205                 goto just_kill_connection;
206
207         wsi->u.ws.close_reason = reason;
208
209         if (wsi->mode == LWS_CONNMODE_WS_CLIENT_WAITING_CONNECT ||
210                         wsi->mode == LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE) {
211
212                 context->protocols[0].callback(context, wsi,
213                         LWS_CALLBACK_CLIENT_CONNECTION_ERROR, NULL, NULL, 0);
214
215                 free(wsi->u.hdr.ah);
216                 goto just_kill_connection;
217         }
218
219
220         if (wsi->mode == LWS_CONNMODE_HTTP_SERVING_ACCEPTED) {
221                 if (wsi->u.http.post_buffer) {
222                         free(wsi->u.http.post_buffer);
223                         wsi->u.http.post_buffer = NULL;
224                 }
225                 if (wsi->u.http.fd >= 0) {
226                         lwsl_debug("closing http fd %d\n", wsi->u.http.fd);
227                         close(wsi->u.http.fd);
228                         wsi->u.http.fd = -1;
229                         context->protocols[0].callback(context, wsi,
230                                 LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0);
231                 }
232         }
233
234 #ifndef LWS_NO_EXTENSIONS
235         /*
236          * are his extensions okay with him closing?  Eg he might be a mux
237          * parent and just his ch1 aspect is closing?
238          */
239
240         for (n = 0; n < wsi->count_active_extensions; n++) {
241                 if (!wsi->active_extensions[n]->callback)
242                         continue;
243
244                 m = wsi->active_extensions[n]->callback(context,
245                         wsi->active_extensions[n], wsi,
246                         LWS_EXT_CALLBACK_CHECK_OK_TO_REALLY_CLOSE,
247                                        wsi->active_extensions_user[n], NULL, 0);
248
249                 /*
250                  * if somebody vetoed actually closing him at this time....
251                  * up to the extension to track the attempted close, let's
252                  * just bail
253                  */
254
255                 if (m) {
256                         lwsl_ext("extension vetoed close\n");
257                         return;
258                 }
259         }
260
261         /*
262          * flush any tx pending from extensions, since we may send close packet
263          * if there are problems with send, just nuke the connection
264          */
265
266         ret = 1;
267         while (ret == 1) {
268
269                 /* default to nobody has more to spill */
270
271                 ret = 0;
272                 eff_buf.token = NULL;
273                 eff_buf.token_len = 0;
274
275                 /* show every extension the new incoming data */
276
277                 for (n = 0; n < wsi->count_active_extensions; n++) {
278                         m = wsi->active_extensions[n]->callback(
279                                         wsi->protocol->owning_server,
280                                         wsi->active_extensions[n], wsi,
281                                         LWS_EXT_CALLBACK_FLUSH_PENDING_TX,
282                                    wsi->active_extensions_user[n], &eff_buf, 0);
283                         if (m < 0) {
284                                 lwsl_ext("Extension reports fatal error\n");
285                                 goto just_kill_connection;
286                         }
287                         if (m)
288                                 /*
289                                  * at least one extension told us he has more
290                                  * to spill, so we will go around again after
291                                  */
292                                 ret = 1;
293                 }
294
295                 /* assuming they left us something to send, send it */
296
297                 if (eff_buf.token_len)
298                         if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
299                                       eff_buf.token_len) != eff_buf.token_len) {
300                                 lwsl_debug("close: ext spill failed\n");
301                                 goto just_kill_connection;
302                         }
303         }
304 #endif
305
306         /*
307          * signal we are closing, libsocket_write will
308          * add any necessary version-specific stuff.  If the write fails,
309          * no worries we are closing anyway.  If we didn't initiate this
310          * close, then our state has been changed to
311          * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this.
312          *
313          * Likewise if it's a second call to close this connection after we
314          * sent the close indication to the peer already, we are in state
315          * WSI_STATE_AWAITING_CLOSE_ACK and will skip doing this a second time.
316          */
317
318         if (old_state == WSI_STATE_ESTABLISHED &&
319                                           reason != LWS_CLOSE_STATUS_NOSTATUS) {
320
321                 lwsl_debug("sending close indication...\n");
322
323                 /* make valgrind happy */
324                 memset(buf, 0, sizeof(buf));
325                 n = libwebsocket_write(wsi,
326                                 &buf[LWS_SEND_BUFFER_PRE_PADDING + 2],
327                                                             0, LWS_WRITE_CLOSE);
328                 if (n >= 0) {
329                         /*
330                          * we have sent a nice protocol level indication we
331                          * now wish to close, we should not send anything more
332                          */
333
334                         wsi->state = WSI_STATE_AWAITING_CLOSE_ACK;
335
336                         /*
337                          * ...and we should wait for a reply for a bit
338                          * out of politeness
339                          */
340
341                         libwebsocket_set_timeout(wsi,
342                                                   PENDING_TIMEOUT_CLOSE_ACK, 1);
343
344                         lwsl_debug("sent close indication, awaiting ack\n");
345
346                         return;
347                 }
348
349                 lwsl_info("close: sending close packet failed, hanging up\n");
350
351                 /* else, the send failed and we should just hang up */
352         }
353
354 just_kill_connection:
355
356         lwsl_debug("close: just_kill_connection\n");
357
358         /*
359          * we won't be servicing or receiving anything further from this guy
360          * delete socket from the internal poll list if still present
361          */
362
363         remove_wsi_socket_from_fds(context, wsi);
364
365         wsi->state = WSI_STATE_DEAD_SOCKET;
366
367         if ((old_state == WSI_STATE_ESTABLISHED ||
368              wsi->mode == LWS_CONNMODE_WS_SERVING ||
369              wsi->mode == LWS_CONNMODE_WS_CLIENT)) {
370
371                 if (wsi->u.ws.rx_user_buffer) {
372                         free(wsi->u.ws.rx_user_buffer);
373                         wsi->u.ws.rx_user_buffer = NULL;
374                 }
375                 if (wsi->u.ws.rxflow_buffer) {
376                         free(wsi->u.ws.rxflow_buffer);
377                         wsi->u.ws.rxflow_buffer = NULL;
378                 }
379                 if (wsi->truncated_send_malloc) {
380                         /* not going to be completed... nuke it */
381                         free(wsi->truncated_send_malloc);
382                         wsi->truncated_send_malloc = NULL;
383                 }
384         }
385
386         /* tell the user it's all over for this guy */
387
388         if (wsi->protocol && wsi->protocol->callback &&
389                         ((old_state == WSI_STATE_ESTABLISHED) ||
390                          (old_state == WSI_STATE_RETURNED_CLOSE_ALREADY) ||
391                          (old_state == WSI_STATE_AWAITING_CLOSE_ACK))) {
392                 lwsl_debug("calling back CLOSED\n");
393                 wsi->protocol->callback(context, wsi, LWS_CALLBACK_CLOSED,
394                                                       wsi->user_space, NULL, 0);
395         } else if ( wsi->mode == LWS_CONNMODE_HTTP_SERVING_ACCEPTED ) {
396                 lwsl_debug("calling back CLOSED_HTTP\n");
397                 context->protocols[0].callback(context, wsi,
398                         LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0 );
399         } else
400                 lwsl_debug("not calling back closed\n");
401
402 #ifndef LWS_NO_EXTENSIONS
403         /* deallocate any active extension contexts */
404
405         for (n = 0; n < wsi->count_active_extensions; n++) {
406                 if (!wsi->active_extensions[n]->callback)
407                         continue;
408
409                 wsi->active_extensions[n]->callback(context,
410                         wsi->active_extensions[n], wsi,
411                                 LWS_EXT_CALLBACK_DESTROY,
412                                        wsi->active_extensions_user[n], NULL, 0);
413
414                 free(wsi->active_extensions_user[n]);
415         }
416
417         /*
418          * inform all extensions in case they tracked this guy out of band
419          * even though not active on him specifically
420          */
421
422         ext = context->extensions;
423         while (ext && ext->callback) {
424                 ext->callback(context, ext, wsi,
425                                 LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING,
426                                        NULL, NULL, 0);
427                 ext++;
428         }
429 #endif
430
431 /*      lwsl_info("closing fd=%d\n", wsi->sock); */
432
433 #ifdef LWS_OPENSSL_SUPPORT
434         if (wsi->ssl) {
435                 n = SSL_get_fd(wsi->ssl);
436                 SSL_shutdown(wsi->ssl);
437                 compatible_close(n);
438                 SSL_free(wsi->ssl);
439         } else {
440 #endif
441                 if (wsi->sock) {
442                         n = shutdown(wsi->sock, SHUT_RDWR);
443                         if (n)
444                                 lwsl_debug("closing: shutdown returned %d\n",
445                                                                         errno);
446
447                         n = compatible_close(wsi->sock);
448                         if (n)
449                                 lwsl_debug("closing: close returned %d\n",
450                                                                         errno);
451                 }
452 #ifdef LWS_OPENSSL_SUPPORT
453         }
454 #endif
455         if (wsi->protocol && wsi->protocol->per_session_data_size &&
456                                         wsi->user_space) /* user code may own */
457                 free(wsi->user_space);
458
459         free(wsi);
460 }
461
462 /**
463  * libwebsockets_get_peer_addresses() - Get client address information
464  * @context:    Libwebsockets context
465  * @wsi:        Local struct libwebsocket associated with
466  * @fd:         Connection socket descriptor
467  * @name:       Buffer to take client address name
468  * @name_len:   Length of client address name buffer
469  * @rip:        Buffer to take client address IP qotted quad
470  * @rip_len:    Length of client address IP buffer
471  *
472  *      This function fills in @name and @rip with the name and IP of
473  *      the client connected with socket descriptor @fd.  Names may be
474  *      truncated if there is not enough room.  If either cannot be
475  *      determined, they will be returned as valid zero-length strings.
476  */
477
478 LWS_VISIBLE void
479 libwebsockets_get_peer_addresses(struct libwebsocket_context *context,
480         struct libwebsocket *wsi, int fd, char *name, int name_len,
481                                         char *rip, int rip_len)
482 {
483         socklen_t len;
484         struct sockaddr_in sin;
485         struct hostent *host;
486         struct hostent *host1;
487         char ip[128];
488         unsigned char *p;
489         int n;
490         int ret = -1;
491 #ifdef AF_LOCAL
492         struct sockaddr_un *un;
493 #endif
494
495         rip[0] = '\0';
496         name[0] = '\0';
497
498         lws_latency_pre(context, wsi);
499
500         len = sizeof(sin);
501         if (getpeername(fd, (struct sockaddr *) &sin, &len) < 0) {
502                 perror("getpeername");
503                 goto bail;
504         }
505
506         host = gethostbyaddr((char *) &sin.sin_addr, sizeof(sin.sin_addr),
507                                                                        AF_INET);
508         if (host == NULL) {
509                 perror("gethostbyaddr");
510                 goto bail;
511         }
512
513         strncpy(name, host->h_name, name_len);
514         name[name_len - 1] = '\0';
515
516         host1 = gethostbyname(host->h_name);
517         if (host1 == NULL)
518                 goto bail;
519         p = (unsigned char *)host1;
520         n = 0;
521         while (p != NULL) {
522                 p = (unsigned char *)host1->h_addr_list[n++];
523                 if (p == NULL)
524                         continue;
525                 if ((host1->h_addrtype != AF_INET)
526 #ifdef AF_LOCAL
527                         && (host1->h_addrtype != AF_LOCAL)
528 #endif
529                         )
530                         continue;
531
532                 if (host1->h_addrtype == AF_INET)
533                         sprintf(ip, "%u.%u.%u.%u", p[0], p[1], p[2], p[3]);
534 #ifdef AF_LOCAL
535                 else {
536                         un = (struct sockaddr_un *)p;
537                         strncpy(ip, un->sun_path, sizeof(ip) - 1);
538                         ip[sizeof(ip) - 1] = '\0';
539                 }
540 #endif
541                 p = NULL;
542                 strncpy(rip, ip, rip_len);
543                 rip[rip_len - 1] = '\0';
544         }
545
546         ret = 0;
547 bail:
548         lws_latency(context, wsi, "libwebsockets_get_peer_addresses", ret, 1);
549 }
550
551 LWS_VISIBLE int libwebsockets_get_random(struct libwebsocket_context *context,
552                                                              void *buf, int len)
553 {
554         int n;
555         char *p = (char *)buf;
556
557 #if defined(WIN32) || defined(_WIN32)
558         for (n = 0; n < len; n++)
559                 p[n] = (unsigned char)rand();
560 #else
561         n = read(context->fd_random, p, len);
562 #endif
563
564         return n;
565 }
566
567 int lws_set_socket_options(struct libwebsocket_context *context, int fd)
568 {
569         int optval = 1;
570         socklen_t optlen = sizeof(optval);
571 #if defined(WIN32) || defined(_WIN32)
572         unsigned long optl = 0;
573 #endif
574 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
575         struct protoent *tcp_proto;
576 #endif
577
578         if (context->ka_time) {
579                 /* enable keepalive on this socket */
580                 optval = 1;
581                 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
582                                              (const void *)&optval, optlen) < 0)
583                         return 1;
584
585 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__CYGWIN__)
586
587                 /*
588                  * didn't find a way to set these per-socket, need to
589                  * tune kernel systemwide values
590                  */
591 #elif WIN32
592                 {
593                         DWORD dwBytesRet;
594                         struct tcp_keepalive alive;
595                         alive.onoff = TRUE;
596                         alive.keepalivetime = context->ka_time;
597                         alive.keepaliveinterval = context->ka_interval;
598
599                         if (WSAIoctl(fd, SIO_KEEPALIVE_VALS, &alive, sizeof(alive), 
600                                                                         NULL, 0, &dwBytesRet, NULL, NULL))
601                                 return 1;
602                 }
603 #else
604                 /* set the keepalive conditions we want on it too */
605                 optval = context->ka_time;
606                 if (setsockopt(fd, IPPROTO_IP, TCP_KEEPIDLE,
607                                              (const void *)&optval, optlen) < 0)
608                         return 1;
609
610                 optval = context->ka_interval;
611                 if (setsockopt(fd, IPPROTO_IP, TCP_KEEPINTVL,
612                                              (const void *)&optval, optlen) < 0)
613                         return 1;
614
615                 optval = context->ka_probes;
616                 if (setsockopt(fd, IPPROTO_IP, TCP_KEEPCNT,
617                                              (const void *)&optval, optlen) < 0)
618                         return 1;
619 #endif
620         }
621
622         /* Disable Nagle */
623         optval = 1;
624 #if !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__NetBSD__)
625         setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&optval, optlen);
626 #else
627         tcp_proto = getprotobyname("TCP");
628         setsockopt(fd, tcp_proto->p_proto, TCP_NODELAY, &optval, optlen);
629 #endif
630
631         /* We are nonblocking... */
632 #if defined(WIN32) || defined(_WIN32)
633         ioctlsocket(fd, FIONBIO, &optl);
634 #else
635         fcntl(fd, F_SETFL, O_NONBLOCK);
636 #endif
637
638         return 0;
639 }
640
641 LWS_VISIBLE int lws_send_pipe_choked(struct libwebsocket *wsi)
642 {
643         struct pollfd fds;
644
645         /* treat the fact we got a truncated send pending as if we're choked */
646         if (wsi->truncated_send_malloc)
647                 return 1;
648
649         fds.fd = wsi->sock;
650         fds.events = POLLOUT;
651         fds.revents = 0;
652
653         if (poll(&fds, 1, 0) != 1)
654                 return 1;
655
656         if ((fds.revents & POLLOUT) == 0)
657                 return 1;
658
659         /* okay to send another packet without blocking */
660
661         return 0;
662 }
663
664 int
665 lws_handle_POLLOUT_event(struct libwebsocket_context *context,
666                                 struct libwebsocket *wsi, struct pollfd *pollfd)
667 {
668         int n;
669
670 #ifndef LWS_NO_EXTENSIONS
671         struct lws_tokens eff_buf;
672         int ret;
673         int m;
674         int handled = 0;
675
676         /* pending truncated sends have uber priority */
677
678         if (wsi->truncated_send_malloc) {
679                 lws_issue_raw(wsi, wsi->truncated_send_malloc +
680                                 wsi->truncated_send_offset,
681                                                 wsi->truncated_send_len);
682                 /* leave POLLOUT active either way */
683                 return 0;
684         }
685
686         for (n = 0; n < wsi->count_active_extensions; n++) {
687                 if (!wsi->active_extensions[n]->callback)
688                         continue;
689
690                 m = wsi->active_extensions[n]->callback(context,
691                         wsi->active_extensions[n], wsi,
692                         LWS_EXT_CALLBACK_IS_WRITEABLE,
693                                        wsi->active_extensions_user[n], NULL, 0);
694                 if (m > handled)
695                         handled = m;
696         }
697
698         if (handled == 1)
699                 goto notify_action;
700
701         if (!wsi->extension_data_pending || handled == 2)
702                 goto user_service;
703
704         /*
705          * check in on the active extensions, see if they
706          * had pending stuff to spill... they need to get the
707          * first look-in otherwise sequence will be disordered
708          *
709          * NULL, zero-length eff_buf means just spill pending
710          */
711
712         ret = 1;
713         while (ret == 1) {
714
715                 /* default to nobody has more to spill */
716
717                 ret = 0;
718                 eff_buf.token = NULL;
719                 eff_buf.token_len = 0;
720
721                 /* give every extension a chance to spill */
722
723                 for (n = 0; n < wsi->count_active_extensions; n++) {
724                         m = wsi->active_extensions[n]->callback(
725                                 wsi->protocol->owning_server,
726                                 wsi->active_extensions[n], wsi,
727                                         LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
728                                    wsi->active_extensions_user[n], &eff_buf, 0);
729                         if (m < 0) {
730                                 lwsl_err("ext reports fatal error\n");
731                                 return -1;
732                         }
733                         if (m)
734                                 /*
735                                  * at least one extension told us he has more
736                                  * to spill, so we will go around again after
737                                  */
738                                 ret = 1;
739                 }
740
741                 /* assuming they gave us something to send, send it */
742
743                 if (eff_buf.token_len) {
744                         n = lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
745                                                              eff_buf.token_len);
746                         if (n < 0)
747                                 return -1;
748                         /*
749                          * Keep amount spilled small to minimize chance of this
750                          */
751                         if (n != eff_buf.token_len) {
752                                 lwsl_err("Unable to spill ext %d vs %s\n",
753                                                           eff_buf.token_len, n);
754                                 return -1;
755                         }
756                 } else
757                         continue;
758
759                 /* no extension has more to spill */
760
761                 if (!ret)
762                         continue;
763
764                 /*
765                  * There's more to spill from an extension, but we just sent
766                  * something... did that leave the pipe choked?
767                  */
768
769                 if (!lws_send_pipe_choked(wsi))
770                         /* no we could add more */
771                         continue;
772
773                 lwsl_info("choked in POLLOUT service\n");
774
775                 /*
776                  * Yes, he's choked.  Leave the POLLOUT masked on so we will
777                  * come back here when he is unchoked.  Don't call the user
778                  * callback to enforce ordering of spilling, he'll get called
779                  * when we come back here and there's nothing more to spill.
780                  */
781
782                 return 0;
783         }
784
785         wsi->extension_data_pending = 0;
786
787 user_service:
788 #endif
789         /* one shot */
790
791         if (pollfd) {
792                 pollfd->events &= ~POLLOUT;
793
794                 /* external POLL support via protocol 0 */
795                 context->protocols[0].callback(context, wsi,
796                         LWS_CALLBACK_CLEAR_MODE_POLL_FD,
797                         wsi->user_space, (void *)(long)wsi->sock, POLLOUT);
798         }
799 #ifndef LWS_NO_EXTENSIONS
800 notify_action:
801 #endif
802
803         if (wsi->mode == LWS_CONNMODE_WS_CLIENT)
804                 n = LWS_CALLBACK_CLIENT_WRITEABLE;
805         else
806                 n = LWS_CALLBACK_SERVER_WRITEABLE;
807
808         return user_callback_handle_rxflow(wsi->protocol->callback, context,
809                         wsi, (enum libwebsocket_callback_reasons) n,
810                                                       wsi->user_space, NULL, 0);
811 }
812
813
814
815 int
816 libwebsocket_service_timeout_check(struct libwebsocket_context *context,
817                                      struct libwebsocket *wsi, unsigned int sec)
818 {
819 #ifndef LWS_NO_EXTENSIONS
820         int n;
821
822         /*
823          * if extensions want in on it (eg, we are a mux parent)
824          * give them a chance to service child timeouts
825          */
826
827         for (n = 0; n < wsi->count_active_extensions; n++)
828                 wsi->active_extensions[n]->callback(
829                                     context, wsi->active_extensions[n],
830                                     wsi, LWS_EXT_CALLBACK_1HZ,
831                                     wsi->active_extensions_user[n], NULL, sec);
832
833 #endif
834         if (!wsi->pending_timeout)
835                 return 0;
836
837         /*
838          * if we went beyond the allowed time, kill the
839          * connection
840          */
841
842         if (sec > wsi->pending_timeout_limit) {
843                 lwsl_info("TIMEDOUT WAITING\n");
844                 libwebsocket_close_and_free_session(context,
845                                 wsi, LWS_CLOSE_STATUS_NOSTATUS);
846                 return 1;
847         }
848
849         return 0;
850 }
851
852 /**
853  * libwebsocket_service_fd() - Service polled socket with something waiting
854  * @context:    Websocket context
855  * @pollfd:     The pollfd entry describing the socket fd and which events
856  *              happened.
857  *
858  *      This function takes a pollfd that has POLLIN or POLLOUT activity and
859  *      services it according to the state of the associated
860  *      struct libwebsocket.
861  *
862  *      The one call deals with all "service" that might happen on a socket
863  *      including listen accepts, http files as well as websocket protocol.
864  *
865  *      If a pollfd says it has something, you can just pass it to
866  *      libwebsocket_serice_fd() whether it is a socket handled by lws or not.
867  *      If it sees it is a lws socket, the traffic will be handled and
868  *      pollfd->revents will be zeroed now.
869  *
870  *      If the socket is foreign to lws, it leaves revents alone.  So you can
871  *      see if you should service yourself by checking the pollfd revents
872  *      after letting lws try to service it.
873  */
874
875 LWS_VISIBLE int
876 libwebsocket_service_fd(struct libwebsocket_context *context,
877                                                           struct pollfd *pollfd)
878 {
879         struct libwebsocket *wsi;
880         int n;
881         int m;
882         int listen_socket_fds_index = 0;
883         struct timeval tv;
884         int timed_out = 0;
885         int our_fd = 0;
886         char draining_flow = 0;
887
888 #ifndef LWS_NO_EXTENSIONS
889         int more = 1;
890 #endif
891         struct lws_tokens eff_buf;
892
893         if (context->listen_service_fd)
894                 listen_socket_fds_index = context->lws_lookup[
895                              context->listen_service_fd]->position_in_fds_table;
896
897         /*
898          * you can call us with pollfd = NULL to just allow the once-per-second
899          * global timeout checks; if less than a second since the last check
900          * it returns immediately then.
901          */
902
903         gettimeofday(&tv, NULL);
904
905         if (context->last_timeout_check_s != tv.tv_sec) {
906                 context->last_timeout_check_s = tv.tv_sec;
907
908                 #ifndef WIN32
909                 /* if our parent went down, don't linger around */
910                 if (context->started_with_parent &&
911                                       kill(context->started_with_parent, 0) < 0)
912                         kill(getpid(), SIGTERM);
913                 #endif
914
915                 /* global timeout check once per second */
916
917                 if (pollfd)
918                         our_fd = pollfd->fd;
919
920                 for (n = 0; n < context->fds_count; n++) {
921                         m = context->fds[n].fd;
922                         wsi = context->lws_lookup[m];
923                         if (!wsi)
924                                 continue;
925
926                         if (libwebsocket_service_timeout_check(context, wsi,
927                                                                      tv.tv_sec))
928                                 /* he did time out... */
929                                 if (m == our_fd) {
930                                         /* it was the guy we came to service! */
931                                         timed_out = 1;
932                                         /* mark as handled */
933                                         pollfd->revents = 0;
934                                 }
935                 }
936         }
937
938         /* the socket we came to service timed out, nothing to do */
939         if (timed_out)
940                 return 0;
941
942         /* just here for timeout management? */
943         if (pollfd == NULL)
944                 return 0;
945
946         /* no, here to service a socket descriptor */
947         wsi = context->lws_lookup[pollfd->fd];
948         if (wsi == NULL)
949                 /* not lws connection ... leave revents alone and return */
950                 return 0;
951
952         /*
953          * so that caller can tell we handled, past here we need to
954          * zero down pollfd->revents after handling
955          */
956
957         /*
958          * deal with listen service piggybacking
959          * every listen_service_modulo services of other fds, we
960          * sneak one in to service the listen socket if there's anything waiting
961          *
962          * To handle connection storms, as found in ab, if we previously saw a
963          * pending connection here, it causes us to check again next time.
964          */
965
966         if (context->listen_service_fd && pollfd !=
967                                        &context->fds[listen_socket_fds_index]) {
968                 context->listen_service_count++;
969                 if (context->listen_service_extraseen ||
970                                 context->listen_service_count ==
971                                                context->listen_service_modulo) {
972                         context->listen_service_count = 0;
973                         m = 1;
974                         if (context->listen_service_extraseen > 5)
975                                 m = 2;
976                         while (m--) {
977                                 /*
978                                  * even with extpoll, we prepared this
979                                  * internal fds for listen
980                                  */
981                                 n = poll(&context->fds[listen_socket_fds_index],
982                                                                           1, 0);
983                                 if (n > 0) { /* there's a conn waiting for us */
984                                         libwebsocket_service_fd(context,
985                                                 &context->
986                                                   fds[listen_socket_fds_index]);
987                                         context->listen_service_extraseen++;
988                                 } else {
989                                         if (context->listen_service_extraseen)
990                                                 context->
991                                                      listen_service_extraseen--;
992                                         break;
993                                 }
994                         }
995                 }
996
997         }
998
999         /* handle session socket closed */
1000
1001         if ((!(pollfd->revents & POLLIN)) &&
1002                         (pollfd->revents & (POLLERR | POLLHUP))) {
1003
1004                 lwsl_debug("Session Socket %p (fd=%d) dead\n",
1005                                                        (void *)wsi, pollfd->fd);
1006
1007                 goto close_and_handled;
1008         }
1009
1010         /* okay, what we came here to do... */
1011
1012         switch (wsi->mode) {
1013
1014 #ifndef LWS_NO_SERVER
1015         case LWS_CONNMODE_HTTP_SERVING:
1016         case LWS_CONNMODE_HTTP_SERVING_ACCEPTED:
1017         case LWS_CONNMODE_SERVER_LISTENER:
1018         case LWS_CONNMODE_SSL_ACK_PENDING:
1019                 n = lws_server_socket_service(context, wsi, pollfd);
1020                 goto handled;
1021 #endif
1022
1023         case LWS_CONNMODE_WS_SERVING:
1024         case LWS_CONNMODE_WS_CLIENT:
1025
1026                 /* the guy requested a callback when it was OK to write */
1027
1028                 if ((pollfd->revents & POLLOUT) &&
1029                         wsi->state == WSI_STATE_ESTABLISHED &&
1030                            lws_handle_POLLOUT_event(context, wsi, pollfd) < 0) {
1031                                 lwsl_info("libwebsocket_service_fd: closing\n");
1032                                 goto close_and_handled;
1033                 }
1034
1035                 if (wsi->u.ws.rxflow_buffer &&
1036                               (wsi->u.ws.rxflow_change_to & LWS_RXFLOW_ALLOW)) {
1037                         lwsl_info("draining rxflow\n");
1038                         /* well, drain it */
1039                         eff_buf.token = (char *)wsi->u.ws.rxflow_buffer +
1040                                                 wsi->u.ws.rxflow_pos;
1041                         eff_buf.token_len = wsi->u.ws.rxflow_len -
1042                                                 wsi->u.ws.rxflow_pos;
1043                         draining_flow = 1;
1044                         goto drain;
1045                 }
1046
1047                 /* any incoming data ready? */
1048
1049                 if (!(pollfd->revents & POLLIN))
1050                         break;
1051
1052 #ifdef LWS_OPENSSL_SUPPORT
1053 read_pending:
1054                 if (wsi->ssl) {
1055                         eff_buf.token_len = SSL_read(wsi->ssl,
1056                                         context->service_buffer,
1057                                                sizeof(context->service_buffer));
1058                         if (!eff_buf.token_len) {
1059                                 n = SSL_get_error(wsi->ssl, eff_buf.token_len);
1060                                 lwsl_err("SSL_read returned 0 with reason %s\n",
1061                                   ERR_error_string(n,
1062                                               (char *)context->service_buffer));
1063                         }
1064                 } else
1065 #endif
1066                         eff_buf.token_len = recv(pollfd->fd,
1067                                 context->service_buffer,
1068                                             sizeof(context->service_buffer), 0);
1069
1070                 if (eff_buf.token_len < 0) {
1071                         lwsl_debug("service_fd read ret = %d, errno = %d\n",
1072                                                       eff_buf.token_len, errno);
1073                         if (errno != EINTR && errno != EAGAIN)
1074                                 goto close_and_handled;
1075                         n = 0;
1076                         goto handled;
1077                 }
1078                 if (!eff_buf.token_len) {
1079                         lwsl_info("service_fd: closing due to 0 length read\n");
1080                         goto close_and_handled;
1081                 }
1082
1083                 /*
1084                  * give any active extensions a chance to munge the buffer
1085                  * before parse.  We pass in a pointer to an lws_tokens struct
1086                  * prepared with the default buffer and content length that's in
1087                  * there.  Rather than rewrite the default buffer, extensions
1088                  * that expect to grow the buffer can adapt .token to
1089                  * point to their own per-connection buffer in the extension
1090                  * user allocation.  By default with no extensions or no
1091                  * extension callback handling, just the normal input buffer is
1092                  * used then so it is efficient.
1093                  */
1094
1095                 eff_buf.token = (char *)context->service_buffer;
1096 drain:
1097 #ifndef LWS_NO_EXTENSIONS
1098                 more = 1;
1099                 while (more) {
1100
1101                         more = 0;
1102
1103                         for (n = 0; n < wsi->count_active_extensions; n++) {
1104                                 m = wsi->active_extensions[n]->callback(context,
1105                                         wsi->active_extensions[n], wsi,
1106                                         LWS_EXT_CALLBACK_PACKET_RX_PREPARSE,
1107                                         wsi->active_extensions_user[n],
1108                                                                    &eff_buf, 0);
1109                                 if (m < 0) {
1110                                         lwsl_ext(
1111                                             "Extension reports fatal error\n");
1112                                         goto close_and_handled;
1113                                 }
1114                                 if (m)
1115                                         more = 1;
1116                         }
1117 #endif
1118                         /* service incoming data */
1119
1120                         if (eff_buf.token_len) {
1121                                 n = libwebsocket_read(context, wsi,
1122                                         (unsigned char *)eff_buf.token,
1123                                                             eff_buf.token_len);
1124                                 if (n < 0) {
1125                                         /* we closed wsi */
1126                                         n = 0;
1127                                         goto handled;
1128                                 }
1129                         }
1130 #ifndef LWS_NO_EXTENSIONS
1131                         eff_buf.token = NULL;
1132                         eff_buf.token_len = 0;
1133                 }
1134 #endif
1135                 if (draining_flow && wsi->u.ws.rxflow_buffer &&
1136                                  wsi->u.ws.rxflow_pos == wsi->u.ws.rxflow_len) {
1137                         lwsl_info("flow buffer: drained\n");
1138                         free(wsi->u.ws.rxflow_buffer);
1139                         wsi->u.ws.rxflow_buffer = NULL;
1140                         /* having drained the rxflow buffer, can rearm POLLIN */
1141                         _libwebsocket_rx_flow_control(wsi);
1142                 }
1143
1144 #ifdef LWS_OPENSSL_SUPPORT
1145                 if (wsi->ssl && SSL_pending(wsi->ssl))
1146                         goto read_pending;
1147 #endif
1148                 break;
1149
1150         default:
1151 #ifdef LWS_NO_CLIENT
1152                 break;
1153 #else
1154                 n = lws_client_socket_service(context, wsi, pollfd);
1155                 goto handled;
1156 #endif
1157         }
1158
1159         n = 0;
1160         goto handled;
1161
1162 close_and_handled:
1163         libwebsocket_close_and_free_session(context, wsi,
1164                                                 LWS_CLOSE_STATUS_NOSTATUS);
1165         n = 1;
1166
1167 handled:
1168         pollfd->revents = 0;
1169         return n;
1170 }
1171
1172
1173 /**
1174  * libwebsocket_context_destroy() - Destroy the websocket context
1175  * @context:    Websocket context
1176  *
1177  *      This function closes any active connections and then frees the
1178  *      context.  After calling this, any further use of the context is
1179  *      undefined.
1180  */
1181 LWS_VISIBLE void
1182 libwebsocket_context_destroy(struct libwebsocket_context *context)
1183 {
1184 #ifndef LWS_NO_EXTENSIONS
1185         int n;
1186         int m;
1187         struct libwebsocket_extension *ext;
1188         struct libwebsocket_protocols *protocol = context->protocols;
1189
1190 #ifdef LWS_LATENCY
1191         if (context->worst_latency_info[0])
1192                 lwsl_notice("Worst latency: %s\n", context->worst_latency_info);
1193 #endif
1194
1195         for (n = 0; n < context->fds_count; n++) {
1196                 struct libwebsocket *wsi =
1197                                         context->lws_lookup[context->fds[n].fd];
1198                 libwebsocket_close_and_free_session(context,
1199                         wsi, LWS_CLOSE_STATUS_NOSTATUS /* no protocol close */);
1200                 n--;
1201         }
1202
1203         /*
1204          * give all extensions a chance to clean up any per-context
1205          * allocations they might have made
1206          */
1207
1208         ext = context->extensions;
1209         m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_DESTRUCT;
1210         if (context->listen_port)
1211                 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_DESTRUCT;
1212         while (ext && ext->callback) {
1213                 ext->callback(context, ext, NULL,
1214                         (enum libwebsocket_extension_callback_reasons)m,
1215                                                                  NULL, NULL, 0);
1216                 ext++;
1217         }
1218
1219         /*
1220          * inform all the protocols that they are done and will have no more
1221          * callbacks
1222          */
1223
1224         while (protocol->callback) {
1225                 protocol->callback(context, NULL, LWS_CALLBACK_PROTOCOL_DESTROY,
1226                                 NULL, NULL, 0);
1227                 protocol++;
1228         }
1229
1230 #endif
1231
1232 #if defined(WIN32) || defined(_WIN32)
1233 #else
1234         close(context->fd_random);
1235 #endif
1236
1237 #ifdef LWS_OPENSSL_SUPPORT
1238         if (context->ssl_ctx)
1239                 SSL_CTX_free(context->ssl_ctx);
1240         if (context->ssl_client_ctx)
1241                 SSL_CTX_free(context->ssl_client_ctx);
1242
1243         ERR_remove_state(0);
1244         ERR_free_strings();
1245         EVP_cleanup();
1246         CRYPTO_cleanup_all_ex_data();
1247 #endif
1248
1249         if (context->fds)
1250                 free(context->fds);
1251         if (context->lws_lookup)
1252                 free(context->lws_lookup);
1253
1254         free(context);
1255
1256 #if defined(WIN32) || defined(_WIN32)
1257         WSACleanup();
1258 #endif
1259 }
1260
1261 /**
1262  * libwebsocket_context_user() - get the user data associated with the context
1263  * @context: Websocket context
1264  *
1265  *      This returns the optional user allocation that can be attached to
1266  *      the context the sockets live in at context_create time.  It's a way
1267  *      to let all sockets serviced in the same context share data without
1268  *      using globals statics in the user code.
1269  */
1270 LWS_EXTERN void *
1271 libwebsocket_context_user(struct libwebsocket_context *context)
1272 {
1273         return context->user_space;
1274 }
1275
1276 /**
1277  * libwebsocket_service() - Service any pending websocket activity
1278  * @context:    Websocket context
1279  * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
1280  *              service otherwise block and service immediately, returning
1281  *              after the timeout if nothing needed service.
1282  *
1283  *      This function deals with any pending websocket traffic, for three
1284  *      kinds of event.  It handles these events on both server and client
1285  *      types of connection the same.
1286  *
1287  *      1) Accept new connections to our context's server
1288  *
1289  *      2) Call the receive callback for incoming frame data received by
1290  *          server or client connections.
1291  *
1292  *      You need to call this service function periodically to all the above
1293  *      functions to happen; if your application is single-threaded you can
1294  *      just call it in your main event loop.
1295  *
1296  *      Alternatively you can fork a new process that asynchronously handles
1297  *      calling this service in a loop.  In that case you are happy if this
1298  *      call blocks your thread until it needs to take care of something and
1299  *      would call it with a large nonzero timeout.  Your loop then takes no
1300  *      CPU while there is nothing happening.
1301  *
1302  *      If you are calling it in a single-threaded app, you don't want it to
1303  *      wait around blocking other things in your loop from happening, so you
1304  *      would call it with a timeout_ms of 0, so it returns immediately if
1305  *      nothing is pending, or as soon as it services whatever was pending.
1306  */
1307
1308 LWS_VISIBLE int
1309 libwebsocket_service(struct libwebsocket_context *context, int timeout_ms)
1310 {
1311         int n;
1312         int m;
1313
1314         /* stay dead once we are dead */
1315
1316         if (context == NULL)
1317                 return 1;
1318
1319         /* wait for something to need service */
1320
1321         n = poll(context->fds, context->fds_count, timeout_ms);
1322         if (n == 0) /* poll timeout */ {
1323                 libwebsocket_service_fd(context, NULL);
1324                 return 0;
1325         }
1326
1327         if (n < 0)
1328                 return -1;
1329
1330         /* any socket with events to service? */
1331
1332         for (n = 0; n < context->fds_count; n++) {
1333                 if (!context->fds[n].revents)
1334                         continue;
1335                 m = libwebsocket_service_fd(context, &context->fds[n]);
1336                 if (m < 0)
1337                         return -1;
1338                 /* if something closed, retry this slot */
1339                 if (m)
1340                         n--;
1341         }
1342
1343         return 0;
1344 }
1345
1346 #ifndef LWS_NO_EXTENSIONS
1347 int
1348 lws_any_extension_handled(struct libwebsocket_context *context,
1349                           struct libwebsocket *wsi,
1350                           enum libwebsocket_extension_callback_reasons r,
1351                                                        void *v, size_t len)
1352 {
1353         int n;
1354         int handled = 0;
1355
1356         /* maybe an extension will take care of it for us */
1357
1358         for (n = 0; n < wsi->count_active_extensions && !handled; n++) {
1359                 if (!wsi->active_extensions[n]->callback)
1360                         continue;
1361
1362                 handled |= wsi->active_extensions[n]->callback(context,
1363                         wsi->active_extensions[n], wsi,
1364                         r, wsi->active_extensions_user[n], v, len);
1365         }
1366
1367         return handled;
1368 }
1369
1370
1371 void *
1372 lws_get_extension_user_matching_ext(struct libwebsocket *wsi,
1373                                            struct libwebsocket_extension *ext)
1374 {
1375         int n = 0;
1376
1377         if (wsi == NULL)
1378                 return NULL;
1379
1380         while (n < wsi->count_active_extensions) {
1381                 if (wsi->active_extensions[n] != ext) {
1382                         n++;
1383                         continue;
1384                 }
1385                 return wsi->active_extensions_user[n];
1386         }
1387
1388         return NULL;
1389 }
1390 #endif
1391
1392 /**
1393  * libwebsocket_callback_on_writable() - Request a callback when this socket
1394  *                                       becomes able to be written to without
1395  *                                       blocking
1396  *
1397  * @context:    libwebsockets context
1398  * @wsi:        Websocket connection instance to get callback for
1399  */
1400
1401 LWS_VISIBLE int
1402 libwebsocket_callback_on_writable(struct libwebsocket_context *context,
1403                                                       struct libwebsocket *wsi)
1404 {
1405 #ifndef LWS_NO_EXTENSIONS
1406         int n;
1407         int handled = 0;
1408
1409         /* maybe an extension will take care of it for us */
1410
1411         for (n = 0; n < wsi->count_active_extensions; n++) {
1412                 if (!wsi->active_extensions[n]->callback)
1413                         continue;
1414
1415                 handled |= wsi->active_extensions[n]->callback(context,
1416                         wsi->active_extensions[n], wsi,
1417                         LWS_EXT_CALLBACK_REQUEST_ON_WRITEABLE,
1418                                        wsi->active_extensions_user[n], NULL, 0);
1419         }
1420
1421         if (handled)
1422                 return 1;
1423 #endif
1424         if (wsi->position_in_fds_table < 0) {
1425                 lwsl_err("libwebsocket_callback_on_writable: failed to find socket %d\n",
1426                                                                      wsi->sock);
1427                 return -1;
1428         }
1429
1430         context->fds[wsi->position_in_fds_table].events |= POLLOUT;
1431
1432         /* external POLL support via protocol 0 */
1433         context->protocols[0].callback(context, wsi,
1434                 LWS_CALLBACK_SET_MODE_POLL_FD,
1435                 wsi->user_space, (void *)(long)wsi->sock, POLLOUT);
1436
1437         return 1;
1438 }
1439
1440 /**
1441  * libwebsocket_callback_on_writable_all_protocol() - Request a callback for
1442  *                      all connections using the given protocol when it
1443  *                      becomes possible to write to each socket without
1444  *                      blocking in turn.
1445  *
1446  * @protocol:   Protocol whose connections will get callbacks
1447  */
1448
1449 LWS_VISIBLE int
1450 libwebsocket_callback_on_writable_all_protocol(
1451                                   const struct libwebsocket_protocols *protocol)
1452 {
1453         struct libwebsocket_context *context = protocol->owning_server;
1454         int n;
1455         struct libwebsocket *wsi;
1456
1457         for (n = 0; n < context->fds_count; n++) {
1458                 wsi = context->lws_lookup[context->fds[n].fd];
1459                 if (!wsi)
1460                         continue;
1461                 if (wsi->protocol == protocol)
1462                         libwebsocket_callback_on_writable(context, wsi);
1463         }
1464
1465         return 0;
1466 }
1467
1468 /**
1469  * libwebsocket_set_timeout() - marks the wsi as subject to a timeout
1470  *
1471  * You will not need this unless you are doing something special
1472  *
1473  * @wsi:        Websocket connection instance
1474  * @reason:     timeout reason
1475  * @secs:       how many seconds
1476  */
1477
1478 void
1479 libwebsocket_set_timeout(struct libwebsocket *wsi,
1480                                           enum pending_timeout reason, int secs)
1481 {
1482         struct timeval tv;
1483
1484         gettimeofday(&tv, NULL);
1485
1486         wsi->pending_timeout_limit = tv.tv_sec + secs;
1487         wsi->pending_timeout = reason;
1488 }
1489
1490
1491 /**
1492  * libwebsocket_get_socket_fd() - returns the socket file descriptor
1493  *
1494  * You will not need this unless you are doing something special
1495  *
1496  * @wsi:        Websocket connection instance
1497  */
1498
1499 LWS_VISIBLE int
1500 libwebsocket_get_socket_fd(struct libwebsocket *wsi)
1501 {
1502         return wsi->sock;
1503 }
1504
1505 #ifdef LWS_LATENCY
1506 void
1507 lws_latency(struct libwebsocket_context *context, struct libwebsocket *wsi,
1508                                      const char *action, int ret, int completed)
1509 {
1510         struct timeval tv;
1511         unsigned long u;
1512         char buf[256];
1513
1514         gettimeofday(&tv, NULL);
1515
1516         u = (tv.tv_sec * 1000000) + tv.tv_usec;
1517
1518         if (action) {
1519                 if (completed) {
1520                         if (wsi->action_start == wsi->latency_start)
1521                                 sprintf(buf,
1522                         "Completion first try lat %luus: %p: ret %d: %s\n",
1523                                         u - wsi->latency_start,
1524                                         (void *)wsi, ret, action);
1525                         else
1526                                 sprintf(buf,
1527                         "Completion %luus: lat %luus: %p: ret %d: %s\n",
1528                                         u - wsi->action_start,
1529                                         u - wsi->latency_start,
1530                                         (void *)wsi, ret, action);
1531                         wsi->action_start = 0;
1532                 } else
1533                         sprintf(buf, "lat %luus: %p: ret %d: %s\n",
1534                                         u - wsi->latency_start,
1535                                                       (void *)wsi, ret, action);
1536                 if (u - wsi->latency_start > context->worst_latency) {
1537                         context->worst_latency = u - wsi->latency_start;
1538                         strcpy(context->worst_latency_info, buf);
1539                 }
1540                 lwsl_latency("%s", buf);
1541         } else {
1542                 wsi->latency_start = u;
1543                 if (!wsi->action_start)
1544                         wsi->action_start = u;
1545         }
1546 }
1547 #endif
1548
1549 #ifdef LWS_NO_SERVER
1550 int
1551 _libwebsocket_rx_flow_control(struct libwebsocket *wsi)
1552 {
1553         return 0;
1554 }
1555 #else
1556 int
1557 _libwebsocket_rx_flow_control(struct libwebsocket *wsi)
1558 {
1559         struct libwebsocket_context *context = wsi->protocol->owning_server;
1560
1561         /* there is no pending change */
1562         if (!(wsi->u.ws.rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE))
1563                 return 0;
1564
1565         /* stuff is still buffered, not ready to really accept new input */
1566         if (wsi->u.ws.rxflow_buffer) {
1567                 /* get ourselves called back to deal with stashed buffer */
1568                 libwebsocket_callback_on_writable(context, wsi);
1569                 return 0;
1570         }
1571
1572         /* pending is cleared, we can change rxflow state */
1573
1574         wsi->u.ws.rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;
1575
1576         lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
1577                               wsi->u.ws.rxflow_change_to & LWS_RXFLOW_ALLOW);
1578
1579         /* adjust the pollfd for this wsi */
1580
1581         if (wsi->u.ws.rxflow_change_to & LWS_RXFLOW_ALLOW)
1582                 context->fds[wsi->position_in_fds_table].events |= POLLIN;
1583         else
1584                 context->fds[wsi->position_in_fds_table].events &= ~POLLIN;
1585
1586         if (wsi->u.ws.rxflow_change_to & LWS_RXFLOW_ALLOW)
1587                 /* external POLL support via protocol 0 */
1588                 context->protocols[0].callback(context, wsi,
1589                         LWS_CALLBACK_SET_MODE_POLL_FD,
1590                         wsi->user_space, (void *)(long)wsi->sock, POLLIN);
1591         else
1592                 /* external POLL support via protocol 0 */
1593                 context->protocols[0].callback(context, wsi,
1594                         LWS_CALLBACK_CLEAR_MODE_POLL_FD,
1595                         wsi->user_space, (void *)(long)wsi->sock, POLLIN);
1596
1597         return 1;
1598 }
1599 #endif
1600
1601 /**
1602  * libwebsocket_rx_flow_control() - Enable and disable socket servicing for
1603  *                              receieved packets.
1604  *
1605  * If the output side of a server process becomes choked, this allows flow
1606  * control for the input side.
1607  *
1608  * @wsi:        Websocket connection instance to get callback for
1609  * @enable:     0 = disable read servicing for this connection, 1 = enable
1610  */
1611
1612 LWS_VISIBLE int
1613 libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable)
1614 {
1615         if (enable == (wsi->u.ws.rxflow_change_to & LWS_RXFLOW_ALLOW))
1616                 return 0;
1617
1618         lwsl_info("libwebsocket_rx_flow_control(0x%p, %d)\n", wsi, enable);
1619         wsi->u.ws.rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable;
1620
1621         return 0;
1622 }
1623
1624 /**
1625  * libwebsocket_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
1626  *
1627  * When the user server code realizes it can accept more input, it can
1628  * call this to have the RX flow restriction removed from all connections using
1629  * the given protocol.
1630  *
1631  * @protocol:   all connections using this protocol will be allowed to receive
1632  */
1633
1634 LWS_VISIBLE void
1635 libwebsocket_rx_flow_allow_all_protocol(
1636                                 const struct libwebsocket_protocols *protocol)
1637 {
1638         struct libwebsocket_context *context = protocol->owning_server;
1639         int n;
1640         struct libwebsocket *wsi;
1641
1642         for (n = 0; n < context->fds_count; n++) {
1643                 wsi = context->lws_lookup[context->fds[n].fd];
1644                 if (!wsi)
1645                         continue;
1646                 if (wsi->protocol == protocol)
1647                         libwebsocket_rx_flow_control(wsi, LWS_RXFLOW_ALLOW);
1648         }
1649 }
1650
1651
1652 /**
1653  * libwebsocket_canonical_hostname() - returns this host's hostname
1654  *
1655  * This is typically used by client code to fill in the host parameter
1656  * when making a client connection.  You can only call it after the context
1657  * has been created.
1658  *
1659  * @context:    Websocket context
1660  */
1661
1662
1663 LWS_VISIBLE extern const char *
1664 libwebsocket_canonical_hostname(struct libwebsocket_context *context)
1665 {
1666         return (const char *)context->canonical_hostname;
1667 }
1668
1669
1670 static void sigpipe_handler(int x)
1671 {
1672 }
1673
1674 #ifdef LWS_OPENSSL_SUPPORT
1675 static int
1676 OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
1677 {
1678
1679         SSL *ssl;
1680         int n;
1681         struct libwebsocket_context *context;
1682
1683         ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1684                 SSL_get_ex_data_X509_STORE_CTX_idx());
1685
1686         /*
1687          * !!! nasty openssl requires the index to come as a library-scope
1688          * static
1689          */
1690         context = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
1691
1692         n = context->protocols[0].callback(NULL, NULL,
1693                 LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
1694                                                    x509_ctx, ssl, preverify_ok);
1695
1696         /* convert return code from 0 = OK to 1 = OK */
1697
1698         if (!n)
1699                 n = 1;
1700         else
1701                 n = 0;
1702
1703         return n;
1704 }
1705 #endif
1706
1707 int user_callback_handle_rxflow(callback_function callback_function,
1708                 struct libwebsocket_context *context,
1709                         struct libwebsocket *wsi,
1710                          enum libwebsocket_callback_reasons reason, void *user,
1711                                                           void *in, size_t len)
1712 {
1713         int n;
1714
1715         n = callback_function(context, wsi, reason, user, in, len);
1716         if (!n)
1717                 n = _libwebsocket_rx_flow_control(wsi);
1718
1719         return n;
1720 }
1721
1722
1723 /**
1724  * libwebsocket_create_context() - Create the websocket handler
1725  * @info:       pointer to struct with parameters
1726  *
1727  *      This function creates the listening socket (if serving) and takes care
1728  *      of all initialization in one step.
1729  *
1730  *      After initialization, it returns a struct libwebsocket_context * that
1731  *      represents this server.  After calling, user code needs to take care
1732  *      of calling libwebsocket_service() with the context pointer to get the
1733  *      server's sockets serviced.  This can be done in the same process context
1734  *      or a forked process, or another thread,
1735  *
1736  *      The protocol callback functions are called for a handful of events
1737  *      including http requests coming in, websocket connections becoming
1738  *      established, and data arriving; it's also called periodically to allow
1739  *      async transmission.
1740  *
1741  *      HTTP requests are sent always to the FIRST protocol in @protocol, since
1742  *      at that time websocket protocol has not been negotiated.  Other
1743  *      protocols after the first one never see any HTTP callack activity.
1744  *
1745  *      The server created is a simple http server by default; part of the
1746  *      websocket standard is upgrading this http connection to a websocket one.
1747  *
1748  *      This allows the same server to provide files like scripts and favicon /
1749  *      images or whatever over http and dynamic data over websockets all in
1750  *      one place; they're all handled in the user callback.
1751  */
1752
1753 LWS_VISIBLE struct libwebsocket_context *
1754 libwebsocket_create_context(struct lws_context_creation_info *info)
1755 {
1756         struct libwebsocket_context *context = NULL;
1757         char *p;
1758         int n;
1759 #ifndef LWS_NO_SERVER
1760         int opt = 1;
1761         struct libwebsocket *wsi;
1762         struct sockaddr_in serv_addr;
1763 #endif
1764 #ifndef LWS_NO_EXTENSIONS
1765         int m;
1766         struct libwebsocket_extension *ext;
1767 #endif
1768
1769 #ifdef LWS_OPENSSL_SUPPORT
1770         SSL_METHOD *method;
1771 #endif
1772
1773 #ifndef LWS_NO_DAEMONIZE
1774         int pid_daemon = get_daemonize_pid();
1775 #endif
1776
1777         lwsl_notice("Initial logging level %d\n", log_level);
1778         lwsl_notice("Library version: %s\n", library_version);
1779         lwsl_info(" LWS_MAX_HEADER_LEN: %u\n", LWS_MAX_HEADER_LEN);
1780         lwsl_info(" LWS_MAX_PROTOCOLS: %u\n", LWS_MAX_PROTOCOLS);
1781 #ifndef LWS_NO_EXTENSIONS
1782         lwsl_info(" LWS_MAX_EXTENSIONS_ACTIVE: %u\n",
1783                                                 LWS_MAX_EXTENSIONS_ACTIVE);
1784 #else
1785         lwsl_notice(" Configured without extension support\n");
1786 #endif
1787         lwsl_info(" SPEC_LATEST_SUPPORTED: %u\n", SPEC_LATEST_SUPPORTED);
1788         lwsl_info(" AWAITING_TIMEOUT: %u\n", AWAITING_TIMEOUT);
1789         if (info->ssl_cipher_list)
1790                 lwsl_info(" SSL ciphers: '%s'\n", info->ssl_cipher_list);
1791         lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH);
1792         lwsl_info(" LWS_MAX_ZLIB_CONN_BUFFER: %u\n", LWS_MAX_ZLIB_CONN_BUFFER);
1793
1794 #ifdef _WIN32
1795         {
1796                 WORD wVersionRequested;
1797                 WSADATA wsaData;
1798                 int err;
1799                 HMODULE wsdll;
1800
1801                 /* Use the MAKEWORD(lowbyte, highbyte) macro from Windef.h */
1802                 wVersionRequested = MAKEWORD(2, 2);
1803
1804                 err = WSAStartup(wVersionRequested, &wsaData);
1805                 if (err != 0) {
1806                         /* Tell the user that we could not find a usable */
1807                         /* Winsock DLL.                                  */
1808                         lwsl_err("WSAStartup failed with error: %d\n", err);
1809                         return NULL;
1810                 }
1811
1812                 /* default to a poll() made out of select() */
1813                 poll = emulated_poll;
1814
1815                 /* if windows socket lib available, use his WSAPoll */
1816                 wsdll = GetModuleHandle(_T("Ws2_32.dll"));
1817                 if (wsdll)
1818                         poll = (PFNWSAPOLL)GetProcAddress(wsdll, "WSAPoll");
1819
1820                 /* Finally fall back to emulated poll if all else fails */
1821                 if (!poll)
1822                         poll = emulated_poll;
1823         }
1824 #endif
1825
1826         context = (struct libwebsocket_context *)
1827                                 malloc(sizeof(struct libwebsocket_context));
1828         if (!context) {
1829                 lwsl_err("No memory for websocket context\n");
1830                 return NULL;
1831         }
1832         memset(context, 0, sizeof(*context));
1833 #ifndef LWS_NO_DAEMONIZE
1834         context->started_with_parent = pid_daemon;
1835         lwsl_notice(" Started with daemon pid %d\n", pid_daemon);
1836 #endif
1837
1838         context->listen_service_extraseen = 0;
1839         context->protocols = info->protocols;
1840         context->listen_port = info->port;
1841         context->http_proxy_port = 0;
1842         context->http_proxy_address[0] = '\0';
1843         context->options = info->options;
1844         /* to reduce this allocation, */
1845         context->max_fds = getdtablesize();
1846         lwsl_notice(" static allocation: %u + (%u x %u fds) = %u bytes\n",
1847                 sizeof(struct libwebsocket_context),
1848                 sizeof(struct pollfd) + sizeof(struct libwebsocket *),
1849                 context->max_fds,
1850                 sizeof(struct libwebsocket_context) +
1851                 ((sizeof(struct pollfd) + sizeof(struct libwebsocket *)) *
1852                                                              context->max_fds));
1853
1854         context->fds = (struct pollfd *)malloc(sizeof(struct pollfd) *
1855                                                               context->max_fds);
1856         if (context->fds == NULL) {
1857                 lwsl_err("Unable to allocate fds array for %d connections\n",
1858                                                               context->max_fds);
1859                 free(context);
1860                 return NULL;
1861         }
1862         context->lws_lookup = (struct libwebsocket **)
1863                       malloc(sizeof(struct libwebsocket *) * context->max_fds);
1864         if (context->lws_lookup == NULL) {
1865                 lwsl_err(
1866                   "Unable to allocate lws_lookup array for %d connections\n",
1867                                                               context->max_fds);
1868                 free(context->fds);
1869                 free(context);
1870                 return NULL;
1871         }
1872         memset(context->lws_lookup, 0, sizeof(struct libwebsocket *) *
1873                                                         context->max_fds);
1874
1875         context->fds_count = 0;
1876 #ifndef LWS_NO_EXTENSIONS
1877         context->extensions = info->extensions;
1878 #endif
1879         context->last_timeout_check_s = 0;
1880         context->user_space = info->user;
1881
1882 #if defined(WIN32) || defined(_WIN32)
1883         context->fd_random = 0;
1884 #else
1885         context->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
1886         if (context->fd_random < 0) {
1887                 lwsl_err("Unable to open random device %s %d\n",
1888                                     SYSTEM_RANDOM_FILEPATH, context->fd_random);
1889                 goto bail;
1890         }
1891 #endif
1892
1893 #ifdef LWS_OPENSSL_SUPPORT
1894         context->use_ssl = 0;
1895         context->allow_non_ssl_on_ssl_port = 0;
1896         context->ssl_ctx = NULL;
1897         context->ssl_client_ctx = NULL;
1898         openssl_websocket_private_data_index = 0;
1899 #endif
1900
1901         strcpy(context->canonical_hostname, "unknown");
1902
1903 #ifndef LWS_NO_SERVER
1904         if (!(info->options & LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME)) {
1905                 /* find canonical hostname */
1906                 gethostname((char *)context->canonical_hostname,
1907                                        sizeof(context->canonical_hostname) - 1);
1908
1909                 lwsl_notice(" canonical_hostname = %s\n",
1910                                         context->canonical_hostname);
1911         }
1912 #endif
1913
1914         /* split the proxy ads:port if given */
1915
1916         p = getenv("http_proxy");
1917         if (p) {
1918                 strncpy(context->http_proxy_address, p,
1919                                       sizeof(context->http_proxy_address) - 1);
1920                 context->http_proxy_address[
1921                                 sizeof(context->http_proxy_address) - 1] = '\0';
1922
1923                 p = strchr(context->http_proxy_address, ':');
1924                 if (p == NULL) {
1925                         lwsl_err("http_proxy needs to be ads:port\n");
1926                         goto bail;
1927                 }
1928                 *p = '\0';
1929                 context->http_proxy_port = atoi(p + 1);
1930
1931                 lwsl_notice(" Proxy %s:%u\n",
1932                                 context->http_proxy_address,
1933                                                       context->http_proxy_port);
1934         }
1935
1936 #ifndef LWS_NO_SERVER
1937         if (info->port) {
1938
1939 #ifdef LWS_OPENSSL_SUPPORT
1940                 context->use_ssl = info->ssl_cert_filepath != NULL &&
1941                                          info->ssl_private_key_filepath != NULL;
1942 #ifdef USE_CYASSL
1943                 lwsl_notice(" Compiled with CYASSL support\n");
1944 #else
1945                 lwsl_notice(" Compiled with OpenSSL support\n");
1946 #endif
1947                 if (context->use_ssl)
1948                         lwsl_notice(" Using SSL mode\n");
1949                 else
1950                         lwsl_notice(" Using non-SSL mode\n");
1951
1952 #else
1953                 if (info->ssl_cert_filepath != NULL &&
1954                                        info->ssl_private_key_filepath != NULL) {
1955                         lwsl_notice(" Not compiled for OpenSSl support!\n");
1956                         goto bail;
1957                 }
1958                 lwsl_notice(" Compiled without SSL support\n");
1959 #endif
1960
1961                 lwsl_notice(
1962                         " per-conn mem: %u + %u headers + protocol rx buf\n",
1963                                 sizeof(struct libwebsocket),
1964                                               sizeof(struct allocated_headers));
1965         }
1966 #endif
1967
1968         /* ignore SIGPIPE */
1969 #if defined(WIN32) || defined(_WIN32)
1970 #else
1971         signal(SIGPIPE, sigpipe_handler);
1972 #endif
1973
1974
1975 #ifdef LWS_OPENSSL_SUPPORT
1976
1977         /* basic openssl init */
1978
1979         SSL_library_init();
1980
1981         OpenSSL_add_all_algorithms();
1982         SSL_load_error_strings();
1983
1984         openssl_websocket_private_data_index =
1985                 SSL_get_ex_new_index(0, "libwebsockets", NULL, NULL, NULL);
1986
1987         /*
1988          * Firefox insists on SSLv23 not SSLv3
1989          * Konq disables SSLv2 by default now, SSLv23 works
1990          */
1991
1992         method = (SSL_METHOD *)SSLv23_server_method();
1993         if (!method) {
1994         int error = ERR_get_error();
1995                 lwsl_err("problem creating ssl method %lu: %s\n", 
1996                         error,
1997                         ERR_error_string(error,
1998                                               (char *)context->service_buffer));
1999                 goto bail;
2000         }
2001         context->ssl_ctx = SSL_CTX_new(method); /* create context */
2002         if (!context->ssl_ctx) {
2003         int error = ERR_get_error();
2004                 lwsl_err("problem creating ssl context %lu: %s\n",
2005                  error,
2006                  ERR_error_string(error,
2007                                   (char *)context->service_buffer));
2008                 goto bail;
2009         }
2010
2011 #ifdef SSL_OP_NO_COMPRESSION
2012         SSL_CTX_set_options(context->ssl_ctx, SSL_OP_NO_COMPRESSION);
2013 #endif
2014         SSL_CTX_set_options(context->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
2015         if (info->ssl_cipher_list)
2016                 SSL_CTX_set_cipher_list(context->ssl_ctx,
2017                                                 info->ssl_cipher_list);
2018
2019 #ifndef LWS_NO_CLIENT
2020
2021         /* client context */
2022
2023         if (info->port == CONTEXT_PORT_NO_LISTEN) {
2024                 method = (SSL_METHOD *)SSLv23_client_method();
2025                 if (!method) {
2026             int error = ERR_get_error();
2027                         lwsl_err("problem creating ssl method %lu: %s\n",
2028                      error,
2029                      ERR_error_string(error,
2030                                               (char *)context->service_buffer));
2031                         goto bail;
2032                 }
2033                 /* create context */
2034                 context->ssl_client_ctx = SSL_CTX_new(method);
2035                 if (!context->ssl_client_ctx) {
2036             int error = ERR_get_error();
2037                         lwsl_err("problem creating ssl context %lu: %s\n",
2038                      error,
2039                      ERR_error_string(error,
2040                                               (char *)context->service_buffer));
2041                         goto bail;
2042                 }
2043
2044 #ifdef SSL_OP_NO_COMPRESSION
2045                 SSL_CTX_set_options(context->ssl_client_ctx,
2046                                                          SSL_OP_NO_COMPRESSION);
2047 #endif
2048                 SSL_CTX_set_options(context->ssl_client_ctx,
2049                                                SSL_OP_CIPHER_SERVER_PREFERENCE);
2050                 if (info->ssl_cipher_list)
2051                         SSL_CTX_set_cipher_list(context->ssl_client_ctx,
2052                                                         info->ssl_cipher_list);
2053
2054                 /* openssl init for cert verification (for client sockets) */
2055                 if (!info->ssl_ca_filepath) {
2056                         if (!SSL_CTX_load_verify_locations(
2057                                 context->ssl_client_ctx, NULL,
2058                                                      LWS_OPENSSL_CLIENT_CERTS))
2059                                 lwsl_err(
2060                                     "Unable to load SSL Client certs from %s "
2061                                     "(set by --with-client-cert-dir= "
2062                                     "in configure) --  client ssl isn't "
2063                                     "going to work", LWS_OPENSSL_CLIENT_CERTS);
2064                 } else
2065                         if (!SSL_CTX_load_verify_locations(
2066                                 context->ssl_client_ctx, info->ssl_ca_filepath,
2067                                                                   NULL))
2068                                 lwsl_err(
2069                                         "Unable to load SSL Client certs "
2070                                         "file from %s -- client ssl isn't "
2071                                         "going to work", info->ssl_ca_filepath);
2072
2073                 /*
2074                  * callback allowing user code to load extra verification certs
2075                  * helping the client to verify server identity
2076                  */
2077
2078                 /* support for client-side certificate authentication */
2079                 if (info->ssl_cert_filepath) {
2080                         n = SSL_CTX_use_certificate_chain_file(
2081                                 context->ssl_client_ctx,
2082                                                 info->ssl_cert_filepath);
2083                         if (n != 1) {
2084                                 lwsl_err("problem getting cert '%s' %lu: %s\n",
2085                                         info->ssl_cert_filepath,
2086                                         ERR_get_error(),
2087                                         ERR_error_string(ERR_get_error(),
2088                                         (char *)context->service_buffer));
2089                                 goto bail;
2090                         }
2091                 } 
2092                 if (info->ssl_private_key_filepath) {
2093                         /* set the private key from KeyFile */
2094                         if (SSL_CTX_use_PrivateKey_file(context->ssl_client_ctx,
2095                                      info->ssl_private_key_filepath,
2096                                                        SSL_FILETYPE_PEM) != 1) {
2097                                 lwsl_err("use_PrivateKey_file '%s' %lu: %s\n",
2098                                         info->ssl_private_key_filepath,
2099                                         ERR_get_error(),
2100                                         ERR_error_string(ERR_get_error(),
2101                                               (char *)context->service_buffer));
2102                                 goto bail;
2103                         }
2104
2105                         /* verify private key */
2106                         if (!SSL_CTX_check_private_key(context->ssl_client_ctx)) {
2107                                 lwsl_err("Private SSL key doesn't match cert\n");
2108                                 goto bail;
2109                         }
2110                 } 
2111
2112                 context->protocols[0].callback(context, NULL,
2113                         LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
2114                         context->ssl_client_ctx, NULL, 0);
2115         }
2116 #endif
2117
2118         /* as a server, are we requiring clients to identify themselves? */
2119
2120         if (info->options &
2121                         LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT) {
2122
2123                 /* absolutely require the client cert */
2124
2125                 SSL_CTX_set_verify(context->ssl_ctx,
2126                        SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2127                                                        OpenSSL_verify_callback);
2128
2129                 /*
2130                  * give user code a chance to load certs into the server
2131                  * allowing it to verify incoming client certs
2132                  */
2133
2134                 context->protocols[0].callback(context, NULL,
2135                         LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
2136                                                      context->ssl_ctx, NULL, 0);
2137         }
2138
2139         if(info->options & LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT) {
2140                 /* Normally SSL listener rejects non-ssl, optionally allow */
2141                 context->allow_non_ssl_on_ssl_port = 1;
2142         }
2143
2144         if (context->use_ssl) {
2145
2146                 /* openssl init for server sockets */
2147
2148                 /* set the local certificate from CertFile */
2149                 n = SSL_CTX_use_certificate_chain_file(context->ssl_ctx,
2150                                         info->ssl_cert_filepath);
2151                 if (n != 1) {
2152             int error = ERR_get_error();
2153                         lwsl_err("problem getting cert '%s' %lu: %s\n",
2154                                 info->ssl_cert_filepath,
2155                                 error,
2156                                 ERR_error_string(error,
2157                                               (char *)context->service_buffer));
2158                         goto bail;
2159                 }
2160                 /* set the private key from KeyFile */
2161                 if (SSL_CTX_use_PrivateKey_file(context->ssl_ctx,
2162                              info->ssl_private_key_filepath,
2163                                                        SSL_FILETYPE_PEM) != 1) {
2164             int error = ERR_get_error();
2165                         lwsl_err("ssl problem getting key '%s' %lu: %s\n",
2166                                 info->ssl_private_key_filepath,
2167                                         error,
2168                                         ERR_error_string(error,
2169                                               (char *)context->service_buffer));
2170                         goto bail;
2171                 }
2172                 /* verify private key */
2173                 if (!SSL_CTX_check_private_key(context->ssl_ctx)) {
2174                         lwsl_err("Private SSL key doesn't match cert\n");
2175                         goto bail;
2176                 }
2177
2178                 /* SSL is happy and has a cert it's content with */
2179         }
2180 #endif
2181
2182 #ifndef LWS_NO_SERVER
2183         /* set up our external listening socket we serve on */
2184
2185         if (info->port) {
2186                 int sockfd;
2187
2188                 sockfd = socket(AF_INET, SOCK_STREAM, 0);
2189                 if (sockfd < 0) {
2190                         lwsl_err("ERROR opening socket\n");
2191                         goto bail;
2192                 }
2193
2194 #ifndef WIN32
2195                 /*
2196                  * allow us to restart even if old sockets in TIME_WAIT
2197                  * (REUSEADDR on Unix means, "don't hang on to this
2198                  * address after the listener is closed."  On Windows, though,
2199                  * it means "don't keep other processes from binding to
2200                  * this address while we're using it)
2201                  */
2202                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
2203                                               (const void *)&opt, sizeof(opt));
2204 #endif
2205
2206                 /* Disable Nagle */
2207                 opt = 1;
2208                 setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY,
2209                                               (const void *)&opt, sizeof(opt));
2210
2211                 #if defined(WIN32) || defined(_WIN32)
2212                 opt = 0;
2213                 ioctlsocket(sockfd, FIONBIO, (unsigned long *)&opt);
2214                 #else
2215                 fcntl(sockfd, F_SETFL, O_NONBLOCK);
2216                 #endif
2217
2218                 bzero((char *) &serv_addr, sizeof(serv_addr));
2219                 serv_addr.sin_family = AF_INET;
2220                 if (info->iface == NULL)
2221                         serv_addr.sin_addr.s_addr = INADDR_ANY;
2222                 else
2223                         if (interface_to_sa(info->iface, &serv_addr,
2224                                                 sizeof(serv_addr)) < 0) {
2225                                 lwsl_err("Unable to find interface %s\n",
2226                                                         info->iface);
2227                                 compatible_close(sockfd);
2228                                 goto bail;
2229                         }
2230                 serv_addr.sin_port = htons(info->port);
2231
2232                 n = bind(sockfd, (struct sockaddr *) &serv_addr,
2233                                                              sizeof(serv_addr));
2234                 if (n < 0) {
2235                         lwsl_err("ERROR on binding to port %d (%d %d)\n",
2236                                                         info->port, n, errno);
2237                         compatible_close(sockfd);
2238                         goto bail;
2239                 }
2240
2241                 wsi = (struct libwebsocket *)malloc(
2242                                         sizeof(struct libwebsocket));
2243                 if (wsi == NULL) {
2244                         lwsl_err("Out of mem\n");
2245                         compatible_close(sockfd);
2246                         goto bail;
2247                 }
2248                 memset(wsi, 0, sizeof(struct libwebsocket));
2249                 wsi->sock = sockfd;
2250 #ifndef LWS_NO_EXTENSIONS
2251                 wsi->count_active_extensions = 0;
2252 #endif
2253                 wsi->mode = LWS_CONNMODE_SERVER_LISTENER;
2254
2255                 insert_wsi_socket_into_fds(context, wsi);
2256
2257                 context->listen_service_modulo = LWS_LISTEN_SERVICE_MODULO;
2258                 context->listen_service_count = 0;
2259                 context->listen_service_fd = sockfd;
2260
2261                 listen(sockfd, LWS_SOMAXCONN);
2262                 lwsl_notice(" Listening on port %d\n", info->port);
2263         }
2264 #endif
2265
2266         /*
2267          * drop any root privs for this process
2268          * to listen on port < 1023 we would have needed root, but now we are
2269          * listening, we don't want the power for anything else
2270          */
2271 #if defined(WIN32) || defined(_WIN32)
2272 #else
2273         if (info->gid != -1)
2274                 if (setgid(info->gid))
2275                         lwsl_warn("setgid: %s\n", strerror(errno));
2276         if (info->uid != -1)
2277                 if (setuid(info->uid))
2278                         lwsl_warn("setuid: %s\n", strerror(errno));
2279 #endif
2280
2281         /* initialize supported protocols */
2282
2283         for (context->count_protocols = 0;
2284                 info->protocols[context->count_protocols].callback;
2285                                                    context->count_protocols++) {
2286
2287                 lwsl_parser("  Protocol: %s\n",
2288                                 info->protocols[context->count_protocols].name);
2289
2290                 info->protocols[context->count_protocols].owning_server =
2291                                                                         context;
2292                 info->protocols[context->count_protocols].protocol_index =
2293                                                        context->count_protocols;
2294
2295                 /*
2296                  * inform all the protocols that they are doing their one-time
2297                  * initialization if they want to
2298                  */
2299                 info->protocols[context->count_protocols].callback(context,
2300                                NULL, LWS_CALLBACK_PROTOCOL_INIT, NULL, NULL, 0);
2301         }
2302
2303 #ifndef LWS_NO_EXTENSIONS
2304         /*
2305          * give all extensions a chance to create any per-context
2306          * allocations they need
2307          */
2308
2309         m = LWS_EXT_CALLBACK_CLIENT_CONTEXT_CONSTRUCT;
2310         if (info->port)
2311                 m = LWS_EXT_CALLBACK_SERVER_CONTEXT_CONSTRUCT;
2312
2313         if (info->extensions) {
2314                 ext = info->extensions;
2315                 while (ext->callback) {
2316                         lwsl_ext("  Extension: %s\n", ext->name);
2317                         ext->callback(context, ext, NULL,
2318                         (enum libwebsocket_extension_callback_reasons)m,
2319                                                                 NULL, NULL, 0);
2320                         ext++;
2321                 }
2322         }
2323 #endif
2324         return context;
2325
2326 bail:
2327         libwebsocket_context_destroy(context);
2328         return NULL;
2329 }
2330
2331 /**
2332  * libwebsocket_set_proxy() - Setups proxy to libwebsocket_context.
2333  * @context:    pointer to struct libwebsocket_context you want set proxy to
2334  * @proxy: pointer to c string containing proxy in format address:port
2335  *
2336  * Returns 0 if proxy string was parsed and proxy was setup. 
2337  * Returns -1 if @proxy is NULL or has incorrect format.
2338  *
2339  * This is only required if your OS does not provide the http_proxy
2340  * enviroment variable (eg, OSX)
2341  *
2342  *   IMPORTANT! You should call this function right after creation of the
2343  *   libwebsocket_context and before call to connect. If you call this
2344  *   function after connect behavior is undefined.
2345  *   This function will override proxy settings made on libwebsocket_context
2346  *   creation with genenv() call.
2347  */
2348
2349 LWS_VISIBLE int
2350 libwebsocket_set_proxy(struct libwebsocket_context *context, const char *proxy)
2351 {
2352         char *p;
2353         
2354         if (!proxy)
2355                 return -1;
2356
2357         strncpy(context->http_proxy_address, proxy,
2358                                 sizeof(context->http_proxy_address) - 1);
2359         context->http_proxy_address[
2360                                 sizeof(context->http_proxy_address) - 1] = '\0';
2361         
2362         p = strchr(context->http_proxy_address, ':');
2363         if (!p) {
2364                 lwsl_err("http_proxy needs to be ads:port\n");
2365
2366                 return -1;
2367         }
2368         *p = '\0';
2369         context->http_proxy_port = atoi(p + 1);
2370         
2371         lwsl_notice(" Proxy %s:%u\n", context->http_proxy_address,
2372                                                 context->http_proxy_port);
2373
2374         return 0;
2375 }
2376
2377 /**
2378  * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket
2379  *                                connection.
2380  * @wsi:        pointer to struct websocket you want to know the protocol of
2381  *
2382  *
2383  *      Some apis can act on all live connections of a given protocol,
2384  *      this is how you can get a pointer to the active protocol if needed.
2385  */
2386
2387 LWS_VISIBLE const struct libwebsocket_protocols *
2388 libwebsockets_get_protocol(struct libwebsocket *wsi)
2389 {
2390         return wsi->protocol;
2391 }
2392
2393 LWS_VISIBLE int
2394 libwebsocket_is_final_fragment(struct libwebsocket *wsi)
2395 {
2396         return wsi->u.ws.final;
2397 }
2398
2399 LWS_VISIBLE unsigned char
2400 libwebsocket_get_reserved_bits(struct libwebsocket *wsi)
2401 {
2402         return wsi->u.ws.rsv;
2403 }
2404
2405 int
2406 libwebsocket_ensure_user_space(struct libwebsocket *wsi)
2407 {
2408         if (!wsi->protocol)
2409                 return 1;
2410
2411         /* allocate the per-connection user memory (if any) */
2412
2413         if (wsi->protocol->per_session_data_size && !wsi->user_space) {
2414                 wsi->user_space = malloc(
2415                                   wsi->protocol->per_session_data_size);
2416                 if (wsi->user_space  == NULL) {
2417                         lwsl_err("Out of memory for conn user space\n");
2418                         return 1;
2419                 }
2420                 memset(wsi->user_space, 0,
2421                                          wsi->protocol->per_session_data_size);
2422         }
2423         return 0;
2424 }
2425
2426 static void lwsl_emit_stderr(int level, const char *line)
2427 {
2428         char buf[300];
2429         struct timeval tv;
2430         int n;
2431
2432         gettimeofday(&tv, NULL);
2433
2434         buf[0] = '\0';
2435         for (n = 0; n < LLL_COUNT; n++)
2436                 if (level == (1 << n)) {
2437                         sprintf(buf, "[%ld:%04d] %s: ", tv.tv_sec,
2438                                 (int)(tv.tv_usec / 100), log_level_names[n]);
2439                         break;
2440                 }
2441
2442         fprintf(stderr, "%s%s", buf, line);
2443 }
2444
2445 #if defined(WIN32) || defined(_WIN32)
2446 LWS_VISIBLE void lwsl_emit_syslog(int level, const char *line)
2447 {
2448         lwsl_emit_stderr(level, line);
2449 }
2450 #else
2451 LWS_VISIBLE void lwsl_emit_syslog(int level, const char *line)
2452 {
2453         int syslog_level = LOG_DEBUG;
2454
2455         switch (level) {
2456         case LLL_ERR:
2457                 syslog_level = LOG_ERR;
2458                 break;
2459         case LLL_WARN:
2460                 syslog_level = LOG_WARNING;
2461                 break;
2462         case LLL_NOTICE:
2463                 syslog_level = LOG_NOTICE;
2464                 break;
2465         case LLL_INFO:
2466                 syslog_level = LOG_INFO;
2467                 break;
2468         }
2469         syslog(syslog_level, "%s", line);
2470 }
2471 #endif
2472
2473 LWS_VISIBLE void _lws_log(int filter, const char *format, ...)
2474 {
2475         char buf[256];
2476         va_list ap;
2477
2478         if (!(log_level & filter))
2479                 return;
2480
2481         va_start(ap, format);
2482         vsnprintf(buf, sizeof(buf), format, ap);
2483         buf[sizeof(buf) - 1] = '\0';
2484         va_end(ap);
2485
2486         lwsl_emit(filter, buf);
2487 }
2488
2489 /**
2490  * lws_set_log_level() - Set the logging bitfield
2491  * @level:      OR together the LLL_ debug contexts you want output from
2492  * @log_emit_function:  NULL to leave it as it is, or a user-supplied
2493  *                      function to perform log string emission instead of
2494  *                      the default stderr one.
2495  *
2496  *      log level defaults to "err", "warn" and "notice" contexts enabled and
2497  *      emission on stderr.
2498  */
2499
2500 LWS_VISIBLE void lws_set_log_level(int level, void (*log_emit_function)(int level,
2501                                                               const char *line))
2502 {
2503         log_level = level;
2504         if (log_emit_function)
2505                 lwsl_emit = log_emit_function;
2506 }