update to 9.7.1-P2
[tridge/bind9.git] / lib / dns / client.c
1 /*
2  * Copyright (C) 2009, 2010  Internet Systems Consortium, Inc. ("ISC")
3  *
4  * Permission to use, copy, modify, and/or distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
9  * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
10  * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
11  * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
12  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
13  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
14  * PERFORMANCE OF THIS SOFTWARE.
15  */
16
17 /* $Id: client.c,v 1.6.32.4 2010/05/19 07:11:19 marka Exp $ */
18
19 #include <config.h>
20
21 #include <stddef.h>
22
23 #include <isc/app.h>
24 #include <isc/mem.h>
25 #include <isc/mutex.h>
26 #include <isc/sockaddr.h>
27 #include <isc/socket.h>
28 #include <isc/task.h>
29 #include <isc/timer.h>
30 #include <isc/util.h>
31
32 #include <dns/adb.h>
33 #include <dns/client.h>
34 #include <dns/db.h>
35 #include <dns/dispatch.h>
36 #include <dns/events.h>
37 #include <dns/forward.h>
38 #include <dns/keytable.h>
39 #include <dns/message.h>
40 #include <dns/name.h>
41 #include <dns/rdata.h>
42 #include <dns/rdatalist.h>
43 #include <dns/rdataset.h>
44 #include <dns/rdatatype.h>
45 #include <dns/rdatasetiter.h>
46 #include <dns/rdatastruct.h>
47 #include <dns/request.h>
48 #include <dns/resolver.h>
49 #include <dns/result.h>
50 #include <dns/tsec.h>
51 #include <dns/tsig.h>
52 #include <dns/view.h>
53
54 #include <dst/dst.h>
55
56 #define DNS_CLIENT_MAGIC                ISC_MAGIC('D', 'N', 'S', 'c')
57 #define DNS_CLIENT_VALID(c)             ISC_MAGIC_VALID(c, DNS_CLIENT_MAGIC)
58
59 #define RCTX_MAGIC                      ISC_MAGIC('R', 'c', 't', 'x')
60 #define RCTX_VALID(c)                   ISC_MAGIC_VALID(c, RCTX_MAGIC)
61
62 #define REQCTX_MAGIC                    ISC_MAGIC('R', 'q', 'c', 'x')
63 #define REQCTX_VALID(c)                 ISC_MAGIC_VALID(c, REQCTX_MAGIC)
64
65 #define UCTX_MAGIC                      ISC_MAGIC('U', 'c', 't', 'x')
66 #define UCTX_VALID(c)                   ISC_MAGIC_VALID(c, UCTX_MAGIC)
67
68 #define MAX_RESTARTS 16
69
70 /*%
71  * DNS client object
72  */
73 struct dns_client {
74         /* Unlocked */
75         unsigned int                    magic;
76         unsigned int                    attributes;
77         isc_mutex_t                     lock;
78         isc_mem_t                       *mctx;
79         isc_appctx_t                    *actx;
80         isc_taskmgr_t                   *taskmgr;
81         isc_task_t                      *task;
82         isc_socketmgr_t                 *socketmgr;
83         isc_timermgr_t                  *timermgr;
84         dns_dispatchmgr_t               *dispatchmgr;
85         dns_dispatch_t                  *dispatchv4;
86         dns_dispatch_t                  *dispatchv6;
87
88         unsigned int                    update_timeout;
89         unsigned int                    update_udptimeout;
90         unsigned int                    update_udpretries;
91         unsigned int                    find_timeout;
92         unsigned int                    find_udpretries;
93
94         /* Locked */
95         unsigned int                    references;
96         dns_viewlist_t                  viewlist;
97         ISC_LIST(struct resctx)         resctxs;
98         ISC_LIST(struct reqctx)         reqctxs;
99         ISC_LIST(struct updatectx)      updatectxs;
100 };
101
102 /*%
103  * Timeout/retry constants for dynamic update borrowed from nsupdate
104  */
105 #define DEF_UPDATE_TIMEOUT      300
106 #define MIN_UPDATE_TIMEOUT      30
107 #define DEF_UPDATE_UDPTIMEOUT   3
108 #define DEF_UPDATE_UDPRETRIES   3
109
110 #define DEF_FIND_TIMEOUT        5
111 #define DEF_FIND_UDPRETRIES     3
112
113 #define DNS_CLIENTATTR_OWNCTX                   0x01
114
115 #define DNS_CLIENTVIEW_NAME                     "dnsclient"
116
117 /*%
118  * Internal state for a single name resolution procedure
119  */
120 typedef struct resctx {
121         /* Unlocked */
122         unsigned int            magic;
123         isc_mutex_t             lock;
124         dns_client_t            *client;
125         isc_boolean_t           want_dnssec;
126
127         /* Locked */
128         ISC_LINK(struct resctx) link;
129         isc_task_t              *task;
130         dns_view_t              *view;
131         unsigned int            restarts;
132         dns_fixedname_t         name;
133         dns_rdatatype_t         type;
134         dns_fetch_t             *fetch;
135         dns_namelist_t          namelist;
136         isc_result_t            result;
137         dns_clientresevent_t    *event;
138         isc_boolean_t           canceled;
139         dns_rdataset_t          *rdataset;
140         dns_rdataset_t          *sigrdataset;
141 } resctx_t;
142
143 /*%
144  * Argument of an internal event for synchronous name resolution.
145  */
146 typedef struct resarg {
147         /* Unlocked */
148         isc_appctx_t            *actx;
149         dns_client_t            *client;
150         isc_mutex_t             lock;
151
152         /* Locked */
153         isc_result_t            result;
154         isc_result_t            vresult;
155         dns_namelist_t          *namelist;
156         dns_clientrestrans_t    *trans;
157         isc_boolean_t           canceled;
158 } resarg_t;
159
160 /*%
161  * Internal state for a single DNS request
162  */
163 typedef struct reqctx {
164         /* Unlocked */
165         unsigned int            magic;
166         isc_mutex_t             lock;
167         dns_client_t            *client;
168         unsigned int            parseoptions;
169
170         /* Locked */
171         ISC_LINK(struct reqctx) link;
172         isc_boolean_t           canceled;
173         dns_tsigkey_t           *tsigkey;
174         dns_request_t           *request;
175         dns_clientreqevent_t    *event;
176 } reqctx_t;
177
178 /*%
179  * Argument of an internal event for synchronous DNS request.
180  */
181 typedef struct reqarg {
182         /* Unlocked */
183         isc_appctx_t            *actx;
184         dns_client_t            *client;
185         isc_mutex_t             lock;
186
187         /* Locked */
188         isc_result_t            result;
189         dns_clientreqtrans_t    *trans;
190         isc_boolean_t           canceled;
191 } reqarg_t;
192
193 /*%
194  * Argument of an internal event for synchronous name resolution.
195  */
196 typedef struct updatearg {
197         /* Unlocked */
198         isc_appctx_t            *actx;
199         dns_client_t            *client;
200         isc_mutex_t             lock;
201
202         /* Locked */
203         isc_result_t            result;
204         dns_clientupdatetrans_t *trans;
205         isc_boolean_t           canceled;
206 } updatearg_t;
207
208 /*%
209  * Internal state for a single dynamic update procedure
210  */
211 typedef struct updatectx {
212         /* Unlocked */
213         unsigned int                    magic;
214         isc_mutex_t                     lock;
215         dns_client_t                    *client;
216
217         /* Locked */
218         dns_request_t                   *updatereq;
219         dns_request_t                   *soareq;
220         dns_clientrestrans_t            *restrans;
221         dns_clientrestrans_t            *restrans2;
222         isc_boolean_t                   canceled;
223
224         /* Task Locked */
225         ISC_LINK(struct updatectx)      link;
226         dns_clientupdatestate_t         state;
227         dns_rdataclass_t                rdclass;
228         dns_view_t                      *view;
229         dns_message_t                   *updatemsg;
230         dns_message_t                   *soaquery;
231         dns_clientupdateevent_t         *event;
232         dns_tsigkey_t                   *tsigkey;
233         dst_key_t                       *sig0key;
234         dns_name_t                      *firstname;
235         dns_name_t                      soaqname;
236         dns_fixedname_t                 zonefname;
237         dns_name_t                      *zonename;
238         isc_sockaddrlist_t              servers;
239         unsigned int                    nservers;
240         isc_sockaddr_t                  *currentserver;
241         struct updatectx                *bp4;
242         struct updatectx                *bp6;
243 } updatectx_t;
244
245 static isc_result_t request_soa(updatectx_t *uctx);
246 static void client_resfind(resctx_t *rctx, dns_fetchevent_t *event);
247 static isc_result_t send_update(updatectx_t *uctx);
248
249 static isc_result_t
250 getudpdispatch(int family, dns_dispatchmgr_t *dispatchmgr,
251                isc_socketmgr_t *socketmgr, isc_taskmgr_t *taskmgr,
252                isc_boolean_t is_shared, dns_dispatch_t **dispp)
253 {
254         unsigned int attrs, attrmask;
255         isc_sockaddr_t sa;
256         dns_dispatch_t *disp;
257         unsigned buffersize, maxbuffers, maxrequests, buckets, increment;
258         isc_result_t result;
259
260         attrs = 0;
261         attrs |= DNS_DISPATCHATTR_UDP;
262         switch (family) {
263         case AF_INET:
264                 attrs |= DNS_DISPATCHATTR_IPV4;
265                 break;
266         case AF_INET6:
267                 attrs |= DNS_DISPATCHATTR_IPV6;
268                 break;
269         default:
270                 INSIST(0);
271         }
272         attrmask = 0;
273         attrmask |= DNS_DISPATCHATTR_UDP;
274         attrmask |= DNS_DISPATCHATTR_TCP;
275         attrmask |= DNS_DISPATCHATTR_IPV4;
276         attrmask |= DNS_DISPATCHATTR_IPV6;
277
278         isc_sockaddr_anyofpf(&sa, family);
279
280         buffersize = 4096;
281         maxbuffers = is_shared ? 1000 : 8;
282         maxrequests = 32768;
283         buckets = is_shared ? 16411 : 3;
284         increment = is_shared ? 16433 : 5;
285
286         disp = NULL;
287         result = dns_dispatch_getudp(dispatchmgr, socketmgr,
288                                      taskmgr, &sa,
289                                      buffersize, maxbuffers, maxrequests,
290                                      buckets, increment,
291                                      attrs, attrmask, &disp);
292         if (result == ISC_R_SUCCESS)
293                 *dispp = disp;
294
295         return (result);
296 }
297
298 static isc_result_t
299 dns_client_createview(isc_mem_t *mctx, dns_rdataclass_t rdclass,
300                       unsigned int options, isc_taskmgr_t *taskmgr,
301                       unsigned int ntasks, isc_socketmgr_t *socketmgr,
302                       isc_timermgr_t *timermgr, dns_dispatchmgr_t *dispatchmgr,
303                       dns_dispatch_t *dispatchv4, dns_dispatch_t *dispatchv6,
304                       dns_view_t **viewp)
305 {
306         isc_result_t result;
307         dns_view_t *view = NULL;
308         const char *dbtype;
309
310         result = dns_view_create(mctx, rdclass, DNS_CLIENTVIEW_NAME, &view);
311         if (result != ISC_R_SUCCESS)
312                 return (result);
313
314         /* Initialize view security roots */
315         result = dns_view_initsecroots(view, mctx);
316         if (result != ISC_R_SUCCESS) {
317                 dns_view_detach(&view);
318                 return (result);
319         }
320
321         result = dns_view_createresolver(view, taskmgr, ntasks, socketmgr,
322                                          timermgr, 0, dispatchmgr,
323                                          dispatchv4, dispatchv6);
324         if (result != ISC_R_SUCCESS) {
325                 dns_view_detach(&view);
326                 return (result);
327         }
328
329         /*
330          * Set cache DB.
331          * XXX: it may be better if specific DB implementations can be
332          * specified via some configuration knob.
333          */
334         if ((options & DNS_CLIENTCREATEOPT_USECACHE) != 0)
335                 dbtype = "rbt";
336         else
337                 dbtype = "ecdb";
338         result = dns_db_create(mctx, dbtype, dns_rootname, dns_dbtype_cache,
339                                rdclass, 0, NULL, &view->cachedb);
340         if (result != ISC_R_SUCCESS) {
341                 dns_view_detach(&view);
342                 return (result);
343         }
344
345         *viewp = view;
346         return (ISC_R_SUCCESS);
347 }
348
349 isc_result_t
350 dns_client_create(dns_client_t **clientp, unsigned int options) {
351         isc_result_t result;
352         isc_mem_t *mctx = NULL;
353         isc_appctx_t *actx = NULL;
354         isc_taskmgr_t *taskmgr = NULL;
355         isc_socketmgr_t *socketmgr = NULL;
356         isc_timermgr_t *timermgr = NULL;
357
358         result = isc_mem_create(0, 0, &mctx);
359         if (result != ISC_R_SUCCESS)
360                 return (result);
361         result = isc_appctx_create(mctx, &actx);
362         if (result != ISC_R_SUCCESS)
363                 goto cleanup;
364         result = isc_app_ctxstart(actx);
365         if (result != ISC_R_SUCCESS)
366                 goto cleanup;
367         result = isc_taskmgr_createinctx(mctx, actx, 1, 0, &taskmgr);
368         if (result != ISC_R_SUCCESS)
369                 goto cleanup;
370         result = isc_socketmgr_createinctx(mctx, actx, &socketmgr);
371         if (result != ISC_R_SUCCESS)
372                 goto cleanup;
373         result = isc_timermgr_createinctx(mctx, actx, &timermgr);
374         if (result != ISC_R_SUCCESS)
375                 goto cleanup;
376
377         result = dns_client_createx(mctx, actx, taskmgr, socketmgr, timermgr,
378                                     options, clientp);
379         if (result != ISC_R_SUCCESS)
380                 goto cleanup;
381
382         (*clientp)->attributes |= DNS_CLIENTATTR_OWNCTX;
383
384         /* client has its own reference to mctx, so we can detach it here */
385         isc_mem_detach(&mctx);
386
387         return (ISC_R_SUCCESS);
388
389  cleanup:
390         if (taskmgr != NULL)
391                 isc_taskmgr_destroy(&taskmgr);
392         if (timermgr != NULL)
393                 isc_timermgr_destroy(&timermgr);
394         if (socketmgr != NULL)
395                 isc_socketmgr_destroy(&socketmgr);
396         if (actx != NULL)
397                 isc_appctx_destroy(&actx);
398         isc_mem_detach(&mctx);
399
400         return (result);
401 }
402
403 isc_result_t
404 dns_client_createx(isc_mem_t *mctx, isc_appctx_t *actx, isc_taskmgr_t *taskmgr,
405                    isc_socketmgr_t *socketmgr, isc_timermgr_t *timermgr,
406                    unsigned int options, dns_client_t **clientp)
407 {
408         dns_client_t *client;
409         isc_result_t result;
410         dns_dispatchmgr_t *dispatchmgr = NULL;
411         dns_dispatch_t *dispatchv4 = NULL;
412         dns_dispatch_t *dispatchv6 = NULL;
413         dns_view_t *view = NULL;
414
415         REQUIRE(mctx != NULL);
416         REQUIRE(taskmgr != NULL);
417         REQUIRE(timermgr != NULL);
418         REQUIRE(socketmgr != NULL);
419         REQUIRE(clientp != NULL && *clientp == NULL);
420
421         client = isc_mem_get(mctx, sizeof(*client));
422         if (client == NULL)
423                 return (ISC_R_NOMEMORY);
424
425         result = isc_mutex_init(&client->lock);
426         if (result != ISC_R_SUCCESS) {
427                 isc_mem_put(mctx, client, sizeof(*client));
428                 return (result);
429         }
430
431         client->actx = actx;
432         client->taskmgr = taskmgr;
433         client->socketmgr = socketmgr;
434         client->timermgr = timermgr;
435
436         client->task = NULL;
437         result = isc_task_create(client->taskmgr, 0, &client->task);
438         if (result != ISC_R_SUCCESS)
439                 goto cleanup;
440
441         result = dns_dispatchmgr_create(mctx, NULL, &dispatchmgr);
442         if (result != ISC_R_SUCCESS)
443                 goto cleanup;
444         client->dispatchmgr = dispatchmgr;
445
446         /* TODO: whether to use dispatch v4 or v6 should be configurable */
447         client->dispatchv4 = NULL;
448         client->dispatchv6 = NULL;
449         result = getudpdispatch(AF_INET, dispatchmgr, socketmgr,
450                                 taskmgr, ISC_TRUE, &dispatchv4);
451         if (result == ISC_R_SUCCESS)
452                 client->dispatchv4 = dispatchv4;
453         result = getudpdispatch(AF_INET6, dispatchmgr, socketmgr,
454                                 taskmgr, ISC_TRUE, &dispatchv6);
455         if (result == ISC_R_SUCCESS)
456                 client->dispatchv6 = dispatchv6;
457
458         /* We need at least one of the dispatchers */
459         if (dispatchv4 == NULL && dispatchv6 == NULL) {
460                 INSIST(result != ISC_R_SUCCESS);
461                 goto cleanup;
462         }
463
464         /* Create the default view for class IN */
465         result = dns_client_createview(mctx, dns_rdataclass_in, options,
466                                        taskmgr, 31, socketmgr, timermgr,
467                                        dispatchmgr, dispatchv4, dispatchv6,
468                                        &view);
469         if (result != ISC_R_SUCCESS)
470                 goto cleanup;
471         ISC_LIST_INIT(client->viewlist);
472         ISC_LIST_APPEND(client->viewlist, view, link);
473
474         dns_view_freeze(view); /* too early? */
475
476         ISC_LIST_INIT(client->resctxs);
477         ISC_LIST_INIT(client->reqctxs);
478         ISC_LIST_INIT(client->updatectxs);
479
480         client->mctx = NULL;
481         isc_mem_attach(mctx, &client->mctx);
482
483         client->update_timeout = DEF_UPDATE_TIMEOUT;
484         client->update_udptimeout = DEF_UPDATE_UDPTIMEOUT;
485         client->update_udpretries = DEF_UPDATE_UDPRETRIES;
486         client->find_timeout = DEF_FIND_TIMEOUT;
487         client->find_udpretries = DEF_FIND_UDPRETRIES;
488
489         client->references = 1;
490         client->magic = DNS_CLIENT_MAGIC;
491
492         *clientp = client;
493
494         return (ISC_R_SUCCESS);
495
496  cleanup:
497         if (dispatchv4 != NULL)
498                 dns_dispatch_detach(&dispatchv4);
499         if (dispatchv6 != NULL)
500                 dns_dispatch_detach(&dispatchv6);
501         if (dispatchmgr != NULL)
502                 dns_dispatchmgr_destroy(&dispatchmgr);
503         if (client->task != NULL)
504                 isc_task_detach(&client->task);
505         isc_mem_put(mctx, client, sizeof(*client));
506
507         return (result);
508 }
509
510 static void
511 destroyclient(dns_client_t **clientp) {
512         dns_client_t *client = *clientp;
513         dns_view_t *view;
514
515         while ((view = ISC_LIST_HEAD(client->viewlist)) != NULL) {
516                 ISC_LIST_UNLINK(client->viewlist, view, link);
517                 dns_view_detach(&view);
518         }
519
520         if (client->dispatchv4 != NULL)
521                 dns_dispatch_detach(&client->dispatchv4);
522         if (client->dispatchv6 != NULL)
523                 dns_dispatch_detach(&client->dispatchv6);
524
525         dns_dispatchmgr_destroy(&client->dispatchmgr);
526
527         isc_task_detach(&client->task);
528
529         /*
530          * If the client has created its own running environments,
531          * destroy them.
532          */
533         if ((client->attributes & DNS_CLIENTATTR_OWNCTX) != 0) {
534                 isc_taskmgr_destroy(&client->taskmgr);
535                 isc_timermgr_destroy(&client->timermgr);
536                 isc_socketmgr_destroy(&client->socketmgr);
537
538                 isc_app_ctxfinish(client->actx);
539                 isc_appctx_destroy(&client->actx);
540         }
541
542         DESTROYLOCK(&client->lock);
543         client->magic = 0;
544
545         isc_mem_putanddetach(&client->mctx, client, sizeof(*client));
546
547         *clientp = NULL;
548 }
549
550 void
551 dns_client_destroy(dns_client_t **clientp) {
552         dns_client_t *client;
553         isc_boolean_t destroyok = ISC_FALSE;
554
555         REQUIRE(clientp != NULL);
556         client = *clientp;
557         REQUIRE(DNS_CLIENT_VALID(client));
558
559         LOCK(&client->lock);
560         client->references--;
561         if (client->references == 0 && ISC_LIST_EMPTY(client->resctxs) &&
562             ISC_LIST_EMPTY(client->reqctxs) &&
563             ISC_LIST_EMPTY(client->updatectxs)) {
564                 destroyok = ISC_TRUE;
565         }
566         UNLOCK(&client->lock);
567
568         if (destroyok)
569                 destroyclient(&client);
570
571         *clientp = NULL;
572 }
573
574 isc_result_t
575 dns_client_setservers(dns_client_t *client, dns_rdataclass_t rdclass,
576                       dns_name_t *namespace, isc_sockaddrlist_t *addrs)
577 {
578         isc_result_t result;
579         dns_view_t *view = NULL;
580
581         REQUIRE(DNS_CLIENT_VALID(client));
582         REQUIRE(addrs != NULL);
583
584         if (namespace == NULL)
585                 namespace = dns_rootname;
586
587         LOCK(&client->lock);
588         result = dns_viewlist_find(&client->viewlist, DNS_CLIENTVIEW_NAME,
589                                    rdclass, &view);
590         if (result != ISC_R_SUCCESS) {
591                 UNLOCK(&client->lock);
592                 return (result);
593         }
594         UNLOCK(&client->lock);
595
596         result = dns_fwdtable_add(view->fwdtable, namespace, addrs,
597                                   dns_fwdpolicy_only);
598
599         dns_view_detach(&view);
600
601         return (result);
602 }
603
604 isc_result_t
605 dns_client_clearservers(dns_client_t *client, dns_rdataclass_t rdclass,
606                         dns_name_t *namespace)
607 {
608         isc_result_t result;
609         dns_view_t *view = NULL;
610
611         REQUIRE(DNS_CLIENT_VALID(client));
612
613         if (namespace == NULL)
614                 namespace = dns_rootname;
615
616         LOCK(&client->lock);
617         result = dns_viewlist_find(&client->viewlist, DNS_CLIENTVIEW_NAME,
618                                    rdclass, &view);
619         if (result != ISC_R_SUCCESS) {
620                 UNLOCK(&client->lock);
621                 return (result);
622         }
623         UNLOCK(&client->lock);
624
625         result = dns_fwdtable_delete(view->fwdtable, namespace);
626
627         dns_view_detach(&view);
628
629         return (result);
630 }
631
632 static isc_result_t
633 getrdataset(isc_mem_t *mctx, dns_rdataset_t **rdatasetp) {
634         dns_rdataset_t *rdataset;
635
636         REQUIRE(mctx != NULL);
637         REQUIRE(rdatasetp != NULL && *rdatasetp == NULL);
638
639         rdataset = isc_mem_get(mctx, sizeof(*rdataset));
640         if (rdataset == NULL)
641                 return (ISC_R_NOMEMORY);
642
643         dns_rdataset_init(rdataset);
644
645         *rdatasetp = rdataset;
646
647         return (ISC_R_SUCCESS);
648 }
649
650 static void
651 putrdataset(isc_mem_t *mctx, dns_rdataset_t **rdatasetp) {
652         dns_rdataset_t *rdataset;
653
654         REQUIRE(rdatasetp != NULL);
655         rdataset = *rdatasetp;
656         REQUIRE(rdataset != NULL);
657
658         if (dns_rdataset_isassociated(rdataset))
659                 dns_rdataset_disassociate(rdataset);
660
661         isc_mem_put(mctx, rdataset, sizeof(*rdataset));
662
663         *rdatasetp = NULL;
664 }
665
666 static void
667 fetch_done(isc_task_t *task, isc_event_t *event) {
668         resctx_t *rctx = event->ev_arg;
669         dns_fetchevent_t *fevent;
670
671         REQUIRE(event->ev_type == DNS_EVENT_FETCHDONE);
672         REQUIRE(RCTX_VALID(rctx));
673         REQUIRE(rctx->task == task);
674         fevent = (dns_fetchevent_t *)event;
675
676         client_resfind(rctx, fevent);
677 }
678
679 static inline isc_result_t
680 start_fetch(resctx_t *rctx) {
681         isc_result_t result;
682
683         /*
684          * The caller must be holding the rctx's lock.
685          */
686
687         REQUIRE(rctx->fetch == NULL);
688
689         result = dns_resolver_createfetch(rctx->view->resolver,
690                                           dns_fixedname_name(&rctx->name),
691                                           rctx->type,
692                                           NULL, NULL, NULL, 0,
693                                           rctx->task, fetch_done, rctx,
694                                           rctx->rdataset,
695                                           rctx->sigrdataset,
696                                           &rctx->fetch);
697
698         return (result);
699 }
700
701 static isc_result_t
702 view_find(resctx_t *rctx, dns_db_t **dbp, dns_dbnode_t **nodep,
703           dns_name_t *foundname)
704 {
705         isc_result_t result;
706         dns_name_t *name = dns_fixedname_name(&rctx->name);
707         dns_rdatatype_t type;
708
709         if (rctx->type == dns_rdatatype_rrsig)
710                 type = dns_rdatatype_any;
711         else
712                 type = rctx->type;
713
714         result = dns_view_find(rctx->view, name, type, 0, 0, ISC_FALSE,
715                                dbp, nodep, foundname, rctx->rdataset,
716                                rctx->sigrdataset);
717
718         return (result);
719 }
720
721 static void
722 client_resfind(resctx_t *rctx, dns_fetchevent_t *event) {
723         isc_mem_t *mctx;
724         isc_result_t result, tresult;
725         isc_result_t vresult = ISC_R_SUCCESS;
726         isc_boolean_t want_restart;
727         isc_boolean_t send_event = ISC_FALSE;
728         dns_name_t *name, *prefix;
729         dns_fixedname_t foundname, fixed;
730         dns_rdataset_t *trdataset;
731         dns_rdata_t rdata = DNS_RDATA_INIT;
732         unsigned int nlabels;
733         int order;
734         dns_namereln_t namereln;
735         dns_rdata_cname_t cname;
736         dns_rdata_dname_t dname;
737
738         REQUIRE(RCTX_VALID(rctx));
739
740         LOCK(&rctx->lock);
741
742         mctx = rctx->view->mctx;
743
744         result = ISC_R_SUCCESS;
745         name = dns_fixedname_name(&rctx->name);
746
747         do {
748                 dns_name_t *fname = NULL;
749                 dns_name_t *ansname = NULL;
750                 dns_db_t *db = NULL;
751                 dns_dbnode_t *node = NULL;
752
753                 rctx->restarts++;
754                 want_restart = ISC_FALSE;
755
756                 if (event == NULL && !rctx->canceled) {
757                         dns_fixedname_init(&foundname);
758                         fname = dns_fixedname_name(&foundname);
759                         INSIST(!dns_rdataset_isassociated(rctx->rdataset));
760                         INSIST(rctx->sigrdataset == NULL ||
761                                !dns_rdataset_isassociated(rctx->sigrdataset));
762                         result = view_find(rctx, &db, &node, fname);
763                         if (result == ISC_R_NOTFOUND) {
764                                 /*
765                                  * We don't know anything about the name.
766                                  * Launch a fetch.
767                                  */
768                                 if (node != NULL) {
769                                         INSIST(db != NULL);
770                                         dns_db_detachnode(db, &node);
771                                 }
772                                 if (db != NULL)
773                                         dns_db_detach(&db);
774                                 result = start_fetch(rctx);
775                                 if (result != ISC_R_SUCCESS) {
776                                         putrdataset(mctx, &rctx->rdataset);
777                                         if (rctx->sigrdataset != NULL)
778                                                 putrdataset(mctx,
779                                                             &rctx->sigrdataset);
780                                         send_event = ISC_TRUE;
781                                 }
782                                 goto done;
783                         }
784                 } else {
785                         INSIST(event->fetch == rctx->fetch);
786                         dns_resolver_destroyfetch(&rctx->fetch);
787                         db = event->db;
788                         node = event->node;
789                         result = event->result;
790                         vresult = event->vresult;
791                         fname = dns_fixedname_name(&event->foundname);
792                         INSIST(event->rdataset == rctx->rdataset);
793                         INSIST(event->sigrdataset == rctx->sigrdataset);
794                 }
795
796                 /*
797                  * If we've been canceled, forget about the result.
798                  */
799                 if (rctx->canceled)
800                         result = ISC_R_CANCELED;
801                 else {
802                         /*
803                          * Otherwise, get some resource for copying the
804                          * result.
805                          */
806                         ansname = isc_mem_get(mctx, sizeof(*ansname));
807                         if (ansname == NULL)
808                                 tresult = ISC_R_NOMEMORY;
809                         else {
810                                 dns_name_t *aname;
811
812                                 aname = dns_fixedname_name(&rctx->name);
813                                 dns_name_init(ansname, NULL);
814                                 tresult = dns_name_dup(aname, mctx, ansname);
815                                 if (tresult != ISC_R_SUCCESS)
816                                         isc_mem_put(mctx, ansname,
817                                                     sizeof(*ansname));
818                         }
819                         if (tresult != ISC_R_SUCCESS)
820                                 result = tresult;
821                 }
822
823                 switch (result) {
824                 case ISC_R_SUCCESS:
825                         send_event = ISC_TRUE;
826                         /*
827                          * This case is handled in the main line below.
828                          */
829                         break;
830                 case DNS_R_CNAME:
831                         /*
832                          * Add the CNAME to the answer list.
833                          */
834                         trdataset = rctx->rdataset;
835                         ISC_LIST_APPEND(ansname->list, rctx->rdataset, link);
836                         rctx->rdataset = NULL;
837                         if (rctx->sigrdataset != NULL) {
838                                 ISC_LIST_APPEND(ansname->list,
839                                                 rctx->sigrdataset, link);
840                                 rctx->sigrdataset = NULL;
841                         }
842                         ISC_LIST_APPEND(rctx->namelist, ansname, link);
843                         ansname = NULL;
844
845                         /*
846                          * Copy the CNAME's target into the lookup's
847                          * query name and start over.
848                          */
849                         tresult = dns_rdataset_first(trdataset);
850                         if (tresult != ISC_R_SUCCESS)
851                                 goto done;
852                         dns_rdataset_current(trdataset, &rdata);
853                         tresult = dns_rdata_tostruct(&rdata, &cname, NULL);
854                         dns_rdata_reset(&rdata);
855                         if (tresult != ISC_R_SUCCESS)
856                                 goto done;
857                         tresult = dns_name_copy(&cname.cname, name, NULL);
858                         dns_rdata_freestruct(&cname);
859                         if (tresult == ISC_R_SUCCESS)
860                                 want_restart = ISC_TRUE;
861                         else
862                                 result = tresult;
863                         goto done;
864                 case DNS_R_DNAME:
865                         /*
866                          * Add the DNAME to the answer list.
867                          */
868                         trdataset = rctx->rdataset;
869                         ISC_LIST_APPEND(ansname->list, rctx->rdataset, link);
870                         rctx->rdataset = NULL;
871                         if (rctx->sigrdataset != NULL) {
872                                 ISC_LIST_APPEND(ansname->list,
873                                                 rctx->sigrdataset, link);
874                                 rctx->sigrdataset = NULL;
875                         }
876                         ISC_LIST_APPEND(rctx->namelist, ansname, link);
877                         ansname = NULL;
878
879                         namereln = dns_name_fullcompare(name, fname, &order,
880                                                         &nlabels);
881                         INSIST(namereln == dns_namereln_subdomain);
882                         /*
883                          * Get the target name of the DNAME.
884                          */
885                         tresult = dns_rdataset_first(trdataset);
886                         if (tresult != ISC_R_SUCCESS) {
887                                 result = tresult;
888                                 goto done;
889                         }
890                         dns_rdataset_current(trdataset, &rdata);
891                         tresult = dns_rdata_tostruct(&rdata, &dname, NULL);
892                         dns_rdata_reset(&rdata);
893                         if (tresult != ISC_R_SUCCESS) {
894                                 result = tresult;
895                                 goto done;
896                         }
897                         /*
898                          * Construct the new query name and start over.
899                          */
900                         dns_fixedname_init(&fixed);
901                         prefix = dns_fixedname_name(&fixed);
902                         dns_name_split(name, nlabels, prefix, NULL);
903                         tresult = dns_name_concatenate(prefix, &dname.dname,
904                                                       name, NULL);
905                         dns_rdata_freestruct(&dname);
906                         if (tresult == ISC_R_SUCCESS)
907                                 want_restart = ISC_TRUE;
908                         else
909                                 result = tresult;
910                         goto done;
911                 case DNS_R_NCACHENXDOMAIN:
912                 case DNS_R_NCACHENXRRSET:
913                         ISC_LIST_APPEND(ansname->list, rctx->rdataset, link);
914                         ISC_LIST_APPEND(rctx->namelist, ansname, link);
915                         ansname = NULL;
916                         rctx->rdataset = NULL;
917                         /* What about sigrdataset? */
918                         if (rctx->sigrdataset != NULL)
919                                 putrdataset(mctx, &rctx->sigrdataset);
920                         send_event = ISC_TRUE;
921                         goto done;
922                 default:
923                         if (rctx->rdataset != NULL)
924                                 putrdataset(mctx, &rctx->rdataset);
925                         if (rctx->sigrdataset != NULL)
926                                 putrdataset(mctx, &rctx->sigrdataset);
927                         send_event = ISC_TRUE;
928                         goto done;
929                 }
930
931                 if (rctx->type == dns_rdatatype_any) {
932                         int n = 0;
933                         dns_rdatasetiter_t *rdsiter = NULL;
934
935                         tresult = dns_db_allrdatasets(db, node, NULL, 0,
936                                                       &rdsiter);
937                         if (tresult != ISC_R_SUCCESS) {
938                                 result = tresult;
939                                 goto done;
940                         }
941
942                         tresult = dns_rdatasetiter_first(rdsiter);
943                         while (tresult == ISC_R_SUCCESS) {
944                                 dns_rdatasetiter_current(rdsiter,
945                                                          rctx->rdataset);
946                                 if (rctx->rdataset->type != 0) {
947                                         ISC_LIST_APPEND(ansname->list,
948                                                         rctx->rdataset,
949                                                         link);
950                                         n++;
951                                         rctx->rdataset = NULL;
952                                 } else {
953                                         /*
954                                          * We're not interested in this
955                                          * rdataset.
956                                          */
957                                         dns_rdataset_disassociate(
958                                                 rctx->rdataset);
959                                 }
960                                 tresult = dns_rdatasetiter_next(rdsiter);
961
962                                 if (tresult == ISC_R_SUCCESS &&
963                                     rctx->rdataset == NULL) {
964                                         tresult = getrdataset(mctx,
965                                                               &rctx->rdataset);
966                                         if (tresult != ISC_R_SUCCESS) {
967                                                 result = tresult;
968                                                 break;
969                                         }
970                                 }
971                         }
972                         if (n == 0) {
973                                 /*
974                                  * We didn't match any rdatasets (which means
975                                  * something went wrong in this
976                                  * implementation).
977                                  */
978                                 result = DNS_R_SERVFAIL; /* better code? */
979                         } else {
980                                 ISC_LIST_APPEND(rctx->namelist, ansname, link);
981                                 ansname = NULL;
982                         }
983                         dns_rdatasetiter_destroy(&rdsiter);
984                         if (tresult != ISC_R_NOMORE)
985                                 result = DNS_R_SERVFAIL; /* ditto */
986                         else
987                                 result = ISC_R_SUCCESS;
988                         goto done;
989                 } else {
990                         /*
991                          * This is the "normal" case -- an ordinary question
992                          * to which we've got the answer.
993                          */
994                         ISC_LIST_APPEND(ansname->list, rctx->rdataset, link);
995                         rctx->rdataset = NULL;
996                         if (rctx->sigrdataset != NULL) {
997                                 ISC_LIST_APPEND(ansname->list,
998                                                 rctx->sigrdataset, link);
999                                 rctx->sigrdataset = NULL;
1000                         }
1001                         ISC_LIST_APPEND(rctx->namelist, ansname, link);
1002                         ansname = NULL;
1003                 }
1004
1005         done:
1006                 /*
1007                  * Free temporary resources
1008                  */
1009                 if (ansname != NULL) {
1010                         dns_rdataset_t *rdataset;
1011
1012                         while ((rdataset = ISC_LIST_HEAD(ansname->list))
1013                                != NULL) {
1014                                 ISC_LIST_UNLINK(ansname->list, rdataset, link);
1015                                 putrdataset(mctx, &rdataset);
1016                         }
1017                         dns_name_free(ansname, mctx);
1018                         isc_mem_put(mctx, ansname, sizeof(*ansname));
1019                 }
1020
1021                 if (node != NULL)
1022                         dns_db_detachnode(db, &node);
1023                 if (db != NULL)
1024                         dns_db_detach(&db);
1025                 if (event != NULL)
1026                         isc_event_free(ISC_EVENT_PTR(&event));
1027
1028                 /*
1029                  * Limit the number of restarts.
1030                  */
1031                 if (want_restart && rctx->restarts == MAX_RESTARTS) {
1032                         want_restart = ISC_FALSE;
1033                         result = ISC_R_QUOTA;
1034                         send_event = ISC_TRUE;
1035                 }
1036
1037                 /*
1038                  * Prepare further find with new resources
1039                  */
1040                 if (want_restart) {
1041                         INSIST(rctx->rdataset == NULL &&
1042                                rctx->sigrdataset == NULL);
1043
1044                         result = getrdataset(mctx, &rctx->rdataset);
1045                         if (result == ISC_R_SUCCESS && rctx->want_dnssec) {
1046                                 result = getrdataset(mctx, &rctx->sigrdataset);
1047                                 if (result != ISC_R_SUCCESS) {
1048                                         putrdataset(mctx, &rctx->rdataset);
1049                                 }
1050                         }
1051
1052                         if (result != ISC_R_SUCCESS) {
1053                                 want_restart = ISC_FALSE;
1054                                 send_event = ISC_TRUE;
1055                         }
1056                 }
1057         } while (want_restart);
1058
1059         if (send_event) {
1060                 isc_task_t *task;
1061
1062                 while ((name = ISC_LIST_HEAD(rctx->namelist)) != NULL) {
1063                         ISC_LIST_UNLINK(rctx->namelist, name, link);
1064                         ISC_LIST_APPEND(rctx->event->answerlist, name, link);
1065                 }
1066
1067                 rctx->event->result = result;
1068                 rctx->event->vresult = vresult;
1069                 task = rctx->event->ev_sender;
1070                 rctx->event->ev_sender = rctx;
1071                 isc_task_sendanddetach(&task, ISC_EVENT_PTR(&rctx->event));
1072         }
1073
1074         UNLOCK(&rctx->lock);
1075 }
1076
1077 static void
1078 resolve_done(isc_task_t *task, isc_event_t *event) {
1079         resarg_t *resarg = event->ev_arg;
1080         dns_clientresevent_t *rev = (dns_clientresevent_t *)event;
1081         dns_name_t *name;
1082
1083         UNUSED(task);
1084
1085         LOCK(&resarg->lock);
1086
1087         resarg->result = rev->result;
1088         resarg->vresult = rev->vresult;
1089         while ((name = ISC_LIST_HEAD(rev->answerlist)) != NULL) {
1090                 ISC_LIST_UNLINK(rev->answerlist, name, link);
1091                 ISC_LIST_APPEND(*resarg->namelist, name, link);
1092         }
1093
1094         dns_client_destroyrestrans(&resarg->trans);
1095         isc_event_free(&event);
1096
1097         if (!resarg->canceled) {
1098                 UNLOCK(&resarg->lock);
1099
1100                 /* Exit from the internal event loop */
1101                 isc_app_ctxsuspend(resarg->actx);
1102         } else {
1103                 /*
1104                  * We have already exited from the loop (due to some
1105                  * unexpected event).  Just clean the arg up.
1106                  */
1107                 UNLOCK(&resarg->lock);
1108                 DESTROYLOCK(&resarg->lock);
1109                 isc_mem_put(resarg->client->mctx, resarg, sizeof(*resarg));
1110         }
1111 }
1112
1113 isc_result_t
1114 dns_client_resolve(dns_client_t *client, dns_name_t *name,
1115                    dns_rdataclass_t rdclass, dns_rdatatype_t type,
1116                    unsigned int options, dns_namelist_t *namelist)
1117 {
1118         isc_result_t result;
1119         isc_appctx_t *actx;
1120         resarg_t *resarg;
1121
1122         REQUIRE(DNS_CLIENT_VALID(client));
1123         REQUIRE(namelist != NULL && ISC_LIST_EMPTY(*namelist));
1124
1125         if ((client->attributes & DNS_CLIENTATTR_OWNCTX) == 0 &&
1126             (options & DNS_CLIENTRESOPT_ALLOWRUN) == 0) {
1127                 /*
1128                  * If the client is run under application's control, we need
1129                  * to create a new running (sub)environment for this
1130                  * particular resolution.
1131                  */
1132                 return (ISC_R_NOTIMPLEMENTED); /* XXXTBD */
1133         } else
1134                 actx = client->actx;
1135
1136         resarg = isc_mem_get(client->mctx, sizeof(*resarg));
1137         if (resarg == NULL)
1138                 return (ISC_R_NOMEMORY);
1139
1140         result = isc_mutex_init(&resarg->lock);
1141         if (result != ISC_R_SUCCESS) {
1142                 isc_mem_put(client->mctx, resarg, sizeof(*resarg));
1143                 return (result);
1144         }
1145
1146         resarg->actx = actx;
1147         resarg->client = client;
1148         resarg->result = DNS_R_SERVFAIL;
1149         resarg->namelist = namelist;
1150         resarg->trans = NULL;
1151         resarg->canceled = ISC_FALSE;
1152         result = dns_client_startresolve(client, name, rdclass, type, options,
1153                                          client->task, resolve_done, resarg,
1154                                          &resarg->trans);
1155         if (result != ISC_R_SUCCESS) {
1156                 DESTROYLOCK(&resarg->lock);
1157                 isc_mem_put(client->mctx, resarg, sizeof(*resarg));
1158                 return (result);
1159         }
1160
1161         /*
1162          * Start internal event loop.  It blocks until the entire process
1163          * is completed.
1164          */
1165         result = isc_app_ctxrun(actx);
1166
1167         LOCK(&resarg->lock);
1168         if (result == ISC_R_SUCCESS || result == ISC_R_SUSPEND)
1169                 result = resarg->result;
1170         if (result != ISC_R_SUCCESS && resarg->vresult != ISC_R_SUCCESS) {
1171                 /*
1172                  * If this lookup failed due to some error in DNSSEC
1173                  * validation, return the validation error code.
1174                  * XXX: or should we pass the validation result separately?
1175                  */
1176                 result = resarg->vresult;
1177         }
1178         if (resarg->trans != NULL) {
1179                 /*
1180                  * Unusual termination (perhaps due to signal).  We need some
1181                  * tricky cleanup process.
1182                  */
1183                 resarg->canceled = ISC_TRUE;
1184                 dns_client_cancelresolve(resarg->trans);
1185
1186                 UNLOCK(&resarg->lock);
1187
1188                 /* resarg will be freed in the event handler. */
1189         } else {
1190                 UNLOCK(&resarg->lock);
1191
1192                 DESTROYLOCK(&resarg->lock);
1193                 isc_mem_put(client->mctx, resarg, sizeof(*resarg));
1194         }
1195
1196         return (result);
1197 }
1198
1199 isc_result_t
1200 dns_client_startresolve(dns_client_t *client, dns_name_t *name,
1201                         dns_rdataclass_t rdclass, dns_rdatatype_t type,
1202                         unsigned int options, isc_task_t *task,
1203                         isc_taskaction_t action, void *arg,
1204                         dns_clientrestrans_t **transp)
1205 {
1206         dns_view_t *view = NULL;
1207         dns_clientresevent_t *event = NULL;
1208         resctx_t *rctx = NULL;
1209         isc_task_t *clone = NULL;
1210         isc_mem_t *mctx;
1211         isc_result_t result;
1212         dns_rdataset_t *rdataset, *sigrdataset;
1213         isc_boolean_t want_dnssec;
1214
1215         REQUIRE(DNS_CLIENT_VALID(client));
1216         REQUIRE(transp != NULL && *transp == NULL);
1217
1218         LOCK(&client->lock);
1219         result = dns_viewlist_find(&client->viewlist, DNS_CLIENTVIEW_NAME,
1220                                    rdclass, &view);
1221         UNLOCK(&client->lock);
1222         if (result != ISC_R_SUCCESS)
1223                 return (result);
1224
1225         mctx = client->mctx;
1226         rdataset = NULL;
1227         sigrdataset = NULL;
1228         want_dnssec = ISC_TF((options & DNS_CLIENTRESOPT_NODNSSEC) == 0);
1229
1230         /*
1231          * Prepare some intermediate resources
1232          */
1233         clone = NULL;
1234         isc_task_attach(task, &clone);
1235         event = (dns_clientresevent_t *)
1236                 isc_event_allocate(mctx, clone, DNS_EVENT_CLIENTRESDONE,
1237                                    action, arg, sizeof(*event));
1238         if (event == NULL) {
1239                 result = ISC_R_NOMEMORY;
1240                 goto cleanup;
1241         }
1242         event->result = DNS_R_SERVFAIL;
1243         ISC_LIST_INIT(event->answerlist);
1244
1245         rctx = isc_mem_get(mctx, sizeof(*rctx));
1246         if (rctx == NULL)
1247                 result = ISC_R_NOMEMORY;
1248         else {
1249                 result = isc_mutex_init(&rctx->lock);
1250                 if (result != ISC_R_SUCCESS) {
1251                         isc_mem_put(mctx, rctx, sizeof(*rctx));
1252                         rctx = NULL;
1253                 }
1254         }
1255         if (result != ISC_R_SUCCESS)
1256                 goto cleanup;
1257
1258         result = getrdataset(mctx, &rdataset);
1259         if (result != ISC_R_SUCCESS)
1260                 goto cleanup;
1261         rctx->rdataset = rdataset;
1262
1263         if (want_dnssec) {
1264                 result = getrdataset(mctx, &sigrdataset);
1265                 if (result != ISC_R_SUCCESS)
1266                         goto cleanup;
1267         }
1268         rctx->sigrdataset = sigrdataset;
1269
1270         dns_fixedname_init(&rctx->name);
1271         result = dns_name_copy(name, dns_fixedname_name(&rctx->name), NULL);
1272         if (result != ISC_R_SUCCESS)
1273                 goto cleanup;
1274
1275         rctx->client = client;
1276         ISC_LINK_INIT(rctx, link);
1277         rctx->canceled = ISC_FALSE;
1278         rctx->task = client->task;
1279         rctx->type = type;
1280         rctx->view = view;
1281         rctx->restarts = 0;
1282         rctx->fetch = NULL;
1283         rctx->want_dnssec = want_dnssec;
1284         ISC_LIST_INIT(rctx->namelist);
1285         rctx->event = event;
1286
1287         rctx->magic = RCTX_MAGIC;
1288
1289         LOCK(&client->lock);
1290         ISC_LIST_APPEND(client->resctxs, rctx, link);
1291         UNLOCK(&client->lock);
1292
1293         client_resfind(rctx, NULL);
1294
1295         *transp = (dns_clientrestrans_t *)rctx;
1296
1297         return (ISC_R_SUCCESS);
1298
1299  cleanup:
1300         if (rdataset != NULL)
1301                 putrdataset(client->mctx, &rdataset);
1302         if (sigrdataset != NULL)
1303                 putrdataset(client->mctx, &sigrdataset);
1304         if (rctx != NULL) {
1305                 DESTROYLOCK(&rctx->lock);
1306                 isc_mem_put(mctx, rctx, sizeof(*rctx));
1307         }
1308         if (event != NULL)
1309                 isc_event_free(ISC_EVENT_PTR(&event));
1310         isc_task_detach(&clone);
1311         dns_view_detach(&view);
1312
1313         return (result);
1314 }
1315
1316 void
1317 dns_client_cancelresolve(dns_clientrestrans_t *trans) {
1318         resctx_t *rctx;
1319
1320         REQUIRE(trans != NULL);
1321         rctx = (resctx_t *)trans;
1322         REQUIRE(RCTX_VALID(rctx));
1323
1324         LOCK(&rctx->lock);
1325
1326         if (!rctx->canceled) {
1327                 rctx->canceled = ISC_TRUE;
1328                 if (rctx->fetch != NULL)
1329                         dns_resolver_cancelfetch(rctx->fetch);
1330         }
1331
1332         UNLOCK(&rctx->lock);
1333 }
1334
1335 void
1336 dns_client_freeresanswer(dns_client_t *client, dns_namelist_t *namelist) {
1337         dns_name_t *name;
1338         dns_rdataset_t *rdataset;
1339
1340         REQUIRE(DNS_CLIENT_VALID(client));
1341         REQUIRE(namelist != NULL);
1342
1343         while ((name = ISC_LIST_HEAD(*namelist)) != NULL) {
1344                 ISC_LIST_UNLINK(*namelist, name, link);
1345                 while ((rdataset = ISC_LIST_HEAD(name->list)) != NULL) {
1346                         ISC_LIST_UNLINK(name->list, rdataset, link);
1347                         putrdataset(client->mctx, &rdataset);
1348                 }
1349                 dns_name_free(name, client->mctx);
1350                 isc_mem_put(client->mctx, name, sizeof(*name));
1351         }
1352 }
1353
1354 void
1355 dns_client_destroyrestrans(dns_clientrestrans_t **transp) {
1356         resctx_t *rctx;
1357         isc_mem_t *mctx;
1358         dns_client_t *client;
1359         isc_boolean_t need_destroyclient = ISC_FALSE;
1360
1361         REQUIRE(transp != NULL);
1362         rctx = (resctx_t *)*transp;
1363         REQUIRE(RCTX_VALID(rctx));
1364         REQUIRE(rctx->fetch == NULL);
1365         REQUIRE(rctx->event == NULL);
1366         client = rctx->client;
1367         REQUIRE(DNS_CLIENT_VALID(client));
1368
1369         mctx = client->mctx;
1370         dns_view_detach(&rctx->view);
1371
1372         LOCK(&client->lock);
1373
1374         INSIST(ISC_LINK_LINKED(rctx, link));
1375         ISC_LIST_UNLINK(client->resctxs, rctx, link);
1376
1377         if (client->references == 0 && ISC_LIST_EMPTY(client->resctxs) &&
1378             ISC_LIST_EMPTY(client->reqctxs) &&
1379             ISC_LIST_EMPTY(client->updatectxs))
1380                 need_destroyclient = ISC_TRUE;
1381
1382         UNLOCK(&client->lock);
1383
1384         INSIST(ISC_LIST_EMPTY(rctx->namelist));
1385
1386         DESTROYLOCK(&rctx->lock);
1387         rctx->magic = 0;
1388
1389         isc_mem_put(mctx, rctx, sizeof(*rctx));
1390
1391         if (need_destroyclient)
1392                 destroyclient(&client);
1393
1394         *transp = NULL;
1395 }
1396
1397 isc_result_t
1398 dns_client_addtrustedkey(dns_client_t *client, dns_rdataclass_t rdclass,
1399                          dns_name_t *keyname, isc_buffer_t *keydatabuf)
1400 {
1401         isc_result_t result;
1402         dns_view_t *view = NULL;
1403         dst_key_t *dstkey = NULL;
1404         dns_keytable_t *secroots = NULL;
1405
1406         REQUIRE(DNS_CLIENT_VALID(client));
1407
1408         LOCK(&client->lock);
1409         result = dns_viewlist_find(&client->viewlist, DNS_CLIENTVIEW_NAME,
1410                                    rdclass, &view);
1411         UNLOCK(&client->lock);
1412         if (result != ISC_R_SUCCESS)
1413                 goto cleanup;
1414
1415         result = dns_view_getsecroots(view, &secroots);
1416         if (result != ISC_R_SUCCESS)
1417                 goto cleanup;
1418
1419         result = dst_key_fromdns(keyname, rdclass, keydatabuf, client->mctx,
1420                                  &dstkey);
1421         if (result != ISC_R_SUCCESS)
1422                 goto cleanup;
1423
1424         result = dns_keytable_add(secroots, ISC_FALSE, &dstkey);
1425
1426  cleanup:
1427         if (view != NULL)
1428                 dns_view_detach(&view);
1429         if (secroots != NULL)
1430                 dns_keytable_detach(&secroots);
1431         return (result);
1432 }
1433
1434 /*%
1435  * Simple request routines
1436  */
1437 static void
1438 request_done(isc_task_t *task, isc_event_t *event) {
1439         dns_requestevent_t *reqev = NULL;
1440         dns_request_t *request;
1441         isc_result_t result, eresult;
1442         reqctx_t *ctx;
1443
1444         UNUSED(task);
1445
1446         REQUIRE(event->ev_type == DNS_EVENT_REQUESTDONE);
1447         reqev = (dns_requestevent_t *)event;
1448         request = reqev->request;
1449         result = eresult = reqev->result;
1450         ctx = reqev->ev_arg;
1451         REQUIRE(REQCTX_VALID(ctx));
1452
1453         isc_event_free(&event);
1454
1455         LOCK(&ctx->lock);
1456
1457         if (eresult == ISC_R_SUCCESS) {
1458                 result = dns_request_getresponse(request, ctx->event->rmessage,
1459                                                  ctx->parseoptions);
1460         }
1461
1462         if (ctx->tsigkey != NULL)
1463                 dns_tsigkey_detach(&ctx->tsigkey);
1464
1465         if (ctx->canceled)
1466                 ctx->event->result = ISC_R_CANCELED;
1467         else
1468                 ctx->event->result = result;
1469         task = ctx->event->ev_sender;
1470         ctx->event->ev_sender = ctx;
1471         isc_task_sendanddetach(&task, ISC_EVENT_PTR(&ctx->event));
1472
1473         UNLOCK(&ctx->lock);
1474 }
1475
1476 static void
1477 localrequest_done(isc_task_t *task, isc_event_t *event) {
1478         reqarg_t *reqarg = event->ev_arg;
1479         dns_clientreqevent_t *rev =(dns_clientreqevent_t *)event;
1480
1481         UNUSED(task);
1482
1483         REQUIRE(event->ev_type == DNS_EVENT_CLIENTREQDONE);
1484
1485         LOCK(&reqarg->lock);
1486
1487         reqarg->result = rev->result;
1488         dns_client_destroyreqtrans(&reqarg->trans);
1489         isc_event_free(&event);
1490
1491         if (!reqarg->canceled) {
1492                 UNLOCK(&reqarg->lock);
1493
1494                 /* Exit from the internal event loop */
1495                 isc_app_ctxsuspend(reqarg->actx);
1496         } else {
1497                 /*
1498                  * We have already exited from the loop (due to some
1499                  * unexpected event).  Just clean the arg up.
1500                  */
1501                 UNLOCK(&reqarg->lock);
1502                 DESTROYLOCK(&reqarg->lock);
1503                 isc_mem_put(reqarg->client->mctx, reqarg, sizeof(*reqarg));
1504         }
1505 }
1506
1507 isc_result_t
1508 dns_client_request(dns_client_t *client, dns_message_t *qmessage,
1509                    dns_message_t *rmessage, isc_sockaddr_t *server,
1510                    unsigned int options, unsigned int parseoptions,
1511                    dns_tsec_t *tsec, unsigned int timeout,
1512                    unsigned int udptimeout, unsigned int udpretries)
1513 {
1514         isc_appctx_t *actx;
1515         reqarg_t *reqarg;
1516         isc_result_t result;
1517
1518         REQUIRE(DNS_CLIENT_VALID(client));
1519         REQUIRE(qmessage != NULL);
1520         REQUIRE(rmessage != NULL);
1521
1522         if ((client->attributes & DNS_CLIENTATTR_OWNCTX) == 0 &&
1523             (options & DNS_CLIENTREQOPT_ALLOWRUN) == 0) {
1524                 /*
1525                  * If the client is run under application's control, we need
1526                  * to create a new running (sub)environment for this
1527                  * particular resolution.
1528                  */
1529                 return (ISC_R_NOTIMPLEMENTED); /* XXXTBD */
1530         } else
1531                 actx = client->actx;
1532
1533         reqarg = isc_mem_get(client->mctx, sizeof(*reqarg));
1534         if (reqarg == NULL)
1535                 return (ISC_R_NOMEMORY);
1536
1537         result = isc_mutex_init(&reqarg->lock);
1538         if (result != ISC_R_SUCCESS) {
1539                 isc_mem_put(client->mctx, reqarg, sizeof(*reqarg));
1540                 return (result);
1541         }
1542
1543         reqarg->actx = actx;
1544         reqarg->client = client;
1545         reqarg->trans = NULL;
1546         reqarg->canceled = ISC_FALSE;
1547
1548         result = dns_client_startrequest(client, qmessage, rmessage, server,
1549                                          options, parseoptions, tsec, timeout,
1550                                          udptimeout, udpretries,
1551                                          client->task, localrequest_done,
1552                                          reqarg, &reqarg->trans);
1553         if (result != ISC_R_SUCCESS) {
1554                 DESTROYLOCK(&reqarg->lock);
1555                 isc_mem_put(client->mctx, reqarg, sizeof(*reqarg));
1556                 return (result);
1557         }
1558
1559         /*
1560          * Start internal event loop.  It blocks until the entire process
1561          * is completed.
1562          */
1563         result = isc_app_ctxrun(actx);
1564
1565         LOCK(&reqarg->lock);
1566         if (result == ISC_R_SUCCESS || result == ISC_R_SUSPEND)
1567                 result = reqarg->result;
1568         if (reqarg->trans != NULL) {
1569                 /*
1570                  * Unusual termination (perhaps due to signal).  We need some
1571                  * tricky cleanup process.
1572                  */
1573                 reqarg->canceled = ISC_TRUE;
1574                 dns_client_cancelresolve(reqarg->trans);
1575
1576                 UNLOCK(&reqarg->lock);
1577
1578                 /* reqarg will be freed in the event handler. */
1579         } else {
1580                 UNLOCK(&reqarg->lock);
1581
1582                 DESTROYLOCK(&reqarg->lock);
1583                 isc_mem_put(client->mctx, reqarg, sizeof(*reqarg));
1584         }
1585
1586         return (result);
1587 }
1588
1589 isc_result_t
1590 dns_client_startrequest(dns_client_t *client, dns_message_t *qmessage,
1591                         dns_message_t *rmessage, isc_sockaddr_t *server,
1592                         unsigned int options, unsigned int parseoptions,
1593                         dns_tsec_t *tsec, unsigned int timeout,
1594                         unsigned int udptimeout, unsigned int udpretries,
1595                         isc_task_t *task, isc_taskaction_t action, void *arg,
1596                         dns_clientreqtrans_t **transp)
1597 {
1598         isc_result_t result;
1599         dns_view_t *view = NULL;
1600         isc_task_t *clone = NULL;
1601         dns_clientreqevent_t *event = NULL;
1602         reqctx_t *ctx = NULL;
1603         dns_tsectype_t tsectype = dns_tsectype_none;
1604
1605         UNUSED(options);
1606
1607         REQUIRE(DNS_CLIENT_VALID(client));
1608         REQUIRE(qmessage != NULL);
1609         REQUIRE(rmessage != NULL);
1610         REQUIRE(transp != NULL && *transp == NULL);
1611
1612         if (tsec != NULL) {
1613                 tsectype = dns_tsec_gettype(tsec);
1614                 if (tsectype != dns_tsectype_tsig)
1615                         return (ISC_R_NOTIMPLEMENTED); /* XXX */
1616         }
1617
1618         LOCK(&client->lock);
1619         result = dns_viewlist_find(&client->viewlist, DNS_CLIENTVIEW_NAME,
1620                                    qmessage->rdclass, &view);
1621         UNLOCK(&client->lock);
1622         if (result != ISC_R_SUCCESS)
1623                 return (result);
1624
1625         clone = NULL;
1626         isc_task_attach(task, &clone);
1627         event = (dns_clientreqevent_t *)
1628                 isc_event_allocate(client->mctx, clone,
1629                                    DNS_EVENT_CLIENTREQDONE,
1630                                    action, arg, sizeof(*event));
1631         if (event == NULL) {
1632                 result = ISC_R_NOMEMORY;
1633                 goto cleanup;
1634         }
1635
1636         ctx = isc_mem_get(client->mctx, sizeof(*ctx));
1637         if (ctx == NULL)
1638                 result = ISC_R_NOMEMORY;
1639         else {
1640                 result = isc_mutex_init(&ctx->lock);
1641                 if (result != ISC_R_SUCCESS) {
1642                         isc_mem_put(client->mctx, ctx, sizeof(*ctx));
1643                         ctx = NULL;
1644                 }
1645         }
1646         if (result != ISC_R_SUCCESS)
1647                 goto cleanup;
1648
1649         ctx->client = client;
1650         ISC_LINK_INIT(ctx, link);
1651         ctx->parseoptions = parseoptions;
1652         ctx->canceled = ISC_FALSE;
1653         ctx->event = event;
1654         ctx->event->rmessage = rmessage;
1655         ctx->tsigkey = NULL;
1656         if (tsec != NULL)
1657                 dns_tsec_getkey(tsec, &ctx->tsigkey);
1658
1659         ctx->magic = REQCTX_MAGIC;
1660
1661         LOCK(&client->lock);
1662         ISC_LIST_APPEND(client->reqctxs, ctx, link);
1663         UNLOCK(&client->lock);
1664
1665         ctx->request = NULL;
1666         result = dns_request_createvia3(view->requestmgr, qmessage, NULL,
1667                                         server, options, ctx->tsigkey,
1668                                         timeout, udptimeout, udpretries,
1669                                         client->task, request_done, ctx,
1670                                         &ctx->request);
1671         if (result == ISC_R_SUCCESS) {
1672                 dns_view_detach(&view);
1673                 *transp = (dns_clientreqtrans_t *)ctx;
1674                 return (ISC_R_SUCCESS);
1675         }
1676
1677  cleanup:
1678         if (ctx != NULL) {
1679                 LOCK(&client->lock);
1680                 ISC_LIST_UNLINK(client->reqctxs, ctx, link);
1681                 UNLOCK(&client->lock);
1682                 DESTROYLOCK(&ctx->lock);
1683                 isc_mem_put(client->mctx, ctx, sizeof(*ctx));
1684         }
1685         if (event != NULL)
1686                 isc_event_free(ISC_EVENT_PTR(&event));
1687         isc_task_detach(&clone);
1688         dns_view_detach(&view);
1689
1690         return (result);
1691 }
1692
1693 void
1694 dns_client_cancelrequest(dns_clientreqtrans_t *trans) {
1695         reqctx_t *ctx;
1696
1697         REQUIRE(trans != NULL);
1698         ctx = (reqctx_t *)trans;
1699         REQUIRE(REQCTX_VALID(ctx));
1700
1701         LOCK(&ctx->lock);
1702
1703         if (!ctx->canceled) {
1704                 ctx->canceled = ISC_TRUE;
1705                 if (ctx->request != NULL)
1706                         dns_request_cancel(ctx->request);
1707         }
1708
1709         UNLOCK(&ctx->lock);
1710 }
1711
1712 void
1713 dns_client_destroyreqtrans(dns_clientreqtrans_t **transp) {
1714         reqctx_t *ctx;
1715         isc_mem_t *mctx;
1716         dns_client_t *client;
1717         isc_boolean_t need_destroyclient = ISC_FALSE;
1718
1719         REQUIRE(transp != NULL);
1720         ctx = (reqctx_t *)*transp;
1721         REQUIRE(REQCTX_VALID(ctx));
1722         client = ctx->client;
1723         REQUIRE(DNS_CLIENT_VALID(client));
1724         REQUIRE(ctx->event == NULL);
1725         REQUIRE(ctx->request != NULL);
1726
1727         dns_request_destroy(&ctx->request);
1728         mctx = client->mctx;
1729
1730         LOCK(&client->lock);
1731
1732         INSIST(ISC_LINK_LINKED(ctx, link));
1733         ISC_LIST_UNLINK(client->reqctxs, ctx, link);
1734
1735         if (client->references == 0 && ISC_LIST_EMPTY(client->resctxs) &&
1736             ISC_LIST_EMPTY(client->reqctxs) &&
1737             ISC_LIST_EMPTY(client->updatectxs)) {
1738                 need_destroyclient = ISC_TRUE;
1739         }
1740
1741         UNLOCK(&client->lock);
1742
1743         DESTROYLOCK(&ctx->lock);
1744         ctx->magic = 0;
1745
1746         isc_mem_put(mctx, ctx, sizeof(*ctx));
1747
1748         if (need_destroyclient)
1749                 destroyclient(&client);
1750
1751         *transp = NULL;
1752 }
1753
1754 /*%
1755  * Dynamic update routines
1756  */
1757 static isc_result_t
1758 rcode2result(dns_rcode_t rcode) {
1759         /* XXX: isn't there a similar function? */
1760         switch (rcode) {
1761         case dns_rcode_formerr:
1762                 return (DNS_R_FORMERR);
1763         case dns_rcode_servfail:
1764                 return (DNS_R_SERVFAIL);
1765         case dns_rcode_nxdomain:
1766                 return (DNS_R_NXDOMAIN);
1767         case dns_rcode_notimp:
1768                 return (DNS_R_NOTIMP);
1769         case dns_rcode_refused:
1770                 return (DNS_R_REFUSED);
1771         case dns_rcode_yxdomain:
1772                 return (DNS_R_YXDOMAIN);
1773         case dns_rcode_yxrrset:
1774                 return (DNS_R_YXRRSET);
1775         case dns_rcode_nxrrset:
1776                 return (DNS_R_NXRRSET);
1777         case dns_rcode_notauth:
1778                 return (DNS_R_NOTAUTH);
1779         case dns_rcode_notzone:
1780                 return (DNS_R_NOTZONE);
1781         case dns_rcode_badvers:
1782                 return (DNS_R_BADVERS);
1783         }
1784
1785         return (ISC_R_FAILURE);
1786 }
1787
1788 static void
1789 update_sendevent(updatectx_t *uctx, isc_result_t result) {
1790         isc_task_t *task;
1791
1792         dns_message_destroy(&uctx->updatemsg);
1793         if (uctx->tsigkey != NULL)
1794                 dns_tsigkey_detach(&uctx->tsigkey);
1795         if (uctx->sig0key != NULL)
1796                 dst_key_free(&uctx->sig0key);
1797
1798         if (uctx->canceled)
1799                 uctx->event->result = ISC_R_CANCELED;
1800         else
1801                 uctx->event->result = result;
1802         uctx->event->state = uctx->state;
1803         task = uctx->event->ev_sender;
1804         uctx->event->ev_sender = uctx;
1805         isc_task_sendanddetach(&task, ISC_EVENT_PTR(&uctx->event));
1806 }
1807
1808 static void
1809 update_done(isc_task_t *task, isc_event_t *event) {
1810         isc_result_t result;
1811         dns_requestevent_t *reqev = NULL;
1812         dns_request_t *request;
1813         dns_message_t *answer = NULL;
1814         updatectx_t *uctx = event->ev_arg;
1815         dns_client_t *client;
1816         unsigned int timeout;
1817
1818         UNUSED(task);
1819
1820         REQUIRE(event->ev_type == DNS_EVENT_REQUESTDONE);
1821         reqev = (dns_requestevent_t *)event;
1822         request = reqev->request;
1823         REQUIRE(UCTX_VALID(uctx));
1824         client = uctx->client;
1825         REQUIRE(DNS_CLIENT_VALID(client));
1826
1827         result = reqev->result;
1828         if (result != ISC_R_SUCCESS)
1829                 goto out;
1830
1831         result = dns_message_create(client->mctx, DNS_MESSAGE_INTENTPARSE,
1832                                     &answer);
1833         if (result != ISC_R_SUCCESS)
1834                 goto out;
1835         uctx->state = dns_clientupdatestate_done;
1836         result = dns_request_getresponse(request, answer,
1837                                          DNS_MESSAGEPARSE_PRESERVEORDER);
1838         if (result == ISC_R_SUCCESS && answer->rcode != dns_rcode_noerror)
1839                 result = rcode2result(answer->rcode);
1840
1841  out:
1842         if (answer != NULL)
1843                 dns_message_destroy(&answer);
1844         isc_event_free(&event);
1845
1846         LOCK(&uctx->lock);
1847         uctx->currentserver = ISC_LIST_NEXT(uctx->currentserver, link);
1848         dns_request_destroy(&uctx->updatereq);
1849         if (result != ISC_R_SUCCESS && !uctx->canceled &&
1850             uctx->currentserver != NULL) {
1851                 dns_message_renderreset(uctx->updatemsg);
1852                 dns_message_settsigkey(uctx->updatemsg, NULL);
1853
1854                 timeout = client->update_timeout / uctx->nservers;
1855                 if (timeout < MIN_UPDATE_TIMEOUT)
1856                         timeout = MIN_UPDATE_TIMEOUT;
1857                 result = dns_request_createvia3(uctx->view->requestmgr,
1858                                                 uctx->updatemsg,
1859                                                 NULL,
1860                                                 uctx->currentserver, 0,
1861                                                 uctx->tsigkey,
1862                                                 timeout,
1863                                                 client->update_udptimeout,
1864                                                 client->update_udpretries,
1865                                                 client->task,
1866                                                 update_done, uctx,
1867                                                 &uctx->updatereq);
1868                 UNLOCK(&uctx->lock);
1869
1870                 if (result == ISC_R_SUCCESS) {
1871                         /* XXX: should we keep the 'done' state here? */
1872                         uctx->state = dns_clientupdatestate_sent;
1873                         return;
1874                 }
1875         } else
1876                 UNLOCK(&uctx->lock);
1877
1878         update_sendevent(uctx, result);
1879 }
1880
1881 static isc_result_t
1882 send_update(updatectx_t *uctx) {
1883         isc_result_t result;
1884         dns_name_t *name = NULL;
1885         dns_rdataset_t *rdataset = NULL;
1886         dns_client_t *client = uctx->client;
1887         unsigned int timeout;
1888
1889         REQUIRE(uctx->zonename != NULL && uctx->currentserver != NULL);
1890
1891         result = dns_message_gettempname(uctx->updatemsg, &name);
1892         if (result != ISC_R_SUCCESS)
1893                 return (result);
1894         dns_name_init(name, NULL);
1895         dns_name_clone(uctx->zonename, name);
1896         result = dns_message_gettemprdataset(uctx->updatemsg, &rdataset);
1897         if (result != ISC_R_SUCCESS) {
1898                 dns_message_puttempname(uctx->updatemsg, &name);
1899                 return (result);
1900         }
1901         dns_rdataset_makequestion(rdataset, uctx->rdclass, dns_rdatatype_soa);
1902         ISC_LIST_INIT(name->list);
1903         ISC_LIST_APPEND(name->list, rdataset, link);
1904         dns_message_addname(uctx->updatemsg, name, DNS_SECTION_ZONE);
1905         if (uctx->tsigkey == NULL && uctx->sig0key != NULL) {
1906                 result = dns_message_setsig0key(uctx->updatemsg,
1907                                                 uctx->sig0key);
1908                 if (result != ISC_R_SUCCESS)
1909                         return (result);
1910         }
1911         timeout = client->update_timeout / uctx->nservers;
1912         if (timeout < MIN_UPDATE_TIMEOUT)
1913                 timeout = MIN_UPDATE_TIMEOUT;
1914         result = dns_request_createvia3(uctx->view->requestmgr,
1915                                         uctx->updatemsg,
1916                                         NULL, uctx->currentserver, 0,
1917                                         uctx->tsigkey, timeout,
1918                                         client->update_udptimeout,
1919                                         client->update_udpretries,
1920                                         client->task, update_done, uctx,
1921                                         &uctx->updatereq);
1922         if (result == ISC_R_SUCCESS &&
1923             uctx->state == dns_clientupdatestate_prepare) {
1924                 uctx->state = dns_clientupdatestate_sent;
1925         }
1926
1927         return (result);
1928 }
1929
1930 static void
1931 resolveaddr_done(isc_task_t *task, isc_event_t *event) {
1932         isc_result_t result;
1933         int family;
1934         dns_rdatatype_t qtype;
1935         dns_clientresevent_t *rev = (dns_clientresevent_t *)event;
1936         dns_name_t *name;
1937         dns_rdataset_t *rdataset;
1938         updatectx_t *uctx;
1939         isc_boolean_t completed = ISC_FALSE;
1940
1941         UNUSED(task);
1942
1943         REQUIRE(event->ev_arg != NULL);
1944         uctx = *(updatectx_t **)event->ev_arg;
1945         REQUIRE(UCTX_VALID(uctx));
1946
1947         if (event->ev_arg == &uctx->bp4) {
1948                 family = AF_INET;
1949                 qtype = dns_rdatatype_a;
1950                 LOCK(&uctx->lock);
1951                 dns_client_destroyrestrans(&uctx->restrans);
1952                 UNLOCK(&uctx->lock);
1953         } else {
1954                 INSIST(event->ev_arg == &uctx->bp6);
1955                 family = AF_INET6;
1956                 qtype = dns_rdatatype_aaaa;
1957                 LOCK(&uctx->lock);
1958                 dns_client_destroyrestrans(&uctx->restrans2);
1959                 UNLOCK(&uctx->lock);
1960         }
1961
1962         result = rev->result;
1963         if (result != ISC_R_SUCCESS)
1964                 goto done;
1965
1966         for (name = ISC_LIST_HEAD(rev->answerlist); name != NULL;
1967              name = ISC_LIST_NEXT(name, link)) {
1968                 for (rdataset = ISC_LIST_HEAD(name->list);
1969                      rdataset != NULL;
1970                      rdataset = ISC_LIST_NEXT(rdataset, link)) {
1971                         if (!dns_rdataset_isassociated(rdataset))
1972                                 continue;
1973                         if (rdataset->type != qtype)
1974                                 continue;
1975
1976                         for (result = dns_rdataset_first(rdataset);
1977                              result == ISC_R_SUCCESS;
1978                              result = dns_rdataset_next(rdataset)) {
1979                                 dns_rdata_t rdata;
1980                                 dns_rdata_in_a_t rdata_a;
1981                                 dns_rdata_in_aaaa_t rdata_aaaa;
1982                                 isc_sockaddr_t *sa;
1983
1984                                 sa = isc_mem_get(uctx->client->mctx,
1985                                                  sizeof(*sa));
1986                                 if (sa == NULL) {
1987                                         /*
1988                                          * If we fail to get a sockaddr,
1989                                          we simply move forward with the
1990                                          * addresses we've got so far.
1991                                          */
1992                                         goto done;
1993                                 }
1994
1995                                 dns_rdata_init(&rdata);
1996                                 switch (family) {
1997                                 case AF_INET:
1998                                         dns_rdataset_current(rdataset, &rdata);
1999                                         dns_rdata_tostruct(&rdata, &rdata_a,
2000                                                            NULL);
2001                                         isc_sockaddr_fromin(sa,
2002                                                             &rdata_a.in_addr,
2003                                                             53);
2004                                         dns_rdata_freestruct(&rdata_a);
2005                                         break;
2006                                 case AF_INET6:
2007                                         dns_rdataset_current(rdataset, &rdata);
2008                                         dns_rdata_tostruct(&rdata, &rdata_aaaa,
2009                                                            NULL);
2010                                         isc_sockaddr_fromin6(sa,
2011                                                              &rdata_aaaa.in6_addr,
2012                                                              53);
2013                                         dns_rdata_freestruct(&rdata_aaaa);
2014                                         break;
2015                                 }
2016
2017                                 ISC_LINK_INIT(sa, link);
2018                                 ISC_LIST_APPEND(uctx->servers, sa, link);
2019                                 uctx->nservers++;
2020                         }
2021                 }
2022         }
2023
2024  done:
2025         dns_client_freeresanswer(uctx->client, &rev->answerlist);
2026         isc_event_free(&event);
2027
2028         LOCK(&uctx->lock);
2029         if (uctx->restrans == NULL && uctx->restrans2 == NULL)
2030                 completed = ISC_TRUE;
2031         UNLOCK(&uctx->lock);
2032
2033         if (completed) {
2034                 INSIST(uctx->currentserver == NULL);
2035                 uctx->currentserver = ISC_LIST_HEAD(uctx->servers);
2036                 if (uctx->currentserver != NULL && !uctx->canceled)
2037                         send_update(uctx);
2038                 else {
2039                         if (result == ISC_R_SUCCESS)
2040                                 result = ISC_R_NOTFOUND;
2041                         update_sendevent(uctx, result);
2042                 }
2043         }
2044 }
2045
2046 static isc_result_t
2047 process_soa(updatectx_t *uctx, dns_rdataset_t *soaset, dns_name_t *soaname) {
2048         isc_result_t result;
2049         dns_rdata_t soarr = DNS_RDATA_INIT;
2050         dns_rdata_soa_t soa;
2051         dns_name_t primary;
2052
2053         result = dns_rdataset_first(soaset);
2054         if (result != ISC_R_SUCCESS)
2055                 return (result);
2056         dns_rdata_init(&soarr);
2057         dns_rdataset_current(soaset, &soarr);
2058         result = dns_rdata_tostruct(&soarr, &soa, NULL);
2059         if (result != ISC_R_SUCCESS)
2060                 return (result);
2061
2062         dns_name_init(&primary, NULL);
2063         dns_name_clone(&soa.origin, &primary);
2064
2065         if (uctx->zonename == NULL) {
2066                 uctx->zonename = dns_fixedname_name(&uctx->zonefname);
2067                 result = dns_name_copy(soaname, uctx->zonename, NULL);
2068                 if (result != ISC_R_SUCCESS)
2069                         goto out;
2070         }
2071
2072         if (uctx->currentserver != NULL)
2073                 result = send_update(uctx);
2074         else {
2075                 /*
2076                  * Get addresses of the primary server.  We don't use the ADB
2077                  * feature so that we could avoid caching data.
2078                  */
2079                 LOCK(&uctx->lock);
2080                 uctx->bp4 = uctx;
2081                 result = dns_client_startresolve(uctx->client, &primary,
2082                                                  uctx->rdclass,
2083                                                  dns_rdatatype_a,
2084                                                  0, uctx->client->task,
2085                                                  resolveaddr_done, &uctx->bp4,
2086                                                  &uctx->restrans);
2087                 if (result == ISC_R_SUCCESS) {
2088                         uctx->bp6 = uctx;
2089                         result = dns_client_startresolve(uctx->client,
2090                                                          &primary,
2091                                                          uctx->rdclass,
2092                                                          dns_rdatatype_aaaa,
2093                                                          0, uctx->client->task,
2094                                                          resolveaddr_done,
2095                                                          &uctx->bp6,
2096                                                          &uctx->restrans2);
2097                 }
2098                 UNLOCK(&uctx->lock);
2099         }
2100
2101  out:
2102         dns_rdata_freestruct(&soa);
2103
2104         return (result);
2105 }
2106
2107 static void
2108 receive_soa(isc_task_t *task, isc_event_t *event) {
2109         dns_requestevent_t *reqev = NULL;
2110         updatectx_t *uctx;
2111         dns_client_t *client;
2112         isc_result_t result, eresult;
2113         dns_request_t *request;
2114         dns_message_t *rcvmsg = NULL;
2115         dns_section_t section;
2116         dns_rdataset_t *soaset = NULL;
2117         int pass = 0;
2118         dns_name_t *name;
2119         dns_message_t *soaquery = NULL;
2120         isc_sockaddr_t *addr;
2121         isc_boolean_t seencname = ISC_FALSE;
2122         isc_boolean_t droplabel = ISC_FALSE;
2123         dns_name_t tname;
2124         unsigned int nlabels;
2125
2126         UNUSED(task);
2127
2128         REQUIRE(event->ev_type == DNS_EVENT_REQUESTDONE);
2129         reqev = (dns_requestevent_t *)event;
2130         request = reqev->request;
2131         result = eresult = reqev->result;
2132         uctx = reqev->ev_arg;
2133         client = uctx->client;
2134         soaquery = uctx->soaquery;
2135         addr = uctx->currentserver;
2136         INSIST(addr != NULL);
2137
2138         isc_event_free(&event);
2139
2140         if (eresult != ISC_R_SUCCESS) {
2141                 result = eresult;
2142                 goto out;
2143         }
2144
2145         result = dns_message_create(uctx->client->mctx,
2146                                     DNS_MESSAGE_INTENTPARSE, &rcvmsg);
2147         if (result != ISC_R_SUCCESS)
2148                 goto out;
2149         result = dns_request_getresponse(request, rcvmsg,
2150                                          DNS_MESSAGEPARSE_PRESERVEORDER);
2151
2152         if (result == DNS_R_TSIGERRORSET) {
2153                 dns_request_t *newrequest = NULL;
2154
2155                 /* Retry SOA request without TSIG */
2156                 dns_message_destroy(&rcvmsg);
2157                 dns_message_renderreset(uctx->soaquery);
2158                 result = dns_request_createvia3(uctx->view->requestmgr,
2159                                                 uctx->soaquery, NULL, addr, 0,
2160                                                 NULL,
2161                                                 client->find_timeout * 20,
2162                                                 client->find_timeout, 3,
2163                                                 uctx->client->task,
2164                                                 receive_soa, uctx,
2165                                                 &newrequest);
2166                 if (result == ISC_R_SUCCESS) {
2167                         LOCK(&uctx->lock);
2168                         dns_request_destroy(&uctx->soareq);
2169                         uctx->soareq = newrequest;
2170                         UNLOCK(&uctx->lock);
2171
2172                         return;
2173                 }
2174                 goto out;
2175         }
2176
2177         section = DNS_SECTION_ANSWER;
2178
2179         if (rcvmsg->rcode != dns_rcode_noerror &&
2180             rcvmsg->rcode != dns_rcode_nxdomain) {
2181                 result = rcode2result(rcvmsg->rcode);
2182                 goto out;
2183         }
2184
2185  lookforsoa:
2186         if (pass == 0)
2187                 section = DNS_SECTION_ANSWER;
2188         else if (pass == 1)
2189                 section = DNS_SECTION_AUTHORITY;
2190         else {
2191                 droplabel = ISC_TRUE;
2192                 goto out;
2193         }
2194
2195         result = dns_message_firstname(rcvmsg, section);
2196         if (result != ISC_R_SUCCESS) {
2197                 pass++;
2198                 goto lookforsoa;
2199         }
2200         while (result == ISC_R_SUCCESS) {
2201                 name = NULL;
2202                 dns_message_currentname(rcvmsg, section, &name);
2203                 soaset = NULL;
2204                 result = dns_message_findtype(name, dns_rdatatype_soa, 0,
2205                                               &soaset);
2206                 if (result == ISC_R_SUCCESS)
2207                         break;
2208                 if (section == DNS_SECTION_ANSWER) {
2209                         dns_rdataset_t *tset = NULL;
2210                         if (dns_message_findtype(name, dns_rdatatype_cname, 0,
2211                                                  &tset) == ISC_R_SUCCESS
2212                             ||
2213                             dns_message_findtype(name, dns_rdatatype_dname, 0,
2214                                                  &tset) == ISC_R_SUCCESS
2215                             )
2216                         {
2217                                 seencname = ISC_TRUE;
2218                                 break;
2219                         }
2220                 }
2221
2222                 result = dns_message_nextname(rcvmsg, section);
2223         }
2224
2225         if (soaset == NULL && !seencname) {
2226                 pass++;
2227                 goto lookforsoa;
2228         }
2229
2230         if (seencname) {
2231                 droplabel = ISC_TRUE;
2232                 goto out;
2233         }
2234
2235         result = process_soa(uctx, soaset, name);
2236
2237  out:
2238         if (droplabel) {
2239                 result = dns_message_firstname(soaquery, DNS_SECTION_QUESTION);
2240                 INSIST(result == ISC_R_SUCCESS);
2241                 name = NULL;
2242                 dns_message_currentname(soaquery, DNS_SECTION_QUESTION, &name);
2243                 nlabels = dns_name_countlabels(name);
2244                 if (nlabels == 1)
2245                         result = DNS_R_SERVFAIL; /* is there a better error? */
2246                 else {
2247                         dns_name_init(&tname, NULL);
2248                         dns_name_getlabelsequence(name, 1, nlabels - 1,
2249                                                   &tname);
2250                         dns_name_clone(&tname, name);
2251                         dns_request_destroy(&request);
2252                         LOCK(&uctx->lock);
2253                         uctx->soareq = NULL;
2254                         UNLOCK(&uctx->lock);
2255                         dns_message_renderreset(soaquery);
2256                         dns_message_settsigkey(soaquery, NULL);
2257                         result = dns_request_createvia3(uctx->view->requestmgr,
2258                                                         soaquery, NULL,
2259                                                         uctx->currentserver, 0,
2260                                                         uctx->tsigkey,
2261                                                         client->find_timeout *
2262                                                         20,
2263                                                         client->find_timeout,
2264                                                         3, client->task,
2265                                                         receive_soa, uctx,
2266                                                         &uctx->soareq);
2267                 }
2268         }
2269
2270         if (!droplabel || result != ISC_R_SUCCESS) {
2271                 dns_message_destroy(&uctx->soaquery);
2272                 LOCK(&uctx->lock);
2273                 dns_request_destroy(&uctx->soareq);
2274                 UNLOCK(&uctx->lock);
2275         }
2276
2277         if (rcvmsg != NULL)
2278                 dns_message_destroy(&rcvmsg);
2279
2280         if (result != ISC_R_SUCCESS)
2281                 update_sendevent(uctx, result);
2282 }
2283
2284 static isc_result_t
2285 request_soa(updatectx_t *uctx) {
2286         isc_result_t result;
2287         dns_message_t *soaquery = uctx->soaquery;
2288         dns_name_t *name = NULL;
2289         dns_rdataset_t *rdataset = NULL;
2290
2291         if (soaquery == NULL) {
2292                 result = dns_message_create(uctx->client->mctx,
2293                                             DNS_MESSAGE_INTENTRENDER,
2294                                             &soaquery);
2295                 if (result != ISC_R_SUCCESS)
2296                         return (result);
2297         }
2298         soaquery->flags |= DNS_MESSAGEFLAG_RD;
2299         result = dns_message_gettempname(soaquery, &name);
2300         if (result != ISC_R_SUCCESS)
2301                 goto fail;
2302         result = dns_message_gettemprdataset(soaquery, &rdataset);
2303         if (result != ISC_R_SUCCESS)
2304                 goto fail;
2305         dns_rdataset_makequestion(rdataset, uctx->rdclass, dns_rdatatype_soa);
2306         dns_name_clone(uctx->firstname, name);
2307         ISC_LIST_APPEND(name->list, rdataset, link);
2308         dns_message_addname(soaquery, name, DNS_SECTION_QUESTION);
2309         rdataset = NULL;
2310         name = NULL;
2311
2312         result = dns_request_createvia3(uctx->view->requestmgr,
2313                                         soaquery, NULL, uctx->currentserver, 0,
2314                                         uctx->tsigkey,
2315                                         uctx->client->find_timeout * 20,
2316                                         uctx->client->find_timeout, 3,
2317                                         uctx->client->task, receive_soa, uctx,
2318                                         &uctx->soareq);
2319         if (result == ISC_R_SUCCESS) {
2320                 uctx->soaquery = soaquery;
2321                 return (ISC_R_SUCCESS);
2322         }
2323
2324  fail:
2325         if (rdataset != NULL) {
2326                 ISC_LIST_UNLINK(name->list, rdataset, link); /* for safety */
2327                 dns_message_puttemprdataset(soaquery, &rdataset);
2328         }
2329         if (name != NULL)
2330                 dns_message_puttempname(soaquery, &name);
2331         dns_message_destroy(&soaquery);
2332
2333         return (result);
2334 }
2335
2336 static void
2337 resolvesoa_done(isc_task_t *task, isc_event_t *event) {
2338         dns_clientresevent_t *rev = (dns_clientresevent_t *)event;
2339         updatectx_t *uctx;
2340         dns_name_t *name, tname;
2341         dns_rdataset_t *rdataset = NULL;
2342         isc_result_t result = rev->result;
2343         unsigned int nlabels;
2344
2345         UNUSED(task);
2346
2347         uctx = event->ev_arg;
2348         REQUIRE(UCTX_VALID(uctx));
2349
2350         LOCK(&uctx->lock);
2351         dns_client_destroyrestrans(&uctx->restrans);
2352         UNLOCK(&uctx->lock);
2353
2354         uctx = event->ev_arg;
2355         if (result != ISC_R_SUCCESS &&
2356             result != DNS_R_NCACHENXDOMAIN &&
2357             result != DNS_R_NCACHENXRRSET) {
2358                 /* XXX: what about DNSSEC failure? */
2359                 goto out;
2360         }
2361
2362         for (name = ISC_LIST_HEAD(rev->answerlist); name != NULL;
2363              name = ISC_LIST_NEXT(name, link)) {
2364                 for (rdataset = ISC_LIST_HEAD(name->list);
2365                      rdataset != NULL;
2366                      rdataset = ISC_LIST_NEXT(rdataset, link)) {
2367                         if (dns_rdataset_isassociated(rdataset) &&
2368                             rdataset->type == dns_rdatatype_soa)
2369                                 break;
2370                 }
2371         }
2372
2373         if (rdataset == NULL) {
2374                 /* Drop one label and retry resolution. */
2375                 nlabels = dns_name_countlabels(&uctx->soaqname);
2376                 if (nlabels == 1) {
2377                         result = DNS_R_SERVFAIL; /* is there a better error? */
2378                         goto out;
2379                 }
2380                 dns_name_init(&tname, NULL);
2381                 dns_name_getlabelsequence(&uctx->soaqname, 1, nlabels - 1,
2382                                           &tname);
2383                 dns_name_clone(&tname, &uctx->soaqname);
2384
2385                 result = dns_client_startresolve(uctx->client, &uctx->soaqname,
2386                                                  uctx->rdclass,
2387                                                  dns_rdatatype_soa, 0,
2388                                                  uctx->client->task,
2389                                                  resolvesoa_done, uctx,
2390                                                  &uctx->restrans);
2391         } else
2392                 result = process_soa(uctx, rdataset, &uctx->soaqname);
2393
2394  out:
2395         dns_client_freeresanswer(uctx->client, &rev->answerlist);
2396         isc_event_free(&event);
2397
2398         if (result != ISC_R_SUCCESS)
2399                 update_sendevent(uctx, result);
2400 }
2401
2402 static isc_result_t
2403 copy_name(isc_mem_t *mctx, dns_message_t *msg, dns_name_t *name,
2404           dns_name_t **newnamep)
2405 {
2406         isc_result_t result;
2407         dns_name_t *newname = NULL;
2408         isc_region_t r;
2409         isc_buffer_t *namebuf = NULL, *rdatabuf = NULL;
2410         dns_rdatalist_t *rdatalist;
2411         dns_rdataset_t *rdataset, *newrdataset;
2412         dns_rdata_t rdata = DNS_RDATA_INIT, *newrdata;
2413
2414         result = dns_message_gettempname(msg, &newname);
2415         if (result != ISC_R_SUCCESS)
2416                 return (result);
2417         result = isc_buffer_allocate(mctx, &namebuf, DNS_NAME_MAXWIRE);
2418         if (result != ISC_R_SUCCESS)
2419                 goto fail;
2420         dns_name_init(newname, NULL);
2421         dns_name_setbuffer(newname, namebuf);
2422         dns_message_takebuffer(msg, &namebuf);
2423         result = dns_name_copy(name, newname, NULL);
2424         if (result != ISC_R_SUCCESS)
2425                 goto fail;
2426
2427         for (rdataset = ISC_LIST_HEAD(name->list); rdataset != NULL;
2428              rdataset = ISC_LIST_NEXT(rdataset, link)) {
2429                 rdatalist = NULL;
2430                 result = dns_message_gettemprdatalist(msg, &rdatalist);
2431                 if (result != ISC_R_SUCCESS)
2432                         goto fail;
2433                 dns_rdatalist_init(rdatalist);
2434                 rdatalist->type = rdataset->type;
2435                 rdatalist->rdclass = rdataset->rdclass;
2436                 rdatalist->covers = rdataset->covers;
2437                 rdatalist->ttl = rdataset->ttl;
2438
2439                 result = dns_rdataset_first(rdataset);
2440                 while (result == ISC_R_SUCCESS) {
2441                         dns_rdata_reset(&rdata);
2442                         dns_rdataset_current(rdataset, &rdata);
2443
2444                         newrdata = NULL;
2445                         result = dns_message_gettemprdata(msg, &newrdata);
2446                         if (result != ISC_R_SUCCESS)
2447                                 goto fail;
2448                         dns_rdata_toregion(&rdata, &r);
2449                         rdatabuf = NULL;
2450                         result = isc_buffer_allocate(mctx, &rdatabuf,
2451                                                      r.length);
2452                         if (result != ISC_R_SUCCESS)
2453                                 goto fail;
2454                         isc_buffer_putmem(rdatabuf, r.base, r.length);
2455                         isc_buffer_usedregion(rdatabuf, &r);
2456                         dns_rdata_init(newrdata);
2457                         dns_rdata_fromregion(newrdata, rdata.rdclass,
2458                                              rdata.type, &r);
2459                         newrdata->flags = rdata.flags;
2460
2461                         ISC_LIST_APPEND(rdatalist->rdata, newrdata, link);
2462                         dns_message_takebuffer(msg, &rdatabuf);
2463
2464                         result = dns_rdataset_next(rdataset);
2465                 }
2466
2467                 newrdataset = NULL;
2468                 result = dns_message_gettemprdataset(msg, &newrdataset);
2469                 if (result != ISC_R_SUCCESS)
2470                         goto fail;
2471                 dns_rdataset_init(newrdataset);
2472                 dns_rdatalist_tordataset(rdatalist, newrdataset);
2473
2474                 ISC_LIST_APPEND(newname->list, newrdataset, link);
2475         }
2476
2477         *newnamep = newname;
2478
2479         return (ISC_R_SUCCESS);
2480
2481  fail:
2482         dns_message_puttempname(msg, &newname);
2483
2484         return (result);
2485
2486 }
2487
2488 static void
2489 internal_update_callback(isc_task_t *task, isc_event_t *event) {
2490         updatearg_t *uarg = event->ev_arg;
2491         dns_clientupdateevent_t *uev = (dns_clientupdateevent_t *)event;
2492
2493         UNUSED(task);
2494
2495         LOCK(&uarg->lock);
2496
2497         uarg->result = uev->result;
2498
2499         dns_client_destroyupdatetrans(&uarg->trans);
2500         isc_event_free(&event);
2501
2502         if (!uarg->canceled) {
2503                 UNLOCK(&uarg->lock);
2504
2505                 /* Exit from the internal event loop */
2506                 isc_app_ctxsuspend(uarg->actx);
2507         } else {
2508                 /*
2509                  * We have already exited from the loop (due to some
2510                  * unexpected event).  Just clean the arg up.
2511                  */
2512                 UNLOCK(&uarg->lock);
2513                 DESTROYLOCK(&uarg->lock);
2514                 isc_mem_put(uarg->client->mctx, uarg, sizeof(*uarg));
2515         }
2516 }
2517
2518 isc_result_t
2519 dns_client_update(dns_client_t *client, dns_rdataclass_t rdclass,
2520                   dns_name_t *zonename, dns_namelist_t *prerequisites,
2521                   dns_namelist_t *updates, isc_sockaddrlist_t *servers,
2522                   dns_tsec_t *tsec, unsigned int options)
2523 {
2524         isc_result_t result;
2525         isc_appctx_t *actx;
2526         updatearg_t *uarg;
2527
2528         REQUIRE(DNS_CLIENT_VALID(client));
2529
2530         if ((client->attributes & DNS_CLIENTATTR_OWNCTX) == 0 &&
2531             (options & DNS_CLIENTRESOPT_ALLOWRUN) == 0) {
2532                 /*
2533                  * If the client is run under application's control, we need
2534                  * to create a new running (sub)environment for this
2535                  * particular resolution.
2536                  */
2537                 return (ISC_R_NOTIMPLEMENTED); /* XXXTBD */
2538         } else
2539                 actx = client->actx;
2540
2541         uarg = isc_mem_get(client->mctx, sizeof(*uarg));
2542         if (uarg == NULL)
2543                 return (ISC_R_NOMEMORY);
2544
2545         result = isc_mutex_init(&uarg->lock);
2546         if (result != ISC_R_SUCCESS) {
2547                 isc_mem_put(client->mctx, uarg, sizeof(*uarg));
2548                 return (result);
2549         }
2550
2551         uarg->actx = actx;
2552         uarg->client = client;
2553         uarg->result = ISC_R_FAILURE;
2554         uarg->trans = NULL;
2555         uarg->canceled = ISC_FALSE;
2556
2557         result = dns_client_startupdate(client, rdclass, zonename,
2558                                         prerequisites, updates, servers,
2559                                         tsec, options, client->task,
2560                                         internal_update_callback, uarg,
2561                                         &uarg->trans);
2562         if (result != ISC_R_SUCCESS) {
2563                 DESTROYLOCK(&uarg->lock);
2564                 isc_mem_put(client->mctx, uarg, sizeof(*uarg));
2565                 return (result);
2566         }
2567
2568         /*
2569          * Start internal event loop.  It blocks until the entire process
2570          * is completed.
2571          */
2572         result = isc_app_ctxrun(actx);
2573
2574         LOCK(&uarg->lock);
2575         if (result == ISC_R_SUCCESS || result == ISC_R_SUSPEND)
2576                 result = uarg->result;
2577
2578         if (uarg->trans != NULL) {
2579                 /*
2580                  * Unusual termination (perhaps due to signal).  We need some
2581                  * tricky cleanup process.
2582                  */
2583                 uarg->canceled = ISC_TRUE;
2584                 dns_client_cancelupdate(uarg->trans);
2585
2586                 UNLOCK(&uarg->lock);
2587
2588                 /* uarg will be freed in the event handler. */
2589         } else {
2590                 UNLOCK(&uarg->lock);
2591
2592                 DESTROYLOCK(&uarg->lock);
2593                 isc_mem_put(client->mctx, uarg, sizeof(*uarg));
2594         }
2595
2596         return (result);
2597 }
2598
2599 isc_result_t
2600 dns_client_startupdate(dns_client_t *client, dns_rdataclass_t rdclass,
2601                        dns_name_t *zonename, dns_namelist_t *prerequisites,
2602                        dns_namelist_t *updates, isc_sockaddrlist_t *servers,
2603                        dns_tsec_t *tsec, unsigned int options,
2604                        isc_task_t *task, isc_taskaction_t action, void *arg,
2605                        dns_clientupdatetrans_t **transp)
2606 {
2607         dns_view_t *view = NULL;
2608         isc_result_t result;
2609         dns_name_t *name, *newname;
2610         updatectx_t *uctx;
2611         isc_task_t *clone = NULL;
2612         dns_section_t section = DNS_SECTION_UPDATE;
2613         isc_sockaddr_t *server, *sa = NULL;
2614         dns_tsectype_t tsectype = dns_tsectype_none;
2615
2616         UNUSED(options);
2617
2618         REQUIRE(DNS_CLIENT_VALID(client));
2619         REQUIRE(transp != NULL && *transp == NULL);
2620         REQUIRE(updates != NULL);
2621         REQUIRE(task != NULL);
2622
2623         if (tsec != NULL) {
2624                 tsectype = dns_tsec_gettype(tsec);
2625                 if (tsectype != dns_tsectype_tsig)
2626                         return (ISC_R_NOTIMPLEMENTED); /* XXX */
2627         }
2628
2629         LOCK(&client->lock);
2630         result = dns_viewlist_find(&client->viewlist, DNS_CLIENTVIEW_NAME,
2631                                    rdclass, &view);
2632         UNLOCK(&client->lock);
2633         if (result != ISC_R_SUCCESS)
2634                 return (result);
2635
2636         /* Create a context and prepare some resources */
2637         uctx = isc_mem_get(client->mctx, sizeof(*uctx));
2638         if (uctx == NULL) {
2639                 dns_view_detach(&view);
2640                 return (ISC_R_NOMEMORY);
2641         }
2642         result = isc_mutex_init(&uctx->lock);
2643         if (result != ISC_R_SUCCESS) {
2644                 dns_view_detach(&view);
2645                 isc_mem_put(client->mctx, uctx, sizeof(*uctx));
2646                 return (ISC_R_NOMEMORY);
2647         }
2648         clone = NULL;
2649         isc_task_attach(task, &clone);
2650         uctx->client = client;
2651         ISC_LINK_INIT(uctx, link);
2652         uctx->state = dns_clientupdatestate_prepare;
2653         uctx->view = view;
2654         uctx->rdclass = rdclass;
2655         uctx->canceled = ISC_FALSE;
2656         uctx->updatemsg = NULL;
2657         uctx->soaquery = NULL;
2658         uctx->updatereq = NULL;
2659         uctx->restrans = NULL;
2660         uctx->restrans2 = NULL;
2661         uctx->bp4 = NULL;
2662         uctx->bp6 = NULL;
2663         uctx->soareq = NULL;
2664         uctx->event = NULL;
2665         uctx->tsigkey = NULL;
2666         uctx->sig0key = NULL;
2667         uctx->zonename = NULL;
2668         dns_name_init(&uctx->soaqname, NULL);
2669         ISC_LIST_INIT(uctx->servers);
2670         uctx->nservers = 0;
2671         uctx->currentserver = NULL;
2672         dns_fixedname_init(&uctx->zonefname);
2673         if (tsec != NULL)
2674                 dns_tsec_getkey(tsec, &uctx->tsigkey);
2675         uctx->event = (dns_clientupdateevent_t *)
2676                 isc_event_allocate(client->mctx, clone, DNS_EVENT_UPDATEDONE,
2677                                    action, arg, sizeof(*uctx->event));
2678         if (uctx->event == NULL)
2679                 goto fail;
2680         if (zonename != NULL) {
2681                 uctx->zonename = dns_fixedname_name(&uctx->zonefname);
2682                 result = dns_name_copy(zonename, uctx->zonename, NULL);
2683         }
2684         if (servers != NULL) {
2685                 for (server = ISC_LIST_HEAD(*servers);
2686                      server != NULL;
2687                      server = ISC_LIST_NEXT(server, link)) {
2688                         sa = isc_mem_get(client->mctx, sizeof(*sa));
2689                         if (sa == NULL)
2690                                 goto fail;
2691                         sa->type = server->type;
2692                         sa->length = server->length;
2693                         ISC_LINK_INIT(sa, link);
2694                         ISC_LIST_APPEND(uctx->servers, sa, link);
2695                         if (uctx->currentserver == NULL)
2696                                 uctx->currentserver = sa;
2697                         uctx->nservers++;
2698                 }
2699         }
2700
2701         /* Make update message */
2702         result = dns_message_create(client->mctx, DNS_MESSAGE_INTENTRENDER,
2703                                     &uctx->updatemsg);
2704         if (result != ISC_R_SUCCESS)
2705                 goto fail;
2706         uctx->updatemsg->opcode = dns_opcode_update;
2707
2708         if (prerequisites != NULL) {
2709                 for (name = ISC_LIST_HEAD(*prerequisites); name != NULL;
2710                      name = ISC_LIST_NEXT(name, link)) {
2711                         newname = NULL;
2712                         result = copy_name(client->mctx, uctx->updatemsg,
2713                                            name, &newname);
2714                         if (result != ISC_R_SUCCESS)
2715                                 goto fail;
2716                         dns_message_addname(uctx->updatemsg, newname,
2717                                             DNS_SECTION_PREREQUISITE);
2718                 }
2719         }
2720
2721         for (name = ISC_LIST_HEAD(*updates); name != NULL;
2722              name = ISC_LIST_NEXT(name, link)) {
2723                 newname = NULL;
2724                 result = copy_name(client->mctx, uctx->updatemsg, name,
2725                                    &newname);
2726                 if (result != ISC_R_SUCCESS)
2727                         goto fail;
2728                 dns_message_addname(uctx->updatemsg, newname,
2729                                     DNS_SECTION_UPDATE);
2730         }
2731
2732         uctx->firstname = NULL;
2733         result = dns_message_firstname(uctx->updatemsg, section);
2734         if (result == ISC_R_NOMORE) {
2735                 section = DNS_SECTION_PREREQUISITE;
2736                 result = dns_message_firstname(uctx->updatemsg, section);
2737         }
2738         if (result != ISC_R_SUCCESS)
2739                 goto fail;
2740         dns_message_currentname(uctx->updatemsg, section, &uctx->firstname);
2741
2742         uctx->magic = UCTX_MAGIC;
2743
2744         LOCK(&client->lock);
2745         ISC_LIST_APPEND(client->updatectxs, uctx, link);
2746         UNLOCK(&client->lock);
2747
2748         if (uctx->zonename != NULL && uctx->currentserver != NULL) {
2749                 result = send_update(uctx);
2750                 if (result != ISC_R_SUCCESS)
2751                         goto fail;
2752         } else if (uctx->currentserver != NULL) {
2753                 result = request_soa(uctx);
2754                 if (result != ISC_R_SUCCESS)
2755                         goto fail;
2756         } else {
2757                 dns_name_clone(uctx->firstname, &uctx->soaqname);
2758                 result = dns_client_startresolve(uctx->client, &uctx->soaqname,
2759                                                  uctx->rdclass,
2760                                                  dns_rdatatype_soa, 0,
2761                                                  client->task, resolvesoa_done,
2762                                                  uctx, &uctx->restrans);
2763                 if (result != ISC_R_SUCCESS)
2764                         goto fail;
2765         }
2766
2767         *transp = (dns_clientupdatetrans_t *)uctx;
2768
2769         return (ISC_R_SUCCESS);
2770
2771  fail:
2772         if (ISC_LINK_LINKED(uctx, link)) {
2773                 LOCK(&client->lock);
2774                 ISC_LIST_UNLINK(client->updatectxs, uctx, link);
2775                 UNLOCK(&client->lock);
2776         }
2777         if (uctx->updatemsg != NULL)
2778                 dns_message_destroy(&uctx->updatemsg);
2779         while ((sa = ISC_LIST_HEAD(uctx->servers)) != NULL) {
2780                 ISC_LIST_UNLINK(uctx->servers, sa, link);
2781                 isc_mem_put(client->mctx, sa, sizeof(*sa));
2782         }
2783         if (uctx->event != NULL)
2784                 isc_event_free(ISC_EVENT_PTR(&uctx->event));
2785         if (uctx->tsigkey != NULL)
2786                 dns_tsigkey_detach(&uctx->tsigkey);
2787         isc_task_detach(&clone);
2788         DESTROYLOCK(&uctx->lock);
2789         uctx->magic = 0;
2790         isc_mem_put(client->mctx, uctx, sizeof(*uctx));
2791         dns_view_detach(&view);
2792
2793         return (result);
2794 }
2795
2796 void
2797 dns_client_cancelupdate(dns_clientupdatetrans_t *trans) {
2798         updatectx_t *uctx;
2799
2800         REQUIRE(trans != NULL);
2801         uctx = (updatectx_t *)trans;
2802         REQUIRE(UCTX_VALID(uctx));
2803
2804         LOCK(&uctx->lock);
2805
2806         if (!uctx->canceled) {
2807                 uctx->canceled = ISC_TRUE;
2808                 if (uctx->updatereq != NULL)
2809                         dns_request_cancel(uctx->updatereq);
2810                 if (uctx->soareq != NULL)
2811                         dns_request_cancel(uctx->soareq);
2812                 if (uctx->restrans != NULL)
2813                         dns_client_cancelresolve(uctx->restrans);
2814                 if (uctx->restrans2 != NULL)
2815                         dns_client_cancelresolve(uctx->restrans2);
2816         }
2817
2818         UNLOCK(&uctx->lock);
2819 }
2820
2821 void
2822 dns_client_destroyupdatetrans(dns_clientupdatetrans_t **transp) {
2823         updatectx_t *uctx;
2824         isc_mem_t *mctx;
2825         dns_client_t *client;
2826         isc_boolean_t need_destroyclient = ISC_FALSE;
2827         isc_sockaddr_t *sa;
2828
2829         REQUIRE(transp != NULL);
2830         uctx = (updatectx_t *)*transp;
2831         REQUIRE(UCTX_VALID(uctx));
2832         client = uctx->client;
2833         REQUIRE(DNS_CLIENT_VALID(client));
2834         REQUIRE(uctx->updatereq == NULL && uctx->updatemsg == NULL &&
2835                 uctx->soareq == NULL && uctx->soaquery == NULL &&
2836                 uctx->event == NULL && uctx->tsigkey == NULL &&
2837                 uctx->sig0key == NULL);
2838
2839         mctx = client->mctx;
2840         dns_view_detach(&uctx->view);
2841         while ((sa = ISC_LIST_HEAD(uctx->servers)) != NULL) {
2842                 ISC_LIST_UNLINK(uctx->servers, sa, link);
2843                 isc_mem_put(mctx, sa, sizeof(*sa));
2844         }
2845
2846         LOCK(&client->lock);
2847
2848         INSIST(ISC_LINK_LINKED(uctx, link));
2849         ISC_LIST_UNLINK(client->updatectxs, uctx, link);
2850
2851         if (client->references == 0 && ISC_LIST_EMPTY(client->resctxs) &&
2852             ISC_LIST_EMPTY(client->reqctxs) &&
2853             ISC_LIST_EMPTY(client->updatectxs))
2854                 need_destroyclient = ISC_TRUE;
2855
2856         UNLOCK(&client->lock);
2857
2858         DESTROYLOCK(&uctx->lock);
2859         uctx->magic = 0;
2860
2861         isc_mem_put(mctx, uctx, sizeof(*uctx));
2862
2863         if (need_destroyclient)
2864                 destroyclient(&client);
2865
2866         *transp = NULL;
2867 }
2868
2869 isc_mem_t *
2870 dns_client_mctx(dns_client_t *client) {
2871
2872         REQUIRE(DNS_CLIENT_VALID(client));
2873         return (client->mctx);
2874 }
2875
2876 typedef struct {
2877         isc_buffer_t    buffer;
2878         dns_rdataset_t  rdataset;
2879         dns_rdatalist_t rdatalist;
2880         dns_rdata_t     rdata;
2881         size_t          size;
2882         isc_mem_t *     mctx;
2883         unsigned char   data[FLEXIBLE_ARRAY_MEMBER];
2884 } dns_client_updaterec_t;
2885
2886 isc_result_t
2887 dns_client_updaterec(dns_client_updateop_t op, dns_name_t *owner,
2888                      dns_rdatatype_t type, dns_rdata_t *source,
2889                      dns_ttl_t ttl, dns_name_t *target,
2890                      dns_rdataset_t *rdataset, dns_rdatalist_t *rdatalist,
2891                      dns_rdata_t *rdata, isc_mem_t *mctx)
2892 {
2893         dns_client_updaterec_t *updaterec = NULL;
2894         size_t size = offsetof(dns_client_updaterec_t, data);
2895
2896         REQUIRE(op < updateop_max);
2897         REQUIRE(owner != NULL);
2898         REQUIRE((rdataset != NULL && rdatalist != NULL && rdata != NULL) ||
2899                 (rdataset == NULL && rdatalist == NULL && rdata == NULL &&
2900                  mctx != NULL));
2901         if (op == updateop_add)
2902                 REQUIRE(source != NULL);
2903         if (source != NULL) {
2904                 REQUIRE(source->type == type);
2905                 REQUIRE(op == updateop_add || op == updateop_delete ||
2906                         op == updateop_exist);
2907         }
2908
2909         size += owner->length;
2910         if (source != NULL)
2911                 size += source->length;
2912
2913         if (rdataset == NULL) {
2914                 updaterec = isc_mem_get(mctx, size);
2915                 if (updaterec == NULL)
2916                         return (ISC_R_NOMEMORY);
2917                 rdataset = &updaterec->rdataset;
2918                 rdatalist = &updaterec->rdatalist;
2919                 rdata = &updaterec->rdata;
2920                 dns_rdataset_init(rdataset);
2921                 dns_rdatalist_init(&updaterec->rdatalist);
2922                 dns_rdata_init(&updaterec->rdata);
2923                 isc_buffer_init(&updaterec->buffer, updaterec->data,
2924                                 size - offsetof(dns_client_updaterec_t, data));
2925                 dns_name_copy(owner, target, &updaterec->buffer);
2926                 if (source != NULL) {
2927                         isc_region_t r;
2928                         dns_rdata_clone(source, rdata);
2929                         dns_rdata_toregion(rdata, &r);
2930                         rdata->data = isc_buffer_used(&updaterec->buffer);
2931                         isc_buffer_copyregion(&updaterec->buffer, &r);
2932                 }
2933                 updaterec->mctx = NULL;
2934                 isc_mem_attach(mctx, &updaterec->mctx);
2935         } else if (source != NULL)
2936                 dns_rdata_clone(source, rdata);
2937
2938         switch (op) {
2939         case updateop_add:
2940                 break;
2941         case updateop_delete:
2942                 if (source != NULL) {
2943                         ttl = 0;
2944                         dns_rdata_makedelete(rdata);
2945                 } else
2946                         dns_rdata_deleterrset(rdata, type);
2947                 break;
2948         case updateop_notexist:
2949                 dns_rdata_notexist(rdata, type);
2950                 break;
2951         case updateop_exist:
2952                 if (source == NULL) {
2953                         ttl = 0;
2954                         dns_rdata_exists(rdata, type);
2955                 }
2956         case updateop_none:
2957                 break;
2958         default:
2959                 INSIST(0);
2960         }
2961
2962         rdatalist->type = rdata->type;
2963         rdatalist->rdclass = rdata->rdclass;
2964         if (source != NULL) {
2965                 rdatalist->covers = dns_rdata_covers(rdata);
2966                 rdatalist->ttl = ttl;
2967         }
2968         ISC_LIST_APPEND(rdatalist->rdata, rdata, link);
2969         dns_rdatalist_tordataset(rdatalist, rdataset);
2970         ISC_LIST_APPEND(target->list, rdataset, link);
2971         if (updaterec != NULL) {
2972                 target->attributes |= DNS_NAMEATTR_HASUPDATEREC;
2973                 dns_name_setbuffer(target, &updaterec->buffer);
2974         }
2975         if (op == updateop_add || op == updateop_delete)
2976                 target->attributes |= DNS_NAMEATTR_UPDATE;
2977         else
2978                 target->attributes |= DNS_NAMEATTR_PREREQUISITE;
2979         return (ISC_R_SUCCESS);
2980 }
2981
2982 void
2983 dns_client_freeupdate(dns_name_t **namep) {
2984         dns_client_updaterec_t *updaterec;
2985         dns_rdatalist_t *rdatalist;
2986         dns_rdataset_t *rdataset;
2987         dns_rdata_t *rdata;
2988         dns_name_t *name;
2989
2990         REQUIRE(namep != NULL && *namep != NULL);
2991
2992         name = *namep;
2993         for (rdataset = ISC_LIST_HEAD(name->list);
2994              rdataset != NULL;
2995              rdataset = ISC_LIST_HEAD(name->list)) {
2996                 ISC_LIST_UNLINK(name->list, rdataset, link);
2997                 rdatalist = NULL;
2998                 dns_rdatalist_fromrdataset(rdataset, &rdatalist);
2999                 if (rdatalist == NULL) {
3000                         dns_rdataset_disassociate(rdataset);
3001                         continue;
3002                 }
3003                 for (rdata = ISC_LIST_HEAD(rdatalist->rdata);
3004                      rdata != NULL;
3005                      rdata = ISC_LIST_HEAD(rdatalist->rdata))
3006                         ISC_LIST_UNLINK(rdatalist->rdata, rdata, link);
3007                 dns_rdataset_disassociate(rdataset);
3008         }
3009
3010         if ((name->attributes & DNS_NAMEATTR_HASUPDATEREC) != 0) {
3011                 updaterec = (dns_client_updaterec_t *)name->buffer;
3012                 INSIST(updaterec != NULL);
3013                 isc_mem_putanddetach(&updaterec->mctx, updaterec,
3014                                      updaterec->size);
3015                 *namep = NULL;
3016         }
3017 }