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