ws-server: restrict returned Sec-Websocket-Protocol to the chosen name only
[platform/upstream/libwebsockets.git] / lib / lws-plat-win.c
1 #ifndef _WINSOCK_DEPRECATED_NO_WARNINGS
2 #define _WINSOCK_DEPRECATED_NO_WARNINGS
3 #endif
4 #include "private-libwebsockets.h"
5
6 unsigned long long
7 time_in_microseconds()
8 {
9 #define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL
10         FILETIME filetime;
11         ULARGE_INTEGER datetime;
12
13 #ifdef _WIN32_WCE
14         GetCurrentFT(&filetime);
15 #else
16         GetSystemTimeAsFileTime(&filetime);
17 #endif
18
19         /*
20          * As per Windows documentation for FILETIME, copy the resulting FILETIME structure to a
21          * ULARGE_INTEGER structure using memcpy (using memcpy instead of direct assignment can
22          * prevent alignment faults on 64-bit Windows).
23          */
24         memcpy(&datetime, &filetime, sizeof(datetime));
25
26         /* Windows file times are in 100s of nanoseconds. */
27         return (datetime.QuadPart - DELTA_EPOCH_IN_MICROSECS) / 10;
28 }
29
30 #ifdef _WIN32_WCE
31 time_t time(time_t *t)
32 {
33         time_t ret = time_in_microseconds() / 1000000;
34         *t = ret;
35         return ret;
36 }
37 #endif
38
39 /* file descriptor hash management */
40
41 struct lws *
42 wsi_from_fd(const struct lws_context *context, lws_sockfd_type fd)
43 {
44         int h = LWS_FD_HASH(fd);
45         int n = 0;
46
47         for (n = 0; n < context->fd_hashtable[h].length; n++)
48                 if (context->fd_hashtable[h].wsi[n]->sock == fd)
49                         return context->fd_hashtable[h].wsi[n];
50
51         return NULL;
52 }
53
54 int
55 insert_wsi(struct lws_context *context, struct lws *wsi)
56 {
57         int h = LWS_FD_HASH(wsi->sock);
58
59         if (context->fd_hashtable[h].length == (getdtablesize() - 1)) {
60                 lwsl_err("hash table overflow\n");
61                 return 1;
62         }
63
64         context->fd_hashtable[h].wsi[context->fd_hashtable[h].length++] = wsi;
65
66         return 0;
67 }
68
69 int
70 delete_from_fd(struct lws_context *context, lws_sockfd_type fd)
71 {
72         int h = LWS_FD_HASH(fd);
73         int n = 0;
74
75         for (n = 0; n < context->fd_hashtable[h].length; n++)
76                 if (context->fd_hashtable[h].wsi[n]->sock == fd) {
77                         while (n < context->fd_hashtable[h].length) {
78                                 context->fd_hashtable[h].wsi[n] =
79                                             context->fd_hashtable[h].wsi[n + 1];
80                                 n++;
81                         }
82                         context->fd_hashtable[h].length--;
83
84                         return 0;
85                 }
86
87         lwsl_err("Failed to find fd %d requested for "
88                  "delete in hashtable\n", fd);
89         return 1;
90 }
91
92 LWS_VISIBLE int lws_get_random(struct lws_context *context,
93                                                              void *buf, int len)
94 {
95         int n;
96         char *p = (char *)buf;
97
98         for (n = 0; n < len; n++)
99                 p[n] = (unsigned char)rand();
100
101         return n;
102 }
103
104 LWS_VISIBLE int lws_send_pipe_choked(struct lws *wsi)
105 {
106         return (int)wsi->sock_send_blocking;
107 }
108
109 LWS_VISIBLE int lws_poll_listen_fd(struct lws_pollfd *fd)
110 {
111         fd_set readfds;
112         struct timeval tv = { 0, 0 };
113
114         assert((fd->events & LWS_POLLIN) == LWS_POLLIN);
115
116         FD_ZERO(&readfds);
117         FD_SET(fd->fd, &readfds);
118
119         return select(fd->fd + 1, &readfds, NULL, NULL, &tv);
120 }
121
122 /**
123  * lws_cancel_service() - Cancel servicing of pending websocket activity
124  * @context:    Websocket context
125  *
126  *      This function let a call to lws_service() waiting for a timeout
127  *      immediately return.
128  */
129 LWS_VISIBLE void
130 lws_cancel_service(struct lws_context *context)
131 {
132         struct lws_context_per_thread *pt = &context->pt[0];
133         int n = context->count_threads;
134
135         while (n--) {
136                 WSASetEvent(pt->events[0]);
137                 pt++;
138         }
139 }
140
141 LWS_VISIBLE void
142 lws_cancel_service_pt(struct lws *wsi)
143 {
144         struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
145         WSASetEvent(pt->events[0]);
146 }
147
148 LWS_VISIBLE void lwsl_emit_syslog(int level, const char *line)
149 {
150         lwsl_emit_stderr(level, line);
151 }
152
153 LWS_VISIBLE int
154 lws_plat_service_tsi(struct lws_context *context, int timeout_ms, int tsi)
155 {
156         struct lws_context_per_thread *pt = &context->pt[tsi];
157         WSANETWORKEVENTS networkevents;
158         struct lws_pollfd *pfd;
159         struct lws *wsi;
160         unsigned int i;
161         DWORD ev;
162         int n, m;
163
164         /* stay dead once we are dead */
165         if (context == NULL)
166                 return 1;
167
168         if (!context->service_tid_detected) {
169                 struct lws _lws;
170
171                 memset(&_lws, 0, sizeof(_lws));
172                 _lws.context = context;
173
174                 context->service_tid_detected = context->protocols[0].callback(
175                         &_lws, LWS_CALLBACK_GET_THREAD_ID, NULL, NULL, 0);
176         }
177         context->service_tid = context->service_tid_detected;
178
179         if (timeout_ms < 0)
180                 goto faked_service;
181
182         for (i = 0; i < pt->fds_count; ++i) {
183                 pfd = &pt->fds[i];
184                 if (pfd->fd == pt->lserv_fd)
185                         continue;
186
187                 if (pfd->events & LWS_POLLOUT) {
188                         wsi = wsi_from_fd(context, pfd->fd);
189                         if (!wsi || wsi->sock_send_blocking)
190                                 continue;
191                         pfd->revents = LWS_POLLOUT;
192                         n = lws_service_fd(context, pfd);
193                         if (n < 0)
194                                 return -1;
195                         /* if something closed, retry this slot */
196                         if (n)
197                                 i--;
198                 }
199         }
200
201         /* if we know something needs service already, don't wait in poll */
202         timeout_ms = lws_service_adjust_timeout(context, timeout_ms, tsi);
203
204         ev = WSAWaitForMultipleEvents(pt->fds_count + 1, pt->events,
205                                       FALSE, timeout_ms, FALSE);
206         context->service_tid = 0;
207
208         if (ev == WSA_WAIT_TIMEOUT) {
209                 lws_service_fd(context, NULL);
210                 return 0;
211         }
212
213         if (ev == WSA_WAIT_EVENT_0) {
214                 WSAResetEvent(pt->events[0]);
215                 return 0;
216         }
217
218         if (ev < WSA_WAIT_EVENT_0 || ev > WSA_WAIT_EVENT_0 + pt->fds_count)
219                 return -1;
220
221         pfd = &pt->fds[ev - WSA_WAIT_EVENT_0 - 1];
222
223         /* eh... is one event at a time the best windows can do? */
224
225         if (WSAEnumNetworkEvents(pfd->fd, pt->events[ev - WSA_WAIT_EVENT_0],
226                                  &networkevents) == SOCKET_ERROR) {
227                 lwsl_err("WSAEnumNetworkEvents() failed with error %d\n",
228                                                                      LWS_ERRNO);
229                 return -1;
230         }
231
232         pfd->revents = (short)networkevents.lNetworkEvents;
233
234         if (pfd->revents & LWS_POLLOUT) {
235                 wsi = wsi_from_fd(context, pfd->fd);
236                 if (wsi)
237                         wsi->sock_send_blocking = 0;
238         }
239
240 faked_service:
241
242         /* if someone faked their LWS_POLLIN, then go through all active fds */
243
244         if (lws_service_flag_pending(context, tsi)) {
245                 /* any socket with events to service? */
246                 for (n = 0; n < (int)pt->fds_count; n++) {
247                         if (!pt->fds[n].revents)
248                                 continue;
249
250                         m = lws_service_fd_tsi(context, &pt->fds[n], tsi);
251                         if (m < 0)
252                                 return -1;
253                         /* if something closed, retry this slot */
254                         if (m)
255                                 n--;
256                 }
257                 return 0;
258         }
259
260         if (timeout_ms < 0)
261                 return 0;
262
263         /* otherwise just do the one... must be a way to improve that... */
264
265         return lws_service_fd_tsi(context, pfd, tsi);
266 }
267
268 LWS_VISIBLE int
269 lws_plat_service(struct lws_context *context, int timeout_ms)
270 {
271         return lws_plat_service_tsi(context, timeout_ms, 0);
272 }
273
274 LWS_VISIBLE int
275 lws_plat_set_socket_options(struct lws_context *context, lws_sockfd_type fd)
276 {
277         int optval = 1;
278         int optlen = sizeof(optval);
279         u_long optl = 1;
280         DWORD dwBytesRet;
281         struct tcp_keepalive alive;
282         int protonbr;
283 #ifndef _WIN32_WCE
284         struct protoent *tcp_proto;
285 #endif
286
287         if (context->ka_time) {
288                 /* enable keepalive on this socket */
289                 optval = 1;
290                 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
291                                              (const char *)&optval, optlen) < 0)
292                         return 1;
293
294                 alive.onoff = TRUE;
295                 alive.keepalivetime = context->ka_time;
296                 alive.keepaliveinterval = context->ka_interval;
297
298                 if (WSAIoctl(fd, SIO_KEEPALIVE_VALS, &alive, sizeof(alive),
299                                               NULL, 0, &dwBytesRet, NULL, NULL))
300                         return 1;
301         }
302
303         /* Disable Nagle */
304         optval = 1;
305 #ifndef _WIN32_WCE
306         tcp_proto = getprotobyname("TCP");
307         if (!tcp_proto) {
308                 lwsl_err("getprotobyname() failed with error %d\n", LWS_ERRNO);
309                 return 1;
310         }
311         protonbr = tcp_proto->p_proto;
312 #else
313         protonbr = 6;
314 #endif
315
316         setsockopt(fd, protonbr, TCP_NODELAY, (const char *)&optval, optlen);
317
318         /* We are nonblocking... */
319         ioctlsocket(fd, FIONBIO, &optl);
320
321         return 0;
322 }
323
324 LWS_VISIBLE void
325 lws_plat_drop_app_privileges(struct lws_context_creation_info *info)
326 {
327 }
328
329 LWS_VISIBLE int
330 lws_plat_context_early_init(void)
331 {
332         WORD wVersionRequested;
333         WSADATA wsaData;
334         int err;
335
336         /* Use the MAKEWORD(lowbyte, highbyte) macro from Windef.h */
337         wVersionRequested = MAKEWORD(2, 2);
338
339         err = WSAStartup(wVersionRequested, &wsaData);
340         if (!err)
341                 return 0;
342         /*
343          * Tell the user that we could not find a usable
344          * Winsock DLL
345          */
346         lwsl_err("WSAStartup failed with error: %d\n", err);
347
348         return 1;
349 }
350
351 LWS_VISIBLE void
352 lws_plat_context_early_destroy(struct lws_context *context)
353 {
354         struct lws_context_per_thread *pt = &context->pt[0];
355         int n = context->count_threads;
356
357         while (n--) {
358                 if (pt->events) {
359                         WSACloseEvent(pt->events[0]);
360                         lws_free(pt->events);
361                 }
362                 pt++;
363         }
364 }
365
366 LWS_VISIBLE void
367 lws_plat_context_late_destroy(struct lws_context *context)
368 {
369         int n;
370
371         for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
372                 if (context->fd_hashtable[n].wsi)
373                         lws_free(context->fd_hashtable[n].wsi);
374         }
375
376         WSACleanup();
377 }
378
379 LWS_VISIBLE LWS_EXTERN int
380 lws_interface_to_sa(int ipv6,
381                 const char *ifname, struct sockaddr_in *addr, size_t addrlen)
382 {
383         long long address = inet_addr(ifname);
384
385         if (address == INADDR_NONE) {
386                 struct hostent *entry = gethostbyname(ifname);
387                 if (entry)
388                         address = ((struct in_addr *)entry->h_addr_list[0])->s_addr;
389         }
390
391         if (address == INADDR_NONE)
392                 return -1;
393
394         addr->sin_addr.s_addr = (unsigned long)address;
395
396         return 0;
397 }
398
399 LWS_VISIBLE void
400 lws_plat_insert_socket_into_fds(struct lws_context *context, struct lws *wsi)
401 {
402         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
403
404         pt->fds[pt->fds_count++].revents = 0;
405         pt->events[pt->fds_count] = WSACreateEvent();
406         WSAEventSelect(wsi->sock, pt->events[pt->fds_count],
407                        LWS_POLLIN | LWS_POLLHUP);
408 }
409
410 LWS_VISIBLE void
411 lws_plat_delete_socket_from_fds(struct lws_context *context,
412                                                 struct lws *wsi, int m)
413 {
414         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
415
416         WSACloseEvent(pt->events[m + 1]);
417         pt->events[m + 1] = pt->events[pt->fds_count--];
418 }
419
420 LWS_VISIBLE void
421 lws_plat_service_periodic(struct lws_context *context)
422 {
423 }
424
425 LWS_VISIBLE int
426 lws_plat_change_pollfd(struct lws_context *context,
427                       struct lws *wsi, struct lws_pollfd *pfd)
428 {
429         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
430         long networkevents = LWS_POLLHUP;
431
432         if ((pfd->events & LWS_POLLIN))
433                 networkevents |= LWS_POLLIN;
434
435         if ((pfd->events & LWS_POLLOUT))
436                 networkevents |= LWS_POLLOUT;
437
438         if (WSAEventSelect(wsi->sock,
439                         pt->events[wsi->position_in_fds_table + 1],
440                                                networkevents) != SOCKET_ERROR)
441                 return 0;
442
443         lwsl_err("WSAEventSelect() failed with error %d\n", LWS_ERRNO);
444
445         return 1;
446 }
447
448 LWS_VISIBLE const char *
449 lws_plat_inet_ntop(int af, const void *src, char *dst, int cnt)
450 {
451         WCHAR *buffer;
452         DWORD bufferlen = cnt;
453         BOOL ok = FALSE;
454
455         buffer = lws_malloc(bufferlen);
456         if (!buffer) {
457                 lwsl_err("Out of memory\n");
458                 return NULL;
459         }
460
461         if (af == AF_INET) {
462                 struct sockaddr_in srcaddr;
463                 bzero(&srcaddr, sizeof(srcaddr));
464                 srcaddr.sin_family = AF_INET;
465                 memcpy(&(srcaddr.sin_addr), src, sizeof(srcaddr.sin_addr));
466
467                 if (!WSAAddressToStringW((struct sockaddr*)&srcaddr, sizeof(srcaddr), 0, buffer, &bufferlen))
468                         ok = TRUE;
469 #ifdef LWS_USE_IPV6
470         } else if (af == AF_INET6) {
471                 struct sockaddr_in6 srcaddr;
472                 bzero(&srcaddr, sizeof(srcaddr));
473                 srcaddr.sin6_family = AF_INET6;
474                 memcpy(&(srcaddr.sin6_addr), src, sizeof(srcaddr.sin6_addr));
475
476                 if (!WSAAddressToStringW((struct sockaddr*)&srcaddr, sizeof(srcaddr), 0, buffer, &bufferlen))
477                         ok = TRUE;
478 #endif
479         } else
480                 lwsl_err("Unsupported type\n");
481
482         if (!ok) {
483                 int rv = WSAGetLastError();
484                 lwsl_err("WSAAddressToString() : %d\n", rv);
485         } else {
486                 if (WideCharToMultiByte(CP_ACP, 0, buffer, bufferlen, dst, cnt, 0, NULL) <= 0)
487                         ok = FALSE;
488         }
489
490         lws_free(buffer);
491         return ok ? dst : NULL;
492 }
493
494 static lws_filefd_type
495 _lws_plat_file_open(struct lws *wsi, const char *filename,
496                     unsigned long *filelen, int flags)
497 {
498         HANDLE ret;
499         WCHAR buf[MAX_PATH];
500
501         (void)wsi;
502         MultiByteToWideChar(CP_UTF8, 0, filename, -1, buf, ARRAY_SIZE(buf));
503         if ((flags & 7) == _O_RDONLY) {
504                 ret = CreateFileW(buf, GENERIC_READ, FILE_SHARE_READ,
505                           NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
506         } else {
507                 lwsl_err("%s: open for write not implemented\n", __func__);
508                 *filelen = 0;
509                 return LWS_INVALID_FILE;
510         }
511
512         if (ret != LWS_INVALID_FILE)
513                 *filelen = GetFileSize(ret, NULL);
514
515         return ret;
516 }
517
518 static int
519 _lws_plat_file_close(struct lws *wsi, lws_filefd_type fd)
520 {
521         (void)wsi;
522
523         CloseHandle((HANDLE)fd);
524
525         return 0;
526 }
527
528 static unsigned long
529 _lws_plat_file_seek_cur(struct lws *wsi, lws_filefd_type fd, long offset)
530 {
531         (void)wsi;
532
533         return SetFilePointer((HANDLE)fd, offset, NULL, FILE_CURRENT);
534 }
535
536 static int
537 _lws_plat_file_read(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
538                     unsigned char* buf, unsigned long len)
539 {
540         DWORD _amount;
541
542         (void *)wsi;
543         if (!ReadFile((HANDLE)fd, buf, (DWORD)len, &_amount, NULL)) {
544                 *amount = 0;
545
546                 return 1;
547         }
548
549         *amount = (unsigned long)_amount;
550
551         return 0;
552 }
553
554 static int
555 _lws_plat_file_write(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
556                      unsigned char* buf, unsigned long len)
557 {
558         (void)wsi;
559         (void)fd;
560         (void)amount;
561         (void)buf;
562         (void)len;
563
564         lwsl_err("%s: not implemented yet on this platform\n", __func__);
565
566         return -1;
567 }
568
569 LWS_VISIBLE int
570 lws_plat_init(struct lws_context *context,
571               struct lws_context_creation_info *info)
572 {
573         struct lws_context_per_thread *pt = &context->pt[0];
574         int i, n = context->count_threads;
575
576         for (i = 0; i < FD_HASHTABLE_MODULUS; i++) {
577                 context->fd_hashtable[i].wsi =
578                         lws_zalloc(sizeof(struct lws*) * context->max_fds);
579
580                 if (!context->fd_hashtable[i].wsi)
581                         return -1;
582         }
583
584         while (n--) {
585                 pt->events = lws_malloc(sizeof(WSAEVENT) *
586                                         (context->fd_limit_per_thread + 1));
587                 if (pt->events == NULL) {
588                         lwsl_err("Unable to allocate events array for %d connections\n",
589                                         context->fd_limit_per_thread + 1);
590                         return 1;
591                 }
592
593                 pt->fds_count = 0;
594                 pt->events[0] = WSACreateEvent();
595
596                 pt++;
597         }
598
599         context->fd_random = 0;
600
601         context->fops.open      = _lws_plat_file_open;
602         context->fops.close     = _lws_plat_file_close;
603         context->fops.seek_cur  = _lws_plat_file_seek_cur;
604         context->fops.read      = _lws_plat_file_read;
605         context->fops.write     = _lws_plat_file_write;
606
607         return 0;
608 }