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