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