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