]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - pythonmod/interface.i
import unbound 1.6.0
[FreeBSD/FreeBSD.git] / pythonmod / interface.i
1 /*
2  * interface.i: unbound python module
3  */
4 %module unboundmodule
5 %{
6 /**
7  * \file 
8  * This is the interface between the unbound server and a python module
9  * called to perform operations on queries.
10  */
11    #include <sys/types.h>
12    #include <sys/socket.h>
13    #include <netinet/in.h>
14    #include <arpa/inet.h>
15    #include <stdarg.h>
16    #include "config.h"
17    #include "util/log.h"
18    #include "util/module.h"
19    #include "util/netevent.h"
20    #include "util/regional.h"
21    #include "util/config_file.h"
22    #include "util/data/msgreply.h"
23    #include "util/data/packed_rrset.h"
24    #include "util/data/dname.h"
25    #include "util/storage/lruhash.h"
26    #include "services/cache/dns.h"
27    #include "services/mesh.h"
28    #include "iterator/iter_delegpt.h"
29    #include "iterator/iter_hints.h"
30    #include "iterator/iter_utils.h"
31    #include "sldns/wire2str.h"
32    #include "sldns/str2wire.h"
33    #include "sldns/pkthdr.h"
34 %}
35
36 %include "stdint.i"  /* uint_16_t can be known type now */
37
38 %inline %{
39    /* converts [len][data][len][data][0] string to a List of labels (PyBytes) */
40    PyObject* GetNameAsLabelList(const char* name, int len) {
41      PyObject* list;
42      int cnt=0, i;
43
44      i = 0;
45      while (i < len) {
46         i += name[i] + 1;
47         cnt++;
48      }
49
50      list = PyList_New(cnt);
51      i = 0; cnt = 0;
52      while (i < len) {
53         PyList_SetItem(list, cnt, PyBytes_FromStringAndSize(name + i + 1, name[i]));
54         i += name[i] + 1;
55         cnt++;
56      }
57      return list;
58    }
59 %}
60
61 /* ************************************************************************************ * 
62    Structure query_info
63  * ************************************************************************************ */
64 /* Query info */
65 %ignore query_info::qname;
66 %ignore query_info::qname_len;
67
68
69 struct query_info {
70    %immutable;
71    char* qname;
72    size_t qname_len;
73    uint16_t qtype;
74    uint16_t qclass;
75    %mutable;
76 };
77
78 %inline %{
79    enum enum_rr_class  { 
80       RR_CLASS_IN = 1,
81       RR_CLASS_CH = 3,
82       RR_CLASS_HS = 4,
83       RR_CLASS_NONE = 254,
84       RR_CLASS_ANY = 255,
85    };
86    
87    enum enum_rr_type {
88       RR_TYPE_A = 1, 
89       RR_TYPE_NS = 2, 
90       RR_TYPE_MD = 3, 
91       RR_TYPE_MF = 4, 
92       RR_TYPE_CNAME = 5, 
93       RR_TYPE_SOA = 6, 
94       RR_TYPE_MB = 7, 
95       RR_TYPE_MG = 8, 
96       RR_TYPE_MR = 9, 
97       RR_TYPE_NULL = 10,
98       RR_TYPE_WKS = 11,
99       RR_TYPE_PTR = 12,
100       RR_TYPE_HINFO = 13,
101       RR_TYPE_MINFO = 14,
102       RR_TYPE_MX = 15,
103       RR_TYPE_TXT = 16,
104       RR_TYPE_RP = 17,
105       RR_TYPE_AFSDB = 18,
106       RR_TYPE_X25 = 19,
107       RR_TYPE_ISDN = 20,
108       RR_TYPE_RT = 21,
109       RR_TYPE_NSAP = 22,
110       RR_TYPE_NSAP_PTR = 23,
111       RR_TYPE_SIG = 24,
112       RR_TYPE_KEY = 25,
113       RR_TYPE_PX = 26,
114       RR_TYPE_GPOS = 27,
115       RR_TYPE_AAAA = 28,
116       RR_TYPE_LOC = 29,
117       RR_TYPE_NXT = 30,
118       RR_TYPE_EID = 31,
119       RR_TYPE_NIMLOC = 32,
120       RR_TYPE_SRV = 33,
121       RR_TYPE_ATMA = 34,
122       RR_TYPE_NAPTR = 35,
123       RR_TYPE_KX = 36,
124       RR_TYPE_CERT = 37,
125       RR_TYPE_A6 = 38,
126       RR_TYPE_DNAME = 39,
127       RR_TYPE_SINK = 40,
128       RR_TYPE_OPT = 41,
129       RR_TYPE_APL = 42,
130       RR_TYPE_DS = 43,
131       RR_TYPE_SSHFP = 44,
132       RR_TYPE_IPSECKEY = 45,
133       RR_TYPE_RRSIG = 46,
134       RR_TYPE_NSEC = 47,      
135       RR_TYPE_DNSKEY = 48,
136       RR_TYPE_DHCID = 49,
137       RR_TYPE_NSEC3 = 50,
138       RR_TYPE_NSEC3PARAMS = 51,
139       RR_TYPE_UINFO = 100,
140       RR_TYPE_UID = 101,
141       RR_TYPE_GID = 102,
142       RR_TYPE_UNSPEC = 103,
143       RR_TYPE_TSIG = 250,
144       RR_TYPE_IXFR = 251,
145       RR_TYPE_AXFR = 252,
146       RR_TYPE_MAILB = 253,
147       RR_TYPE_MAILA = 254,
148       RR_TYPE_ANY = 255,
149       RR_TYPE_DLV = 32769,
150    };
151
152    PyObject* _get_qname(struct query_info* q) {
153       return PyBytes_FromStringAndSize((char*)q->qname, q->qname_len);
154    } 
155
156    PyObject* _get_qname_components(struct query_info* q) {
157       return GetNameAsLabelList((const char*)q->qname, q->qname_len);
158    }
159 %}
160
161 %inline %{
162    PyObject* dnameAsStr(const char* dname) {
163        char buf[LDNS_MAX_DOMAINLEN+1];
164        buf[0] = '\0';
165        dname_str((uint8_t*)dname, buf);
166        return PyBytes_FromString(buf);
167    }
168 %}
169
170 %extend query_info {
171    %pythoncode %{
172         def _get_qtype_str(self): return sldns_wire2str_type(self.qtype)
173         __swig_getmethods__["qtype_str"] = _get_qtype_str
174         if _newclass:qtype_str = _swig_property(_get_qtype_str)
175
176         def _get_qclass_str(self): return sldns_wire2str_class(self.qclass)
177         __swig_getmethods__["qclass_str"] = _get_qclass_str
178         if _newclass:qclass_str = _swig_property(_get_qclass_str)
179
180         __swig_getmethods__["qname"] = _unboundmodule._get_qname
181         if _newclass:qname = _swig_property(_unboundmodule._get_qname)
182         
183         __swig_getmethods__["qname_list"] = _unboundmodule._get_qname_components
184         if _newclass:qname_list = _swig_property(_unboundmodule._get_qname_components)
185
186         def _get_qname_str(self): return dnameAsStr(self.qname)
187         __swig_getmethods__["qname_str"] = _get_qname_str
188         if _newclass:qname_str = _swig_property(_get_qname_str)
189    %}
190 }
191
192 /* ************************************************************************************ * 
193    Structure packed_rrset_key
194  * ************************************************************************************ */
195 %ignore packed_rrset_key::dname;
196 %ignore packed_rrset_key::dname_len;
197
198 /* RRsets */
199 struct packed_rrset_key {
200    %immutable;
201    char*    dname;
202    size_t   dname_len;
203    uint32_t flags; 
204    uint16_t type;  /* rrset type in network format */
205    uint16_t rrset_class;  /* rrset class in network format */
206    %mutable;
207 };
208
209 /**
210  * This subroutine converts values between the host and network byte order.
211  * Specifically, ntohs() converts 16-bit quantities from network byte order to
212  * host byte order.
213  */
214 uint16_t ntohs(uint16_t netshort);
215
216 %inline %{
217    PyObject* _get_dname(struct packed_rrset_key* k) {
218       return PyBytes_FromStringAndSize((char*)k->dname, k->dname_len);
219    } 
220    PyObject* _get_dname_components(struct packed_rrset_key* k) {
221       return GetNameAsLabelList((char*)k->dname, k->dname_len);
222    }
223 %}
224
225 %extend packed_rrset_key {
226    %pythoncode %{
227         def _get_type_str(self): return sldns_wire2str_type(_unboundmodule.ntohs(self.type))
228         __swig_getmethods__["type_str"] = _get_type_str
229         if _newclass:type_str = _swig_property(_get_type_str)
230
231         def _get_class_str(self): return sldns_wire2str_class(_unboundmodule.ntohs(self.rrset_class))
232         __swig_getmethods__["rrset_class_str"] = _get_class_str
233         if _newclass:rrset_class_str = _swig_property(_get_class_str)
234
235         __swig_getmethods__["dname"] = _unboundmodule._get_dname
236         if _newclass:dname = _swig_property(_unboundmodule._get_dname)
237
238         __swig_getmethods__["dname_list"] = _unboundmodule._get_dname_components
239         if _newclass:dname_list = _swig_property(_unboundmodule._get_dname_components)
240
241         def _get_dname_str(self): return dnameAsStr(self.dname)
242         __swig_getmethods__["dname_str"] = _get_dname_str
243         if _newclass:dname_str = _swig_property(_get_dname_str)
244    %}
245 }
246
247 #if defined(SWIGWORDSIZE64) 
248 typedef long int                rrset_id_t;
249 #else 
250 typedef long long int           rrset_id_t;
251 #endif 
252
253 struct ub_packed_rrset_key {
254    struct lruhash_entry entry;
255    rrset_id_t id;
256    struct packed_rrset_key rk;
257 };
258
259 struct lruhash_entry {
260   lock_rw_t lock;
261   struct lruhash_entry* overflow_next;
262   struct lruhash_entry* lru_next;
263   struct lruhash_entry* lru_prev;
264   hashvalue_t hash;
265   void* key;
266   struct packed_rrset_data* data;
267 };
268
269 %ignore packed_rrset_data::rr_len;
270 %ignore packed_rrset_data::rr_ttl;
271 %ignore packed_rrset_data::rr_data;
272
273 struct packed_rrset_data {
274   /* TTL (in seconds like time()) */
275   uint32_t ttl;
276
277   /* number of rrs */
278   size_t count;
279   /* number of rrsigs */
280   size_t rrsig_count;
281
282   enum rrset_trust trust; 
283   enum sec_status security;
284
285   /* length of every rr's rdata */
286   size_t* rr_len;
287   /* ttl of every rr */
288   uint32_t *rr_ttl;
289   /* array of pointers to every rr's rdata. The rr_data[i] rdata is stored in
290    * uncompressed wireformat. */
291   uint8_t** rr_data;
292 };
293
294 %pythoncode %{
295     class RRSetData_RRLen:
296         def __init__(self, obj): self.obj = obj
297         def __getitem__(self, index): return _unboundmodule._get_data_rr_len(self.obj, index)
298         def __len__(self): return obj.count + obj.rrsig_count
299     class RRSetData_RRTTL:
300         def __init__(self, obj): self.obj = obj
301         def __getitem__(self, index): return _unboundmodule._get_data_rr_ttl(self.obj, index)
302         def __setitem__(self, index, value): _unboundmodule._set_data_rr_ttl(self.obj, index, value)
303         def __len__(self): return obj.count + obj.rrsig_count
304     class RRSetData_RRData:
305         def __init__(self, obj): self.obj = obj
306         def __getitem__(self, index): return _unboundmodule._get_data_rr_data(self.obj, index)
307         def __len__(self): return obj.count + obj.rrsig_count
308 %}
309
310 %inline %{
311    PyObject* _get_data_rr_len(struct packed_rrset_data* d, int idx) {
312      if ((d != NULL) && (idx >= 0) && 
313              ((size_t)idx < (d->count+d->rrsig_count))) 
314         return PyInt_FromLong(d->rr_len[idx]);
315      return Py_None;
316    }
317    void _set_data_rr_ttl(struct packed_rrset_data* d, int idx, uint32_t ttl)
318    {
319      if ((d != NULL) && (idx >= 0) && 
320              ((size_t)idx < (d->count+d->rrsig_count))) 
321         d->rr_ttl[idx] = ttl;
322    }
323    PyObject* _get_data_rr_ttl(struct packed_rrset_data* d, int idx) {
324      if ((d != NULL) && (idx >= 0) && 
325              ((size_t)idx < (d->count+d->rrsig_count))) 
326         return PyInt_FromLong(d->rr_ttl[idx]);
327      return Py_None;
328    }
329    PyObject* _get_data_rr_data(struct packed_rrset_data* d, int idx) {
330      if ((d != NULL) && (idx >= 0) && 
331              ((size_t)idx < (d->count+d->rrsig_count))) 
332         return PyBytes_FromStringAndSize((char*)d->rr_data[idx],
333                 d->rr_len[idx]);
334      return Py_None;
335    }
336 %}
337
338 %extend packed_rrset_data {
339    %pythoncode %{
340         def _get_data_rr_len(self): return RRSetData_RRLen(self)
341         __swig_getmethods__["rr_len"] = _get_data_rr_len
342         if _newclass:rr_len = _swig_property(_get_data_rr_len)
343         def _get_data_rr_ttl(self): return RRSetData_RRTTL(self)
344         __swig_getmethods__["rr_ttl"] =_get_data_rr_ttl
345         if _newclass:rr_len = _swig_property(_get_data_rr_ttl)
346         def _get_data_rr_data(self): return RRSetData_RRData(self)
347         __swig_getmethods__["rr_data"] = _get_data_rr_data
348         if _newclass:rr_len = _swig_property(_get_data_rr_data)
349    %}
350 }
351
352 /* ************************************************************************************ * 
353    Structure reply_info
354  * ************************************************************************************ */
355 /* Messages */
356 %ignore reply_info::rrsets;
357 %ignore reply_info::ref;
358
359 struct reply_info {
360    uint16_t flags;
361    uint16_t qdcount;
362    uint32_t ttl;
363    uint32_t prefetch_ttl;
364
365    uint16_t authoritative;
366    enum sec_status security;
367
368    size_t an_numrrsets;
369    size_t ns_numrrsets;
370    size_t ar_numrrsets;
371    size_t rrset_count;  /* an_numrrsets + ns_numrrsets + ar_numrrsets */
372
373    struct ub_packed_rrset_key** rrsets;
374    struct rrset_ref ref[1];  /* ? */
375 };
376
377 struct rrset_ref {
378    struct ub_packed_rrset_key* key;
379    rrset_id_t id;
380 };
381
382 struct dns_msg {
383    struct query_info qinfo;
384    struct reply_info *rep;
385 };
386
387 %pythoncode %{
388     class ReplyInfo_RRSet:
389         def __init__(self, obj): self.obj = obj
390         def __getitem__(self, index): return _unboundmodule._rrset_rrsets_get(self.obj, index)
391         def __len__(self): return obj.rrset_count
392
393     class ReplyInfo_Ref:
394         def __init__(self, obj): self.obj = obj
395         def __getitem__(self, index): return _unboundmodule._rrset_ref_get(self.obj, index)
396         def __len__(self): return obj.rrset_count
397 %}
398
399 %inline %{
400    struct ub_packed_rrset_key* _rrset_rrsets_get(struct reply_info* r, int idx) {
401      if ((r != NULL) && (idx >= 0) && ((size_t)idx < r->rrset_count))
402         return r->rrsets[idx];
403      return NULL;
404    }
405
406    struct rrset_ref* _rrset_ref_get(struct reply_info* r, int idx) {
407      if ((r != NULL) && (idx >= 0) && ((size_t)idx < r->rrset_count)) {
408 /* printf("_rrset_ref_get: %lX key:%lX\n", r->ref + idx, r->ref[idx].key); */
409              return &(r->ref[idx]);
410 /*        return &(r->ref[idx]); */
411      }
412 /* printf("_rrset_ref_get: NULL\n"); */
413      return NULL;
414    }
415 %}
416
417 %extend reply_info {
418    %pythoncode %{
419         def _rrset_ref_get(self): return ReplyInfo_Ref(self)
420         __swig_getmethods__["ref"] = _rrset_ref_get
421         if _newclass:ref = _swig_property(_rrset_ref_get)
422
423         def _rrset_rrsets_get(self): return ReplyInfo_RRSet(self)
424         __swig_getmethods__["rrsets"] = _rrset_rrsets_get
425         if _newclass:rrsets = _swig_property(_rrset_rrsets_get)
426    %}
427 }
428
429 /* ************************************************************************************ * 
430    Structure mesh_state
431  * ************************************************************************************ */
432 struct mesh_state {
433    struct mesh_reply* reply_list;
434 };
435
436 struct mesh_reply {
437    struct mesh_reply* next;
438    struct comm_reply query_reply;
439 };
440
441 struct comm_reply {
442    
443 };
444
445 %inline %{
446
447   PyObject* _comm_reply_addr_get(struct comm_reply* reply) {
448      char dest[64];
449      reply_addr2str(reply, dest, 64);
450      if (dest[0] == 0)
451         return Py_None;
452      return PyBytes_FromString(dest);
453   }
454
455   PyObject* _comm_reply_family_get(struct comm_reply* reply) {
456
457         int af = (int)((struct sockaddr_in*) &(reply->addr))->sin_family;
458
459         switch(af) {
460            case AF_INET: return PyBytes_FromString("ip4");
461            case AF_INET6: return PyBytes_FromString("ip6");
462            case AF_UNIX: return PyBytes_FromString("unix");
463         }
464
465         return Py_None;
466   }
467
468   PyObject* _comm_reply_port_get(struct comm_reply* reply) {
469      uint16_t port;
470      port = ntohs(((struct sockaddr_in*)&(reply->addr))->sin_port);
471      return PyInt_FromLong(port);
472   }
473
474 %}
475
476 %extend comm_reply {
477    %pythoncode %{
478         def _addr_get(self): return _comm_reply_addr_get(self)
479         __swig_getmethods__["addr"] = _addr_get
480         if _newclass:addr = _swig_property(_addr_get)
481
482         def _port_get(self): return _comm_reply_port_get(self)
483         __swig_getmethods__["port"] = _port_get
484         if _newclass:port = _swig_property(_port_get)
485
486         def _family_get(self): return _comm_reply_family_get(self)
487         __swig_getmethods__["family"] = _family_get
488         if _newclass:family = _swig_property(_family_get)
489    %}
490 }
491
492 /* ************************************************************************************ * 
493    Structure edns_option
494  * ************************************************************************************ */
495 /* Rename the members to follow the python convention of marking them as
496  * private. Access to the opt_code and opt_data members is given by the later
497  * python defined code and data members respectively. */
498 %rename(_next) edns_option::next;
499 %rename(_opt_code) edns_option::opt_code;
500 %rename(_opt_len) edns_option::opt_len;
501 %rename(_opt_data) edns_option::opt_data;
502 struct edns_option {
503         struct edns_option* next;
504         uint16_t opt_code;
505         size_t opt_len;
506         uint8_t* opt_data;
507 };
508
509 %inline %{
510     PyObject* _edns_option_opt_code_get(struct edns_option* option) {
511         uint16_t opt_code = option->opt_code;
512         return PyInt_FromLong(opt_code);
513     }
514
515     PyObject* _edns_option_opt_data_get(struct edns_option* option) {
516         return PyByteArray_FromStringAndSize((uint8_t*)option->opt_data,
517             option->opt_len);
518     }
519 %}
520 %extend edns_option {
521     %pythoncode %{
522         def _opt_code_get(self): return _edns_option_opt_code_get(self)
523         __swig_getmethods__["code"] = _opt_code_get
524         if _newclass: opt_code = _swig_property(_opt_code_get)
525
526         def _opt_data_get(self): return _edns_option_opt_data_get(self)
527         __swig_getmethods__["data"] = _opt_data_get
528         if _newclass: opt_data = _swig_property(_opt_data_get)
529     %}
530 }
531
532 /* ************************************************************************************ * 
533    Structure edns_data
534  * ************************************************************************************ */
535 /* This is ignored because we will pass a double pointer of this to Python
536  * with custom getmethods. This is done to bypass Swig's behavior to pass NULL
537  * pointers as None. */
538 %ignore edns_data::opt_list;
539 struct edns_data {
540         int edns_present;
541         uint8_t ext_rcode;
542         uint8_t edns_version;
543         uint16_t bits;
544         uint16_t udp_size;
545         struct edns_option* opt_list;
546 };
547 %inline %{
548     struct edns_option** _edns_data_opt_list_get(struct edns_data* edns) {
549        return &edns->opt_list;
550     }
551 %}
552 %extend edns_data {
553     %pythoncode %{
554         def _opt_list_iter(self): return EdnsOptsListIter(self.opt_list)
555         __swig_getmethods__["opt_list_iter"] = _opt_list_iter
556         if _newclass:opt_list_iter = _swig_property(_opt_list_iter)
557         def _opt_list(self): return _edns_data_opt_list_get(self)
558         __swig_getmethods__["opt_list"] = _opt_list
559         if _newclass:opt_list = _swig_property(_opt_list)
560     %}
561 }
562
563 /* ************************************************************************************ *
564    Structure module_env
565  * ************************************************************************************ */
566 struct module_env {
567         struct config_file* cfg;
568         struct slabhash* msg_cache;
569         struct rrset_cache* rrset_cache;
570         struct infra_cache* infra_cache;
571         struct key_cache* key_cache;
572
573         /* --- services --- */
574         struct outbound_entry* (*send_query)(struct query_info* qinfo,
575                 uint16_t flags, int dnssec, int want_dnssec, int nocaps,
576                 struct sockaddr_storage* addr, socklen_t addrlen,
577                 uint8_t* zone, size_t zonelen, int ssl_upstream,
578                 struct module_qstate* q);
579         void (*detach_subs)(struct module_qstate* qstate);
580         int (*attach_sub)(struct module_qstate* qstate, 
581                 struct query_info* qinfo, uint16_t qflags, int prime, 
582                 int valrec, struct module_qstate** newq);
583         void (*kill_sub)(struct module_qstate* newq);
584         int (*detect_cycle)(struct module_qstate* qstate, 
585                 struct query_info* qinfo, uint16_t flags, int prime,
586                 int valrec);
587
588         struct regional* scratch;
589         struct sldns_buffer* scratch_buffer;
590         struct worker* worker;
591         struct mesh_area* mesh;
592         struct alloc_cache* alloc;
593         struct ub_randstate* rnd;
594         time_t* now;
595         struct timeval* now_tv;
596         int need_to_validate;
597         struct val_anchors* anchors;
598         struct val_neg_cache* neg_cache;
599         struct comm_timer* probe_timer;
600         struct iter_forwards* fwds;
601         struct iter_hints* hints;
602         void* modinfo[MAX_MODULE];
603
604         void* inplace_cb_lists[inplace_cb_types_total];
605         struct edns_known_option* edns_known_options;
606         size_t edns_known_options_num;
607 };
608
609
610 /* ************************************************************************************ *
611    Structure module_qstate
612  * ************************************************************************************ */
613 %ignore module_qstate::ext_state;
614 %ignore module_qstate::minfo;
615
616 /* These are ignored because we will pass a double pointer of them to Python
617  * with custom getmethods. This is done to bypass Swig's behavior to pass NULL
618  * pointers as None. */
619 %ignore module_qstate::edns_opts_front_in;
620 %ignore module_qstate::edns_opts_back_out;
621 %ignore module_qstate::edns_opts_back_in;
622 %ignore module_qstate::edns_opts_front_out;
623
624 /* Query state */
625 struct module_qstate {
626    struct query_info qinfo;
627    uint16_t query_flags;  /* See QF_BIT_xx constants */
628    int is_priming;
629    int is_valrec;
630
631    struct comm_reply* reply;
632    struct dns_msg* return_msg;
633    int return_rcode;
634    struct regional* region; /* unwrapped */
635
636    int curmod;
637
638    enum module_ext_state ext_state[MAX_MODULE];
639    void* minfo[MAX_MODULE];
640    time_t prefetch_leeway;
641
642    struct module_env* env;         /* unwrapped */
643    struct mesh_state* mesh_info;
644
645    struct edns_option* edns_opts_front_in;
646    struct edns_option* edns_opts_back_out;
647    struct edns_option* edns_opts_back_in;
648    struct edns_option* edns_opts_front_out;
649    int no_cache_lookup;
650    int no_cache_store;
651 };
652
653 %constant int MODULE_COUNT = MAX_MODULE;
654
655 %constant int QF_BIT_CD = 0x0010;
656 %constant int QF_BIT_AD = 0x0020;
657 %constant int QF_BIT_Z  = 0x0040;
658 %constant int QF_BIT_RA = 0x0080;
659 %constant int QF_BIT_RD = 0x0100;
660 %constant int QF_BIT_TC = 0x0200;
661 %constant int QF_BIT_AA = 0x0400;
662 %constant int QF_BIT_QR = 0x8000;
663
664 %inline %{
665  enum enum_return_rcode {
666    RCODE_NOERROR = 0,
667    RCODE_FORMERR = 1,
668    RCODE_SERVFAIL = 2,
669    RCODE_NXDOMAIN = 3,
670    RCODE_NOTIMPL = 4,
671    RCODE_REFUSED = 5,
672    RCODE_YXDOMAIN = 6,
673    RCODE_YXRRSET = 7,
674    RCODE_NXRRSET = 8,
675    RCODE_NOTAUTH = 9,
676    RCODE_NOTZONE = 10
677  };
678 %}
679
680 %pythoncode %{
681     class ExtState:
682         def __init__(self, obj): self.obj = obj
683         def __str__(self):
684             return ", ".join([_unboundmodule.strextstate(_unboundmodule._ext_state_get(self.obj,a)) for a in range(0, _unboundmodule.MODULE_COUNT)])
685         def __getitem__(self, index): return _unboundmodule._ext_state_get(self.obj, index)
686         def __setitem__(self, index, value): _unboundmodule._ext_state_set(self.obj, index, value)
687         def __len__(self): return _unboundmodule.MODULE_COUNT
688
689     class EdnsOptsListIter:
690         def __init__(self, obj):
691             self._current = obj
692             self._temp = None
693         def __iter__(self): return self
694         def __next__(self):
695             """Python 3 compatibility"""
696             return self._get_next()
697         def next(self):
698             """Python 2 compatibility"""
699             return self._get_next()
700         def _get_next(self):
701             if not edns_opt_list_is_empty(self._current):
702                 self._temp = self._current
703                 self._current = _p_p_edns_option_get_next(self._current)
704                 return _dereference_edns_option(self._temp)
705             else:
706                 raise StopIteration
707 %}
708
709 %inline %{
710    enum module_ext_state _ext_state_get(struct module_qstate* q, int idx) {
711      if ((q != NULL) && (idx >= 0) && (idx < MAX_MODULE)) {
712         return q->ext_state[idx];
713      } 
714      return 0;
715    }
716
717    void _ext_state_set(struct module_qstate* q, int idx, enum module_ext_state state) {
718      if ((q != NULL) && (idx >= 0) && (idx < MAX_MODULE)) {
719         q->ext_state[idx] = state;
720      } 
721    }
722
723    int edns_opt_list_is_empty(struct edns_option** opt) {
724         if (!opt || !(*opt)) return 1;
725         return 0;
726    }
727
728    struct edns_option* _dereference_edns_option(struct edns_option** opt) {
729         if (!opt) return NULL;
730         return *opt;
731    }
732
733    struct edns_option** _p_p_edns_option_get_next(struct edns_option** opt) {
734         return &(*opt)->next;
735    }
736
737    struct edns_option** _edns_opts_front_in_get(struct module_qstate* q) {
738         return &q->edns_opts_front_in;
739    }
740
741    struct edns_option** _edns_opts_back_out_get(struct module_qstate* q) {
742         return &q->edns_opts_back_out;
743    }
744
745    struct edns_option** _edns_opts_back_in_get(struct module_qstate* q) {
746         return &q->edns_opts_back_in;
747    }
748
749    struct edns_option** _edns_opts_front_out_get(struct module_qstate* q) {
750         return &q->edns_opts_front_out;
751    }
752 %}
753
754 %extend module_qstate {
755    %pythoncode %{
756         def set_ext_state(self, id, state):
757             """Sets the ext state"""
758             _unboundmodule._ext_state_set(self, id, state)
759
760         def __ext_state_get(self): return ExtState(self)
761         __swig_getmethods__["ext_state"] = __ext_state_get
762         if _newclass:ext_state = _swig_property(__ext_state_get)#, __ext_state_set)
763
764         def _edns_opts_front_in_iter(self): return EdnsOptsListIter(self.edns_opts_front_in)
765         __swig_getmethods__["edns_opts_front_in_iter"] = _edns_opts_front_in_iter
766         if _newclass:edns_opts_front_in_iter = _swig_property(_edns_opts_front_in_iter)
767         def _edns_opts_back_out_iter(self): return EdnsOptsListIter(self.edns_opts_back_out)
768         __swig_getmethods__["edns_opts_back_out_iter"] = _edns_opts_back_out_iter
769         if _newclass:edns_opts_back_out_iter = _swig_property(_edns_opts_back_out_iter)
770         def _edns_opts_back_in_iter(self): return EdnsOptsListIter(self.edns_opts_back_in)
771         __swig_getmethods__["edns_opts_back_in_iter"] = _edns_opts_back_in_iter
772         if _newclass:edns_opts_back_in_iter = _swig_property(_edns_opts_back_in_iter)
773         def _edns_opts_front_out_iter(self): return EdnsOptsListIter(self.edns_opts_front_out)
774         __swig_getmethods__["edns_opts_front_out_iter"] = _edns_opts_front_out_iter
775         if _newclass:edns_opts_front_out_iter = _swig_property(_edns_opts_front_out_iter)
776
777         def _edns_opts_front_in(self): return _edns_opts_front_in_get(self)
778         __swig_getmethods__["edns_opts_front_in"] = _edns_opts_front_in
779         if _newclass:edns_opts_front_in = _swig_property(_edns_opts_front_in)
780         def _edns_opts_back_out(self): return _edns_opts_back_out_get(self)
781         __swig_getmethods__["edns_opts_back_out"] = _edns_opts_back_out
782         if _newclass:edns_opts_back_out = _swig_property(_edns_opts_back_out)
783         def _edns_opts_back_in(self): return _edns_opts_back_in_get(self)
784         __swig_getmethods__["edns_opts_back_in"] = _edns_opts_back_in
785         if _newclass:edns_opts_back_in = _swig_property(_edns_opts_back_in)
786         def _edns_opts_front_out(self): return _edns_opts_front_out_get(self)
787         __swig_getmethods__["edns_opts_front_out"] = _edns_opts_front_out
788         if _newclass:edns_opts_front_out = _swig_property(_edns_opts_front_out)
789    %}
790 }
791
792 /* ************************************************************************************ * 
793    Structure config_strlist
794  * ************************************************************************************ */
795 struct config_strlist {
796    struct config_strlist* next;
797    char* str;
798 };
799
800 /* ************************************************************************************ * 
801    Structure config_str2list
802  * ************************************************************************************ */
803 struct config_str2list {
804    struct config_str2list* next;
805    char* str;
806    char* str2;
807 };
808
809 /* ************************************************************************************ * 
810    Structure config_file
811  * ************************************************************************************ */
812 struct config_file {
813    int verbosity;
814    int stat_interval;
815    int stat_cumulative;
816    int stat_extended;
817    int num_threads;
818    int port;
819    int do_ip4;
820    int do_ip6;
821    int do_udp;
822    int do_tcp;
823    int outgoing_num_ports;
824    size_t outgoing_num_tcp;
825    size_t incoming_num_tcp;
826    int* outgoing_avail_ports;
827    size_t msg_buffer_size;
828    size_t msg_cache_size;
829    size_t msg_cache_slabs;
830    size_t num_queries_per_thread;
831    size_t jostle_time;
832    size_t rrset_cache_size;
833    size_t rrset_cache_slabs;
834    int host_ttl;
835    size_t infra_cache_slabs;
836    size_t infra_cache_numhosts;
837    char* target_fetch_policy;
838    int if_automatic;
839    int num_ifs;
840    char **ifs;
841    int num_out_ifs;
842    char **out_ifs;
843    struct config_strlist* root_hints;
844    struct config_stub* stubs;
845    struct config_stub* forwards;
846    struct config_strlist* donotqueryaddrs;
847    struct config_str2list* acls;
848    int donotquery_localhost;
849    int harden_short_bufsize;
850    int harden_large_queries;
851    int harden_glue;
852    int harden_dnssec_stripped;
853    int harden_referral_path;
854    int use_caps_bits_for_id;
855    struct config_strlist* private_address;
856    struct config_strlist* private_domain;
857    size_t unwanted_threshold;
858    char* chrootdir;
859    char* username;
860    char* directory;
861    char* logfile;
862    char* pidfile;
863    int use_syslog;
864    int hide_identity;
865    int hide_version;
866    char* identity;
867    char* version;
868    char* module_conf;
869    struct config_strlist* trust_anchor_file_list;
870    struct config_strlist* trust_anchor_list;
871    struct config_strlist* trusted_keys_file_list;
872    char* dlv_anchor_file;
873    struct config_strlist* dlv_anchor_list;
874    int max_ttl;
875    int32_t val_date_override;
876    int bogus_ttl; 
877    int val_clean_additional;
878    int val_permissive_mode;
879    char* val_nsec3_key_iterations;
880    size_t key_cache_size;
881    size_t key_cache_slabs;
882    size_t neg_cache_size;
883    struct config_str2list* local_zones;
884    struct config_strlist* local_zones_nodefault;
885    struct config_strlist* local_data;
886    int remote_control_enable;
887    struct config_strlist* control_ifs;
888    int control_port;
889    char* server_key_file;
890    char* server_cert_file;
891    char* control_key_file;
892    char* control_cert_file;
893    int do_daemonize;
894    char* python_script;
895 };
896
897 /* ************************************************************************************ * 
898    ASN: Adding structures related to forwards_lookup and dns_cache_find_delegation
899  * ************************************************************************************ */
900 struct delegpt_ns {
901     struct delegpt_ns* next;
902     int resolved;
903     uint8_t got4;
904     uint8_t got6;
905     uint8_t lame;
906     uint8_t done_pside4;
907     uint8_t done_pside6;
908 };
909
910 struct delegpt_addr {
911     struct delegpt_addr* next_result;
912     struct delegpt_addr* next_usable;
913     struct delegpt_addr* next_target;
914     int attempts;
915     int sel_rtt;
916     int bogus;
917     int lame;
918 };
919
920 struct delegpt {
921     int namelabs;
922     struct delegpt_ns* nslist;
923     struct delegpt_addr* target_list;
924     struct delegpt_addr* usable_list;
925     struct delegpt_addr* result_list;
926     int bogus;
927     uint8_t has_parent_side_NS;
928     uint8_t dp_type_mlc;
929 };
930
931
932 %inline %{
933    PyObject* _get_dp_dname(struct delegpt* dp) {
934       return PyBytes_FromStringAndSize((char*)dp->name, dp->namelen);
935    } 
936    PyObject* _get_dp_dname_components(struct delegpt* dp) {
937       return GetNameAsLabelList((char*)dp->name, dp->namelen);
938    }
939    PyObject* _get_dpns_dname(struct delegpt_ns* dpns) {
940       return PyBytes_FromStringAndSize((char*)dpns->name, dpns->namelen);
941    }
942    PyObject* _get_dpns_dname_components(struct delegpt_ns* dpns) {
943       return GetNameAsLabelList((char*)dpns->name, dpns->namelen);
944    }
945
946   PyObject* _delegpt_addr_addr_get(struct delegpt_addr* target) {
947      char dest[64];
948      delegpt_addr_addr2str(target, dest, 64);
949      if (dest[0] == 0)
950         return Py_None;
951      return PyBytes_FromString(dest);
952   }
953
954 %}
955
956 %extend delegpt {
957    %pythoncode %{
958         __swig_getmethods__["dname"] = _unboundmodule._get_dp_dname
959         if _newclass:dname = _swig_property(_unboundmodule._get_dp_dname)
960
961         __swig_getmethods__["dname_list"] = _unboundmodule._get_dp_dname_components
962         if _newclass:dname_list = _swig_property(_unboundmodule._get_dp_dname_components)
963
964         def _get_dname_str(self): return dnameAsStr(self.dname)
965         __swig_getmethods__["dname_str"] = _get_dname_str
966         if _newclass:dname_str = _swig_property(_get_dname_str)
967    %}
968 }
969 %extend delegpt_ns {
970    %pythoncode %{
971         __swig_getmethods__["dname"] = _unboundmodule._get_dpns_dname
972         if _newclass:dname = _swig_property(_unboundmodule._get_dpns_dname)
973
974         __swig_getmethods__["dname_list"] = _unboundmodule._get_dpns_dname_components
975         if _newclass:dname_list = _swig_property(_unboundmodule._get_dpns_dname_components)
976
977         def _get_dname_str(self): return dnameAsStr(self.dname)
978         __swig_getmethods__["dname_str"] = _get_dname_str
979         if _newclass:dname_str = _swig_property(_get_dname_str)
980    %}
981 }
982 %extend delegpt_addr {
983    %pythoncode %{
984         def _addr_get(self): return _delegpt_addr_addr_get(self)
985         __swig_getmethods__["addr"] = _addr_get
986         if _newclass:addr = _swig_property(_addr_get)
987    %}
988 }
989
990 /* ************************************************************************************ * 
991    Enums
992  * ************************************************************************************ */
993 %rename ("MODULE_STATE_INITIAL") "module_state_initial";
994 %rename ("MODULE_WAIT_REPLY") "module_wait_reply";
995 %rename ("MODULE_WAIT_MODULE") "module_wait_module";
996 %rename ("MODULE_WAIT_SUBQUERY") "module_wait_subquery";
997 %rename ("MODULE_ERROR") "module_error";
998 %rename ("MODULE_FINISHED") "module_finished";
999
1000 enum module_ext_state {
1001    module_state_initial = 0,
1002    module_wait_reply,
1003    module_wait_module,
1004    module_wait_subquery,
1005    module_error,
1006    module_finished
1007 };
1008
1009 %rename ("MODULE_EVENT_NEW") "module_event_new";
1010 %rename ("MODULE_EVENT_PASS") "module_event_pass";
1011 %rename ("MODULE_EVENT_REPLY") "module_event_reply";
1012 %rename ("MODULE_EVENT_NOREPLY") "module_event_noreply";
1013 %rename ("MODULE_EVENT_CAPSFAIL") "module_event_capsfail";
1014 %rename ("MODULE_EVENT_MODDONE") "module_event_moddone";
1015 %rename ("MODULE_EVENT_ERROR") "module_event_error";
1016
1017 enum module_ev {
1018    module_event_new = 0,
1019    module_event_pass,
1020    module_event_reply,
1021    module_event_noreply,
1022    module_event_capsfail,
1023    module_event_moddone,
1024    module_event_error
1025 };
1026
1027 enum sec_status {
1028    sec_status_unchecked = 0,
1029    sec_status_bogus,
1030    sec_status_indeterminate,
1031    sec_status_insecure,
1032    sec_status_secure
1033 };
1034
1035 enum verbosity_value {
1036    NO_VERBOSE = 0,
1037    VERB_OPS,
1038    VERB_DETAIL,
1039    VERB_QUERY,
1040    VERB_ALGO
1041 };
1042
1043 %constant uint16_t PKT_QR = 1;      /* QueRy - query flag */
1044 %constant uint16_t PKT_AA = 2;      /* Authoritative Answer - server flag */
1045 %constant uint16_t PKT_TC = 4;      /* TrunCated - server flag */
1046 %constant uint16_t PKT_RD = 8;      /* Recursion Desired - query flag */
1047 %constant uint16_t PKT_CD = 16;     /* Checking Disabled - query flag */
1048 %constant uint16_t PKT_RA = 32;     /* Recursion Available - server flag */
1049 %constant uint16_t PKT_AD = 64;     /* Authenticated Data - server flag */
1050
1051 %{
1052 int checkList(PyObject *l) 
1053 {
1054     PyObject* item;
1055     int i;
1056
1057     if (l == Py_None) 
1058        return 1;
1059
1060     if (PyList_Check(l)) 
1061     {
1062        for (i=0; i < PyList_Size(l); i++) 
1063        {
1064            item = PyList_GetItem(l, i);
1065            if (!PyBytes_Check(item))
1066               return 0;
1067        }
1068        return 1;
1069     }
1070
1071     return 0;
1072 }
1073
1074 int pushRRList(sldns_buffer* qb, PyObject *l, uint32_t default_ttl, int qsec,
1075         size_t count_offset)
1076 {
1077     PyObject* item;
1078     int i;
1079     size_t len;
1080
1081     for (i=0; i < PyList_Size(l); i++) 
1082     {
1083         item = PyList_GetItem(l, i);
1084
1085         len = sldns_buffer_remaining(qb);
1086         if(qsec) {
1087                 if(sldns_str2wire_rr_question_buf(PyBytes_AsString(item),
1088                         sldns_buffer_current(qb), &len, NULL, NULL, 0, NULL, 0)
1089                         != 0)
1090                         return 0;
1091         } else {
1092                 if(sldns_str2wire_rr_buf(PyBytes_AsString(item),
1093                         sldns_buffer_current(qb), &len, NULL, default_ttl,
1094                         NULL, 0, NULL, 0) != 0)
1095                         return 0;
1096         }
1097         sldns_buffer_skip(qb, len);
1098
1099         sldns_buffer_write_u16_at(qb, count_offset,
1100                 sldns_buffer_read_u16_at(qb, count_offset)+1);
1101     }
1102     return 1;
1103 }
1104
1105 int set_return_msg(struct module_qstate* qstate, 
1106                    const char* rr_name, sldns_rr_type rr_type, sldns_rr_class rr_class , uint16_t flags, uint32_t default_ttl,
1107                    PyObject* question, PyObject* answer, PyObject* authority, PyObject* additional) 
1108 {
1109      sldns_buffer *qb = 0;
1110      int res = 1;
1111      size_t l;
1112      uint16_t PKT_QR = 1;
1113      uint16_t PKT_AA = 2;
1114      uint16_t PKT_TC = 4;
1115      uint16_t PKT_RD = 8;
1116      uint16_t PKT_CD = 16;
1117      uint16_t PKT_RA = 32;
1118      uint16_t PKT_AD = 64;
1119  
1120      if ((!checkList(question)) || (!checkList(answer)) || (!checkList(authority)) || (!checkList(additional)))
1121         return 0;
1122      if ((qb = sldns_buffer_new(LDNS_RR_BUF_SIZE)) == 0) return 0;
1123
1124      /* write header */
1125      sldns_buffer_write_u16(qb, 0); /* ID */
1126      sldns_buffer_write_u16(qb, 0); /* flags */
1127      sldns_buffer_write_u16(qb, 1); /* qdcount */
1128      sldns_buffer_write_u16(qb, 0); /* ancount */
1129      sldns_buffer_write_u16(qb, 0); /* nscount */
1130      sldns_buffer_write_u16(qb, 0); /* arcount */
1131      if ((flags&PKT_QR)) LDNS_QR_SET(sldns_buffer_begin(qb));
1132      if ((flags&PKT_AA)) LDNS_AA_SET(sldns_buffer_begin(qb));
1133      if ((flags&PKT_TC)) LDNS_TC_SET(sldns_buffer_begin(qb));
1134      if ((flags&PKT_RD)) LDNS_RD_SET(sldns_buffer_begin(qb));
1135      if ((flags&PKT_CD)) LDNS_CD_SET(sldns_buffer_begin(qb));
1136      if ((flags&PKT_RA)) LDNS_RA_SET(sldns_buffer_begin(qb));
1137      if ((flags&PKT_AD)) LDNS_AD_SET(sldns_buffer_begin(qb));
1138
1139      /* write the query */
1140      l = sldns_buffer_remaining(qb);
1141      if(sldns_str2wire_dname_buf(rr_name, sldns_buffer_current(qb), &l) != 0) {
1142              sldns_buffer_free(qb);
1143              return 0;
1144      }
1145      sldns_buffer_skip(qb, l);
1146      if (rr_type == 0) { rr_type = LDNS_RR_TYPE_A; }
1147      if (rr_class == 0) { rr_class = LDNS_RR_CLASS_IN; }
1148      sldns_buffer_write_u16(qb, rr_type);
1149      sldns_buffer_write_u16(qb, rr_class);
1150
1151      /* write RR sections */
1152      if(res && !pushRRList(qb, question, default_ttl, 1, LDNS_QDCOUNT_OFF))
1153              res = 0;
1154      if(res && !pushRRList(qb, answer, default_ttl, 0, LDNS_ANCOUNT_OFF))
1155              res = 0;
1156      if(res && !pushRRList(qb, authority, default_ttl, 0, LDNS_NSCOUNT_OFF))
1157              res = 0;
1158      if(res && !pushRRList(qb, additional, default_ttl, 0, LDNS_ARCOUNT_OFF))
1159              res = 0;
1160
1161      if (res) res = createResponse(qstate, qb);
1162
1163      if (qb) sldns_buffer_free(qb);
1164      return res;
1165 }
1166 %}
1167
1168 int set_return_msg(struct module_qstate* qstate, 
1169                    const char* rr_name, int rr_type, int rr_class , uint16_t flags, uint32_t default_ttl,
1170                    PyObject* question, PyObject* answer, PyObject* authority, PyObject* additional);
1171
1172 %pythoncode %{
1173     class DNSMessage:
1174         def __init__(self, rr_name, rr_type, rr_class = RR_CLASS_IN, query_flags = 0, default_ttl = 0):
1175             """Query flags is a combination of PKT_xx contants"""
1176             self.rr_name = rr_name
1177             self.rr_type = rr_type
1178             self.rr_class = rr_class
1179             self.default_ttl = default_ttl
1180             self.query_flags = query_flags
1181             self.question = []
1182             self.answer = []
1183             self.authority = []
1184             self.additional = []
1185
1186         def set_return_msg(self, qstate):
1187             """Returns 1 if OK"""
1188             status = _unboundmodule.set_return_msg(qstate, self.rr_name, self.rr_type, self.rr_class, 
1189                                            self.query_flags, self.default_ttl,
1190                                            self.question, self.answer, self.authority, self.additional)
1191
1192             if (status) and (PKT_AA & self.query_flags):
1193                 qstate.return_msg.rep.authoritative = 1
1194
1195             return status 
1196
1197 %}
1198 /* ************************************************************************************ * 
1199    ASN: Delegation pointer related functions
1200  * ************************************************************************************ */
1201
1202 /* Functions which we will need to lookup delegations */
1203 struct delegpt* dns_cache_find_delegation(struct module_env* env,
1204         uint8_t* qname, size_t qnamelen, uint16_t qtype, uint16_t qclass,
1205         struct regional* region, struct dns_msg** msg, uint32_t timenow);
1206 int iter_dp_is_useless(struct query_info* qinfo, uint16_t qflags,
1207         struct delegpt* dp);
1208 struct iter_hints_stub* hints_lookup_stub(struct iter_hints* hints,
1209         uint8_t* qname, uint16_t qclass, struct delegpt* dp);
1210
1211 /* Custom function to perform logic similar to the one in daemon/cachedump.c */
1212 struct delegpt* find_delegation(struct module_qstate* qstate, char *nm, size_t nmlen);
1213
1214 %{
1215 #define BIT_RD 0x100
1216
1217 struct delegpt* find_delegation(struct module_qstate* qstate, char *nm, size_t nmlen)
1218 {
1219     struct delegpt *dp;
1220     struct dns_msg *msg = NULL;
1221     struct regional* region = qstate->env->scratch;
1222     char b[260];
1223     struct query_info qinfo;
1224     struct iter_hints_stub* stub;
1225     uint32_t timenow = *qstate->env->now;
1226
1227     regional_free_all(region);
1228     qinfo.qname = (uint8_t*)nm;
1229     qinfo.qname_len = nmlen;
1230     qinfo.qtype = LDNS_RR_TYPE_A;
1231     qinfo.qclass = LDNS_RR_CLASS_IN;
1232
1233     while(1) {
1234         dp = dns_cache_find_delegation(qstate->env, (uint8_t*)nm, nmlen, qinfo.qtype, qinfo.qclass, region, &msg, timenow);
1235         if(!dp)
1236             return NULL;
1237         if(iter_dp_is_useless(&qinfo, BIT_RD, dp)) {
1238             if (dname_is_root((uint8_t*)nm))
1239                 return NULL;
1240             nm = (char*)dp->name;
1241             nmlen = dp->namelen;
1242             dname_remove_label((uint8_t**)&nm, &nmlen);
1243             dname_str((uint8_t*)nm, b);
1244             continue;
1245         }
1246         stub = hints_lookup_stub(qstate->env->hints, qinfo.qname, qinfo.qclass, dp);
1247         if (stub) {
1248             return stub->dp;
1249         } else {
1250             return dp;
1251         }
1252     }
1253     return NULL;
1254 }
1255 %}
1256
1257 /* ************************************************************************************ * 
1258    Functions
1259  * ************************************************************************************ */
1260 /******************************
1261  * Various debuging functions *
1262  ******************************/
1263 void verbose(enum verbosity_value level, const char* format, ...);
1264 void log_info(const char* format, ...);
1265 void log_err(const char* format, ...);
1266 void log_warn(const char* format, ...);
1267 void log_hex(const char* msg, void* data, size_t length);
1268 void log_dns_msg(const char* str, struct query_info* qinfo, struct reply_info* rep);
1269 void log_query_info(enum verbosity_value v, const char* str, struct query_info* qinf);
1270 void regional_log_stats(struct regional *r);
1271
1272 /***************************************************************************
1273  * Free allocated memory from marked sources returning corresponding types *
1274  ***************************************************************************/
1275 %typemap(newfree, noblock = 1) char * {
1276   free($1);
1277 }
1278
1279 /***************************************************
1280  * Mark as source returning newly allocated memory *
1281  ***************************************************/
1282 %newobject sldns_wire2str_type;
1283 %newobject sldns_wire2str_class;
1284
1285 /******************
1286  * LDNS functions *
1287  ******************/
1288 char *sldns_wire2str_type(const uint16_t atype);
1289 char *sldns_wire2str_class(const uint16_t aclass);
1290
1291 /**********************************
1292  * Functions from pythonmod_utils *
1293  **********************************/
1294 int storeQueryInCache(struct module_qstate* qstate, struct query_info* qinfo, struct reply_info* msgrep, int is_referral);
1295 void invalidateQueryInCache(struct module_qstate* qstate, struct query_info* qinfo);
1296
1297 /*******************************
1298  * Module conversion functions *
1299  *******************************/
1300 const char* strextstate(enum module_ext_state s);
1301 const char* strmodulevent(enum module_ev e);
1302
1303 /**************************
1304  * Edns related functions *
1305  **************************/
1306 struct edns_option* edns_opt_list_find(struct edns_option* list, uint16_t code);
1307 int edns_register_option(uint16_t opt_code, int bypass_cache_stage,
1308     int no_aggregation, struct module_env* env);
1309
1310 %pythoncode %{
1311     def register_edns_option(env, code, bypass_cache_stage=False,
1312                              no_aggregation=False):
1313         """Wrapper function to provide keyword attributes."""
1314         return edns_register_option(code, bypass_cache_stage,
1315                                     no_aggregation, env)
1316 %}
1317
1318 /******************************
1319  * Callback related functions *
1320  ******************************/
1321 /* typemap to check if argument is callable */
1322 %typemap(in) PyObject *py_cb {
1323   if (!PyCallable_Check($input)) {
1324       SWIG_exception_fail(SWIG_TypeError, "Need a callable object!");
1325       return NULL;
1326   }
1327   $1 = $input;
1328 }
1329 /* typemap to get content/size from a bytearray  */
1330 %typemap(in) (size_t len, uint8_t* py_bytearray_data) {
1331     if (!PyByteArray_CheckExact($input)) {
1332         SWIG_exception_fail(SWIG_TypeError, "Expected bytearray!");
1333         return NULL;
1334     }
1335     $2 = PyByteArray_AsString($input);
1336     $1 = PyByteArray_Size($input);
1337 }
1338
1339 int edns_opt_list_remove(struct edns_option** list, uint16_t code);
1340 int edns_opt_list_append(struct edns_option** list, uint16_t code, size_t len,
1341     uint8_t* py_bytearray_data, struct regional* region);
1342
1343 %{
1344     /* This function is called by unbound in order to call the python
1345      * callback function. */
1346     int python_inplace_cb_reply_generic(struct query_info* qinfo,
1347         struct module_qstate* qstate, struct reply_info* rep, int rcode,
1348         struct edns_data* edns, struct edns_option** opt_list_out,
1349         struct regional* region, void* python_callback)
1350     {
1351         PyObject *func, *py_edns, *py_qstate, *py_opt_list_out, *py_qinfo;
1352         PyObject *py_rep, *py_region;
1353         PyObject *result;
1354         int res = 0;
1355
1356         func = (PyObject *) python_callback;
1357         PyGILState_STATE gstate = PyGILState_Ensure();
1358         py_edns = SWIG_NewPointerObj((void*) edns, SWIGTYPE_p_edns_data, 0);
1359         py_qstate = SWIG_NewPointerObj((void*) qstate,
1360             SWIGTYPE_p_module_qstate, 0);
1361         py_opt_list_out = SWIG_NewPointerObj((void*) opt_list_out,
1362             SWIGTYPE_p_p_edns_option, 0);
1363         py_qinfo = SWIG_NewPointerObj((void*) qinfo, SWIGTYPE_p_query_info, 0);
1364         py_rep = SWIG_NewPointerObj((void*) rep, SWIGTYPE_p_reply_info, 0);
1365         py_region = SWIG_NewPointerObj((void*) region, SWIGTYPE_p_regional, 0);
1366         result = PyObject_CallFunction(func, "OOOiOOO", py_qinfo, py_qstate,
1367             py_rep, rcode, py_edns, py_opt_list_out, py_region);
1368         Py_XDECREF(py_edns);
1369         Py_XDECREF(py_qstate);
1370         Py_XDECREF(py_opt_list_out);
1371         Py_XDECREF(py_qinfo);
1372         Py_XDECREF(py_rep);
1373         Py_XDECREF(py_region);
1374         if (result) {
1375             res = PyInt_AsLong(result);
1376         }
1377         Py_XDECREF(result);
1378         PyGILState_Release(gstate);
1379         return res;
1380     }
1381
1382     /* Swig implementations for Python */
1383     static int register_inplace_cb_reply(PyObject* py_cb,
1384         struct module_env* env)
1385     {
1386         int ret = inplace_cb_reply_register(
1387             python_inplace_cb_reply_generic, (void*) py_cb, env);
1388         if (ret) Py_INCREF(py_cb);
1389         return ret;
1390     }
1391     static int register_inplace_cb_reply_cache(PyObject* py_cb,
1392         struct module_env* env)
1393     {
1394         int ret = inplace_cb_reply_cache_register(
1395             python_inplace_cb_reply_generic, (void*) py_cb, env);
1396         if (ret) Py_INCREF(py_cb);
1397         return ret;
1398     }
1399     static int register_inplace_cb_reply_local(PyObject* py_cb,
1400         struct module_env* env)
1401     {
1402         int ret = inplace_cb_reply_local_register(
1403             python_inplace_cb_reply_generic, (void*) py_cb, env);
1404         if (ret) Py_INCREF(py_cb);
1405         return ret;
1406     }
1407     static int register_inplace_cb_reply_servfail(PyObject* py_cb,
1408         struct module_env* env)
1409     {
1410         int ret = inplace_cb_reply_servfail_register(
1411             python_inplace_cb_reply_generic, (void*) py_cb, env);
1412         if (ret) Py_INCREF(py_cb);
1413         return ret;
1414     }
1415 %}
1416 /* C declarations */
1417 int inplace_cb_reply_register(
1418     inplace_cb_reply_func_t* cb, void* cb_arg, struct module_env* env);
1419 int inplace_cb_reply_cache_register(
1420     inplace_cb_reply_func_t* cb, void* cb_arg, struct module_env* env);
1421 int inplace_cb_reply_local_register(
1422     inplace_cb_reply_func_t* cb, void* cb_arg, struct module_env* env);
1423 int inplace_cb_reply_servfail_register(
1424     inplace_cb_reply_func_t* cb, void* cb_arg, struct module_env* env);
1425
1426 /* Swig declarations */
1427 static int register_inplace_cb_reply(PyObject* py_cb,
1428     struct module_env* env);
1429 static int register_inplace_cb_reply_cache(PyObject* py_cb,
1430     struct module_env* env);
1431 static int register_inplace_cb_reply_local(PyObject* py_cb,
1432     struct module_env* env);
1433 static int register_inplace_cb_reply_servfail(PyObject* py_cb,
1434     struct module_env* env);