Merged silc_1_0_branch to trunk.
[silc.git] / lib / silcutil / win32 / silcwin32schedule.c
1 /*
2
3   silcwin32schedule.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 2001 Pekka Riikonen
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; either version 2 of the License, or
12   (at your option) any later version.
13   
14   This program is distributed in the hope that it will be useful,
15   but WITHOUT ANY WARRANTY; without even the implied warranty of
16   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   GNU General Public License for more details.
18
19 */
20 /* $Id$ */
21
22 #include "silcincludes.h"
23 #include "silcschedule_i.h"
24
25 /* Our "select()" for WIN32. This mimics the behaviour of select() system
26    call. It does not call the Winsock's select() though. Its functions
27    are derived from GLib's g_poll() and from some old Xemacs's sys_select().
28
29    This makes following assumptions, which I don't know whether they
30    are correct or not:
31
32    o SILC_TASK_WRITE is ignored, if set this will return immediately.
33    o If all arguments except timeout are NULL then this will register
34      a timeout with SetTimer and will wait just for Windows messages
35      with WaitMessage.
36    o MsgWaitForMultipleObjects is used to wait all kind of events, this
37      includes SOCKETs and Windows messages.
38    o All Windows messages are dispatched from this function.
39    o The Operating System has Winsock 2.
40
41    References:
42
43    o http://msdn.microsoft.com/library/default.asp?
44      url=/library/en-us/winui/hh/winui/messques_77zk.asp 
45    o http://msdn.microsoft.com/library/default.asp?
46      url=/library/en-us/winsock/hh/winsock/apistart_9g1e.asp
47    o http://msdn.microsoft.com/library/default.asp?
48      url=/library/en-us/dnmgmt/html/msdn_getpeek.asp
49    o http://developer.novell.com/support/winsock/doc/toc.htm
50
51 */
52
53 int silc_select(SilcScheduleFd fds, SilcUInt32 fds_count, struct timeval *timeout)
54 {
55   HANDLE handles[MAXIMUM_WAIT_OBJECTS];
56   DWORD ready, curtime;
57   LONG timeo;
58   int nhandles = 0, i;
59   MSG msg;
60
61   if (fds_count > MAXIMUM_WAIT_OBJECTS)
62     fds_count = MAXIMUM_WAIT_OBJECTS;
63
64   for (i = 0; i < fds_count; i++) {
65     if (!fds[i].events)
66       continue;
67
68     if (fds[i].events & SILC_TASK_READ)
69       handles[nhandles++] = (HANDLE)fds[i].fd;
70
71     /* If writing then just set the bit and return */
72     if (fds[i].events & SILC_TASK_WRITE) {
73       fds[i].revents = SILC_TASK_WRITE;
74       return 1;
75     }
76
77     fds[i].revents = 0;
78   }
79
80   timeo = (timeout ? (timeout->tv_sec * 1000) + (timeout->tv_usec / 1000) :
81            INFINITE);
82
83   /* If we have nothing to wait and timeout is set then register a timeout
84      and wait just for windows messages. */
85   if (nhandles == 0 && timeout) {
86     UINT timer = SetTimer(NULL, 0, timeo, NULL);
87     curtime = GetTickCount();
88     while (timer) {
89       WaitMessage();
90
91       while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
92         if (msg.message == WM_TIMER) {
93           KillTimer(NULL, timer);
94           return 0;
95         }
96         TranslateMessage(&msg); 
97         DispatchMessage(&msg); 
98       }
99
100       KillTimer(NULL, timer);
101       if (timeo != INFINITE) {
102         timeo -= GetTickCount() - curtime;
103         curtime = GetTickCount();
104         if (timeo < 0)
105           timeo = 0;
106       }
107       timer = SetTimer(NULL, 0, timeo, NULL);
108     }
109   }
110
111  retry:
112   curtime = GetTickCount();
113   ready = MsgWaitForMultipleObjects(nhandles, handles, FALSE, timeo, 
114                                     QS_ALLINPUT);
115
116   if (ready == WAIT_FAILED) {
117     /* Wait failed with error */
118     SILC_LOG_WARNING(("WaitForMultipleObjects() failed"));
119     return -1;
120   } else if (ready >= WAIT_ABANDONED_0 &&
121              ready < WAIT_ABANDONED_0 + nhandles) {
122     /* Signal abandoned */
123     SILC_LOG_WARNING(("WaitForMultipleObjects() failed (ABANDONED)"));
124     return -1;
125   } else if (ready == WAIT_TIMEOUT) {
126     /* Timeout */
127     return 0;
128   } else if (ready == WAIT_OBJECT_0 + nhandles) {
129     /* Windows messages. The MSDN online says that if the application
130        creates a window then its main loop (and we're assuming that
131        it is our SILC Scheduler) must handle the Windows messages, so do
132        it here as the MSDN suggests. */
133     while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
134       TranslateMessage(&msg); 
135       DispatchMessage(&msg); 
136     }
137
138     /* If timeout is set then we must update the timeout since we won't
139        return and we will give the wait another try. */
140     if (timeo != INFINITE) {
141       timeo -= GetTickCount() - curtime;
142       curtime = GetTickCount();
143       if (timeo < 0)
144         timeo = 0;
145     }
146
147     /* Give the wait another try */
148    goto retry;
149   } else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles) {
150     /* Some other event, like SOCKET or something. */
151
152     /* Go through all fds even though only one was set. This is to avoid
153        starvation of high numbered fds. */
154     ready -= WAIT_OBJECT_0;
155     do {
156       for (i = 0; i < fds_count; i++) {
157         if (!fds[i].events)
158           continue;
159         
160         if (fds[i].fd == (int)handles[ready]) {
161           fds[i].revents |= SILC_TASK_READ;
162           break;
163         }
164       }
165
166       /* Check the status of the next handle and set its fd to the fd
167          set if data is available. */
168       while (++ready < fds_count)
169         if (WaitForSingleObject(handles[ready], 0) == WAIT_OBJECT_0)
170           break;
171     } while (ready < fds_count);
172
173     return i + 1;
174   }
175
176   return -1;
177 }
178
179 #ifdef SILC_THREADS
180
181 /* Internal wakeup context. */
182 typedef struct {
183   HANDLE wakeup_sema;
184   SilcTask wakeup_task;
185 } *SilcWin32Wakeup;
186
187 SILC_TASK_CALLBACK(silc_schedule_wakeup_cb)
188 {
189   /* Nothing */
190 }
191
192 #endif /* SILC_THREADS */
193
194 /* Initializes the platform specific scheduler.  This for example initializes
195    the wakeup mechanism of the scheduler.  In multi-threaded environment
196    the scheduler needs to be wakenup when tasks are added or removed from
197    the task queues.  Returns context to the platform specific scheduler. */
198
199 void *silc_schedule_internal_init(SilcSchedule schedule, void *app_context)
200 {
201 #ifdef SILC_THREADS
202   SilcWin32Wakeup wakeup;
203
204   wakeup = silc_calloc(1, sizeof(*wakeup));
205
206   wakeup->wakeup_sema = CreateSemaphore(NULL, 0, 100, NULL);
207   if (!wakeup->wakeup_sema) {
208     silc_free(wakeup);
209     return NULL;
210   }
211
212   wakeup->wakeup_task = 
213     silc_schedule_task_add(schedule, (int)wakeup->wakeup_sema,
214                            silc_schedule_wakeup_cb, wakeup,
215                            0, 0, SILC_TASK_FD, 
216                            SILC_TASK_PRI_NORMAL);
217   if (!wakeup->wakeup_task) {
218     CloseHandle(wakeup->wakeup_sema);
219     silc_free(wakeup);
220     return NULL;
221   }
222
223   return (void *)wakeup;
224 #else
225   return NULL;
226 #endif
227 }
228
229 /* Uninitializes the platform specific scheduler context. */
230
231 void silc_schedule_internal_uninit(void *context)
232 {
233 #ifdef SILC_THREADS
234   SilcWin32Wakeup wakeup = (SilcWin32Wakeup)context;
235
236   if (!wakeup)
237     return;
238
239   CloseHandle(wakeup->wakeup_sema);
240   silc_free(wakeup);
241 #endif
242 }
243
244 /* Wakes up the scheduler */
245
246 void silc_schedule_internal_wakeup(void *context)
247 {
248 #ifdef SILC_THREADS
249   SilcWin32Wakeup wakeup = (SilcWin32Wakeup)context;
250
251   if (!wakeup)
252     return;
253
254   ReleaseSemaphore(wakeup->wakeup_sema, 1, NULL);
255 #endif
256 }
257
258 /* Register signal */
259
260 void silc_schedule_internal_signal_register(void *context,
261                                             SilcUInt32 signal,
262                                             SilcTaskCallback callback,
263                                             void *callback_context)
264 {
265
266 }
267
268 /* Unregister signal */
269
270 void silc_schedule_internal_signal_unregister(void *context,
271                                               SilcUInt32 signal,
272                                               SilcTaskCallback callback,
273                                               void *callback_context)
274 {
275
276 }
277
278 /* Mark signal to be called later. */
279
280 void silc_schedule_internal_signal_call(void *context, SilcUInt32 signal)
281 {
282
283 }
284
285 /* Call all signals */
286
287 void silc_schedule_internal_signals_call(void *context,
288                                          SilcSchedule schedule)
289 {
290
291 }
292
293 /* Block registered signals in scheduler. */
294
295 void silc_schedule_internal_signals_block(void *context)
296 {
297
298 }
299
300 /* Unblock registered signals in schedule. */
301
302 void silc_schedule_internal_signals_unblock(void *context)
303 {
304
305 }