Blob


1 /* $OpenBSD$ */
2 /*
3 * Copyright (c) 2012 Eric Faurot <eric@openbsd.org>
4 *
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 */
18 #include "openbsd-compat.h"
20 #include <sys/types.h>
21 #include <sys/socket.h>
22 #include <netdb.h>
24 #include <asr.h>
25 #include <event.h>
26 #include <stdlib.h>
28 struct event_asr {
29 struct event ev;
30 struct asr_query *async;
31 void (*cb)(struct asr_result *, void *);
32 void *arg;
33 };
35 struct event_asr * event_asr_run(struct asr_query *,
36 void (*)(struct asr_result *, void *), void *);
37 void event_asr_abort(struct event_asr *);
39 static void
40 event_asr_dispatch(int fd __attribute__((__unused__)),
41 short ev __attribute__((__unused__)), void *arg)
42 {
43 struct event_asr *eva = arg;
44 struct asr_result ar;
45 struct timeval tv;
47 event_del(&eva->ev);
49 if (asr_run(eva->async, &ar)) {
50 eva->cb(&ar, eva->arg);
51 free(eva);
52 } else {
53 event_set(&eva->ev, ar.ar_fd,
54 ar.ar_cond == ASR_WANT_READ ? EV_READ : EV_WRITE,
55 event_asr_dispatch, eva);
56 tv.tv_sec = ar.ar_timeout / 1000;
57 tv.tv_usec = (ar.ar_timeout % 1000) * 1000;
58 event_add(&eva->ev, &tv);
59 }
60 }
62 struct event_asr *
63 event_asr_run(struct asr_query *async, void (*cb)(struct asr_result *, void *),
64 void *arg)
65 {
66 struct event_asr *eva;
67 struct timeval tv;
69 eva = calloc(1, sizeof *eva);
70 if (eva == NULL)
71 return (NULL);
72 eva->async = async;
73 eva->cb = cb;
74 eva->arg = arg;
75 tv.tv_sec = 0;
76 tv.tv_usec = 0;
77 evtimer_set(&eva->ev, event_asr_dispatch, eva);
78 evtimer_add(&eva->ev, &tv);
79 return (eva);
80 }
82 void
83 event_asr_abort(struct event_asr *eva)
84 {
85 asr_abort(eva->async);
86 event_del(&eva->ev);
87 free(eva);
88 }