updates.
[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
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 writefds are ignored, if set this will return immediately.
32    o exceptfds are ignored totally
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://developer.novell.com/support/winsock/doc/toc.htm
48
49 */
50
51 int silc_select(int n, fd_set *readfds, fd_set *writefds,
52                 fd_set *exceptfds, struct timeval *timeout)
53 {
54   HANDLE handles[MAXIMUM_WAIT_OBJECTS];
55   DWORD ready, curtime, timeo;
56   int nhandles = 0, i;
57   MSG msg;
58
59   /* Check fd sets (ignoring the exceptfds) */
60   if (readfds) {
61     for (i = 0; i < n - 1; i++)
62       if (FD_ISSET(i, readfds))
63         handles[nhandles++] = (HANDLE)i;
64
65     FD_ZERO(readfds);
66   }
67
68   /* If writefds is set then return immediately */
69   if (writefds) {
70     for (i = 0; i < n - 1; i++)
71       if (FD_ISSET(i, writefds))
72         return 1;
73   }
74
75   timeo = (timeout ? (timeout->tv_sec * 1000) + (timeout->tv_usec / 1000) :
76            INFINITE);
77
78   /* If we have nothing to wait and timeout is set then register a timeout
79      and wait just for windows messages. */
80   if (nhandles == 0 && timeout) {
81     UINT timer = SetTimer(NULL, 0, timeo, NULL);
82     curtime = GetTickCount();
83     while (timer) {
84       WaitMessage();
85       KillTimer(NULL, timer);
86
87       while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
88         if (msg.message == WM_TIMER)
89           return 0;
90         TranslateMessage(&msg); 
91         DispatchMessage(&msg); 
92       }
93
94       if (timeo != INFINITE) {
95         timeo -= GetTickCount() - curtime;
96         if (timeo < 0)
97           timeo = 0;
98         timer = SetTimer(NULL, 0, timeo, NULL);
99       }
100     }
101   }
102
103  retry:
104   curtime = GetTickCount();
105   ready = MsgWaitForMultipleObjects(nhandles, handles, FALSE, timeo, 
106                                     QS_ALLINPUT);
107
108   if (ready == WAIT_FAILED) {
109     /* Wait failed with error */
110     SILC_LOG_WARNING(("WaitForMultipleObjects() failed"));
111     return -1;
112
113   } else if (ready >= WAIT_ABANDONED_0 &&
114              ready < WAIT_ABANDONED_0 + nhandles) {
115     /* Signal abandoned */
116     SILC_LOG_WARNING(("WaitForMultipleObjects() failed (ABANDONED)"));
117     return -1;
118   } else if (ready == WAIT_TIMEOUT) {
119     /* Timeout */
120     return 0;
121   } else if (ready == WAIT_OBJECT_0 + nhandles) {
122     /* Windows messages. The MSDN online says that if the application
123        creates a window then its main loop (and we're assuming that
124        it is our SILC Scheduler) must handle the Windows messages, so do
125        it here as the MSDN suggests. */
126     while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
127       TranslateMessage(&msg); 
128       DispatchMessage(&msg); 
129     }
130
131     /* If timeout is set then we must update the timeout since we won't
132        return and we will give the wait another try. */
133     if (timeo != INFINITE) {
134       timeo -= GetTickCount() - curtime;
135       if (timeo < 0)
136         timeo = 0;
137     }
138
139     /* Give the wait another try */
140    goto retry;
141   } else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles &&
142              readfds) {
143     /* Some other event, like SOCKET or something. */
144
145     /* Go through all fds even though only one was set. This is to avoid
146        starvation of high numbered fds. */
147     ready -= WAIT_OBJECT_0;
148     i = 0;
149     do {
150       /* Set the handle to fd set */
151       FD_SET((int)handles[ready], readfds);
152       i++;
153
154       /* Check the status of the next handle and set it's fd to the fd
155          set if data is available. */
156       while (++ready < n)
157         if (WaitForSingleObject(handles[ready], 0) == WAIT_OBJECT_0)
158           break;
159     } while (ready < n);
160
161     return i;
162   }
163
164   return -1;
165 }