]> mj.ucw.cz Git - libucw.git/blob - ucw/mainloop.h
0bf4e2edfadc10ea4577ecd41b8bf22470db0c7a
[libucw.git] / ucw / mainloop.h
1 /*
2  *      UCW Library -- Main Loop
3  *
4  *      (c) 2004--2005 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #ifndef _UCW_MAINLOOP_H
11 #define _UCW_MAINLOOP_H
12
13 #include "ucw/clists.h"
14
15 /***
16  * [[conventions]]
17  * Conventions
18  * -----------
19  *
20  * The descriptions of structures contain some fields marked with `[*]`.
21  * These are the only ones that are intended to be manipulated by the user.
22  * The remaining fields serve for internal use only and you must initialize them
23  * to zeroes.
24  ***/
25
26 /***
27  * [[time]]
28  * Time manipulation
29  * -----------------
30  *
31  * This part allows you to get the current time and request
32  * to have your function called when the time comes.
33  ***/
34
35 extern timestamp_t main_now;                    /** Current time in milliseconds since the UNIX epoch. See @main_get_time(). **/
36 extern ucw_time_t main_now_seconds;             /** Current time in seconds since the epoch. **/
37 extern timestamp_t main_idle_time;              /** Total time in milliseconds spent in the poll() call. **/
38 extern clist main_file_list, main_hook_list, main_hook_done_list, main_process_list;
39
40 /**
41  * This is a description of a timer.
42  * You fill in a handler function, any user-defined data you wish to pass
43  * to the handler, and then you invoke @timer_add().
44  *
45  * The handler() function must either call @timer_del() to delete the timer,
46  * or call @timer_add() with a different expiration time.
47  **/
48 struct main_timer {
49   cnode n;
50   timestamp_t expires;
51   uns index;
52   void (*handler)(struct main_timer *tm);       /* [*] Function to be called when the timer expires. */
53   void *data;                                   /* [*] Data for use by the handler */
54 };
55
56 /**
57  * Adds a new timer into the mainloop to be watched and called
58  * when it expires. It can also be used to modify an already running
59  * timer. It is permitted (and usual) to call this function from the
60  * timer's handler itself if you want the timer to trigger again.
61  *
62  * The @expire parameter is absolute, just add <<var_main_now,`main_now`>> if you need a relative timer.
63  **/
64 void timer_add(struct main_timer *tm, timestamp_t expires);
65 /**
66  * Removes a timer from the active ones. It is permitted (and usual) to call
67  * this function from the timer's handler itself if you want to deactivate
68  * the timer.
69  **/
70 void timer_del(struct main_timer *tm);
71
72 /**
73  * Forces refresh of <<var_main_now,`main_now`>>. You do not usually
74  * need to call this, since it is called every time the loop polls for
75  * changes. It is here if you need extra precision or some of the
76  * hooks takes a long time.
77  **/
78 void main_get_time(void);
79
80 /***
81  * [[file]]
82  * Activity on file descriptors
83  * ----------------------------
84  *
85  * You can let the mainloop watch over a set of file descriptors
86  * for a changes.
87  *
88  * It supports two ways of use. With the first one, you provide
89  * low-level handlers for reading and writing (`read_handler` and
90  * `write_handler`). They will be called every time the file descriptor
91  * is ready to be read from or written to.
92  *
93  * Return non-zero if you want to get the handler called again right now (you
94  * handled a block of data and expect more). If you return `0`, the hook will
95  * be called again in the next iteration, if it is still ready to be read/written.
96  *
97  * This way is suitable for listening sockets, interactive connections, where
98  * you need to parse everything that comes right away and similar cases.
99  *
100  * The second way is to ask mainloop to read or write a buffer of data. You
101  * provide a `read_done` or `write_done` handler respectively and call @file_read()
102  * or @file_write(). This is handy for data connections where you need to transfer
103  * data between two endpoints or for binary connections where the size of message
104  * is known in advance.
105  *
106  * It is possible to combine both methods, but it may be tricky to do it right.
107  *
108  * Both ways use `error_handler` to notify you about errors.
109  ***/
110
111 /**
112  * If you want mainloop to watch a file descriptor, fill at last `fd` into this
113  * structure. To get any useful information from the mainloop, provide some handlers
114  * too.
115  *
116  * After that, insert it into the mainloop by calling @file_add().
117  **/
118 struct main_file {
119   cnode n;
120   int fd;                                       /* [*] File descriptor */
121   int (*read_handler)(struct main_file *fi);    /* [*] To be called when ready for reading/writing; must call file_chg() afterwards */
122   int (*write_handler)(struct main_file *fi);
123   void (*error_handler)(struct main_file *fi, int cause);       /* [*] Handler to call on errors */
124   void *data;                                   /* [*] Data for use by the handlers */
125   byte *rbuf;                                   /* Read/write pointers for use by file_read/write */
126   uns rpos, rlen;
127   byte *wbuf;
128   uns wpos, wlen;
129   void (*read_done)(struct main_file *fi);      /* [*] Called when file_read is finished; rpos < rlen if EOF */
130   void (*write_done)(struct main_file *fi);     /* [*] Called when file_write is finished */
131   struct main_timer timer;
132   struct pollfd *pollfd;
133 };
134
135 /**
136  * Specifies when or why an error happened. This is passed to the error handler.
137  * `errno` is still set to the original source of error. The only exception
138  * is `MFERR_TIMEOUT`, in which case `errno` is not set and the only possible
139  * cause of it is timeout on the file descriptor (see @file_set_timeout).
140  **/
141 enum main_file_err_cause {
142   MFERR_READ,
143   MFERR_WRITE,
144   MFERR_TIMEOUT
145 };
146
147 /**
148  * Inserts a <<struct_main_file,`main_file`>> structure into the mainloop to be
149  * watched for activity. You can call this at any time, even inside a handler
150  * (of course for a different file descriptor than the one of the handler).
151  **/
152 void file_add(struct main_file *fi);
153 /**
154  * Tells the mainloop the file has changed its state. Call it whenever you
155  * change any of the handlers.
156  *
157  * Can be called only on active files (only the ones added by @file_add()).
158  **/
159 void file_chg(struct main_file *fi);
160 /**
161  * Removes a file from the watched set. You have to call this on closed files
162  * too, since the mainloop does not handle close in any way.
163  *
164  * Can be called from a handler.
165  **/
166 void file_del(struct main_file *fi);
167 /**
168  * Asks the mainloop to read @len bytes of data from @fi into @buf.
169  * It cancels any previous unfinished read requested this way and overwrites
170  * `read_handler`.
171  *
172  * When the read is done, read_done() handler is called. If an EOF occurred,
173  * `rpos < rlen` (eg. not all data were read).
174  *
175  * Can be called from a handler.
176  *
177  * You can use a call with zero @len to cancel current read, but all read data
178  * will be thrown away.
179  **/
180 void file_read(struct main_file *fi, void *buf, uns len);
181 /**
182  * Requests that the mainloop writes @len bytes of data from @buf to @fi.
183  * Cancels any previous unfinished write and overwrites `write_handler`.
184  *
185  * When it is written, write_done() handler is called.
186  *
187  * Can be called from a handler.
188  *
189  * If you call it with zero @len, it will cancel the previous write, but note
190  * some data may already be written.
191  **/
192 void file_write(struct main_file *fi, void *buf, uns len);
193 /**
194  * Sets a timer for a file @fi. If the timer is not overwritten or disabled
195  * until @expires, the file timeouts and error_handler() is called with
196  * <<enum_main_file_err_cause,`MFERR_TIMEOUT`>>.
197  *
198  * The mainloop does not disable or reset it, when something happens, it just
199  * bundles a timer with the file. If you want to watch for inactivity, it is
200  * your task to reset it whenever your handler is called.
201  *
202  * The @expires parameter is absolute (add <<var_main_now,`main_now`>> if you
203  * need relative). The call and overwrites previously set timeout. Value of `0`
204  * disables the timeout (the <<enum_main_file_err_cause,`MFERR_TIMEOUT`>> will
205  * not trigger).
206  *
207  * The use-cases for this are mainly sockets or pipes, when:
208  *
209  * - You want to drop inactive connections (no data come or go for a given time, not
210  *   incomplete messages).
211  * - You want to enforce answer in a given time (for example authentication).
212  * - You give maximum time for a whole connection.
213  **/
214 void file_set_timeout(struct main_file *fi, timestamp_t expires);
215 /**
216  * Closes all file descriptors known to mainloop. Often used between fork()
217  * and exec().
218  **/
219 void file_close_all(void);
220
221 /***
222  * [[hooks]]
223  * Loop hooks
224  * ----------
225  *
226  * The hooks are called whenever the mainloop perform an iteration.
227  * You can shutdown the mainloop from within them or request an iteration
228  * to happen without sleeping (just poll, no waiting for events).
229  ***/
230
231 /**
232  * A hook. It contains the function to call and some user data.
233  *
234  * The handler() must return one value from
235  * <<enum_main_hook_return,`main_hook_return`>>.
236  *
237  * Fill with the hook and data and pass it to @hook_add().
238  **/
239 struct main_hook {
240   cnode n;
241   int (*handler)(struct main_hook *ho);         /* [*] Hook function; returns HOOK_xxx */
242   void *data;                                   /* [*] For use by the handler */
243 };
244
245 /**
246  * Return value of the hook handler().
247  * Specifies what should happen next.
248  *
249  * - `HOOK_IDLE` -- Let the loop sleep until something happens, call after that.
250  * - `HOOK_RETRY` -- Force the loop to perform another iteration without sleeping.
251  *   This will cause calling of all the hooks again soon.
252  * - `HOOK_DONE` -- The loop will terminate if all hooks return this.
253  * - `HOOK_SHUTDOWN` -- Shuts down the loop.
254  **/
255 enum main_hook_return {
256   HOOK_IDLE,
257   HOOK_RETRY,
258   HOOK_DONE = -1,
259   HOOK_SHUTDOWN = -2
260 };
261
262 /**
263  * Inserts a new hook into the loop.
264  * The hook will be scheduled at least once before next sleep.
265  * May be called from inside a hook handler too.
266  **/
267 void hook_add(struct main_hook *ho);
268 /**
269  * Removes an existing hook from the loop.
270  * May be called from inside a hook handler (to delete itself or other hook).
271  **/
272 void hook_del(struct main_hook *ho);
273
274 /***
275  * [[process]]
276  * Child processes
277  * ---------------
278  *
279  * The main loop can watch child processes and notify you,
280  * when some of them terminates.
281  ***/
282
283 /**
284  * Description of a watched process.
285  * You fill in the handler() and `data`.
286  * The rest is set with @process_fork().
287  **/
288 struct main_process {
289   cnode n;
290   int pid;                                      /* Process id (0=not running) */
291   int status;                                   /* Exit status (-1=fork failed) */
292   char status_msg[EXIT_STATUS_MSG_SIZE];
293   void (*handler)(struct main_process *mp);     /* [*] Called when the process exits; process_del done automatically */
294   void *data;                                   /* [*] For use by the handler */
295 };
296
297 /**
298  * Asks the mainloop to watch this process.
299  * As it is done automatically in @process_fork(), you need this only
300  * if you removed the process previously by @process_del().
301  **/
302 void process_add(struct main_process *mp);
303 /**
304  * Removes the process from the watched set. This is done
305  * automatically, when the process terminates, so you need it only
306  * when you do not want to watch a running process any more.
307  */
308 void process_del(struct main_process *mp);
309 /**
310  * Forks and fills the @mp with information about the new process.
311  *
312  * If the fork() succeeds, it:
313  *
314  * - Returns 0 in the child.
315  * - Returns 1 in the parent and calls @process_add() on it.
316  *
317  * In the case of unsuccessful fork(), it:
318  *
319  * - Fills in the `status_msg` and sets `status` to -1.
320  * - Calls the handler() as if the process terminated.
321  * - Returns 1.
322  **/
323 int process_fork(struct main_process *mp);
324
325 /***
326  * [[control]]
327  * Control of the mainloop
328  * -----------------------
329  *
330  * These functions control the mainloop as a whole.
331  ***/
332
333 extern uns main_shutdown;                       /** Setting this to nonzero forces the @main_loop() function to terminate. **/
334 void main_init(void);                           /** Initializes the mainloop structures. Call before any `*_add` function. **/
335 /**
336  * Start the mainloop.
337  * It will watch the provided objects and call callbacks.
338  * Terminates when someone sets <<var_main_shutdown,`main_shutdown`>>
339  * to nonzero, when all <<hook,hooks>> return
340  * <<enum_main_hook_return,`HOOK_DONE`>> or at last one <<hook,hook>>
341  * returns <<enum_main_hook_return,`HOOK_SHUTDOWN`>>.
342  **/
343 void main_loop(void);
344 void main_debug(void);                          /** Prints a lot of debug information about current status of the mainloop. **/
345
346 #endif