2 * libunbound.i: pyUnbound module (libunbound wrapper for Python)
4 * Copyright (c) 2009, Zdenek Vasicek (vasicek AT fit.vutbr.cz)
5 * Marek Vavrusa (xvavru00 AT stud.fit.vutbr.cz)
7 * This software is open source.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
13 * * Redistributions of source code must retain the above copyright notice,
14 * this list of conditions and the following disclaimer.
16 * * Redistributions in binary form must reproduce the above copyright notice,
17 * this list of conditions and the following disclaimer in the documentation
18 * and/or other materials provided with the distribution.
20 * * Neither the name of the organization nor the names of its
21 * contributors may be used to endorse or promote products derived from this
22 * software without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
26 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
27 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
29 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
32 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34 * POSSIBILITY OF SUCH DAMAGE.
37 /* store state of warning output, restored at later pop */
38 #pragma GCC diagnostic push
39 /* ignore gcc8 METH_NOARGS function cast warnings for swig function pointers */
40 #pragma GCC diagnostic ignored "-Wcast-function-type"
44 /* restore state of warning output, remove the functioncast ignore */
45 #pragma GCC diagnostic pop
46 #include <sys/types.h>
47 #ifdef HAVE_SYS_SOCKET_H
48 #include <sys/socket.h>
50 #ifdef HAVE_NETINET_IN_H
51 #include <netinet/in.h>
53 #ifdef HAVE_ARPA_INET_H
54 #include <arpa/inet.h>
56 #include "libunbound/unbound.h"
64 import __builtin__ as builtins
66 # Ensure compatibility with older python versions
67 if 'bytes' not in vars():
71 if isinstance(s, int):
73 return builtins.ord(s)
77 #if PY_MAJOR_VERSION >= 3
78 %include "file_py3.i" // python 3 FILE *
83 %feature("docstring") strerror "Convert error value to a human readable string."
85 // ================================================================================
86 // ub_resolve - perform resolution and validation
87 // ================================================================================
88 %typemap(in,numinputs=0,noblock=1) (struct ub_result** result)
90 struct ub_result* newubr;
94 /* result generation */
95 %typemap(argout,noblock=1) (struct ub_result** result)
97 if(1) { /* new code block for variable on stack */
99 tuple = PyTuple_New(2);
100 PyTuple_SetItem(tuple, 0, $result);
102 PyTuple_SetItem(tuple, 1, SWIG_NewPointerObj(SWIG_as_voidptr(newubr), SWIGTYPE_p_ub_result, SWIG_POINTER_OWN | 0 ));
104 PyTuple_SetItem(tuple, 1, Py_None);
111 // ================================================================================
112 // ub_ctx - validation context
113 // ================================================================================
114 %nodefaultctor ub_ctx; //no default constructor & destructor
115 %nodefaultdtor ub_ctx;
117 %newobject ub_ctx_create;
118 %delobject ub_ctx_delete;
119 %rename(_ub_ctx_delete) ub_ctx_delete;
121 %newobject ub_resolve;
124 void ub_ctx_free_dbg (struct ub_ctx* c) {
125 printf("******** UB_CTX free 0x%p ************\n", c);
132 /** a host address */
134 /** an authoritative name server */
136 /** a mail destination (Obsolete - use MX) */
138 /** a mail forwarder (Obsolete - use MX) */
140 /** the canonical name for an alias */
142 /** marks the start of a zone of authority */
144 /** a mailbox domain name (EXPERIMENTAL) */
146 /** a mail group member (EXPERIMENTAL) */
148 /** a mail rename domain name (EXPERIMENTAL) */
150 /** a null RR (EXPERIMENTAL) */
152 /** a well known service description */
154 /** a domain name pointer */
156 /** host information */
158 /** mailbox or mail list information */
177 RR_TYPE_NSAP_PTR = 23,
188 /** LOC record RFC1876 */
192 /** draft-ietf-nimrod-dns-01.txt */
194 /** draft-ietf-nimrod-dns-01.txt */
196 /** SRV record RFC2782 */
198 /** http://www.jhsoft.com/rfc/af-saa-0069.000.rtf */
210 /** dnsind-kitchen-sink-02.txt */
212 /** Pseudo OPT record... */
216 /** draft-ietf-dnsext-delegation */
218 /** SSH Key Fingerprint */
220 /** draft-richardson-ipseckey-rr-11.txt */
221 RR_TYPE_IPSECKEY = 45,
222 /** draft-ietf-dnsext-dnssec-25 */
229 RR_TYPE_NSEC3PARAMS = 51,
234 RR_TYPE_UNSPEC = 103,
239 /** A request for mailbox-related records (MB, MG or MR) */
241 /** A request for mail agent RRs (Obsolete - see MX) */
243 /** any type (wildcard) */
246 /* RFC 4431, 5074, DNSSEC Lookaside Validation */
257 /** Hesiod (Dyer 87) */
259 /** None class, dynamic update */
266 %feature("docstring") ub_ctx "Unbound resolving and validation context.
268 The validation context is created to hold the resolver status, validation keys and a small cache (containing messages, rrsets, roundtrip times, trusted keys, lameness information).
273 >>> ctx = unbound.ub_ctx()
274 >>> ctx.resolvconf(\"/etc/resolv.conf\")
275 >>> status, result = ctx.resolve(\"www.google.com\", unbound.RR_TYPE_A, unbound.RR_CLASS_IN)
276 >>> if status==0 and result.havedata:
277 >>> print \"Result:\",result.data.address_list
278 Result: ['74.125.43.147', '74.125.43.99', '74.125.43.103', '74.125.43.104']
285 """Creates a resolving and validation context.
287 An exception is invoked if the process of creation an ub_ctx instance fails.
289 self.this = _unbound.ub_ctx_create()
291 raise Exception("Fatal error: unbound context initialization failed")
293 #__swig_destroy__ = _unbound.ub_ctx_free_dbg
294 __swig_destroy__ = _unbound._ub_ctx_delete
298 """Add a trust anchor to the given context.
300 The trust anchor is a string, on one line, that holds a valid DNSKEY or DS RR.
303 string, with zone-format RR on one line. [domainname] [TTL optional] [type] [class optional] [rdata contents]
304 :returns: (int) 0 if OK, else error.
306 return _unbound.ub_ctx_add_ta(self,ta)
307 #parameters: struct ub_ctx *,char *,
310 def add_ta_file(self,fname):
311 """Add trust anchors to the given context.
313 Pass name of a file with DS and DNSKEY records (like from dig or drill).
316 filename of file with keyfile with trust anchors.
317 :returns: (int) 0 if OK, else error.
319 return _unbound.ub_ctx_add_ta_file(self,fname)
320 #parameters: struct ub_ctx *,char *,
323 def config(self,fname):
324 """setup configuration for the given context.
327 unbound config file (not all settings applicable). This is a power-users interface that lets you specify all sorts of options. For some specific options, such as adding trust anchors, special routines exist.
328 :returns: (int) 0 if OK, else error.
330 return _unbound.ub_ctx_config(self,fname)
331 #parameters: struct ub_ctx *,char *,
334 def debuglevel(self,d):
335 """Set debug verbosity for the context Output is directed to stderr.
338 debug level, 0 is off, 1 is very minimal, 2 is detailed, and 3 is lots.
339 :returns: (int) 0 if OK, else error.
341 return _unbound.ub_ctx_debuglevel(self,d)
342 #parameters: struct ub_ctx *,int,
345 def debugout(self,out):
346 """Set debug output (and error output) to the specified stream.
348 Pass None to disable. Default is stderr.
351 File stream to log to.
352 :returns: (int) 0 if OK, else error.
356 In order to log into file, use
360 ctx = unbound.ub_ctx()
361 fw = fopen("debug.log")
365 Another option is to print the debug informations to stderr output
369 ctx = unbound.ub_ctx()
371 ctx.debugout(sys.stderr)
373 return _unbound.ub_ctx_debugout(self,out)
374 #parameters: struct ub_ctx *,void *,
377 def hosts(self,fname="/etc/hosts"):
378 """Read list of hosts from the filename given.
380 Usually "/etc/hosts". These addresses are not flagged as DNSSEC secure when queried for.
383 file name string. If None "/etc/hosts" is used.
384 :returns: (int) 0 if OK, else error.
386 return _unbound.ub_ctx_hosts(self,fname)
387 #parameters: struct ub_ctx *,char *,
390 def print_local_zones(self):
391 """Print the local zones and their content (RR data) to the debug output.
393 :returns: (int) 0 if OK, else error.
395 return _unbound.ub_ctx_print_local_zones(self)
396 #parameters: struct ub_ctx *,
399 def resolvconf(self,fname="/etc/resolv.conf"):
400 """Read list of nameservers to use from the filename given.
402 Usually "/etc/resolv.conf". Uses those nameservers as caching proxies. If they do not support DNSSEC, validation may fail.
404 Only nameservers are picked up, the searchdomain, ndots and other settings from resolv.conf(5) are ignored.
407 file name string. If None "/etc/resolv.conf" is used.
408 :returns: (int) 0 if OK, else error.
410 return _unbound.ub_ctx_resolvconf(self,fname)
411 #parameters: struct ub_ctx *,char *,
414 def set_async(self,dothread):
415 """Set a context behaviour for asynchronous action.
418 if True, enables threading and a call to :meth:`resolve_async` creates a thread to handle work in the background.
419 If False, a process is forked to handle work in the background.
420 Changes to this setting after :meth:`async` calls have been made have no effect (delete and re-create the context to change).
421 :returns: (int) 0 if OK, else error.
423 return _unbound.ub_ctx_async(self,dothread)
424 #parameters: struct ub_ctx *,int,
427 def set_fwd(self,addr):
428 """Set machine to forward DNS queries to, the caching resolver to use.
430 IP4 or IP6 address. Forwards all DNS requests to that machine, which is expected to run a recursive resolver. If the is not DNSSEC-capable, validation may fail. Can be called several times, in that case the addresses are used as backup servers.
432 To read the list of nameservers from /etc/resolv.conf (from DHCP or so), use the call :meth:`resolvconf`.
435 address, IP4 or IP6 in string format. If the addr is None, forwarding is disabled.
436 :returns: (int) 0 if OK, else error.
438 return _unbound.ub_ctx_set_fwd(self,addr)
439 #parameters: struct ub_ctx *,char *,
442 def set_option(self,opt,val):
443 """Set an option for the context.
445 Changes to the options after :meth:`resolve`, :meth:`resolve_async`, :meth:`zone_add`, :meth:`zone_remove`, :meth:`data_add` or :meth:`data_remove` have no effect (you have to delete and re-create the context).
448 option name from the unbound.conf config file format. (not all settings applicable). The name includes the trailing ':' for example set_option("logfile:", "mylog.txt"); This is a power-users interface that lets you specify all sorts of options. For some specific options, such as adding trust anchors, special routines exist.
451 :returns: (int) 0 if OK, else error.
453 return _unbound.ub_ctx_set_option(self,opt,val)
454 #parameters: struct ub_ctx *,char *,char *,
457 def trustedkeys(self,fname):
458 """Add trust anchors to the given context.
460 Pass the name of a bind-style config file with trusted-keys{}.
463 filename of file with bind-style config entries with trust anchors.
464 :returns: (int) 0 if OK, else error.
466 return _unbound.ub_ctx_trustedkeys(self,fname)
467 #parameters: struct ub_ctx *,char *,
471 def zone_print(self):
472 """Print local zones using debugout"""
473 _unbound.ub_ctx_print_local_zones(self)
475 def zone_add(self,zonename,zonetype):
476 """Add new local zone
478 :param zonename: zone domain name (e.g. myzone.)
479 :param zonetype: type of the zone ("static",...)
480 :returns: (int) 0 if OK, else error.
482 return _unbound.ub_ctx_zone_add(self,zonename, zonetype)
483 #parameters: struct ub_ctx *,char*, char*
486 def zone_remove(self,zonename):
489 If exists, removes local zone with all the RRs.
491 :param zonename: zone domain name
492 :returns: (int) 0 if OK, else error.
494 return _unbound.ub_ctx_zone_remove(self,zonename)
495 #parameters: struct ub_ctx *,char*
498 def data_add(self,rrdata):
499 """Add new local RR data
501 :param rrdata: string, in zone-format on one line. [domainname] [TTL optional] [type] [class optional] [rdata contents]
502 :returns: (int) 0 if OK, else error.
509 >>> ctx = unbound.ub_ctx()
510 >>> ctx.zone_add("mydomain.net.","static")
512 >>> status = ctx.data_add("test.mydomain.net. IN A 192.168.1.1")
514 >>> status, result = ctx.resolve("test.mydomain.net")
515 >>> if status==0 and result.havedata:
516 >>> print \"Result:\",result.data.address_list
517 Result: ['192.168.1.1']
520 return _unbound.ub_ctx_data_add(self,rrdata)
521 #parameters: struct ub_ctx *,char*
524 def data_remove(self,rrdata):
525 """Remove local RR data
527 If exists, remove resource record from local zone
529 :param rrdata: string, in zone-format on one line. [domainname] [TTL optional] [type] [class optional] [rdata contents]
530 :returns: (int) 0 if OK, else error.
532 return _unbound.ub_ctx_data_remove(self,rrdata)
533 #parameters: struct ub_ctx *,char*
537 def cancel(self,async_id):
538 """Cancel an async query in progress.
540 Its callback will not be called.
543 which query to cancel.
544 :returns: (int) 0 if OK, else error.
546 return _unbound.ub_cancel(self,async_id)
547 #parameters: struct ub_ctx *,int,
551 """Get file descriptor.
553 Wait for it to become readable, at this point answers are returned from the asynchronous validating resolver. Then call the ub_process to continue processing. This routine works immediately after context creation, the fd does not change.
555 :returns: (int) -1 on error, or file descriptor to use select(2) with.
557 return _unbound.ub_fd(self)
558 #parameters: struct ub_ctx *,
562 """Poll a context to see if it has any new results Do not poll in a loop, instead extract the fd below to poll for readiness, and then check, or wait using the wait routine.
564 :returns: (int) 0 if nothing to read, or nonzero if a result is available. If nonzero, call ctx_process() to do callbacks.
566 return _unbound.ub_poll(self)
567 #parameters: struct ub_ctx *,
571 """Call this routine to continue processing results from the validating resolver (when the fd becomes readable).
573 Will perform necessary callbacks.
575 :returns: (int) 0 if OK, else error.
577 return _unbound.ub_process(self)
578 #parameters: struct ub_ctx *,
581 def resolve(self,name,rrtype=RR_TYPE_A,rrclass=RR_CLASS_IN):
582 """Perform resolution and validation of the target name.
585 domain name in text format (a string or unicode string). IDN domain name have to be passed as a unicode string.
587 type of RR in host order (optional argument). Default value is RR_TYPE_A (A class).
589 class of RR in host order (optional argument). Default value is RR_CLASS_IN (for internet).
590 :returns: * (int) 0 if OK, else error.
591 * (:class:`ub_result`) the result data is returned in a newly allocated result structure. May be None on return, return value is set to an error in that case (out of memory).
593 if isinstance(name, bytes): #probably IDN
594 return _unbound.ub_resolve(self,name,rrtype,rrclass)
596 return _unbound.ub_resolve(self,idn2dname(name),rrtype,rrclass)
597 #parameters: struct ub_ctx *,char *,int,int,
598 #retvals: int,struct ub_result **
600 def resolve_async(self,name,mydata,callback,rrtype=RR_TYPE_A,rrclass=RR_CLASS_IN):
601 """Perform resolution and validation of the target name.
603 Asynchronous, after a while, the callback will be called with your data and the result.
604 If an error happens during processing, your callback will be called with error set to a nonzero value (and result==None).
607 domain name in text format (a string or unicode string). IDN domain name have to be passed as a unicode string.
609 this data is your own data (you can pass arbitrary python object or None) which are passed on to the callback function.
611 call-back function which is called on completion of the resolution.
613 type of RR in host order (optional argument). Default value is RR_TYPE_A (A class).
615 class of RR in host order (optional argument). Default value is RR_CLASS_IN (for internet).
616 :returns: * (int) 0 if OK, else error.
617 * (int) async_id, an identifier number is returned for the query as it is in progress. It can be used to cancel the query.
619 **Call-back function:**
620 The call-back function looks as the follows::
622 def call_back(mydata, status, result):
626 * `mydata` - mydata object
627 * `status` - 0 when a result has been found
628 * `result` - the result structure. The result may be None, in that case err is set.
631 if isinstance(name, bytes): #probably IDN
632 return _unbound._ub_resolve_async(self,name,rrtype,rrclass,mydata,callback)
634 return _unbound._ub_resolve_async(self,idn2dname(name),rrtype,rrclass,mydata,callback)
635 #parameters: struct ub_ctx *,char *,int,int,void *,ub_callback_t,
639 """Wait for a context to finish with results.
641 Calls after the wait for you. After the wait, there are no more outstanding asynchronous queries.
643 :returns: (int) 0 if OK, else error.
645 return _unbound.ub_wait(self)
646 #parameters: struct ub_ctx *,
654 // ================================================================================
655 // ub_result - validation and resolution results
656 // ================================================================================
657 %nodefaultctor ub_result; //no default constructor & destructor
658 %nodefaultdtor ub_result;
660 %delobject ub_resolve_free;
661 %rename(_ub_resolve_free) ub_resolve_free;
664 void ub_resolve_free_dbg (struct ub_result* r) {
665 printf("******** UB_RESOLVE free 0x%p ************\n", r);
670 %feature("docstring") ub_result "The validation and resolution results."
674 enum result_enum_rcode {
691 """Class which makes the resolution results accessible"""
692 def __init__(self, data):
693 """Creates ub_data class
694 :param data: a list of the result data in RAW format
697 raise Exception("ub_data init: No data")
701 """Represents data as string"""
702 return ';'.join([' '.join(map(lambda x:"%02X" % ord(x),a)) for a in self.data])
705 def dname2str(s, ofs=0, maxlen=0):
706 """Parses DNAME and produces a list of labels
708 :param ofs: where the conversion should start to parse data
709 :param maxlen: maximum length (0 means parse to the end)
710 :returns: list of labels (string)
718 slen = min(slen, maxlen)
722 complen = ord(s[idx])
723 # In python 3.x `str()` converts the string to unicode which is the expected text string type
724 res.append(str(s[idx+1:idx+1+complen].decode()))
729 def as_raw_data(self):
730 """Returns a list of RAW strings"""
733 raw = property(as_raw_data, doc="Returns RAW data (a list of binary encoded strings). See :meth:`as_raw_data`")
735 def as_mx_list(self):
736 """Represents data as a list of MX records (query for RR_TYPE_MX)
738 :returns: list of tuples (priority, dname)
740 return [(256*ord(rdf[0])+ord(rdf[1]),'.'.join([a for a in self.dname2str(rdf,2)])) for rdf in self.data]
742 mx_list = property(as_mx_list, doc="Returns a list of tuples containing priority and domain names. See :meth:`as_mx_list`")
744 def as_idn_mx_list(self):
745 """Represents data as a list of MX records (query for RR_TYPE_MX)
747 :returns: list of tuples (priority, unicode dname)
749 return [(256*ord(rdf[0])+ord(rdf[1]),'.'.join([encodings.idna.ToUnicode(a) for a in self.dname2str(rdf,2)])) for rdf in self.data]
751 mx_list_idn = property(as_idn_mx_list, doc="Returns a list of tuples containing priority and IDN domain names. See :meth:`as_idn_mx_list`")
753 def as_address_list(self):
754 """Represents data as a list of IP addresses (query for RR_TYPE_PTR)
756 :returns: list of strings
758 return ['.'.join(map(lambda x:str(ord(x)),a)) for a in self.data]
760 address_list = property(as_address_list, doc="Returns a list of IP addresses. See :meth:`as_address_list`")
762 def as_domain_list(self):
763 """Represents data as a list of domain names (query for RR_TYPE_A)
765 :returns: list of strings
767 return map(lambda x:'.'.join(self.dname2str(x)), self.data)
769 domain_list = property(as_domain_list, doc="Returns a list of domain names. See :meth:`as_domain_list`")
771 def as_idn_domain_list(self):
772 """Represents data as a list of unicode domain names (query for RR_TYPE_A)
774 :returns: list of strings
776 return map(lambda x: '.'.join([encodings.idna.ToUnicode(a) for a in self.dname2str(x)]), self.data)
778 domain_list_idn = property(as_idn_domain_list, doc="Returns a list of IDN domain names. See :meth:`as_idn_domain_list`")
786 PyObject* _ub_result_data(struct ub_result* result) {
790 if ((result == 0) || (!result->havedata) || (result->data == 0))
793 for (cnt=0,i=0;;i++,cnt++)
794 if (result->data[i] == 0)
797 list = PyList_New(cnt);
799 PyList_SetItem(list, i, PyBytes_FromStringAndSize(result->data[i],result->len[i]));
804 PyObject* _packet() {
805 return PyBytes_FromStringAndSize($self->answer_packet, $self->answer_len);
810 raise Exception("This class can't be created directly.")
812 #__swig_destroy__ = _unbound.ub_resolve_free_dbg
813 __swig_destroy__ = _unbound._ub_resolve_free
815 #havedata = property(_unbound.ub_result_havedata_get, _unbound.ub_result_havedata_set, "Havedata property")
817 rcode2str = {RCODE_NOERROR:'no error', RCODE_FORMERR:'form error', RCODE_SERVFAIL:'serv fail', RCODE_NXDOMAIN:'nx domain', RCODE_NOTIMPL:'not implemented', RCODE_REFUSED:'refused', RCODE_YXDOMAIN:'yxdomain', RCODE_YXRRSET:'yxrrset', RCODE_NXRRSET:'nxrrset', RCODE_NOTAUTH:'not auth', RCODE_NOTZONE:'not zone'}
819 def _get_rcode_str(self):
820 """Returns rcode in display representation form
824 return self.rcode2str[self.rcode]
826 __swig_getmethods__["rcode_str"] = _get_rcode_str
827 if _newclass:rcode_str = _swig_property(_get_rcode_str)
829 def _get_raw_data(self):
830 """Result data, a list of network order DNS rdata items.
832 Data are represented as a list of strings. To decode RAW data to the list of IP addresses use :attr:`data` attribute which returns an :class:`ub_data` instance containing conversion function.
834 return self._ub_result_data(self)
836 __swig_getmethods__["rawdata"] = _get_raw_data
837 rawdata = property(_get_raw_data, doc="Returns raw data, a list of rdata items. To decode RAW data use the :attr:`data` attribute which returns an instance of :class:`ub_data` containing the conversion functions.")
840 if not self.havedata: return None
841 return ub_data(self._ub_result_data(self))
843 __swig_getmethods__["data"] = _get_data
844 __swig_getmethods__["packet"] = _packet
845 data = property(_get_data, doc="Returns :class:`ub_data` instance containing various decoding functions or None")
851 %exception ub_resolve
853 //printf("resolve_start(%lX)\n",(long unsigned int)arg1);
854 Py_BEGIN_ALLOW_THREADS
857 //printf("resolve_stop()\n");
860 %include "libunbound/unbound.h"
863 //SWIG will see the ub_ctx as a class
868 //ub_ctx_debugout void* parameter correction
869 int ub_ctx_debugout(struct ub_ctx* ctx, FILE* out);
871 // ================================================================================
872 // ub_resolve_async - perform asynchronous resolution and validation
873 // ================================================================================
875 %typemap(in,numinputs=0,noblock=1) (int* async_id)
881 %apply PyObject* {void* mydata}
883 /* result generation */
884 %typemap(argout,noblock=1) (int* async_id)
886 if(1) { /* new code block for variable on stack */
888 tuple = PyTuple_New(2);
889 PyTuple_SetItem(tuple, 0, $result);
890 PyTuple_SetItem(tuple, 1, SWIG_From_int(asyncid));
895 // Grab a Python function object as a Python object.
896 %typemap(in) (PyObject *pyfunc) {
897 if (!PyCallable_Check($input))
899 PyErr_SetString(PyExc_TypeError, "Need a callable object!");
905 // Python callback workaround
906 int _ub_resolve_async(struct ub_ctx* ctx, char* name, int rrtype, int rrclass, void* mydata, PyObject *pyfunc, int* async_id);
914 static void PythonCallBack(void* iddata, int status, struct ub_result* result)
919 id = (struct cb_data*) iddata;
920 arglist = Py_BuildValue("(OiO)",id->data,status, SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ub_result, 0 | 0 )); // Build argument list
921 fresult = PyEval_CallObject(id->func,arglist); // Call Python
925 ub_resolve_free(result); //free ub_result
926 //ub_resolve_free_dbg(result); //free ub_result
927 Py_DECREF(arglist); // Trash arglist
931 int _ub_resolve_async(struct ub_ctx* ctx, char* name, int rrtype, int rrclass, PyObject* mydata, PyObject *pyfunc, int* async_id) {
934 id = (struct cb_data*) malloc(sizeof(struct cb_data));
938 r = ub_resolve_async(ctx,name,rrtype,rrclass, (void *) id, PythonCallBack, async_id);
947 ub_resolve_async = _unbound._ub_resolve_async
950 """Reverse domain name
952 Usable for reverse lookups when the IP address should be reversed
954 return '.'.join([a for a in domain.split(".")][::-1])
956 def idn2dname(idnname):
957 """Converts domain name in IDN format to canonic domain name
959 :param idnname: (unicode string) IDN name
960 :returns: (string) domain name
962 return '.'.join([encodings.idna.ToASCII(a) if a else '' for a in idnname.split('.')])
965 """Converts canonic domain name in IDN format to unicode string
967 :param name: (string) domain name
968 :returns: (unicode string) domain name
970 return '.'.join([encodings.idna.ToUnicode(a) for a in name.split('.')])