public api remove context from user callback API BREAK
[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 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         context->service_tid = context->protocols[0].callback(NULL,
153                                      LWS_CALLBACK_GET_THREAD_ID, NULL, NULL, 0);
154
155         for (i = 0; i < context->fds_count; ++i) {
156                 pfd = &context->fds[i];
157                 if (pfd->fd == context->listen_service_fd)
158                         continue;
159
160                 if (pfd->events & LWS_POLLOUT) {
161                         wsi = wsi_from_fd(context, pfd->fd);
162                         if (!wsi || wsi->sock_send_blocking)
163                                 continue;
164                         pfd->revents = LWS_POLLOUT;
165                         n = lws_service_fd(context, pfd);
166                         if (n < 0)
167                                 return -1;
168                         /* if something closed, retry this slot */
169                         if (n)
170                                 i--;
171                 }
172         }
173
174         ev = WSAWaitForMultipleEvents(context->fds_count + 1,
175                                      context->events, FALSE, timeout_ms, FALSE);
176         context->service_tid = 0;
177
178         if (ev == WSA_WAIT_TIMEOUT) {
179                 lws_service_fd(context, NULL);
180                 return 0;
181         }
182
183         if (ev == WSA_WAIT_EVENT_0) {
184                 WSAResetEvent(context->events[0]);
185                 return 0;
186         }
187
188         if (ev < WSA_WAIT_EVENT_0 || ev > WSA_WAIT_EVENT_0 + context->fds_count)
189                 return -1;
190
191         pfd = &context->fds[ev - WSA_WAIT_EVENT_0 - 1];
192
193         if (WSAEnumNetworkEvents(pfd->fd,
194                         context->events[ev - WSA_WAIT_EVENT_0],
195                                               &networkevents) == SOCKET_ERROR) {
196                 lwsl_err("WSAEnumNetworkEvents() failed with error %d\n",
197                                                                      LWS_ERRNO);
198                 return -1;
199         }
200
201         pfd->revents = (short)networkevents.lNetworkEvents;
202
203         if (pfd->revents & LWS_POLLOUT) {
204                 wsi = wsi_from_fd(context, pfd->fd);
205                 if (wsi)
206                         wsi->sock_send_blocking = FALSE;
207         }
208
209         return lws_service_fd(context, pfd);
210 }
211
212 LWS_VISIBLE int
213 lws_plat_set_socket_options(struct lws_context *context, lws_sockfd_type fd)
214 {
215         int optval = 1;
216         int optlen = sizeof(optval);
217         u_long optl = 1;
218         DWORD dwBytesRet;
219         struct tcp_keepalive alive;
220         struct protoent *tcp_proto;
221
222         if (context->ka_time) {
223                 /* enable keepalive on this socket */
224                 optval = 1;
225                 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
226                                              (const char *)&optval, optlen) < 0)
227                         return 1;
228
229                 alive.onoff = TRUE;
230                 alive.keepalivetime = context->ka_time;
231                 alive.keepaliveinterval = context->ka_interval;
232
233                 if (WSAIoctl(fd, SIO_KEEPALIVE_VALS, &alive, sizeof(alive),
234                                               NULL, 0, &dwBytesRet, NULL, NULL))
235                         return 1;
236         }
237
238         /* Disable Nagle */
239         optval = 1;
240         tcp_proto = getprotobyname("TCP");
241         if (!tcp_proto) {
242                 lwsl_err("getprotobyname() failed with error %d\n", LWS_ERRNO);
243                 return 1;
244         }
245
246         setsockopt(fd, tcp_proto->p_proto, TCP_NODELAY, (const char *)&optval, optlen);
247
248         /* We are nonblocking... */
249         ioctlsocket(fd, FIONBIO, &optl);
250
251         return 0;
252 }
253
254 LWS_VISIBLE void
255 lws_plat_drop_app_privileges(struct lws_context_creation_info *info)
256 {
257 }
258
259 LWS_VISIBLE int
260 lws_plat_context_early_init(void)
261 {
262         WORD wVersionRequested;
263         WSADATA wsaData;
264         int err;
265
266         /* Use the MAKEWORD(lowbyte, highbyte) macro from Windef.h */
267         wVersionRequested = MAKEWORD(2, 2);
268
269         err = WSAStartup(wVersionRequested, &wsaData);
270         if (!err)
271                 return 0;
272         /*
273          * Tell the user that we could not find a usable
274          * Winsock DLL
275          */
276         lwsl_err("WSAStartup failed with error: %d\n", err);
277
278         return 1;
279 }
280
281 LWS_VISIBLE void
282 lws_plat_context_early_destroy(struct lws_context *context)
283 {
284         if (context->events) {
285                 WSACloseEvent(context->events[0]);
286                 lws_free(context->events);
287         }
288 }
289
290 LWS_VISIBLE void
291 lws_plat_context_late_destroy(struct lws_context *context)
292 {
293         int n;
294
295         for (n = 0; n < FD_HASHTABLE_MODULUS; n++) {
296                 if (context->fd_hashtable[n].wsi)
297                         lws_free(context->fd_hashtable[n].wsi);
298         }
299
300         WSACleanup();
301 }
302
303 LWS_VISIBLE int
304 interface_to_sa(struct lws_context *context,
305                 const char *ifname, struct sockaddr_in *addr, size_t addrlen)
306 {
307         long long address = inet_addr(ifname);
308
309         if (address == INADDR_NONE) {
310                 struct hostent *entry = gethostbyname(ifname);
311                 if (entry)
312                         address = ((struct in_addr *)entry->h_addr_list[0])->s_addr;
313         }
314
315         if (address == INADDR_NONE)
316                 return -1;
317
318         addr->sin_addr.s_addr = (unsigned long)address;
319
320         return 0;
321 }
322
323 LWS_VISIBLE void
324 lws_plat_insert_socket_into_fds(struct lws_context *context,
325                                                        struct lws *wsi)
326 {
327         context->fds[context->fds_count++].revents = 0;
328         context->events[context->fds_count] = WSACreateEvent();
329         WSAEventSelect(wsi->sock, context->events[context->fds_count], LWS_POLLIN);
330 }
331
332 LWS_VISIBLE void
333 lws_plat_delete_socket_from_fds(struct lws_context *context,
334                                                 struct lws *wsi, int m)
335 {
336         WSACloseEvent(context->events[m + 1]);
337         context->events[m + 1] = context->events[context->fds_count + 1];
338 }
339
340 LWS_VISIBLE void
341 lws_plat_service_periodic(struct lws_context *context)
342 {
343 }
344
345 LWS_VISIBLE int
346 lws_plat_change_pollfd(struct lws_context *context,
347                       struct lws *wsi, struct lws_pollfd *pfd)
348 {
349         long networkevents = LWS_POLLHUP;
350
351         if ((pfd->events & LWS_POLLIN))
352                 networkevents |= LWS_POLLIN;
353
354         if ((pfd->events & LWS_POLLOUT))
355                 networkevents |= LWS_POLLOUT;
356
357         if (WSAEventSelect(wsi->sock,
358                         context->events[wsi->position_in_fds_table + 1],
359                                                networkevents) != SOCKET_ERROR)
360                 return 0;
361
362         lwsl_err("WSAEventSelect() failed with error %d\n", LWS_ERRNO);
363
364         return 1;
365 }
366
367 LWS_VISIBLE const char *
368 lws_plat_inet_ntop(int af, const void *src, char *dst, int cnt)
369 {
370         WCHAR *buffer;
371         DWORD bufferlen = cnt;
372         BOOL ok = FALSE;
373
374         buffer = lws_malloc(bufferlen);
375         if (!buffer) {
376                 lwsl_err("Out of memory\n");
377                 return NULL;
378         }
379
380         if (af == AF_INET) {
381                 struct sockaddr_in srcaddr;
382                 bzero(&srcaddr, sizeof(srcaddr));
383                 srcaddr.sin_family = AF_INET;
384                 memcpy(&(srcaddr.sin_addr), src, sizeof(srcaddr.sin_addr));
385
386                 if (!WSAAddressToStringW((struct sockaddr*)&srcaddr, sizeof(srcaddr), 0, buffer, &bufferlen))
387                         ok = TRUE;
388 #ifdef LWS_USE_IPV6
389         } else if (af == AF_INET6) {
390                 struct sockaddr_in6 srcaddr;
391                 bzero(&srcaddr, sizeof(srcaddr));
392                 srcaddr.sin6_family = AF_INET6;
393                 memcpy(&(srcaddr.sin6_addr), src, sizeof(srcaddr.sin6_addr));
394
395                 if (!WSAAddressToStringW((struct sockaddr*)&srcaddr, sizeof(srcaddr), 0, buffer, &bufferlen))
396                         ok = TRUE;
397 #endif
398         } else
399                 lwsl_err("Unsupported type\n");
400
401         if (!ok) {
402                 int rv = WSAGetLastError();
403                 lwsl_err("WSAAddressToString() : %d\n", rv);
404         } else {
405                 if (WideCharToMultiByte(CP_ACP, 0, buffer, bufferlen, dst, cnt, 0, NULL) <= 0)
406                         ok = FALSE;
407         }
408
409         lws_free(buffer);
410         return ok ? dst : NULL;
411 }
412
413 static lws_filefd_type
414 _lws_plat_file_open(struct lws *wsi, const char *filename,
415                     unsigned long *filelen, int flags)
416 {
417         HANDLE ret;
418         WCHAR buf[MAX_PATH];
419
420         (void)wsi;
421         MultiByteToWideChar(CP_UTF8, 0, filename, -1, buf, ARRAY_SIZE(buf));
422         if ((flags & 7) == _O_RDONLY) {
423                 ret = CreateFileW(buf, GENERIC_READ, FILE_SHARE_READ,
424                           NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
425         } else {
426                 lwsl_err("%s: open for write not implemented\n", __func__);
427                 *filelen = 0;
428                 return LWS_INVALID_FILE;
429         }
430
431         if (ret != LWS_INVALID_FILE)
432                 *filelen = GetFileSize(ret, NULL);
433
434         return ret;
435 }
436
437 static int
438 _lws_plat_file_close(struct lws *wsi, lws_filefd_type fd)
439 {
440         (void)wsi;
441
442         CloseHandle((HANDLE)fd);
443
444         return 0;
445 }
446
447 static unsigned long
448 _lws_plat_file_seek_cur(struct lws *wsi, lws_filefd_type fd, long offset)
449 {
450         (void)wsi;
451
452         return SetFilePointer((HANDLE)fd, offset, NULL, FILE_CURRENT);
453 }
454
455 static int
456 _lws_plat_file_read(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
457                     unsigned char* buf, unsigned long len)
458 {
459         DWORD _amount;
460
461         (void *)wsi;
462         if (!ReadFile((HANDLE)fd, buf, (DWORD)len, &_amount, NULL)) {
463                 *amount = 0;
464
465                 return 1;
466         }
467
468         *amount = (unsigned long)_amount;
469
470         return 0;
471 }
472
473 static int
474 _lws_plat_file_write(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
475                      unsigned char* buf, unsigned long len)
476 {
477         (void)wsi;
478         (void)fd;
479         (void)amount;
480         (void)buf;
481         (void)len;
482
483         lwsl_err("%s: not implemented yet on this platform\n", __func__);
484
485         return -1;
486 }
487
488 LWS_VISIBLE int
489 lws_plat_init(struct lws_context *context,
490               struct lws_context_creation_info *info)
491 {
492         int i;
493
494         for (i = 0; i < FD_HASHTABLE_MODULUS; i++) {
495                 context->fd_hashtable[i].wsi =
496                         lws_zalloc(sizeof(struct lws*) * context->max_fds);
497
498                 if (!context->fd_hashtable[i].wsi)
499                         return -1;
500         }
501
502         context->events = lws_malloc(sizeof(WSAEVENT) * (context->max_fds + 1));
503         if (context->events == NULL) {
504                 lwsl_err("Unable to allocate events array for %d connections\n",
505                         context->max_fds);
506                 return 1;
507         }
508
509         context->fds_count = 0;
510         context->events[0] = WSACreateEvent();
511
512         context->fd_random = 0;
513
514         context->fops.open      = _lws_plat_file_open;
515         context->fops.close     = _lws_plat_file_close;
516         context->fops.seek_cur  = _lws_plat_file_seek_cur;
517         context->fops.read      = _lws_plat_file_read;
518         context->fops.write     = _lws_plat_file_write;
519
520         return 0;
521 }