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