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