EasyPG 1.07 Released
[packages] / xemacs-packages / net-utils / dns.el
1 ;;; dns.el --- Domain Name Service lookups
2
3 ;; Copyright (C) 2002-2016 Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: network comm
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 3 of the License, or
13 ;; (at your option) 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.  If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;;; Code:
26
27 (defvar dns-timeout 5
28   "How many seconds to wait when doing DNS queries.")
29
30 (defvar dns-servers nil
31   "List of DNS servers to query.
32 If nil, /etc/resolv.conf and nslookup will be consulted.")
33
34 (defvar dns-servers-valid-for-interfaces (featurep 'xemacs)
35   "The return value of `network-interface-list' when `dns-servers' was set.
36 If the set of network interfaces and/or their IP addresses
37 change, then presumably the list of DNS servers needs to be
38 updated.  Set this variable to t to disable the check.
39
40 Defaults to t on XEmacs and SXEmacs as they do not have
41 `network-interface-list'.")
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   (with-temp-buffer
112     (unless (featurep 'xemacs) (set-buffer-multibyte nil))
113     (insert string)
114     (goto-char (point-min))
115     (dns-read-name buffer)))
116
117 (defun dns-read-name (&optional buffer)
118   (let ((ended nil)
119         (name nil)
120         length)
121     (while (not ended)
122       (setq length (dns-read-bytes 1))
123       (if (= 192 (logand length (lsh 3 6)))
124           (let ((offset (+ (* (logand 63 length) 256)
125                            (dns-read-bytes 1))))
126             (save-excursion
127               (when buffer
128                 (set-buffer buffer))
129               (goto-char (1+ offset))
130               (setq ended (dns-read-name buffer))))
131         (if (zerop length)
132             (setq ended t)
133           (push (buffer-substring (point)
134                                   (progn (forward-char length) (point)))
135                 name))))
136     (if (stringp ended)
137         (if (null name)
138             ended
139           (concat (mapconcat 'identity (nreverse name) ".") "." ended))
140       (mapconcat 'identity (nreverse name) "."))))
141
142 (defun dns-write (spec &optional tcp-p)
143   "Write a DNS packet according to SPEC.
144 If TCP-P, the first two bytes of the package with be the length field."
145   (with-temp-buffer
146     (unless (featurep 'xemacs) (set-buffer-multibyte nil))
147     (dns-write-bytes (dns-get 'id spec) 2)
148     (dns-write-bytes
149      (logior
150       (lsh (if (dns-get 'response-p spec) 1 0) -7)
151       (lsh
152        (cond
153         ((eq (dns-get 'opcode spec) 'query) 0)
154         ((eq (dns-get 'opcode spec) 'inverse-query) 1)
155         ((eq (dns-get 'opcode spec) 'status) 2)
156         (t (error "No such opcode: %s" (dns-get 'opcode spec))))
157        -3)
158       (lsh (if (dns-get 'authoritative-p spec) 1 0) -2)
159       (lsh (if (dns-get 'truncated-p spec) 1 0) -1)
160       (lsh (if (dns-get 'recursion-desired-p spec) 1 0) 0)))
161     (dns-write-bytes
162      (cond
163       ((eq (dns-get 'response-code spec) 'no-error) 0)
164       ((eq (dns-get 'response-code spec) 'format-error) 1)
165       ((eq (dns-get 'response-code spec) 'server-failure) 2)
166       ((eq (dns-get 'response-code spec) 'name-error) 3)
167       ((eq (dns-get 'response-code spec) 'not-implemented) 4)
168       ((eq (dns-get 'response-code spec) 'refused) 5)
169       (t 0)))
170     (dns-write-bytes (length (dns-get 'queries spec)) 2)
171     (dns-write-bytes (length (dns-get 'answers spec)) 2)
172     (dns-write-bytes (length (dns-get 'authorities spec)) 2)
173     (dns-write-bytes (length (dns-get 'additionals spec)) 2)
174     (dolist (query (dns-get 'queries spec))
175       (dns-write-name (car query))
176       (dns-write-bytes (cadr (assq (or (dns-get 'type query) 'A)
177                                    dns-query-types)) 2)
178       (dns-write-bytes (cadr (assq (or (dns-get 'class query) 'IN)
179                                    dns-classes)) 2))
180     (dolist (slot '(answers authorities additionals))
181       (dolist (resource (dns-get slot spec))
182         (dns-write-name (car resource))
183       (dns-write-bytes (cadr (assq (dns-get 'type resource) dns-query-types))
184                        2)
185       (dns-write-bytes (cadr (assq (dns-get 'class resource) dns-classes))
186                        2)
187       (dns-write-bytes (dns-get 'ttl resource) 4)
188       (dns-write-bytes (length (dns-get 'data resource)) 2)
189       (insert (dns-get 'data resource))))
190     (when tcp-p
191       (goto-char (point-min))
192       (dns-write-bytes (buffer-size) 2))
193     (buffer-string)))
194
195 (defun dns-read (packet)
196   (with-temp-buffer
197     (unless (featurep 'xemacs) (set-buffer-multibyte nil))
198     (let ((spec nil)
199           queries answers authorities additionals)
200       (insert packet)
201       (goto-char (point-min))
202       (push (list 'id (dns-read-bytes 2)) spec)
203       (let ((byte (dns-read-bytes 1)))
204         (push (list 'response-p (if (zerop (logand byte (lsh 1 7))) nil t))
205               spec)
206         (let ((opcode (logand byte (lsh 7 3))))
207           (push (list 'opcode
208                       (cond ((eq opcode 0) 'query)
209                             ((eq opcode 1) 'inverse-query)
210                             ((eq opcode 2) 'status)))
211                 spec))
212         (push (list 'authoritative-p (if (zerop (logand byte (lsh 1 2)))
213                                          nil t)) spec)
214         (push (list 'truncated-p (if (zerop (logand byte (lsh 1 2))) nil t))
215               spec)
216         (push (list 'recursion-desired-p
217                     (if (zerop (logand byte (lsh 1 0))) nil t)) spec))
218       (let ((rc (logand (dns-read-bytes 1) 15)))
219         (push (list 'response-code
220                     (cond
221                      ((eq rc 0) 'no-error)
222                      ((eq rc 1) 'format-error)
223                      ((eq rc 2) 'server-failure)
224                      ((eq rc 3) 'name-error)
225                      ((eq rc 4) 'not-implemented)
226                      ((eq rc 5) 'refused)))
227               spec))
228       (setq queries (dns-read-bytes 2))
229       (setq answers (dns-read-bytes 2))
230       (setq authorities (dns-read-bytes 2))
231       (setq additionals (dns-read-bytes 2))
232       (let ((qs nil))
233         (dotimes (i queries)
234           (push (list (dns-read-name)
235                       (list 'type (dns-inverse-get (dns-read-bytes 2)
236                                                    dns-query-types))
237                       (list 'class (dns-inverse-get (dns-read-bytes 2)
238                                                     dns-classes)))
239                 qs))
240         (push (list 'queries qs) spec))
241       (dolist (slot '(answers authorities additionals))
242         (let ((qs nil)
243               type)
244           (dotimes (i (symbol-value slot))
245             (push (list (dns-read-name)
246                         (list 'type
247                               (setq type (dns-inverse-get (dns-read-bytes 2)
248                                                           dns-query-types)))
249                         (list 'class (dns-inverse-get (dns-read-bytes 2)
250                                                       dns-classes))
251                         (list 'ttl (dns-read-bytes 4))
252                         (let ((length (dns-read-bytes 2)))
253                           (list 'data
254                                 (dns-read-type
255                                  (buffer-substring
256                                   (point)
257                                   (progn (forward-char length) (point)))
258                                  type))))
259                   qs))
260           (push (list slot qs) spec)))
261       (nreverse spec))))
262
263 (defun dns-read-int32 ()
264   ;; Full 32 bit Integers can't be handled by 32-bit Emacsen.  If we
265   ;; use floats, it works.
266   (format "%.0f" (+ (* (dns-read-bytes 1) 16777216.0)
267                     (dns-read-bytes 3))))
268
269 (defun dns-read-type (string type)
270   (let ((buffer (current-buffer))
271         (point (point)))
272     (prog1
273         (with-temp-buffer
274           (unless (featurep 'xemacs) (set-buffer-multibyte nil))
275           (insert string)
276           (goto-char (point-min))
277           (cond
278            ((eq type 'A)
279             (let ((bytes nil))
280               (dotimes (i 4)
281                 (push (dns-read-bytes 1) bytes))
282               (mapconcat 'number-to-string (nreverse bytes) ".")))
283            ((eq type 'AAAA)
284             (let (hextets)
285               (dotimes (i 8)
286                 (push (dns-read-bytes 2) hextets))
287               (mapconcat (lambda (n) (format "%x" n))
288                          (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 (declare-function network-interface-list "process.c")
310
311 (defun dns-servers-up-to-date-p ()
312   "Return false if we need to recheck the list of DNS servers."
313   (and dns-servers
314        (or (eq dns-servers-valid-for-interfaces t)
315            ;; `network-interface-list' was introduced in Emacs 22.1.
316            (not (fboundp 'network-interface-list))
317            (equal dns-servers-valid-for-interfaces
318                   (network-interface-list)))))
319
320 (defun dns-set-servers ()
321   "Set `dns-servers' to a list of DNS servers or nil if none are found.
322 Parses \"/etc/resolv.conf\" or calls \"nslookup\"."
323   (or (when (file-exists-p "/etc/resolv.conf")
324         (setq dns-servers nil)
325         (with-temp-buffer
326           (insert-file-contents "/etc/resolv.conf")
327           (goto-char (point-min))
328           (while (re-search-forward "^nameserver[\t ]+\\([^ \t\n]+\\)" nil t)
329             (push (match-string 1) dns-servers))
330           (setq dns-servers (nreverse dns-servers))))
331       (when (executable-find "nslookup")
332         (with-temp-buffer
333           (call-process "nslookup" nil t nil "localhost")
334           (goto-char (point-min))
335           (re-search-forward
336            "^Address:[ \t]*\\([0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+\\)" nil t)
337           (setq dns-servers (list (match-string 1))))))
338   (when-fboundp 'network-interface-list
339     (setq dns-servers-valid-for-interfaces (network-interface-list))))
340
341 (defun dns-read-txt (string)
342   (if (> (length string) 1)
343       (substring string 1)
344     string))
345
346 (defun dns-get-txt-answer (answers)
347   (let ((result "")
348         (do-next nil))
349     (dolist (answer answers)
350       (dolist (elem answer)
351         (when (consp elem)
352           (cond
353            ((eq (car elem) 'type)
354             (setq do-next (eq (cadr elem) 'TXT)))
355            ((eq (car elem) 'data)
356             (when do-next
357               (setq result (concat result (dns-read-txt (cadr elem))))))))))
358     result))
359
360 ;;; Interface functions.
361 (defmacro dns-make-network-process (server)
362   (if (featurep 'xemacs)
363       `(let ((coding-system-for-read 'binary)
364              (coding-system-for-write 'binary))
365          (open-network-stream "dns" (current-buffer)
366                               ,server "domain" 'udp))
367     `(let ((server ,server)
368            (coding-system-for-read 'binary)
369            (coding-system-for-write 'binary))
370        (if (fboundp 'make-network-process)
371            (make-network-process
372             :name "dns"
373             :coding 'binary
374             :buffer (current-buffer)
375             :host server
376             :service "domain"
377             :type 'datagram)
378          ;; Older versions of Emacs doesn't have
379          ;; `make-network-process', so we fall back on opening a TCP
380          ;; connection to the DNS server.
381          (open-network-stream "dns" (current-buffer) server "domain")))))
382
383 (defvar dns-cache (make-vector 4096 0))
384
385 (defun dns-query-cached (name &optional type fullp reversep)
386   (let* ((key (format "%s:%s:%s:%s" name type fullp reversep))
387          (sym (intern-soft key dns-cache)))
388     (if (and sym
389              (boundp sym))
390         (symbol-value sym)
391       (let ((result (dns-query name type fullp reversep)))
392         (set (intern key dns-cache) result)
393         result))))
394
395 ;; The old names `query-dns' and `query-dns-cached' weren't used in Emacs 23
396 ;; yet, so no alias are provided.  --rsteib
397
398 (defun dns-query (name &optional type fullp reversep)
399   "Query a DNS server for NAME of TYPE.
400 If FULLP, return the entire record returned.
401 If REVERSEP, look up an IP address."
402   (setq type (or type 'A))
403   (unless (dns-servers-up-to-date-p)
404     (dns-set-servers))
405
406   (when reversep
407     (setq name (concat
408                 (mapconcat 'identity (nreverse (split-string name "\\.")) ".")
409                 ".in-addr.arpa")
410           type 'PTR))
411
412   (if (not dns-servers)
413       (message "No DNS server configuration found")
414     (with-temp-buffer
415       (unless (featurep 'xemacs) (set-buffer-multibyte nil))
416       (let ((process (condition-case ()
417                          (dns-make-network-process (car dns-servers))
418                        (error
419                         (message
420                          "dns: Got an error while trying to talk to %s"
421                          (car dns-servers))
422                         nil)))
423             (tcp-p (and (not (fboundp 'make-network-process))
424                         (not (featurep 'xemacs))))
425             (step 100)
426             (times (* dns-timeout 1000))
427             (id (random 65000)))
428         (when process
429           (process-send-string
430            process
431            (dns-write `((id ,id)
432                         (opcode query)
433                         (queries ((,name (type ,type))))
434                         (recursion-desired-p t))
435                       tcp-p))
436           (while (and (zerop (buffer-size))
437                       (> times 0))
438             (sit-for (/ step 1000.0))
439             (accept-process-output process 0 step)
440             (setq times (- times step)))
441           (condition-case nil
442               (delete-process process)
443             (error nil))
444           (when (and tcp-p
445                      (>= (buffer-size) 2))
446             (goto-char (point-min))
447             (delete-region (point) (+ (point) 2)))
448           (when (and (>= (buffer-size) 2)
449                      ;; We had a time-out.
450                      (> times 0))
451             (let ((result (dns-read (buffer-string))))
452               (if fullp
453                   result
454                 (let ((answer (car (dns-get 'answers result))))
455                   (when (eq type (dns-get 'type answer))
456                     (if (eq type 'TXT)
457                         (dns-get-txt-answer (dns-get 'answers result))
458                       (dns-get 'data answer))))))))))))
459
460 (provide 'dns)
461
462 ;;; dns.el ends here