Initial Commit
[packages] / xemacs-packages / net-utils / dns.el
1 ;;; dns.el --- Domain Name Service lookups
2
3 ;; Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: network
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23 ;; Boston, MA 02110-1301, USA.
24
25 ;;; Commentary:
26
27 ;;; Code:
28
29 (eval-when-compile (require 'cl))
30
31 (eval-when-compile
32   (defvar default-enable-multibyte-characters))
33
34 (require 'mm-util)
35
36 (defvar dns-timeout 5
37   "How many seconds to wait when doing DNS queries.")
38
39 (defvar dns-servers nil
40   "Which DNS servers to query.
41 If nil, /etc/resolv.conf will be consulted.")
42
43 ;;; Internal code:
44
45 (defvar dns-query-types
46   '((A 1)
47     (NS 2)
48     (MD 3)
49     (MF 4)
50     (CNAME 5)
51     (SOA 6)
52     (MB 7)
53     (MG 8)
54     (MR 9)
55     (NULL 10)
56     (WKS 11)
57     (PTR 12)
58     (HINFO 13)
59     (MINFO 14)
60     (MX 15)
61     (TXT 16)
62     (AAAA 28) ; RFC3596
63     (SRV 33) ; RFC2782
64     (AXFR 252)
65     (MAILB 253)
66     (MAILA 254)
67     (* 255))
68   "Names of query types and their values.")
69
70 (defvar dns-classes
71   '((IN 1)
72     (CS 2)
73     (CH 3)
74     (HS 4))
75   "Classes of queries.")
76
77 (defun dns-write-bytes (value &optional length)
78   (let (bytes)
79     (dotimes (i (or length 1))
80       (push (% value 256) bytes)
81       (setq value (/ value 256)))
82     (dolist (byte bytes)
83       (insert byte))))
84
85 (defun dns-read-bytes (length)
86   (let ((value 0))
87     (dotimes (i length)
88       (setq value (logior (* value 256) (following-char)))
89       (forward-char 1))
90     value))
91
92 (defun dns-get (type spec)
93   (cadr (assq type spec)))
94
95 (defun dns-inverse-get (value spec)
96   (let ((found nil))
97     (while (and (not found)
98                 spec)
99       (if (eq value (cadr (car spec)))
100           (setq found (caar spec))
101         (pop spec)))
102     found))
103
104 (defun dns-write-name (name)
105   (dolist (part (split-string name "\\."))
106     (dns-write-bytes (length part))
107     (insert part))
108   (dns-write-bytes 0))
109
110 (defun dns-read-string-name (string buffer)
111   (mm-with-unibyte-buffer
112     (insert string)
113     (goto-char (point-min))
114     (dns-read-name buffer)))
115
116 (defun dns-read-name (&optional buffer)
117   (let ((ended nil)
118         (name nil)
119         length)
120     (while (not ended)
121       (setq length (dns-read-bytes 1))
122       (if (= 192 (logand length (lsh 3 6)))
123           (let ((offset (+ (* (logand 63 length) 256)
124                            (dns-read-bytes 1))))
125             (save-excursion
126               (when buffer
127                 (set-buffer buffer))
128               (goto-char (1+ offset))
129               (setq ended (dns-read-name buffer))))
130         (if (zerop length)
131             (setq ended t)
132           (push (buffer-substring (point)
133                                   (progn (forward-char length) (point)))
134                 name))))
135     (if (stringp ended)
136         (if (null name)
137             ended
138           (concat (mapconcat 'identity (nreverse name) ".") "." ended))
139       (mapconcat 'identity (nreverse name) "."))))
140
141 (defun dns-write (spec &optional tcp-p)
142   "Write a DNS packet according to SPEC.
143 If TCP-P, the first two bytes of the package with be the length field."
144   (with-temp-buffer
145     (dns-write-bytes (dns-get 'id spec) 2)
146     (dns-write-bytes
147      (logior
148       (lsh (if (dns-get 'response-p spec) 1 0) -7)
149       (lsh
150        (cond
151         ((eq (dns-get 'opcode spec) 'query) 0)
152         ((eq (dns-get 'opcode spec) 'inverse-query) 1)
153         ((eq (dns-get 'opcode spec) 'status) 2)
154         (t (error "No such opcode: %s" (dns-get 'opcode spec))))
155        -3)
156       (lsh (if (dns-get 'authoritative-p spec) 1 0) -2)
157       (lsh (if (dns-get 'truncated-p spec) 1 0) -1)
158       (lsh (if (dns-get 'recursion-desired-p spec) 1 0) 0)))
159     (dns-write-bytes
160      (cond 
161       ((eq (dns-get 'response-code spec) 'no-error) 0)
162       ((eq (dns-get 'response-code spec) 'format-error) 1)
163       ((eq (dns-get 'response-code spec) 'server-failure) 2)
164       ((eq (dns-get 'response-code spec) 'name-error) 3)
165       ((eq (dns-get 'response-code spec) 'not-implemented) 4)
166       ((eq (dns-get 'response-code spec) 'refused) 5)
167       (t 0)))
168     (dns-write-bytes (length (dns-get 'queries spec)) 2)
169     (dns-write-bytes (length (dns-get 'answers spec)) 2)
170     (dns-write-bytes (length (dns-get 'authorities spec)) 2)
171     (dns-write-bytes (length (dns-get 'additionals spec)) 2)
172     (dolist (query (dns-get 'queries spec))
173       (dns-write-name (car query))
174       (dns-write-bytes (cadr (assq (or (dns-get 'type query) 'A)
175                                    dns-query-types)) 2)
176       (dns-write-bytes (cadr (assq (or (dns-get 'class query) 'IN)
177                                    dns-classes)) 2))
178     (dolist (slot '(answers authorities additionals))
179       (dolist (resource (dns-get slot spec))
180         (dns-write-name (car resource))
181       (dns-write-bytes (cadr (assq (dns-get 'type resource) dns-query-types))
182                        2)
183       (dns-write-bytes (cadr (assq (dns-get 'class resource) dns-classes))
184                        2)
185       (dns-write-bytes (dns-get 'ttl resource) 4)
186       (dns-write-bytes (length (dns-get 'data resource)) 2)
187       (insert (dns-get 'data resource))))
188     (when tcp-p
189       (goto-char (point-min))
190       (dns-write-bytes (buffer-size) 2))
191     (buffer-string)))
192
193 (eval-when-compile
194   (defvar answers)
195   (defvar authorities)
196   (defvar additionals))
197
198 (defun dns-read (packet)
199   (mm-with-unibyte-buffer
200     (let ((spec nil)
201           queries answers authorities additionals)
202       (insert packet)
203       (goto-char (point-min))
204       (push (list 'id (dns-read-bytes 2)) spec)
205       (let ((byte (dns-read-bytes 1)))
206         (push (list 'response-p (if (zerop (logand byte (lsh 1 7))) nil t))
207               spec)
208         (let ((opcode (logand byte (lsh 7 3))))
209           (push (list 'opcode
210                       (cond ((eq opcode 0) 'query)
211                             ((eq opcode 1) 'inverse-query)
212                             ((eq opcode 2) 'status)))
213                 spec))
214         (push (list 'authoritative-p (if (zerop (logand byte (lsh 1 2)))
215                                          nil t)) spec)
216         (push (list 'truncated-p (if (zerop (logand byte (lsh 1 2))) nil t))
217               spec)
218         (push (list 'recursion-desired-p
219                     (if (zerop (logand byte (lsh 1 0))) nil t)) spec))
220       (let ((rc (logand (dns-read-bytes 1) 15)))
221         (push (list 'response-code
222                     (cond
223                      ((eq rc 0) 'no-error)
224                      ((eq rc 1) 'format-error)
225                      ((eq rc 2) 'server-failure)
226                      ((eq rc 3) 'name-error)
227                      ((eq rc 4) 'not-implemented)
228                      ((eq rc 5) 'refused)))
229               spec))
230       (setq queries (dns-read-bytes 2))
231       (setq answers (dns-read-bytes 2))
232       (setq authorities (dns-read-bytes 2))
233       (setq additionals (dns-read-bytes 2))
234       (let ((qs nil))
235         (dotimes (i queries)
236           (push (list (dns-read-name)
237                       (list 'type (dns-inverse-get (dns-read-bytes 2)
238                                                    dns-query-types))
239                       (list 'class (dns-inverse-get (dns-read-bytes 2)
240                                                     dns-classes)))
241                 qs))
242         (push (list 'queries qs) spec))
243     (dolist (slot '(answers authorities additionals))
244       (let ((qs nil)
245             type)
246         (dotimes (i (symbol-value slot))
247           (push (list (dns-read-name)
248                       (list 'type
249                             (setq type (dns-inverse-get (dns-read-bytes 2)
250                                                         dns-query-types)))
251                       (list 'class (dns-inverse-get (dns-read-bytes 2)
252                                                     dns-classes))
253                       (list 'ttl (dns-read-bytes 4))
254                       (let ((length (dns-read-bytes 2)))
255                         (list 'data
256                               (dns-read-type
257                                (buffer-substring
258                                 (point)
259                                 (progn (forward-char length) (point)))
260                                type))))
261                 qs))
262         (push (list slot qs) spec)))
263     (nreverse spec))))
264
265 (defun dns-read-int32 ()
266   ;; Full 32 bit Integers can't be handled by Emacs.  If we use
267   ;; floats, it works.
268   (format "%.0f" (+ (* (dns-read-bytes 1) 16777216.0)
269                     (dns-read-bytes 3))))
270
271 (defun dns-read-type (string type)
272   (let ((buffer (current-buffer))
273         (point (point)))
274     (prog1
275         (mm-with-unibyte-buffer
276           (insert string)
277           (goto-char (point-min))
278           (cond
279            ((eq type 'A)
280             (let ((bytes nil))
281               (dotimes (i 4)
282                 (push (dns-read-bytes 1) bytes))
283               (mapconcat 'number-to-string (nreverse bytes) ".")))
284            ((eq type 'AAAA)
285             (let (hextets)
286               (dotimes (i 8)
287                 (push (dns-read-bytes 2) hextets))
288               (mapconcat (lambda (n) (format "%x" n)) (nreverse hextets) ":")))
289            ((eq type 'SOA)
290             (list (list 'mname (dns-read-name buffer))
291                   (list 'rname (dns-read-name buffer))
292                   (list 'serial (dns-read-int32))
293                   (list 'refresh (dns-read-int32))
294                   (list 'retry (dns-read-int32))
295                   (list 'expire (dns-read-int32))
296                   (list 'minimum (dns-read-int32))))
297            ((eq type 'SRV)
298             (list (list 'priority (dns-read-bytes 2))
299                   (list 'weight (dns-read-bytes 2))
300                   (list 'port (dns-read-bytes 2))
301                   (list 'target (dns-read-name buffer))))
302            ((eq type 'MX)
303             (cons (dns-read-bytes 2) (dns-read-name buffer)))
304            ((or (eq type 'CNAME) (eq type 'NS) (eq type 'PTR))
305             (dns-read-string-name string buffer))
306            (t string)))
307       (goto-char point))))
308
309 (defun dns-parse-resolv-conf ()
310   (when (file-exists-p "/etc/resolv.conf")
311     (with-temp-buffer
312       (insert-file-contents "/etc/resolv.conf")
313       (goto-char (point-min))
314       (while (re-search-forward "^nameserver[\t ]+\\([^ \t\n]+\\)" nil t)
315         (push (match-string 1) dns-servers))
316       (setq dns-servers (nreverse dns-servers)))))
317
318 (defun dns-read-txt (string)
319   (if (> (length string) 1)
320       (substring string 1)
321     string))
322
323 (defun dns-get-txt-answer (answers)
324   (let ((result "")
325         (do-next nil))
326     (dolist (answer answers)
327       (dolist (elem answer)
328         (when (consp elem)
329           (cond
330            ((eq (car elem) 'type)
331             (setq do-next (eq (cadr elem) 'TXT)))
332            ((eq (car elem) 'data)
333             (when do-next
334               (setq result (concat result (dns-read-txt (cadr elem))))))))))
335     result))
336
337 ;;; Interface functions.
338 (defmacro dns-make-network-process (server)
339   (if (featurep 'xemacs)
340       `(let ((coding-system-for-read 'binary)
341              (coding-system-for-write 'binary))
342          (open-network-stream "dns" (current-buffer)
343                               ,server "domain" 'udp))
344     `(let ((server ,server)
345            (coding-system-for-read 'binary)
346            (coding-system-for-write 'binary))
347        (if (fboundp 'make-network-process)
348            (make-network-process
349             :name "dns"
350             :coding 'binary
351             :buffer (current-buffer)
352             :host server
353             :service "domain"
354             :type 'datagram)
355          ;; Older versions of Emacs doesn't have
356          ;; `make-network-process', so we fall back on opening a TCP
357          ;; connection to the DNS server.
358          (open-network-stream "dns" (current-buffer) server "domain")))))
359
360 (defvar dns-cache (make-vector 4096 0))
361
362 (defun query-dns-cached (name &optional type fullp reversep)
363   (let* ((key (format "%s:%s:%s:%s" name type fullp reversep))
364          (sym (intern-soft key dns-cache)))
365     (if (and sym
366              (boundp sym))
367         (symbol-value sym)
368       (let ((result (query-dns name type fullp reversep)))
369         (set (intern key dns-cache) result)
370         result))))
371
372 (defun query-dns (name &optional type fullp reversep)
373   "Query a DNS server for NAME of TYPE.
374 If FULLP, return the entire record returned.
375 If REVERSEP, look up an IP address."
376   (setq type (or type 'A))
377   (unless dns-servers
378     (dns-parse-resolv-conf))
379
380   (when reversep
381     (setq name (concat
382                 (mapconcat 'identity (nreverse (split-string name "\\.")) ".")
383                 ".in-addr.arpa")
384           type 'PTR))
385
386   (if (not dns-servers)
387       (message "No DNS server configuration found")
388     (mm-with-unibyte-buffer
389       (let ((process (condition-case ()
390                          (dns-make-network-process (car dns-servers))
391                        (error
392                         (message "dns: Got an error while trying to talk to %s"
393                                  (car dns-servers))
394                         nil)))
395             (tcp-p (and (not (fboundp 'make-network-process))
396                         (not (featurep 'xemacs))))
397             (step 100)
398             (times (* dns-timeout 1000))
399             (id (random 65000)))
400         (when process
401           (process-send-string
402            process
403            (dns-write `((id ,id)
404                         (opcode query)
405                         (queries ((,name (type ,type))))
406                         (recursion-desired-p t))
407                       tcp-p))
408           (while (and (zerop (buffer-size))
409                       (> times 0))
410             (sit-for (/ step 1000.0))
411             (accept-process-output process 0 step)
412             (decf times step))
413           (ignore-errors
414             (delete-process process))
415           (when (and tcp-p
416                      (>= (buffer-size) 2))
417             (goto-char (point-min))
418             (delete-region (point) (+ (point) 2)))
419           (when (and (>= (buffer-size) 2)
420                      ;; We had a time-out.
421                      (> times 0))
422             (let ((result (dns-read (buffer-string))))
423               (if fullp
424                   result
425                 (let ((answer (car (dns-get 'answers result))))
426                   (when (eq type (dns-get 'type answer))
427                     (if (eq type 'TXT)
428                         (dns-get-txt-answer (dns-get 'answers result))
429                       (dns-get 'data answer))))))))))))
430
431 (provide 'dns)
432
433 ;;; dns.el ends here