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