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