3518dfdaef2753db0c8dea0edbe3556c68ce8d75
[strongswan.git] / src / libstrongswan / processing / watcher.c
1 /*
2 * Copyright (C) 2013 Martin Willi
3 * Copyright (C) 2013 revosec AG
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 */
15
16 #include "watcher.h"
17
18 #include <library.h>
19 #include <threading/thread.h>
20 #include <threading/mutex.h>
21 #include <threading/condvar.h>
22 #include <collections/linked_list.h>
23 #include <processing/jobs/callback_job.h>
24
25 #include <unistd.h>
26 #include <errno.h>
27 #ifndef WIN32
28 #include <sys/select.h>
29 #endif
30 #include <fcntl.h>
31
32 typedef struct private_watcher_t private_watcher_t;
33
34 /**
35 * Private data of an watcher_t object.
36 */
37 struct private_watcher_t {
38
39 /**
40 * Public watcher_t interface.
41 */
42 watcher_t public;
43
44 /**
45 * List of registered FDs, as entry_t
46 */
47 linked_list_t *fds;
48
49 /**
50 * Pending update of FD list?
51 */
52 bool pending;
53
54 /**
55 * Is watcher running?
56 */
57 bool running;
58
59 /**
60 * Lock to access FD list
61 */
62 mutex_t *mutex;
63
64 /**
65 * Condvar to signal completion of callback
66 */
67 condvar_t *condvar;
68
69 /**
70 * Notification pipe to signal watcher thread
71 */
72 int notify[2];
73
74 /**
75 * List of callback jobs to process by watcher thread, as job_t
76 */
77 linked_list_t *jobs;
78 };
79
80 /**
81 * Entry for a registered file descriptor
82 */
83 typedef struct {
84 /** file descriptor */
85 int fd;
86 /** events to watch */
87 watcher_event_t events;
88 /** registered callback function */
89 watcher_cb_t cb;
90 /** user data to pass to callback */
91 void *data;
92 /** callback(s) currently active? */
93 int in_callback;
94 } entry_t;
95
96 /**
97 * Data we pass on for an async notification
98 */
99 typedef struct {
100 /** file descriptor */
101 int fd;
102 /** event type */
103 watcher_event_t event;
104 /** registered callback function */
105 watcher_cb_t cb;
106 /** user data to pass to callback */
107 void *data;
108 /** keep registered? */
109 bool keep;
110 /** reference to watcher */
111 private_watcher_t *this;
112 } notify_data_t;
113
114 /**
115 * Notify watcher thread about changes
116 */
117 static void update(private_watcher_t *this)
118 {
119 char buf[1] = { 'u' };
120
121 this->pending = TRUE;
122 if (this->notify[1] != -1)
123 {
124 #ifdef WIN32
125 if (send(this->notify[1], buf, sizeof(buf), 0) == -1)
126 #else
127 if (write(this->notify[1], buf, sizeof(buf)) == -1)
128 #endif
129 {
130 DBG1(DBG_JOB, "notifying watcher failed: %s", strerror(errno));
131 }
132 }
133 }
134
135 /**
136 * Cleanup function if callback gets cancelled
137 */
138 static void unregister(notify_data_t *data)
139 {
140 /* if a thread processing a callback gets cancelled, we mark the entry
141 * as cancelled, like the callback would return FALSE. This is required
142 * to not queue this watcher again if all threads have been gone. */
143 data->keep = FALSE;
144 }
145
146 /**
147 * Execute callback of registered FD, asynchronous
148 */
149 static job_requeue_t notify_async(notify_data_t *data)
150 {
151 thread_cleanup_push((void*)unregister, data);
152 data->keep = data->cb(data->data, data->fd, data->event);
153 thread_cleanup_pop(FALSE);
154 return JOB_REQUEUE_NONE;
155 }
156
157 /**
158 * Clean up notification data, reactivate FD
159 */
160 static void notify_end(notify_data_t *data)
161 {
162 private_watcher_t *this = data->this;
163 enumerator_t *enumerator;
164 entry_t *entry;
165
166 /* reactivate the disabled entry */
167 this->mutex->lock(this->mutex);
168 enumerator = this->fds->create_enumerator(this->fds);
169 while (enumerator->enumerate(enumerator, &entry))
170 {
171 if (entry->fd == data->fd)
172 {
173 if (!data->keep)
174 {
175 entry->events &= ~data->event;
176 if (!entry->events)
177 {
178 this->fds->remove_at(this->fds, enumerator);
179 free(entry);
180 break;
181 }
182 }
183 entry->in_callback--;
184 break;
185 }
186 }
187 enumerator->destroy(enumerator);
188
189 update(this);
190 this->condvar->broadcast(this->condvar);
191 this->mutex->unlock(this->mutex);
192
193 free(data);
194 }
195
196 /**
197 * Execute the callback for a registered FD
198 */
199 static void notify(private_watcher_t *this, entry_t *entry,
200 watcher_event_t event)
201 {
202 notify_data_t *data;
203
204 /* get a copy of entry for async job, but with specific event */
205 INIT(data,
206 .fd = entry->fd,
207 .event = event,
208 .cb = entry->cb,
209 .data = entry->data,
210 .keep = TRUE,
211 .this = this,
212 );
213
214 /* deactivate entry, so we can select() other FDs even if the async
215 * processing did not handle the event yet */
216 entry->in_callback++;
217
218 this->jobs->insert_last(this->jobs,
219 callback_job_create_with_prio((void*)notify_async, data,
220 (void*)notify_end, (callback_job_cancel_t)return_false,
221 JOB_PRIO_CRITICAL));
222 }
223
224 /**
225 * Thread cancellation function for watcher thread
226 */
227 static void activate_all(private_watcher_t *this)
228 {
229 enumerator_t *enumerator;
230 entry_t *entry;
231
232 /* When the watcher thread gets cancelled, we have to reactivate any entry
233 * and signal threads in remove() to go on. */
234
235 this->mutex->lock(this->mutex);
236 enumerator = this->fds->create_enumerator(this->fds);
237 while (enumerator->enumerate(enumerator, &entry))
238 {
239 entry->in_callback = 0;
240 }
241 enumerator->destroy(enumerator);
242 this->running = FALSE;
243 this->condvar->broadcast(this->condvar);
244 this->mutex->unlock(this->mutex);
245 }
246
247 /**
248 * Dispatching function
249 */
250 static job_requeue_t watch(private_watcher_t *this)
251 {
252 enumerator_t *enumerator;
253 entry_t *entry;
254 fd_set rd, wr, ex;
255 int maxfd = 0, res;
256 bool rebuild = FALSE;
257
258 FD_ZERO(&rd);
259 FD_ZERO(&wr);
260 FD_ZERO(&ex);
261
262 this->mutex->lock(this->mutex);
263
264 if (this->fds->get_count(this->fds) == 0)
265 {
266 this->running = FALSE;
267 this->mutex->unlock(this->mutex);
268 return JOB_REQUEUE_NONE;
269 }
270
271 if (this->notify[0] != -1)
272 {
273 FD_SET(this->notify[0], &rd);
274 maxfd = this->notify[0];
275 }
276
277 enumerator = this->fds->create_enumerator(this->fds);
278 while (enumerator->enumerate(enumerator, &entry))
279 {
280 if (!entry->in_callback)
281 {
282 if (entry->events & WATCHER_READ)
283 {
284 DBG3(DBG_JOB, " watching %d for reading", entry->fd);
285 FD_SET(entry->fd, &rd);
286 }
287 if (entry->events & WATCHER_WRITE)
288 {
289 DBG3(DBG_JOB, " watching %d for writing", entry->fd);
290 FD_SET(entry->fd, &wr);
291 }
292 if (entry->events & WATCHER_EXCEPT)
293 {
294 DBG3(DBG_JOB, " watching %d for exceptions", entry->fd);
295 FD_SET(entry->fd, &ex);
296 }
297 maxfd = max(maxfd, entry->fd);
298 }
299 }
300 enumerator->destroy(enumerator);
301 this->mutex->unlock(this->mutex);
302
303 while (!rebuild)
304 {
305 char buf[1];
306 bool old;
307 ssize_t len;
308 job_t *job;
309
310 DBG2(DBG_JOB, "watcher going to select()");
311 thread_cleanup_push((void*)activate_all, this);
312 old = thread_cancelability(TRUE);
313
314 res = select(maxfd + 1, &rd, &wr, &ex, NULL);
315 thread_cancelability(old);
316 thread_cleanup_pop(FALSE);
317
318 if (res > 0)
319 {
320 if (this->notify[0] != -1 && FD_ISSET(this->notify[0], &rd))
321 {
322 while (TRUE)
323 {
324 #ifdef WIN32
325 len = recv(this->notify[0], buf, sizeof(buf), 0);
326 #else
327 len = read(this->notify[0], buf, sizeof(buf));
328 #endif
329 if (len == -1)
330 {
331 if (errno != EAGAIN && errno != EWOULDBLOCK)
332 {
333 DBG1(DBG_JOB, "reading watcher notify failed: %s",
334 strerror(errno));
335 }
336 break;
337 }
338 }
339 this->pending = FALSE;
340 DBG2(DBG_JOB, "watcher got notification, rebuilding");
341 return JOB_REQUEUE_DIRECT;
342 }
343
344 this->mutex->lock(this->mutex);
345 enumerator = this->fds->create_enumerator(this->fds);
346 while (enumerator->enumerate(enumerator, &entry))
347 {
348 if (entry->in_callback)
349 {
350 rebuild = TRUE;
351 break;
352 }
353 if (FD_ISSET(entry->fd, &rd) && (entry->events & WATCHER_READ))
354 {
355 DBG2(DBG_JOB, "watched FD %d ready to read", entry->fd);
356 notify(this, entry, WATCHER_READ);
357 }
358 if (FD_ISSET(entry->fd, &wr) && (entry->events & WATCHER_WRITE))
359 {
360 DBG2(DBG_JOB, "watched FD %d ready to write", entry->fd);
361 notify(this, entry, WATCHER_WRITE);
362 }
363 if (FD_ISSET(entry->fd, &ex) && (entry->events & WATCHER_EXCEPT))
364 {
365 DBG2(DBG_JOB, "watched FD %d has exception", entry->fd);
366 notify(this, entry, WATCHER_EXCEPT);
367 }
368 }
369 enumerator->destroy(enumerator);
370 this->mutex->unlock(this->mutex);
371
372 if (this->jobs->get_count(this->jobs))
373 {
374 while (this->jobs->remove_first(this->jobs,
375 (void**)&job) == SUCCESS)
376 {
377 lib->processor->execute_job(lib->processor, job);
378 }
379 /* we temporarily disable a notified FD, rebuild FDSET */
380 return JOB_REQUEUE_DIRECT;
381 }
382 }
383 else
384 {
385 if (!this->pending && errno != EINTR)
386 { /* complain only if no pending updates */
387 DBG1(DBG_JOB, "watcher select() error: %s", strerror(errno));
388 }
389 return JOB_REQUEUE_DIRECT;
390 }
391 }
392 return JOB_REQUEUE_DIRECT;
393 }
394
395 METHOD(watcher_t, add, void,
396 private_watcher_t *this, int fd, watcher_event_t events,
397 watcher_cb_t cb, void *data)
398 {
399 entry_t *entry;
400
401 INIT(entry,
402 .fd = fd,
403 .events = events,
404 .cb = cb,
405 .data = data,
406 );
407
408 this->mutex->lock(this->mutex);
409 this->fds->insert_last(this->fds, entry);
410 if (!this->running)
411 {
412 this->running = TRUE;
413 lib->processor->queue_job(lib->processor,
414 (job_t*)callback_job_create_with_prio((void*)watch, this,
415 NULL, (callback_job_cancel_t)return_false, JOB_PRIO_CRITICAL));
416 }
417 else
418 {
419 update(this);
420 }
421 this->mutex->unlock(this->mutex);
422 }
423
424 METHOD(watcher_t, remove_, void,
425 private_watcher_t *this, int fd)
426 {
427 enumerator_t *enumerator;
428 entry_t *entry;
429
430 this->mutex->lock(this->mutex);
431 while (TRUE)
432 {
433 bool is_in_callback = FALSE;
434
435 enumerator = this->fds->create_enumerator(this->fds);
436 while (enumerator->enumerate(enumerator, &entry))
437 {
438 if (entry->fd == fd)
439 {
440 if (this->running && entry->in_callback)
441 {
442 is_in_callback = TRUE;
443 break;
444 }
445 this->fds->remove_at(this->fds, enumerator);
446 free(entry);
447 }
448 }
449 enumerator->destroy(enumerator);
450 if (!is_in_callback)
451 {
452 break;
453 }
454 this->condvar->wait(this->condvar, this->mutex);
455 }
456
457 update(this);
458 this->mutex->unlock(this->mutex);
459 }
460
461 METHOD(watcher_t, destroy, void,
462 private_watcher_t *this)
463 {
464 this->mutex->destroy(this->mutex);
465 this->condvar->destroy(this->condvar);
466 this->fds->destroy(this->fds);
467 if (this->notify[0] != -1)
468 {
469 close(this->notify[0]);
470 }
471 if (this->notify[1] != -1)
472 {
473 close(this->notify[1]);
474 }
475 this->jobs->destroy(this->jobs);
476 free(this);
477 }
478
479 #ifdef WIN32
480
481 /**
482 * Create notify pipe with a TCP socketpair
483 */
484 static bool create_notify(private_watcher_t *this)
485 {
486 u_long on = 1;
487
488 if (socketpair(AF_INET, SOCK_STREAM, 0, this->notify) == 0)
489 {
490 /* use non-blocking I/O on read-end of notify pipe */
491 if (ioctlsocket(this->notify[0], FIONBIO, &on) == 0)
492 {
493 return TRUE;
494 }
495 DBG1(DBG_LIB, "setting watcher notify pipe read-end non-blocking "
496 "failed: %s", strerror(errno));
497 }
498 return FALSE;
499 }
500
501 #else /* !WIN32 */
502
503 /**
504 * Create a notify pipe with a one-directional pipe
505 */
506 static bool create_notify(private_watcher_t *this)
507 {
508 int flags;
509
510 if (pipe(this->notify) == 0)
511 {
512 /* use non-blocking I/O on read-end of notify pipe */
513 flags = fcntl(this->notify[0], F_GETFL);
514 if (flags != -1 &&
515 fcntl(this->notify[0], F_SETFL, flags | O_NONBLOCK) != -1)
516 {
517 return TRUE;
518 }
519 DBG1(DBG_LIB, "setting watcher notify pipe read-end non-blocking "
520 "failed: %s", strerror(errno));
521 }
522 return FALSE;
523 }
524
525 #endif /* !WIN32 */
526
527 /**
528 * See header
529 */
530 watcher_t *watcher_create()
531 {
532 private_watcher_t *this;
533
534 INIT(this,
535 .public = {
536 .add = _add,
537 .remove = _remove_,
538 .destroy = _destroy,
539 },
540 .fds = linked_list_create(),
541 .mutex = mutex_create(MUTEX_TYPE_DEFAULT),
542 .condvar = condvar_create(CONDVAR_TYPE_DEFAULT),
543 .jobs = linked_list_create(),
544 .notify = {-1, -1},
545 );
546
547 if (!create_notify(this))
548 {
549 DBG1(DBG_LIB, "creating watcher notify pipe failed: %s",
550 strerror(errno));
551 }
552 return &this->public;
553 }