Windows: Fix implementation of lws_plat_inet_ntop()
[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 LWS_VISIBLE int libwebsockets_get_random(struct libwebsocket_context *context,
37                                                              void *buf, int len)
38 {
39         int n;
40         char *p = (char *)buf;
41
42         for (n = 0; n < len; n++)
43                 p[n] = (unsigned char)rand();
44
45         return n;
46 }
47
48 LWS_VISIBLE int lws_send_pipe_choked(struct libwebsocket *wsi)
49 {
50         return wsi->sock_send_blocking;
51 }
52
53 LWS_VISIBLE int lws_poll_listen_fd(struct libwebsocket_pollfd *fd)
54 {
55         fd_set readfds;
56         struct timeval tv = { 0, 0 };
57
58         assert(fd->events == LWS_POLLIN);
59
60         FD_ZERO(&readfds);
61         FD_SET(fd->fd, &readfds);
62
63         return select(fd->fd + 1, &readfds, NULL, NULL, &tv);
64 }
65
66 /**
67  * libwebsocket_cancel_service() - Cancel servicing of pending websocket activity
68  * @context:    Websocket context
69  *
70  *      This function let a call to libwebsocket_service() waiting for a timeout
71  *      immediately return.
72  */
73 LWS_VISIBLE void
74 libwebsocket_cancel_service(struct libwebsocket_context *context)
75 {
76         WSASetEvent(context->events[0]);
77 }
78
79 LWS_VISIBLE void lwsl_emit_syslog(int level, const char *line)
80 {
81         lwsl_emit_stderr(level, line);
82 }
83
84 LWS_VISIBLE int
85 lws_plat_service(struct libwebsocket_context *context, int timeout_ms)
86 {
87         int n;
88         int i;
89         DWORD ev;
90         WSANETWORKEVENTS networkevents;
91         struct libwebsocket_pollfd *pfd;
92
93         /* stay dead once we are dead */
94
95         if (context == NULL)
96                 return 1;
97
98         context->service_tid = context->protocols[0].callback(context, NULL,
99                                      LWS_CALLBACK_GET_THREAD_ID, NULL, NULL, 0);
100
101         for (i = 0; i < context->fds_count; ++i) {
102                 pfd = &context->fds[i];
103                 if (pfd->fd == context->listen_service_fd)
104                         continue;
105
106                 if (pfd->events & LWS_POLLOUT) {
107                         if (context->lws_lookup[pfd->fd]->sock_send_blocking)
108                                 continue;
109                         pfd->revents = LWS_POLLOUT;
110                         n = libwebsocket_service_fd(context, pfd);
111                         if (n < 0)
112                                 return n;
113                 }
114         }
115
116         ev = WSAWaitForMultipleEvents(context->fds_count + 1,
117                                      context->events, FALSE, timeout_ms, FALSE);
118         context->service_tid = 0;
119
120         if (ev == WSA_WAIT_TIMEOUT) {
121                 libwebsocket_service_fd(context, NULL);
122                 return 0;
123         }
124
125         if (ev == WSA_WAIT_EVENT_0) {
126                 WSAResetEvent(context->events[0]);
127                 return 0;
128         }
129
130         if (ev < WSA_WAIT_EVENT_0 || ev > WSA_WAIT_EVENT_0 + context->fds_count)
131                 return -1;
132
133         pfd = &context->fds[ev - WSA_WAIT_EVENT_0 - 1];
134
135         if (WSAEnumNetworkEvents(pfd->fd,
136                         context->events[ev - WSA_WAIT_EVENT_0],
137                                               &networkevents) == SOCKET_ERROR) {
138                 lwsl_err("WSAEnumNetworkEvents() failed with error %d\n",
139                                                                      LWS_ERRNO);
140                 return -1;
141         }
142
143         pfd->revents = networkevents.lNetworkEvents;
144
145         if (pfd->revents & LWS_POLLOUT)
146                 context->lws_lookup[pfd->fd]->sock_send_blocking = FALSE;
147
148         return libwebsocket_service_fd(context, pfd);
149 }
150
151 LWS_VISIBLE int
152 lws_plat_set_socket_options(struct libwebsocket_context *context, int fd)
153 {
154         int optval = 1;
155         int optlen = sizeof(optval);
156         u_long optl = 1;
157         DWORD dwBytesRet;
158         struct tcp_keepalive alive;
159         struct protoent *tcp_proto;
160                         
161         if (context->ka_time) {
162                 /* enable keepalive on this socket */
163                 optval = 1;
164                 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
165                                              (const char *)&optval, optlen) < 0)
166                         return 1;
167
168                 alive.onoff = TRUE;
169                 alive.keepalivetime = context->ka_time;
170                 alive.keepaliveinterval = context->ka_interval;
171
172                 if (WSAIoctl(fd, SIO_KEEPALIVE_VALS, &alive, sizeof(alive), 
173                                               NULL, 0, &dwBytesRet, NULL, NULL))
174                         return 1;
175         }
176
177         /* Disable Nagle */
178         optval = 1;
179         tcp_proto = getprotobyname("TCP");
180         setsockopt(fd, tcp_proto->p_proto, TCP_NODELAY, (const char *)&optval, optlen);
181
182         /* We are nonblocking... */
183         ioctlsocket(fd, FIONBIO, &optl);
184
185         return 0;
186 }
187
188 LWS_VISIBLE void
189 lws_plat_drop_app_privileges(struct lws_context_creation_info *info)
190 {
191 }
192
193 LWS_VISIBLE int
194 lws_plat_init_fd_tables(struct libwebsocket_context *context)
195 {
196         context->events = (WSAEVENT *)malloc(sizeof(WSAEVENT) *
197                                                         (context->max_fds + 1));
198         if (context->events == NULL) {
199                 lwsl_err("Unable to allocate events array for %d connections\n",
200                         context->max_fds);
201                 return 1;
202         }
203         
204         context->fds_count = 0;
205         context->events[0] = WSACreateEvent();
206         
207         context->fd_random = 0;
208
209         return 0;
210 }
211
212 LWS_VISIBLE int
213 lws_plat_context_early_init(void)
214 {
215         WORD wVersionRequested;
216         WSADATA wsaData;
217         int err;
218
219         /* Use the MAKEWORD(lowbyte, highbyte) macro from Windef.h */
220         wVersionRequested = MAKEWORD(2, 2);
221
222         err = WSAStartup(wVersionRequested, &wsaData);
223         if (!err)
224                 return 0;
225         /*
226          * Tell the user that we could not find a usable
227          * Winsock DLL
228          */
229         lwsl_err("WSAStartup failed with error: %d\n", err);
230
231         return 1;
232 }
233
234 LWS_VISIBLE void
235 lws_plat_context_early_destroy(struct libwebsocket_context *context)
236 {
237         if (context->events) {
238                 WSACloseEvent(context->events[0]);
239                 free(context->events);
240         }
241 }
242
243 LWS_VISIBLE void
244 lws_plat_context_late_destroy(struct libwebsocket_context *context)
245 {
246         WSACleanup();
247 }
248
249 LWS_VISIBLE int
250 interface_to_sa(struct libwebsocket_context *context,
251                 const char *ifname, struct sockaddr_in *addr, size_t addrlen)
252 {
253         return -1;
254 }
255
256 LWS_VISIBLE void
257 lws_plat_insert_socket_into_fds(struct libwebsocket_context *context,
258                                                        struct libwebsocket *wsi)
259 {
260         context->fds[context->fds_count++].revents = 0;
261         context->events[context->fds_count] = WSACreateEvent();
262         WSAEventSelect(wsi->sock, context->events[context->fds_count], LWS_POLLIN);
263 }
264
265 LWS_VISIBLE void
266 lws_plat_delete_socket_from_fds(struct libwebsocket_context *context,
267                                                 struct libwebsocket *wsi, int m)
268 {
269         WSACloseEvent(context->events[m + 1]);
270         context->events[m + 1] = context->events[context->fds_count + 1];
271 }
272
273 LWS_VISIBLE void
274 lws_plat_service_periodic(struct libwebsocket_context *context)
275 {
276 }
277
278 LWS_VISIBLE int
279 lws_plat_change_pollfd(struct libwebsocket_context *context,
280                       struct libwebsocket *wsi, struct libwebsocket_pollfd *pfd)
281 {
282         long networkevents = LWS_POLLOUT | LWS_POLLHUP;
283                 
284         if ((pfd->events & LWS_POLLIN))
285                 networkevents |= LWS_POLLIN;
286
287         if (WSAEventSelect(wsi->sock,
288                         context->events[wsi->position_in_fds_table + 1],
289                                                networkevents) != SOCKET_ERROR)
290                 return 0;
291
292         lwsl_err("WSAEventSelect() failed with error %d\n", LWS_ERRNO);
293
294         return 1;
295 }
296
297 LWS_VISIBLE HANDLE
298 lws_plat_open_file(const char* filename, unsigned long* filelen)
299 {
300         HANDLE ret;
301         WCHAR buffer[MAX_PATH];
302
303         MultiByteToWideChar(CP_UTF8, 0, filename, -1, buffer,
304                                 sizeof(buffer) / sizeof(buffer[0]));
305         ret = CreateFileW(buffer, GENERIC_READ, FILE_SHARE_READ,
306                                 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
307
308         if (ret != LWS_INVALID_FILE)
309                 *filelen = GetFileSize(ret, NULL);
310
311         return ret;
312 }
313
314 LWS_VISIBLE const char *
315 lws_plat_inet_ntop(int af, const void *src, char *dst, int cnt)
316
317         WCHAR *buffer;
318         DWORD bufferlen = cnt;
319         BOOL ok = FALSE;
320
321         buffer = malloc(bufferlen);
322         if (!buffer) {
323                 lwsl_err("Out of memory\n");
324                 return NULL;
325         }
326
327         if (af == AF_INET) {
328                 struct sockaddr_in srcaddr;
329                 bzero(&srcaddr, sizeof(srcaddr));
330                 srcaddr.sin_family = AF_INET;
331                 memcpy(&(srcaddr.sin_addr), src, sizeof(srcaddr.sin_addr));
332
333                 if (!WSAAddressToStringW((struct sockaddr*)&srcaddr, sizeof(srcaddr), 0, buffer, &bufferlen))
334                         ok = TRUE;
335 #ifdef LWS_USE_IPV6
336         } else if (af == AF_INET6) {
337                 struct sockaddr_in6 srcaddr;
338                 bzero(&srcaddr, sizeof(srcaddr));
339                 srcaddr.sin6_family = AF_INET6;
340                 memcpy(&(srcaddr.sin6_addr), src, sizeof(srcaddr.sin6_addr));
341
342                 if (!WSAAddressToStringW((struct sockaddr*)&srcaddr, sizeof(srcaddr), 0, buffer, &bufferlen))
343                         ok = TRUE;
344 #endif
345         } else
346                 lwsl_err("Unsupported type\n");
347
348         if (!ok) {
349                 int rv = WSAGetLastError();
350                 lwsl_err("WSAAddressToString() : %d\n", rv);
351         } else {
352                 if (WideCharToMultiByte(CP_ACP, 0, buffer, bufferlen, dst, cnt, 0, NULL) <= 0)
353                         ok = FALSE;
354         }
355
356         free(buffer);
357         return ok ? dst : NULL;
358 }