win32 inet_top
[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 static 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         socklen_t optlen = sizeof(optval);
156         u_long optl = 1;
157         DWORD dwBytesRet;
158         struct tcp_keepalive alive;
159                         
160         if (context->ka_time) {
161                 /* enable keepalive on this socket */
162                 optval = 1;
163                 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
164                                              (const void *)&optval, optlen) < 0)
165                         return 1;
166
167                 alive.onoff = TRUE;
168                 alive.keepalivetime = context->ka_time;
169                 alive.keepaliveinterval = context->ka_interval;
170
171                 if (WSAIoctl(fd, SIO_KEEPALIVE_VALS, &alive, sizeof(alive), 
172                                               NULL, 0, &dwBytesRet, NULL, NULL))
173                         return 1;
174         }
175
176         /* Disable Nagle */
177         optval = 1;
178         tcp_proto = getprotobyname("TCP");
179         setsockopt(fd, tcp_proto->p_proto, TCP_NODELAY, &optval, optlen);
180
181         /* We are nonblocking... */
182         ioctlsocket(fd, FIONBIO, &optl);
183
184         return 0;
185 }
186
187 LWS_VISIBLE void
188 lws_plat_drop_app_privileges(struct lws_context_creation_info *info)
189 {
190 }
191
192 LWS_VISIBLE int
193 lws_plat_init_fd_tables(struct libwebsocket_context *context)
194 {
195         context->events = (WSAEVENT *)malloc(sizeof(WSAEVENT) *
196                                                         (context->max_fds + 1));
197         if (context->events == NULL) {
198                 lwsl_err("Unable to allocate events array for %d connections\n",
199                         context->max_fds);
200                 return 1;
201         }
202         
203         context->fds_count = 0;
204         context->events[0] = WSACreateEvent();
205         
206         context->fd_random = 0;
207
208         return 0;
209 }
210
211 LWS_VISIBLE int
212 lws_plat_context_early_init(void)
213 {
214         WORD wVersionRequested;
215         WSADATA wsaData;
216         int err;
217
218         /* Use the MAKEWORD(lowbyte, highbyte) macro from Windef.h */
219         wVersionRequested = MAKEWORD(2, 2);
220
221         err = WSAStartup(wVersionRequested, &wsaData);
222         if (!err)
223                 return 0;
224         /*
225          * Tell the user that we could not find a usable
226          * Winsock DLL
227          */
228         lwsl_err("WSAStartup failed with error: %d\n", err);
229
230         return 1;
231 }
232
233 LWS_VISIBLE void
234 lws_plat_context_early_destroy(struct libwebsocket_context *context)
235 {
236         if (context->events) {
237                 WSACloseEvent(context->events[0]);
238                 free(context->events);
239         }
240 }
241
242 LWS_VISIBLE void
243 lws_plat_context_late_destroy(struct libwebsocket_context *context)
244 {
245         WSACleanup();
246 }
247
248 LWS_VISIBLE int
249 interface_to_sa(struct libwebsocket_context *context,
250                 const char *ifname, struct sockaddr_in *addr, size_t addrlen)
251 {
252         return -1;
253 }
254
255 LWS_VISIBLE void
256 lws_plat_insert_socket_into_fds(struct libwebsocket_context *context,
257                                                        struct libwebsocket *wsi)
258 {
259         context->fds[context->fds_count++].revents = 0;
260         context->events[context->fds_count] = WSACreateEvent();
261         WSAEventSelect(wsi->sock, context->events[context->fds_count], LWS_POLLIN);
262 }
263
264 LWS_VISIBLE void
265 lws_plat_delete_socket_from_fds(struct libwebsocket_context *context,
266                                                 struct libwebsocket *wsi, int m)
267 {
268         WSACloseEvent(context->events[m + 1]);
269         context->events[m + 1] = context->events[context->fds_count + 1];
270 }
271
272 LWS_VISIBLE void
273 lws_plat_service_periodic(struct libwebsocket_context *context)
274 {
275 }
276
277 LWS_VISIBLE int
278 lws_plat_change_pollfd(struct libwebsocket_context *context,
279                       struct libwebsocket *wsi, struct libwebsocket_pollfd *pfd)
280 {
281         long networkevents = LWS_POLLOUT | LWS_POLLHUP;
282                 
283         if ((pfd->events & LWS_POLLIN))
284                 networkevents |= LWS_POLLIN;
285
286         if (WSAEventSelect(wsi->sock,
287                         context->events[wsi->position_in_fds_table + 1],
288                                                networkevents) != SOCKET_ERROR)
289                 return 0;
290
291         lwsl_err("WSAEventSelect() failed with error %d\n", LWS_ERRNO);
292
293         return 1;
294 }
295
296 LWS_VISIBLE HANDLE
297 lws_plat_open_file(const char* filename, unsigned long* filelen)
298 {
299         HANDLE ret;
300         WCHAR buffer[MAX_PATH];
301
302         MultiByteToWideChar(CP_UTF8, 0, filename, -1, buffer,
303                                 sizeof(buffer) / sizeof(buffer[0]));
304         ret = CreateFileW(buffer, GENERIC_READ, FILE_SHARE_READ,
305                                 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
306
307         if (ret != LWS_INVALID_FILE)
308                 *filelen = GetFileSize(ret, NULL);
309
310         return ret;
311 }
312
313 /* 
314  * Windows doesn't have an "inet_top"
315  * This came from http://memset.wordpress.com/2010/10/09/inet_ntop-for-win32/
316  * suggested by Joakim Soderberg
317  */
318
319 LWS_VISIBLE
320 const char *inet_ntop(int af, const void *src, char *dst, int cnt)
321
322         struct sockaddr_in srcaddr;
323         DWORD rv;
324
325         memset(&srcaddr, 0, sizeof(struct sockaddr_in));
326         memcpy(&(srcaddr.sin_addr), src, sizeof(srcaddr.sin_addr));
327
328         srcaddr.sin_family = af;
329         if (!WSAAddressToString((struct sockaddr*) &srcaddr,
330                             sizeof(struct sockaddr_in), 0, dst, (LPDWORD) &cnt))
331                 return dst;
332
333         rv = WSAGetLastError();
334         lwsl_err("WSAAddressToString() : %d\n",rv);
335
336         return NULL;
337 }