Nuke arch-tags.
[emacs.git] / lisp / net / socks.el
blobdf4ffb732496d483abc34d1cdeab934326b1b5ef
1 ;;; socks.el --- A Socks v5 Client for Emacs
3 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2002,
4 ;; 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
6 ;; Author: William M. Perry <wmperry@gnu.org>
7 ;; Dave Love <fx@gnu.org>
8 ;; Keywords: comm, firewalls
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; This is an implementation of the SOCKS v5 protocol as defined in
28 ;; RFC 1928.
30 ;; TODO
31 ;; - Finish the redirection rules stuff
32 ;; - Implement composition of servers. Recursively evaluate the
33 ;; redirection rules and do SOCKS-over-HTTP and SOCKS-in-SOCKS
35 (eval-when-compile
36 (require 'wid-edit))
37 (require 'custom)
39 (if (not (fboundp 'split-string))
40 (defun split-string (string &optional pattern)
41 "Return a list of substrings of STRING which are separated by PATTERN.
42 If PATTERN is omitted, it defaults to \"[ \\f\\t\\n\\r\\v]+\"."
43 (or pattern
44 (setq pattern "[ \f\t\n\r\v]+"))
45 (let (parts (start 0))
46 (while (string-match pattern string start)
47 (setq parts (cons (substring string start (match-beginning 0)) parts)
48 start (match-end 0)))
49 (nreverse (cons (substring string start) parts)))))
50 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
51 ;;; Custom widgets
52 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
53 (define-widget 'dynamic-choice 'menu-choice
54 "A pretty simple dynamic dropdown list"
55 :format "%[%t%]: %v"
56 :tag "Network"
57 :case-fold t
58 :void '(item :format "invalid (%t)\n")
59 :value-create 's5-widget-value-create
60 :value-delete 'widget-children-value-delete
61 :value-get 'widget-choice-value-get
62 :value-inline 'widget-choice-value-inline
63 :mouse-down-action 'widget-choice-mouse-down-action
64 :action 'widget-choice-action
65 :error "Make a choice"
66 :validate 'widget-choice-validate
67 :match 's5-dynamic-choice-match
68 :match-inline 's5-dynamic-choice-match-inline)
70 (defun s5-dynamic-choice-match (widget value)
71 (let ((choices (funcall (widget-get widget :choice-function)))
72 current found)
73 (while (and choices (not found))
74 (setq current (car choices)
75 choices (cdr choices)
76 found (widget-apply current :match value)))
77 found))
79 (defun s5-dynamic-choice-match-inline (widget value)
80 (let ((choices (funcall (widget-get widget :choice-function)))
81 current found)
82 (while (and choices (not found))
83 (setq current (car choices)
84 choices (cdr choices)
85 found (widget-match-inline current value)))
86 found))
88 (defun s5-widget-value-create (widget)
89 (let ((choices (funcall (widget-get widget :choice-function)))
90 (value (widget-get widget :value)))
91 (if (not value)
92 (widget-put widget :value (widget-value (car choices))))
93 (widget-put widget :args choices)
94 (widget-choice-value-create widget)))
96 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
97 ;;; Customization support
98 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
99 (defgroup socks nil
100 "SOCKS Support"
101 :version "22.2"
102 :prefix "socks-"
103 :group 'processes)
105 '(defcustom socks-server-aliases nil
106 "A list of server aliases for use in access control and filtering rules."
107 :group 'socks
108 :type '(repeat (list :format "%v"
109 :value ("" "" 1080 5)
110 (string :tag "Alias")
111 (string :tag "Hostname/IP Address")
112 (integer :tag "Port #")
113 (choice :tag "SOCKS Version"
114 (integer :tag "SOCKS v4" :value 4)
115 (integer :tag "SOCKS v5" :value 5)))))
117 '(defcustom socks-network-aliases
118 '(("Anywhere" (netmask "0.0.0.0" "0.0.0.0")))
119 "A list of network aliases for use in subsequent rules."
120 :group 'socks
121 :type '(repeat (list :format "%v"
122 :value (netmask "" "255.255.255.0")
123 (string :tag "Alias")
124 (radio-button-choice
125 :format "%v"
126 (list :tag "IP address range"
127 (const :format "" :value range)
128 (string :tag "From")
129 (string :tag "To"))
130 (list :tag "IP address/netmask"
131 (const :format "" :value netmask)
132 (string :tag "IP Address")
133 (string :tag "Netmask"))
134 (list :tag "Domain Name"
135 (const :format "" :value domain)
136 (string :tag "Domain name"))
137 (list :tag "Unique hostname/IP address"
138 (const :format "" :value exact)
139 (string :tag "Hostname/IP Address"))))))
141 '(defun s5-servers-filter ()
142 (if socks-server-aliases
143 (mapcar (lambda (x) (list 'const :tag (car x) :value (car x))) s5-server-aliases)
144 '((const :tag "No aliases defined" :value nil))))
146 '(defun s5-network-aliases-filter ()
147 (mapcar (lambda (x) (list 'const :tag (car x) :value (car x)))
148 socks-network-aliases))
150 '(defcustom socks-redirection-rules
152 "A list of redirection rules."
153 :group 'socks
154 :type '(repeat (list :format "%v"
155 :value ("Anywhere" nil)
156 (dynamic-choice :choice-function s5-network-aliases-filter
157 :tag "Destination network")
158 (radio-button-choice
159 :tag "Connection type"
160 (const :tag "Direct connection" :value nil)
161 (dynamic-choice :format "%t: %[%v%]"
162 :choice-function s5-servers-filter
163 :tag "Proxy chain via")))))
165 (defcustom socks-server
166 (list "Default server" "socks" 1080 5)
168 :group 'socks
169 :type '(list
170 (string :format "" :value "Default server")
171 (string :tag "Server")
172 (integer :tag "Port")
173 (radio-button-choice :tag "SOCKS Version"
174 :format "%t: %v"
175 (const :tag "SOCKS v4 " :format "%t" :value 4)
176 (const :tag "SOCKS v5" :format "%t" :value 5))))
179 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
180 ;;; Get down to the nitty gritty
181 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
182 (defconst socks-version 5)
183 (defvar socks-debug nil)
185 ;; Common socks v5 commands
186 (defconst socks-connect-command 1)
187 (defconst socks-bind-command 2)
188 (defconst socks-udp-associate-command 3)
190 ;; Miscellaneous other socks constants
191 (defconst socks-authentication-null 0)
192 (defconst socks-authentication-failure 255)
194 ;; Response codes
195 (defconst socks-response-success 0)
196 (defconst socks-response-general-failure 1)
197 (defconst socks-response-access-denied 2)
198 (defconst socks-response-network-unreachable 3)
199 (defconst socks-response-host-unreachable 4)
200 (defconst socks-response-connection-refused 5)
201 (defconst socks-response-ttl-expired 6)
202 (defconst socks-response-cmd-not-supported 7)
203 (defconst socks-response-address-not-supported 8)
205 (defvar socks-errors
206 '("Succeeded"
207 "General SOCKS server failure"
208 "Connection not allowed by ruleset"
209 "Network unreachable"
210 "Host unreachable"
211 "Connection refused"
212 "Time-to-live expired"
213 "Command not supported"
214 "Address type not supported"))
216 ;; The socks v5 address types
217 (defconst socks-address-type-v4 1)
218 (defconst socks-address-type-name 3)
219 (defconst socks-address-type-v6 4)
221 ;; Base variables
222 (defvar socks-timeout 5)
223 (defvar socks-connections (make-hash-table :size 13))
225 ;; Miscellaneous stuff for authentication
226 (defvar socks-authentication-methods nil)
227 (defvar socks-username (user-login-name))
228 (defvar socks-password nil)
230 (defun socks-register-authentication-method (id desc callback)
231 (let ((old (assq id socks-authentication-methods)))
232 (if old
233 (setcdr old (cons desc callback))
234 (setq socks-authentication-methods
235 (cons (cons id (cons desc callback))
236 socks-authentication-methods)))))
238 (defun socks-unregister-authentication-method (id)
239 (let ((old (assq id socks-authentication-methods)))
240 (if old
241 (setq socks-authentication-methods
242 (delq old socks-authentication-methods)))))
244 (socks-register-authentication-method 0 "No authentication" 'identity)
246 (defun socks-build-auth-list ()
247 (let ((num 0)
248 (retval ""))
249 (mapc
250 (function
251 (lambda (x)
252 (if (fboundp (cdr (cdr x)))
253 (setq retval (format "%s%c" retval (car x))
254 num (1+ num)))))
255 (reverse socks-authentication-methods))
256 (format "%c%s" num retval)))
258 (defconst socks-state-waiting-for-auth 0)
259 (defconst socks-state-submethod-negotiation 1)
260 (defconst socks-state-authenticated 2)
261 (defconst socks-state-waiting 3)
262 (defconst socks-state-connected 4)
264 (defmacro socks-wait-for-state-change (proc htable cur-state)
265 `(while (and (= (gethash 'state ,htable) ,cur-state)
266 (memq (process-status ,proc) '(run open)))
267 (accept-process-output ,proc socks-timeout)))
269 (defun socks-filter (proc string)
270 (let ((info (gethash proc socks-connections))
271 state version desired-len)
272 (or info (error "socks-filter called on non-SOCKS connection %S" proc))
273 (setq state (gethash 'state info))
274 (cond
275 ((= state socks-state-waiting-for-auth)
276 (puthash 'scratch (concat string (gethash 'scratch info)) info)
277 (setq string (gethash 'scratch info))
278 (if (< (length string) 2)
279 nil ; We need to spin some more
280 (puthash 'authtype (aref string 1) info)
281 (puthash 'scratch (substring string 2 nil) info)
282 (puthash 'state socks-state-submethod-negotiation info)))
283 ((= state socks-state-submethod-negotiation)
285 ((= state socks-state-authenticated)
287 ((= state socks-state-waiting)
288 (puthash 'scratch (concat string (gethash 'scratch info)) info)
289 (setq string (gethash 'scratch info))
290 (setq version (gethash 'server-protocol info))
291 (cond
292 ((equal version 'http)
293 (if (not (string-match "\r\n\r\n" string))
294 nil ; Need to spin some more
295 (puthash 'state socks-state-connected info)
296 (puthash 'reply 0 info)
297 (puthash 'response string info)))
298 ((equal version 4)
299 (if (< (length string) 2)
300 nil ; Can't know how much to read yet
301 (setq desired-len
302 (+ 4 ; address length
303 2 ; port
304 2 ; initial data
306 (if (< (length string) desired-len)
307 nil ; need to spin some more
308 (let ((response (aref string 1)))
309 (if (= response 90)
310 (setq response 0))
311 (puthash 'state socks-state-connected info)
312 (puthash 'reply response info)
313 (puthash 'response string info)))))
314 ((equal version 5)
315 (if (< (length string) 4)
317 (setq desired-len
318 (+ 6 ; Standard socks header
319 (cond
320 ((= (aref string 3) socks-address-type-v4) 4)
321 ((= (aref string 3) socks-address-type-v6) 16)
322 ((= (aref string 3) socks-address-type-name)
323 (if (< (length string) 5)
325 (+ 1 (aref string 4)))))))
326 (if (< (length string) desired-len)
327 nil ; Need to spin some more
328 (puthash 'state socks-state-connected info)
329 (puthash 'reply (aref string 1) info)
330 (puthash 'response string info))))))
331 ((= state socks-state-connected)
337 (declare-function socks-original-open-network-stream "socks") ; fset
339 (defvar socks-override-functions nil
340 "*Whether to overwrite the open-network-stream function with the SOCKSified
341 version.")
343 (if (fboundp 'socks-original-open-network-stream)
344 nil ; Do nothing, we've been here already
345 (defalias 'socks-original-open-network-stream
346 (symbol-function 'open-network-stream))
347 (if socks-override-functions
348 (defalias 'open-network-stream 'socks-open-network-stream)))
350 (defun socks-open-connection (server-info)
351 (interactive)
352 (save-excursion
353 (let ((proc (socks-original-open-network-stream "socks"
355 (nth 1 server-info)
356 (nth 2 server-info)))
357 (info (make-hash-table :size 13))
358 (authtype nil)
359 version)
361 ;; Initialize process and info about the process
362 (set-process-filter proc 'socks-filter)
363 (set-process-query-on-exit-flag proc nil)
364 (puthash proc info socks-connections)
365 (puthash 'state socks-state-waiting-for-auth info)
366 (puthash 'authtype socks-authentication-failure info)
367 (puthash 'server-protocol (nth 3 server-info) info)
368 (puthash 'server-name (nth 1 server-info) info)
369 (setq version (nth 3 server-info))
370 (cond
371 ((equal version 'http)
372 ;; Don't really have to do any connection setup under http
373 nil)
374 ((equal version 4)
375 ;; Don't really have to do any connection setup under v4
376 nil)
377 ((equal version 5)
378 ;; Need to handle all the authentication crap under v5
379 ;; Send what we think we can handle for authentication types
380 (process-send-string proc (format "%c%s" socks-version
381 (socks-build-auth-list)))
383 ;; Basically just do a select() until we change states.
384 (socks-wait-for-state-change proc info socks-state-waiting-for-auth)
385 (setq authtype (gethash 'authtype info))
386 (cond
387 ((= authtype socks-authentication-null)
388 (and socks-debug (message "No authentication necessary")))
389 ((= authtype socks-authentication-failure)
390 (error "No acceptable authentication methods found"))
392 (let* ((auth-type (gethash 'authtype info))
393 (auth-handler (assoc auth-type socks-authentication-methods))
394 (auth-func (and auth-handler (cdr (cdr auth-handler))))
395 (auth-desc (and auth-handler (car (cdr auth-handler)))))
396 (set-process-filter proc nil)
397 (if (and auth-func (fboundp auth-func)
398 (funcall auth-func proc))
399 nil ; We succeeded!
400 (delete-process proc)
401 (error "Failed to use auth method: %s (%d)"
402 (or auth-desc "Unknown") auth-type))
406 (puthash 'state socks-state-authenticated info)
407 (set-process-filter proc 'socks-filter)))
408 proc)))
410 (defun socks-send-command (proc command atype address port)
411 (let ((addr (cond
412 ((or (= atype socks-address-type-v4)
413 (= atype socks-address-type-v6))
414 address)
415 ((= atype socks-address-type-name)
416 (format "%c%s" (length address) address))
418 (error "Unkown address type: %d" atype))))
419 (info (gethash proc socks-connections))
420 request version)
421 (or info (error "socks-send-command called on non-SOCKS connection %S"
422 proc))
423 (puthash 'state socks-state-waiting info)
424 (setq version (gethash 'server-protocol info))
425 (cond
426 ((equal version 'http)
427 (setq request (format (eval-when-compile
428 (concat
429 "CONNECT %s:%d HTTP/1.0\r\n"
430 "User-Agent: Emacs/SOCKS v1.0\r\n"
431 "\r\n"))
432 (cond
433 ((equal atype socks-address-type-name) address)
435 (error "Unsupported address type for HTTP: %d" atype)))
436 port)))
437 ((equal version 4)
438 (setq request (string-make-unibyte
439 (format
440 "%c%c%c%c%s%s%c"
441 version ; version
442 command ; command
443 (lsh port -8) ; port, high byte
444 (- port (lsh (lsh port -8) 8)) ; port, low byte
445 addr ; address
446 (user-full-name) ; username
447 0 ; terminate username
448 ))))
449 ((equal version 5)
450 (setq request (string-make-unibyte
451 (format
452 "%c%c%c%c%s%c%c"
453 version ; version
454 command ; command
455 0 ; reserved
456 atype ; address type
457 addr ; address
458 (lsh port -8) ; port, high byte
459 (- port (lsh (lsh port -8) 8)) ; port, low byte
460 ))))
462 (error "Unknown protocol version: %d" version)))
463 (process-send-string proc request)
464 (socks-wait-for-state-change proc info socks-state-waiting)
465 (process-status proc)
466 (if (= (or (gethash 'reply info) 1) socks-response-success)
467 nil ; Sweet sweet success!
468 (delete-process proc)
469 (error "SOCKS: %s" (nth (or (gethash 'reply info) 1) socks-errors)))
470 proc))
473 ;; Replacement functions for open-network-stream, etc.
474 (defvar socks-noproxy nil
475 "*List of regexps matching hosts that we should not socksify connections to")
477 (defun socks-find-route (host service)
478 (let ((route socks-server)
479 (noproxy socks-noproxy))
480 (while noproxy
481 (if (eq ?! (aref (car noproxy) 0))
482 (if (string-match (substring (car noproxy) 1) host)
483 (setq noproxy nil))
484 (if (string-match (car noproxy) host)
485 (setq route nil
486 noproxy nil)))
487 (setq noproxy (cdr noproxy)))
488 route))
490 (defvar socks-services-file "/etc/services")
491 (defvar socks-tcp-services (make-hash-table :size 13 :test 'equal))
492 (defvar socks-udp-services (make-hash-table :size 13 :test 'equal))
494 (defun socks-parse-services ()
495 (if (not (and (file-exists-p socks-services-file)
496 (file-readable-p socks-services-file)))
497 (error "Could not find services file: %s" socks-services-file))
498 (clrhash socks-tcp-services)
499 (clrhash socks-udp-services)
500 (with-current-buffer (get-buffer-create " *socks-tmp*")
501 (erase-buffer)
502 (insert-file-contents socks-services-file)
503 ;; Nuke comments
504 (goto-char (point-min))
505 (while (re-search-forward "#.*" nil t)
506 (replace-match ""))
507 ;; Nuke empty lines
508 (goto-char (point-min))
509 (while (re-search-forward "^[ \t\n]+" nil t)
510 (replace-match ""))
511 ;; Now find all the lines
512 (goto-char (point-min))
513 (let (name port type)
514 (while (re-search-forward "^\\([^ \t]+\\)[ \t]+\\([0-9]+\\)/\\([a-z]+\\)"
515 nil t)
516 (setq name (downcase (match-string 1))
517 port (string-to-number (match-string 2))
518 type (downcase (match-string 3)))
519 (puthash name port (if (equal type "udp")
520 socks-udp-services
521 socks-tcp-services))))))
523 (defun socks-find-services-entry (service &optional udp)
524 "Return the port # associated with SERVICE"
525 (if (= (hash-table-count socks-tcp-services) 0)
526 (socks-parse-services))
527 (gethash (downcase service)
528 (if udp socks-udp-services socks-tcp-services)))
530 (defun socks-open-network-stream (name buffer host service)
531 (let* ((route (socks-find-route host service))
532 proc info version atype)
533 (if (not route)
534 (socks-original-open-network-stream name buffer host service)
535 (setq proc (socks-open-connection route)
536 info (gethash proc socks-connections)
537 version (gethash 'server-protocol info))
538 (cond
539 ((equal version 4)
540 (setq host (socks-nslookup-host host))
541 (if (not (listp host))
542 (error "Could not get IP address for: %s" host))
543 (setq host (apply 'format "%c%c%c%c" host))
544 (setq atype socks-address-type-v4))
546 (setq atype socks-address-type-name)))
547 (socks-send-command proc
548 socks-connect-command
549 atype
550 host
551 (if (stringp service)
553 (socks-find-services-entry service)
554 (error "Unknown service: %s" service))
555 service))
556 (puthash 'buffer buffer info)
557 (puthash 'host host info)
558 (puthash 'service host info)
559 (set-process-filter proc nil)
560 (set-process-buffer proc (if buffer (get-buffer-create buffer)))
561 proc)))
563 ;; Authentication modules go here
565 ;; Basic username/password authentication, ala RFC 1929
566 (socks-register-authentication-method 2 "Username/Password"
567 'socks-username/password-auth)
569 (defconst socks-username/password-auth-version 1)
571 (defun socks-username/password-auth-filter (proc str)
572 (let ((info (gethash proc socks-connections)))
573 (or info (error "socks-filter called on non-SOCKS connection %S" proc))
574 (puthash 'scratch (concat (gethash 'scratch info) str) info)
575 (if (< (length (gethash 'scratch info)) 2)
577 (puthash 'password-auth-status (aref (gethash 'scratch info) 1) info)
578 (puthash 'state socks-state-authenticated info))))
580 (defun socks-username/password-auth (proc)
581 (let* ((info (gethash proc socks-connections))
582 (state (gethash 'state info)))
583 (if (not socks-password)
584 (setq socks-password (read-passwd
585 (format "Password for %s@%s: "
586 socks-username
587 (gethash 'server-name info)))))
588 (puthash 'scratch "" info)
589 (set-process-filter proc 'socks-username/password-auth-filter)
590 (process-send-string proc
591 (format "%c%c%s%c%s"
592 socks-username/password-auth-version
593 (length socks-username)
594 socks-username
595 (length socks-password)
596 socks-password))
597 (socks-wait-for-state-change proc info state)
598 (= (gethash 'password-auth-status info) 0)))
601 ;; More advanced GSS/API stuff, not yet implemented - volunteers?
602 ;; (socks-register-authentication-method 1 "GSS/API" 'socks-gssapi-auth)
604 (defun socks-gssapi-auth (proc)
605 nil)
608 ;; CHAP stuff
609 ;; (socks-register-authentication-method 3 "CHAP" 'socks-chap-auth)
610 (defun socks-chap-auth (proc)
611 nil)
614 ;; CRAM stuff
615 ;; (socks-register-authentication-method 5 "CRAM" 'socks-cram-auth)
616 (defun socks-cram-auth (proc)
617 nil)
620 (defcustom socks-nslookup-program "nslookup"
621 "*If non-NIL then a string naming the nslookup program."
622 :type '(choice (const :tag "None" :value nil) string)
623 :group 'socks)
625 (defun socks-nslookup-host (host)
626 "Attempt to resolve the given HOSTNAME using nslookup if possible."
627 (interactive "sHost: ")
628 (if socks-nslookup-program
629 (let ((proc (start-process " *nslookup*" " *nslookup*"
630 socks-nslookup-program host))
631 (res host))
632 (set-process-query-on-exit-flag proc nil)
633 (with-current-buffer (process-buffer proc)
634 (while (progn
635 (accept-process-output proc)
636 (memq (process-status proc) '(run open))))
637 (goto-char (point-min))
638 (if (re-search-forward "Name:.*\nAddress\\(es\\)?: *\\([0-9.]+\\)$" nil t)
639 (progn
640 (setq res (buffer-substring (match-beginning 2)
641 (match-end 2))
642 res (mapcar 'string-to-int (split-string res "\\.")))))
643 (kill-buffer (current-buffer)))
644 res)
645 host))
647 (provide 'socks)
649 ;;; socks.el ends here