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.
38 #include <sys/types.h>
39 #include <sys/socket.h>
40 #include <netinet/in.h>
41 #include <arpa/inet.h>
42 #include "libunbound/unbound.h"
50 import __builtin__ as builtins
52 # Ensure compatibility with older python versions
53 if 'bytes' not in vars():
57 if isinstance(s, int):
59 return builtins.ord(s)
63 #if PY_MAJOR_VERSION >= 3
64 %include "file_py3.i" // python 3 FILE *
69 %feature("docstring") strerror "Convert error value to a human readable string."
71 // ================================================================================
72 // ub_resolve - perform resolution and validation
73 // ================================================================================
74 %typemap(in,numinputs=0,noblock=1) (struct ub_result** result)
76 struct ub_result* newubr;
80 /* result generation */
81 %typemap(argout,noblock=1) (struct ub_result** result)
83 if(1) { /* new code block for variable on stack */
85 tuple = PyTuple_New(2);
86 PyTuple_SetItem(tuple, 0, $result);
88 PyTuple_SetItem(tuple, 1, SWIG_NewPointerObj(SWIG_as_voidptr(newubr), SWIGTYPE_p_ub_result, SWIG_POINTER_OWN | 0 ));
90 PyTuple_SetItem(tuple, 1, Py_None);
97 // ================================================================================
98 // ub_ctx - validation context
99 // ================================================================================
100 %nodefaultctor ub_ctx; //no default constructor & destructor
101 %nodefaultdtor ub_ctx;
103 %newobject ub_ctx_create;
104 %delobject ub_ctx_delete;
105 %rename(_ub_ctx_delete) ub_ctx_delete;
107 %newobject ub_resolve;
110 void ub_ctx_free_dbg (struct ub_ctx* c) {
111 printf("******** UB_CTX free 0x%lX ************\n", (long unsigned int)c);
118 /** a host address */
120 /** an authoritative name server */
122 /** a mail destination (Obsolete - use MX) */
124 /** a mail forwarder (Obsolete - use MX) */
126 /** the canonical name for an alias */
128 /** marks the start of a zone of authority */
130 /** a mailbox domain name (EXPERIMENTAL) */
132 /** a mail group member (EXPERIMENTAL) */
134 /** a mail rename domain name (EXPERIMENTAL) */
136 /** a null RR (EXPERIMENTAL) */
138 /** a well known service description */
140 /** a domain name pointer */
142 /** host information */
144 /** mailbox or mail list information */
163 RR_TYPE_NSAP_PTR = 23,
174 /** LOC record RFC1876 */
178 /** draft-ietf-nimrod-dns-01.txt */
180 /** draft-ietf-nimrod-dns-01.txt */
182 /** SRV record RFC2782 */
184 /** http://www.jhsoft.com/rfc/af-saa-0069.000.rtf */
196 /** dnsind-kitchen-sink-02.txt */
198 /** Pseudo OPT record... */
202 /** draft-ietf-dnsext-delegation */
204 /** SSH Key Fingerprint */
206 /** draft-richardson-ipseckey-rr-11.txt */
207 RR_TYPE_IPSECKEY = 45,
208 /** draft-ietf-dnsext-dnssec-25 */
215 RR_TYPE_NSEC3PARAMS = 51,
220 RR_TYPE_UNSPEC = 103,
225 /** A request for mailbox-related records (MB, MG or MR) */
227 /** A request for mail agent RRs (Obsolete - see MX) */
229 /** any type (wildcard) */
232 /* RFC 4431, 5074, DNSSEC Lookaside Validation */
243 /** Hesiod (Dyer 87) */
245 /** None class, dynamic update */
252 %feature("docstring") ub_ctx "Unbound resolving and validation context.
254 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).
259 >>> ctx = unbound.ub_ctx()
260 >>> ctx.resolvconf(\"/etc/resolv.conf\")
261 >>> status, result = ctx.resolve(\"www.google.com\", unbound.RR_TYPE_A, unbound.RR_CLASS_IN)
262 >>> if status==0 and result.havedata:
263 >>> print \"Result:\",result.data.address_list
264 Result: ['74.125.43.147', '74.125.43.99', '74.125.43.103', '74.125.43.104']
271 """Creates a resolving and validation context.
273 An exception is invoked if the process of creation an ub_ctx instance fails.
275 self.this = _unbound.ub_ctx_create()
277 raise Exception("Fatal error: unbound context initialization failed")
279 #__swig_destroy__ = _unbound.ub_ctx_free_dbg
280 __swig_destroy__ = _unbound._ub_ctx_delete
284 """Add a trust anchor to the given context.
286 The trust anchor is a string, on one line, that holds a valid DNSKEY or DS RR.
289 string, with zone-format RR on one line. [domainname] [TTL optional] [type] [class optional] [rdata contents]
290 :returns: (int) 0 if OK, else error.
292 return _unbound.ub_ctx_add_ta(self,ta)
293 #parameters: struct ub_ctx *,char *,
296 def add_ta_file(self,fname):
297 """Add trust anchors to the given context.
299 Pass name of a file with DS and DNSKEY records (like from dig or drill).
302 filename of file with keyfile with trust anchors.
303 :returns: (int) 0 if OK, else error.
305 return _unbound.ub_ctx_add_ta_file(self,fname)
306 #parameters: struct ub_ctx *,char *,
309 def config(self,fname):
310 """setup configuration for the given context.
313 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.
314 :returns: (int) 0 if OK, else error.
316 return _unbound.ub_ctx_config(self,fname)
317 #parameters: struct ub_ctx *,char *,
320 def debuglevel(self,d):
321 """Set debug verbosity for the context Output is directed to stderr.
324 debug level, 0 is off, 1 is very minimal, 2 is detailed, and 3 is lots.
325 :returns: (int) 0 if OK, else error.
327 return _unbound.ub_ctx_debuglevel(self,d)
328 #parameters: struct ub_ctx *,int,
331 def debugout(self,out):
332 """Set debug output (and error output) to the specified stream.
334 Pass None to disable. Default is stderr.
337 File stream to log to.
338 :returns: (int) 0 if OK, else error.
342 In order to log into file, use
346 ctx = unbound.ub_ctx()
347 fw = fopen("debug.log")
351 Another option is to print the debug informations to stderr output
355 ctx = unbound.ub_ctx()
357 ctx.debugout(sys.stderr)
359 return _unbound.ub_ctx_debugout(self,out)
360 #parameters: struct ub_ctx *,void *,
363 def hosts(self,fname="/etc/hosts"):
364 """Read list of hosts from the filename given.
366 Usually "/etc/hosts". These addresses are not flagged as DNSSEC secure when queried for.
369 file name string. If None "/etc/hosts" is used.
370 :returns: (int) 0 if OK, else error.
372 return _unbound.ub_ctx_hosts(self,fname)
373 #parameters: struct ub_ctx *,char *,
376 def print_local_zones(self):
377 """Print the local zones and their content (RR data) to the debug output.
379 :returns: (int) 0 if OK, else error.
381 return _unbound.ub_ctx_print_local_zones(self)
382 #parameters: struct ub_ctx *,
385 def resolvconf(self,fname="/etc/resolv.conf"):
386 """Read list of nameservers to use from the filename given.
388 Usually "/etc/resolv.conf". Uses those nameservers as caching proxies. If they do not support DNSSEC, validation may fail.
390 Only nameservers are picked up, the searchdomain, ndots and other settings from resolv.conf(5) are ignored.
393 file name string. If None "/etc/resolv.conf" is used.
394 :returns: (int) 0 if OK, else error.
396 return _unbound.ub_ctx_resolvconf(self,fname)
397 #parameters: struct ub_ctx *,char *,
400 def set_async(self,dothread):
401 """Set a context behaviour for asynchronous action.
404 if True, enables threading and a call to :meth:`resolve_async` creates a thread to handle work in the background.
405 If False, a process is forked to handle work in the background.
406 Changes to this setting after :meth:`async` calls have been made have no effect (delete and re-create the context to change).
407 :returns: (int) 0 if OK, else error.
409 return _unbound.ub_ctx_async(self,dothread)
410 #parameters: struct ub_ctx *,int,
413 def set_fwd(self,addr):
414 """Set machine to forward DNS queries to, the caching resolver to use.
416 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.
418 To read the list of nameservers from /etc/resolv.conf (from DHCP or so), use the call :meth:`resolvconf`.
421 address, IP4 or IP6 in string format. If the addr is None, forwarding is disabled.
422 :returns: (int) 0 if OK, else error.
424 return _unbound.ub_ctx_set_fwd(self,addr)
425 #parameters: struct ub_ctx *,char *,
428 def set_option(self,opt,val):
429 """Set an option for the context.
431 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).
434 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.
437 :returns: (int) 0 if OK, else error.
439 return _unbound.ub_ctx_set_option(self,opt,val)
440 #parameters: struct ub_ctx *,char *,char *,
443 def trustedkeys(self,fname):
444 """Add trust anchors to the given context.
446 Pass the name of a bind-style config file with trusted-keys{}.
449 filename of file with bind-style config entries with trust anchors.
450 :returns: (int) 0 if OK, else error.
452 return _unbound.ub_ctx_trustedkeys(self,fname)
453 #parameters: struct ub_ctx *,char *,
457 def zone_print(self):
458 """Print local zones using debugout"""
459 _unbound.ub_ctx_print_local_zones(self)
461 def zone_add(self,zonename,zonetype):
462 """Add new local zone
464 :param zonename: zone domain name (e.g. myzone.)
465 :param zonetype: type of the zone ("static",...)
466 :returns: (int) 0 if OK, else error.
468 return _unbound.ub_ctx_zone_add(self,zonename, zonetype)
469 #parameters: struct ub_ctx *,char*, char*
472 def zone_remove(self,zonename):
475 If exists, removes local zone with all the RRs.
477 :param zonename: zone domain name
478 :returns: (int) 0 if OK, else error.
480 return _unbound.ub_ctx_zone_remove(self,zonename)
481 #parameters: struct ub_ctx *,char*
484 def data_add(self,rrdata):
485 """Add new local RR data
487 :param rrdata: string, in zone-format on one line. [domainname] [TTL optional] [type] [class optional] [rdata contents]
488 :returns: (int) 0 if OK, else error.
495 >>> ctx = unbound.ub_ctx()
496 >>> ctx.zone_add("mydomain.net.","static")
498 >>> status = ctx.data_add("test.mydomain.net. IN A 192.168.1.1")
500 >>> status, result = ctx.resolve("test.mydomain.net")
501 >>> if status==0 and result.havedata:
502 >>> print \"Result:\",result.data.address_list
503 Result: ['192.168.1.1']
506 return _unbound.ub_ctx_data_add(self,rrdata)
507 #parameters: struct ub_ctx *,char*
510 def data_remove(self,rrdata):
511 """Remove local RR data
513 If exists, remove resource record from local zone
515 :param rrdata: string, in zone-format on one line. [domainname] [TTL optional] [type] [class optional] [rdata contents]
516 :returns: (int) 0 if OK, else error.
518 return _unbound.ub_ctx_data_remove(self,rrdata)
519 #parameters: struct ub_ctx *,char*
523 def cancel(self,async_id):
524 """Cancel an async query in progress.
526 Its callback will not be called.
529 which query to cancel.
530 :returns: (int) 0 if OK, else error.
532 return _unbound.ub_cancel(self,async_id)
533 #parameters: struct ub_ctx *,int,
537 """Get file descriptor.
539 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.
541 :returns: (int) -1 on error, or file descriptor to use select(2) with.
543 return _unbound.ub_fd(self)
544 #parameters: struct ub_ctx *,
548 """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.
550 :returns: (int) 0 if nothing to read, or nonzero if a result is available. If nonzero, call ctx_process() to do callbacks.
552 return _unbound.ub_poll(self)
553 #parameters: struct ub_ctx *,
557 """Call this routine to continue processing results from the validating resolver (when the fd becomes readable).
559 Will perform necessary callbacks.
561 :returns: (int) 0 if OK, else error.
563 return _unbound.ub_process(self)
564 #parameters: struct ub_ctx *,
567 def resolve(self,name,rrtype=RR_TYPE_A,rrclass=RR_CLASS_IN):
568 """Perform resolution and validation of the target name.
571 domain name in text format (a string or unicode string). IDN domain name have to be passed as a unicode string.
573 type of RR in host order (optional argument). Default value is RR_TYPE_A (A class).
575 class of RR in host order (optional argument). Default value is RR_CLASS_IN (for internet).
576 :returns: * (int) 0 if OK, else error.
577 * (: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).
579 if isinstance(name, bytes): #probably IDN
580 return _unbound.ub_resolve(self,name,rrtype,rrclass)
582 return _unbound.ub_resolve(self,idn2dname(name),rrtype,rrclass)
583 #parameters: struct ub_ctx *,char *,int,int,
584 #retvals: int,struct ub_result **
586 def resolve_async(self,name,mydata,callback,rrtype=RR_TYPE_A,rrclass=RR_CLASS_IN):
587 """Perform resolution and validation of the target name.
589 Asynchronous, after a while, the callback will be called with your data and the result.
590 If an error happens during processing, your callback will be called with error set to a nonzero value (and result==None).
593 domain name in text format (a string or unicode string). IDN domain name have to be passed as a unicode string.
595 this data is your own data (you can pass arbitrary python object or None) which are passed on to the callback function.
597 call-back function which is called on completion of the resolution.
599 type of RR in host order (optional argument). Default value is RR_TYPE_A (A class).
601 class of RR in host order (optional argument). Default value is RR_CLASS_IN (for internet).
602 :returns: * (int) 0 if OK, else error.
603 * (int) async_id, an identifier number is returned for the query as it is in progress. It can be used to cancel the query.
605 **Call-back function:**
606 The call-back function looks as the follows::
608 def call_back(mydata, status, result):
612 * `mydata` - mydata object
613 * `status` - 0 when a result has been found
614 * `result` - the result structure. The result may be None, in that case err is set.
617 if isinstance(name, bytes): #probably IDN
618 return _unbound._ub_resolve_async(self,name,rrtype,rrclass,mydata,callback)
620 return _unbound._ub_resolve_async(self,idn2dname(name),rrtype,rrclass,mydata,callback)
621 #parameters: struct ub_ctx *,char *,int,int,void *,ub_callback_t,
625 """Wait for a context to finish with results.
627 Calls after the wait for you. After the wait, there are no more outstanding asynchronous queries.
629 :returns: (int) 0 if OK, else error.
631 return _unbound.ub_wait(self)
632 #parameters: struct ub_ctx *,
640 // ================================================================================
641 // ub_result - validation and resolution results
642 // ================================================================================
643 %nodefaultctor ub_result; //no default constructor & destructor
644 %nodefaultdtor ub_result;
646 %delobject ub_resolve_free;
647 %rename(_ub_resolve_free) ub_resolve_free;
650 void ub_resolve_free_dbg (struct ub_result* r) {
651 printf("******** UB_RESOLVE free 0x%lX ************\n", (long unsigned int)r);
656 %feature("docstring") ub_result "The validation and resolution results."
660 enum result_enum_rcode {
677 """Class which makes the resolution results accessible"""
678 def __init__(self, data):
679 """Creates ub_data class
680 :param data: a list of the result data in RAW format
683 raise Exception("ub_data init: No data")
687 """Represents data as string"""
688 return ';'.join([' '.join(map(lambda x:"%02X" % ord(x),a)) for a in self.data])
691 def dname2str(s, ofs=0, maxlen=0):
692 """Parses DNAME and produces a list of labels
694 :param ofs: where the conversion should start to parse data
695 :param maxlen: maximum length (0 means parse to the end)
696 :returns: list of labels (string)
704 slen = min(slen, maxlen)
708 complen = ord(s[idx])
709 # In python 3.x `str()` converts the string to unicode which is the expected text string type
710 res.append(str(s[idx+1:idx+1+complen].decode()))
715 def as_raw_data(self):
716 """Returns a list of RAW strings"""
719 raw = property(as_raw_data, doc="Returns RAW data (a list of binary encoded strings). See :meth:`as_raw_data`")
721 def as_mx_list(self):
722 """Represents data as a list of MX records (query for RR_TYPE_MX)
724 :returns: list of tuples (priority, dname)
726 return [(256*ord(rdf[0])+ord(rdf[1]),'.'.join([a for a in self.dname2str(rdf,2)])) for rdf in self.data]
728 mx_list = property(as_mx_list, doc="Returns a list of tuples containing priority and domain names. See :meth:`as_mx_list`")
730 def as_idn_mx_list(self):
731 """Represents data as a list of MX records (query for RR_TYPE_MX)
733 :returns: list of tuples (priority, unicode dname)
735 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]
737 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`")
739 def as_address_list(self):
740 """Represents data as a list of IP addresses (query for RR_TYPE_PTR)
742 :returns: list of strings
744 return ['.'.join(map(lambda x:str(ord(x)),a)) for a in self.data]
746 address_list = property(as_address_list, doc="Returns a list of IP addresses. See :meth:`as_address_list`")
748 def as_domain_list(self):
749 """Represents data as a list of domain names (query for RR_TYPE_A)
751 :returns: list of strings
753 return map(lambda x:'.'.join(self.dname2str(x)), self.data)
755 domain_list = property(as_domain_list, doc="Returns a list of domain names. See :meth:`as_domain_list`")
757 def as_idn_domain_list(self):
758 """Represents data as a list of unicode domain names (query for RR_TYPE_A)
760 :returns: list of strings
762 return map(lambda x: '.'.join([encodings.idna.ToUnicode(a) for a in self.dname2str(x)]), self.data)
764 domain_list_idn = property(as_idn_domain_list, doc="Returns a list of IDN domain names. See :meth:`as_idn_domain_list`")
772 PyObject* _ub_result_data(struct ub_result* result) {
776 if ((result == 0) || (!result->havedata) || (result->data == 0))
779 for (cnt=0,i=0;;i++,cnt++)
780 if (result->data[i] == 0)
783 list = PyList_New(cnt);
785 PyList_SetItem(list, i, PyBytes_FromStringAndSize(result->data[i],result->len[i]));
790 PyObject* _packet() {
791 return PyBytes_FromStringAndSize($self->answer_packet, $self->answer_len);
796 raise Exception("This class can't be created directly.")
798 #__swig_destroy__ = _unbound.ub_resolve_free_dbg
799 __swig_destroy__ = _unbound._ub_resolve_free
801 #havedata = property(_unbound.ub_result_havedata_get, _unbound.ub_result_havedata_set, "Havedata property")
803 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'}
805 def _get_rcode_str(self):
806 """Returns rcode in display representation form
810 return self.rcode2str[self.rcode]
812 __swig_getmethods__["rcode_str"] = _get_rcode_str
813 if _newclass:rcode_str = _swig_property(_get_rcode_str)
815 def _get_raw_data(self):
816 """Result data, a list of network order DNS rdata items.
818 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.
820 return self._ub_result_data(self)
822 __swig_getmethods__["rawdata"] = _get_raw_data
823 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.")
826 if not self.havedata: return None
827 return ub_data(self._ub_result_data(self))
829 __swig_getmethods__["data"] = _get_data
830 __swig_getmethods__["packet"] = _packet
831 data = property(_get_data, doc="Returns :class:`ub_data` instance containing various decoding functions or None")
837 %exception ub_resolve
839 //printf("resolve_start(%lX)\n",(long unsigned int)arg1);
840 Py_BEGIN_ALLOW_THREADS
843 //printf("resolve_stop()\n");
846 %include "libunbound/unbound.h"
849 //SWIG will see the ub_ctx as a class
854 //ub_ctx_debugout void* parameter correction
855 int ub_ctx_debugout(struct ub_ctx* ctx, FILE* out);
857 // ================================================================================
858 // ub_resolve_async - perform asynchronous resolution and validation
859 // ================================================================================
861 %typemap(in,numinputs=0,noblock=1) (int* async_id)
867 %apply PyObject* {void* mydata}
869 /* result generation */
870 %typemap(argout,noblock=1) (int* async_id)
872 if(1) { /* new code block for variable on stack */
874 tuple = PyTuple_New(2);
875 PyTuple_SetItem(tuple, 0, $result);
876 PyTuple_SetItem(tuple, 1, SWIG_From_int(asyncid));
881 // Grab a Python function object as a Python object.
882 %typemap(in) (PyObject *pyfunc) {
883 if (!PyCallable_Check($input))
885 PyErr_SetString(PyExc_TypeError, "Need a callable object!");
891 // Python callback workaround
892 int _ub_resolve_async(struct ub_ctx* ctx, char* name, int rrtype, int rrclass, void* mydata, PyObject *pyfunc, int* async_id);
900 static void PythonCallBack(void* iddata, int status, struct ub_result* result)
905 id = (struct cb_data*) iddata;
906 arglist = Py_BuildValue("(OiO)",id->data,status, SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ub_result, 0 | 0 )); // Build argument list
907 fresult = PyEval_CallObject(id->func,arglist); // Call Python
911 ub_resolve_free(result); //free ub_result
912 //ub_resolve_free_dbg(result); //free ub_result
913 Py_DECREF(arglist); // Trash arglist
917 int _ub_resolve_async(struct ub_ctx* ctx, char* name, int rrtype, int rrclass, PyObject* mydata, PyObject *pyfunc, int* async_id) {
920 id = (struct cb_data*) malloc(sizeof(struct cb_data));
924 r = ub_resolve_async(ctx,name,rrtype,rrclass, (void *) id, PythonCallBack, async_id);
933 ub_resolve_async = _unbound._ub_resolve_async
936 """Reverse domain name
938 Usable for reverse lookups when the IP address should be reversed
940 return '.'.join([a for a in domain.split(".")][::-1])
942 def idn2dname(idnname):
943 """Converts domain name in IDN format to canonic domain name
945 :param idnname: (unicode string) IDN name
946 :returns: (string) domain name
948 return '.'.join([encodings.idna.ToASCII(a) if a else '' for a in idnname.split('.')])
951 """Converts canonic domain name in IDN format to unicode string
953 :param name: (string) domain name
954 :returns: (unicode string) domain name
956 return '.'.join([encodings.idna.ToUnicode(a) for a in name.split('.')])