unofficial mirror of bug-gnu-emacs@gnu.org 
 help / color / mirror / code / Atom feed
blob b93a114a198e93f128c96b60016b4c33736dd001 26367 bytes (raw)
name: lisp/net/socks.el 	 # note: path name is non-authoritative(*)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
 
;;; socks.el --- A Socks v5 Client for Emacs  -*- lexical-binding:t -*-

;; Copyright (C) 1996-2000, 2002, 2007-2024 Free Software Foundation,
;; Inc.

;; Author: William M. Perry <wmperry@gnu.org>
;;         Dave Love <fx@gnu.org>
;; Keywords: comm, firewalls

;; This file is part of GNU Emacs.

;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.

;;; Commentary:

;; This is an implementation of the SOCKS v5 protocol as defined in
;; RFC 1928.

;; TODO
;; - Finish the redirection rules stuff
;; - Implement composition of servers.  Recursively evaluate the
;;   redirection rules and do SOCKS-over-HTTP and SOCKS-in-SOCKS

;;; Code:

(eval-when-compile (require 'cl-lib))

;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;; Custom widgets
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; (eval-when-compile
;;   (require 'wid-edit))

;; (define-widget 'dynamic-choice 'menu-choice
;;   "A pretty simple dynamic dropdown list"
;;   :format "%[%t%]: %v"
;;   :tag "Network"
;;   :case-fold t
;;   :void '(item :format "invalid (%t)\n")
;;   :value-create 's5-widget-value-create
;;   :value-delete 'widget-children-value-delete
;;   :value-get 'widget-choice-value-get
;;   :value-inline 'widget-choice-value-inline
;;   :mouse-down-action 'widget-choice-mouse-down-action
;;   :action 'widget-choice-action
;;   :error "Make a choice"
;;   :validate 'widget-choice-validate
;;   :match 's5-dynamic-choice-match
;;   :match-inline 's5-dynamic-choice-match-inline)
;;
;; (defun s5-dynamic-choice-match (widget value)
;;   (let ((choices (funcall (widget-get widget :choice-function)))
;; 	current found)
;;     (while (and choices (not found))
;;       (setq current (car choices)
;; 	    choices (cdr choices)
;; 	    found (widget-apply current :match value)))
;;     found))
;;
;; (defun s5-dynamic-choice-match-inline (widget value)
;;   (let ((choices (funcall (widget-get widget :choice-function)))
;; 	current found)
;;     (while (and choices (not found))
;;       (setq current (car choices)
;; 	    choices (cdr choices)
;; 	    found (widget-match-inline current value)))
;;     found))
;;
;; (defun s5-widget-value-create (widget)
;;   (let ((choices (funcall (widget-get widget :choice-function)))
;; 	(value (widget-get widget :value)))
;;     (if (not value)
;; 	(widget-put widget :value (widget-value (car choices))))
;;     (widget-put widget :args choices)
;;     (widget-choice-value-create widget)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Customization support
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defgroup socks nil
  "SOCKS support."
  :version "22.2"
  :prefix "socks-"
  :group 'processes)

;; (defcustom socks-server-aliases nil
;;   "A list of server aliases for use in access control and filtering rules."
;;   :type '(repeat (list :format "%v"
;; 		       :value ("" "" 1080 5)
;; 		       (string :tag "Alias")
;; 		       (string :tag "Hostname/IP Address")
;; 		       (integer :tag "Port #")
;; 		       (choice :tag "SOCKS Version"
;; 			       (integer :tag "SOCKS v4" :value 4)
;; 			       (integer :tag "SOCKS v5" :value 5)))))
;;
;; (defcustom socks-network-aliases
;;   '(("Anywhere" (netmask "0.0.0.0" "0.0.0.0")))
;;   "A list of network aliases for use in subsequent rules."
;;   :type '(repeat (list :format "%v"
;; 		       :value (netmask "" "255.255.255.0")
;; 		       (string :tag "Alias")
;; 		       (radio-button-choice
;; 			:format "%v"
;; 			(list :tag  "IP address range"
;; 			      (const :format "" :value range)
;; 			      (string :tag "From")
;; 			      (string :tag "To"))
;; 			(list :tag  "IP address/netmask"
;; 			      (const :format "" :value netmask)
;; 			      (string :tag "IP Address")
;; 			      (string :tag "Netmask"))
;; 			(list :tag  "Domain Name"
;; 			      (const :format "" :value domain)
;; 			      (string :tag "Domain name"))
;; 			(list :tag  "Unique hostname/IP address"
;; 			      (const :format "" :value exact)
;; 			      (string :tag "Hostname/IP Address"))))))
;;
;; (defun s5-servers-filter ()
;;   (if socks-server-aliases
;;       (mapcar (lambda (x) (list 'const :tag (car x) :value (car x))) s5-server-aliases)
;;     '((const :tag "No aliases defined" :value nil))))
;;
;; (defun s5-network-aliases-filter ()
;;   (mapcar (lambda (x) (list 'const :tag (car x) :value (car x)))
;; 	  socks-network-aliases))
;;
;; (defcustom socks-redirection-rules
;;    nil
;;    "A list of redirection rules."
;;    :type '(repeat (list :format "%v"
;; 			:value ("Anywhere" nil)
;; 			(dynamic-choice :choice-function s5-network-aliases-filter
;; 					:tag "Destination network")
;; 			(radio-button-choice
;; 			 :tag "Connection type"
;; 			 (const :tag "Direct connection" :value nil)
;; 			 (dynamic-choice :format "%t: %[%v%]"
;; 					 :choice-function s5-servers-filter
;; 					 :tag "Proxy chain via")))))

(defcustom socks-server
  (list "Default server" "socks" 1080 5)
  "Socks server."
  :type '(list
	  (string :format "" :value "Default server")
	  (string :tag "Server")
	  (integer :tag "Port")
	  (radio-button-choice :tag "SOCKS Version"
			       :format "%t: %v"
			       (const :tag "SOCKS v4  " :format "%t" :value 4)
                               (const :tag "SOCKS v4a"  :format "%t" :value 4a)
			       (const :tag "SOCKS v5"   :format "%t" :value 5))))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Get down to the nitty gritty
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defconst socks-version 5)
(defvar socks-debug nil)

;; Common socks v5 commands
(defconst socks-connect-command 1)
(defconst socks-bind-command 2)
(defconst socks-udp-associate-command 3)

;; Miscellaneous other socks constants
(defconst socks-authentication-null 0)
(defconst socks-authentication-failure 255)

;; Extensions
(defconst socks-resolve-command #xf0)

;; Response codes
(defconst socks-response-success               0)
(defconst socks-response-general-failure       1)
(defconst socks-response-access-denied         2)
(defconst socks-response-network-unreachable   3)
(defconst socks-response-host-unreachable      4)
(defconst socks-response-connection-refused    5)
(defconst socks-response-ttl-expired           6)
(defconst socks-response-cmd-not-supported     7)
(defconst socks-response-address-not-supported 8)

(defvar socks-errors
  '("Succeeded"
    "General SOCKS server failure"
    "Connection not allowed by ruleset"
    "Network unreachable"
    "Host unreachable"
    "Connection refused"
    "Time-to-live expired"
    "Command not supported"
    "Address type not supported"))

(defconst socks--errors-4
  '("Granted"
    "Rejected or failed"
    "Cannot connect to identd on the client"
    "Client and identd report differing user IDs"))

;; The socks v5 address types
(defconst socks-address-type-v4   1)
(defconst socks-address-type-name 3)
(defconst socks-address-type-v6   4)

;; Base variables
(defvar socks-timeout 5)

;; Miscellaneous stuff for authentication
(defvar socks-authentication-methods nil)
(defvar socks-username (user-login-name))
(defvar socks-password nil)

(defun socks-register-authentication-method (id desc callback)
  (let ((old (assq id socks-authentication-methods)))
    (if old
	(setcdr old (cons desc callback))
      (setq socks-authentication-methods
	    (cons (cons id (cons desc callback))
		  socks-authentication-methods)))))

(defun socks-unregister-authentication-method (id)
  (let ((old (assq id socks-authentication-methods)))
    (if old
	(setq socks-authentication-methods
	      (delq old socks-authentication-methods)))))

(socks-register-authentication-method 0 "No authentication" 'identity)

(defun socks-build-auth-list ()
  (let ((num 0)
	(retval ""))
    (mapc
     (lambda (x)
       (if (fboundp (cdr (cdr x)))
           (setq retval (format "%s%c" retval (car x))
                 num (1+ num))))
     (reverse socks-authentication-methods))
    (format "%c%s" num retval)))

(defconst socks-state-waiting-for-auth 0)
(defconst socks-state-submethod-negotiation 1)
(defconst socks-state-authenticated 2)
(defconst socks-state-waiting 3)
(defconst socks-state-connected 4)

(defun socks-wait-for-state-change (proc cur-state)
  (while (and (= (process-get proc 'socks-state) cur-state)
	      (memq (process-status proc) '(run open)))
    (accept-process-output proc socks-timeout)))

(defun socks-filter (proc string)
  (let (state version desired-len)
    (or (process-get proc 'socks)
        (error "socks-filter called on non-SOCKS connection %S" proc))
    (setq state (process-get proc 'socks-state))
    (cond
     ((= state socks-state-waiting-for-auth)
      (cl-callf (lambda (s) (setq string (concat s string)))
          (process-get proc 'socks-scratch))
      (if (< (length string) 2)
	  nil				; We need to spin some more
	(process-put proc 'socks-authtype (aref string 1))
	(process-put proc 'socks-scratch (substring string 2 nil))
	(process-put proc 'socks-state socks-state-submethod-negotiation)))
     ((= state socks-state-submethod-negotiation)
      )
     ((= state socks-state-authenticated)
      )
     ((= state socks-state-waiting)
      (cl-callf (lambda (s) (setq string (concat s string)))
          (process-get proc 'socks-scratch))
      (setq version (process-get proc 'socks-server-protocol))
      (cond
       ((equal version 'http)
	(if (not (string-search "\r\n\r\n" string))
	    nil			; Need to spin some more
	  (process-put proc 'socks-state socks-state-connected)
	  (process-put proc 'socks-reply 0)
	  (process-put proc 'socks-response string)))
       ((equal version 4)
	(if (< (length string) 2)
	    nil			; Can't know how much to read yet
	  (setq desired-len
		(+ 4 ; address length
		   2 ; port
		   2 ; initial data
		   ))
	  (if (< (length string) desired-len)
	      nil			; need to spin some more
	    (let ((response (aref string 1)))
	      (if (= response 90)
		  (setq response 0))
	      (process-put proc 'socks-state socks-state-connected)
	      (process-put proc 'socks-reply response)
	      (process-put proc 'socks-response string)))))
       ((equal version 5)
	(if (< (length string) 4)
	    nil
	  (setq desired-len
		(+ 6			; Standard socks header
		   (pcase (aref string 3)
		     ((pred (= socks-address-type-v4)) 4)
		     ((pred (= socks-address-type-v6)) 16)
		     ((pred (= socks-address-type-name))
		      (if (< (length string) 5)
			  255
                        (+ 1 (aref string 4))))
                     (0 0))))
	  (if (< (length string) desired-len)
	      nil			; Need to spin some more
	    (process-put proc 'socks-state socks-state-connected)
	    (process-put proc 'socks-reply (aref string 1))
	    (process-put proc 'socks-response string))))))
     ((= state socks-state-connected)))))

;; FIXME this is a terrible idea.
;; It is not even compatible with the argument spec of open-network-stream
;; in 24.1.

(defvar socks-override-functions nil
  "If non-nil, overwrite `open-network-stream' function with SOCKSified version.")

(when socks-override-functions
  (advice-add 'open-network-stream :around #'socks--open-network-stream))

(defun socks-open-connection (server-info)
  (save-excursion
    (let ((proc
           (let ((socks-override-functions nil))
             (open-network-stream "socks"
				  nil
				  (nth 1 server-info)
				  (nth 2 server-info))))
	  (authtype nil)
	  version)

      ;; Initialize process and info about the process
      (set-process-filter proc #'socks-filter)
      (set-process-query-on-exit-flag proc nil)
      (process-put proc 'socks t)
      (process-put proc 'socks-state socks-state-waiting-for-auth)
      (process-put proc 'socks-authtype socks-authentication-failure)
      (process-put proc 'socks-server-protocol (nth 3 server-info))
      (process-put proc 'socks-server-name (nth 1 server-info))
      (setq version (nth 3 server-info))
      (cond
       ((equal version 'http)
	;; Don't really have to do any connection setup under http
	nil)
       ((equal version 4)
	;; Don't really have to do any connection setup under v4
	nil)
       ((equal version 5)
	;; Need to handle all the authentication crap under v5
	;; Send what we think we can handle for authentication types
	(process-send-string proc (format "%c%s" socks-version
					  (socks-build-auth-list)))

	;; Basically just do a select() until we change states.
	(socks-wait-for-state-change proc socks-state-waiting-for-auth)
	(setq authtype (process-get proc 'socks-authtype))
	(cond
	 ((= authtype socks-authentication-null)
	  (and socks-debug (message "No authentication necessary")))
	 ((= authtype socks-authentication-failure)
	  (error "No acceptable authentication methods found"))
	 (t
	  (let* ((auth-type (process-get proc 'socks-authtype))
		 (auth-handler (assoc auth-type socks-authentication-methods))
		 (auth-func (and auth-handler (cdr (cdr auth-handler))))
		 (auth-desc (and auth-handler (car (cdr auth-handler)))))
	    (set-process-filter proc nil)
	    (if (and auth-func (fboundp auth-func)
		     (funcall auth-func proc))
		nil			; We succeeded!
	      (delete-process proc)
	      (error "Failed to use auth method: %s (%d)"
		     (or auth-desc "Unknown") auth-type))
	    )
	  )
	 )
	(process-put proc 'socks-state socks-state-authenticated)
	(process-put proc 'socks-scratch "")
	(set-process-filter proc #'socks-filter)))
      proc)))

(defun socks-send-command (proc command atype address port)
  "Send COMMAND to SOCKS service PROC for proxying ADDRESS and PORT.
When ATYPE indicates an IP, param ADDRESS must be given as raw bytes."
  (let ((addr (cond
	       ((or (= atype socks-address-type-v4)
		    (= atype socks-address-type-v6))
		address)
	       ((= atype socks-address-type-name)
		(format "%c%s" (length address) address))
	       (t
		(error "Unknown address type: %d" atype))))
        trailing
	request version)
    (or (process-get proc 'socks)
        (error "socks-send-command called on non-SOCKS connection %S" proc))
    (process-put proc 'socks-state socks-state-waiting)
    (setq version (process-get proc 'socks-server-protocol))
    (cond
     ((equal version 'http)
      (setq request (format (concat
			     "CONNECT %s:%d HTTP/1.0\r\n"
			     "User-Agent: Emacs/SOCKS v1.0\r\n"
			     "\r\n")
			    (cond
			     ((equal atype socks-address-type-name) address)
			     (t
			      (error "Unsupported address type for HTTP: %d" atype)))
			    port)))
     ((and (eq version '4a)
           (setf addr "\0\0\0\1"
                 trailing (concat address "\0")
                 version 4 ; become version 4
                 (process-get proc 'socks-server-protocol) 4)
           nil)) ; fall through
     ((equal version 4)
      (setq request (concat
		     (unibyte-string
		      version             ; version
		      command             ; command
		      (ash port -8)       ; port, high byte
		      (logand port #xff)) ; port, low byte
		     addr                 ; address
                     socks-username       ; username
                     "\0"                 ; terminate username
                     trailing)))          ; optional host to look up
     ((equal version 5)
      (setq request (concat
		     (unibyte-string
		      version		; version
		      command		; command
		      0			; reserved
		      atype)		; address type
		     addr		; address
		     (unibyte-string
                      (ash port -8)          ; port, high byte
		      (logand port #xff))))) ; port, low byte
     (t
      (error "Unknown protocol version: %d" version)))
    (process-send-string proc request)
    (socks-wait-for-state-change proc socks-state-waiting)
    (process-status proc)
    (if (= (or (process-get proc 'socks-reply) 1) socks-response-success)
	nil				; Sweet sweet success!
      (delete-process proc)
      (error "SOCKS: %s"
             (let ((err (process-get proc 'socks-reply)))
               (if (eql version 5)
                   (nth (or err 1) socks-errors)
                 ;; The defined error codes for v4 range from
                 ;; 90-93, but we store them in a simple list.
                 (nth (pcase err (90 0) (92 2) (93 3) (_ 1))
                      socks--errors-4)))))
    proc))

\f
;; Replacement functions for open-network-stream, etc.
(defvar socks-noproxy nil
  "List of regexps matching hosts that we should not socksify connections to.")

(defun socks-find-route (host _service)
  (let ((route socks-server)
	(noproxy socks-noproxy))
    (while noproxy
      (if (eq ?! (aref (car noproxy) 0))
	  (if (string-match (substring (car noproxy) 1) host)
	      (setq noproxy nil))
	(if (string-match (car noproxy) host)
	    (setq route nil
		  noproxy nil)))
      (setq noproxy (cdr noproxy)))
    route))

(defvar socks-services-file "/etc/services")
(defvar socks-tcp-services (make-hash-table :size 13 :test 'equal))
(defvar socks-udp-services (make-hash-table :size 13 :test 'equal))

(defun socks-parse-services ()
  (if (not (and (file-exists-p socks-services-file)
		(file-readable-p socks-services-file)))
      (error "Could not find services file: %s" socks-services-file))
  (clrhash socks-tcp-services)
  (clrhash socks-udp-services)
  (with-current-buffer (get-buffer-create " *socks-tmp*")
    (erase-buffer)
    (insert-file-contents socks-services-file)
    ;; Nuke comments
    (goto-char (point-min))
    (while (re-search-forward "#.*" nil t)
      (replace-match ""))
    ;; Nuke empty lines
    (goto-char (point-min))
    (while (re-search-forward "^[ \t\n]+" nil t)
      (replace-match ""))
    ;; Now find all the lines
    (goto-char (point-min))
    (let (name port type)
      (while (re-search-forward "^\\([^ \t]+\\)[ \t]+\\([0-9]+\\)/\\([a-z]+\\)"
				nil t)
	(setq name (downcase (match-string 1))
	      port (string-to-number (match-string 2))
	      type (downcase (match-string 3)))
	(puthash name port (if (equal type "udp")
			       socks-udp-services
			     socks-tcp-services))))))

(defun socks-find-services-entry (service &optional udp)
  "Return the port # associated with SERVICE."
  (if (= (hash-table-count socks-tcp-services) 0)
      (socks-parse-services))
  (gethash (downcase service)
	      (if udp socks-udp-services socks-tcp-services)))

(defun socks-open-network-stream (name buffer host service)
  (let ((socks-override-functions t))
    (socks--open-network-stream
     (lambda (&rest args)
       (let ((socks-override-functions nil))
         (apply #'open-network-stream args)))
     name buffer host service)))

(defun socks--open-network-stream (orig-fun name buffer host service &rest params)
  (let ((route (and socks-override-functions
                    (socks-find-route host service))))
    (if (not route)
	(apply orig-fun name buffer host service params)
      ;; FIXME: Obey `params'!
      (let* ((proc (socks-open-connection route))
	     (version (process-get proc 'socks-server-protocol))
             (atype
              (cond
               ((equal version 4)
	        (setq host (socks-nslookup-host host))
	        (if (not (listp host))
	            (error "Could not get IP address for: %s" host))
		(setq host (apply #'unibyte-string host))
                socks-address-type-v4)
               (t
                socks-address-type-name))))
        (socks-send-command proc
			    socks-connect-command
			    atype
			    host
			    (if (stringp service)
			        (or
			         (socks-find-services-entry service)
			         (error "Unknown service: %s" service))
			      service))
        (process-put proc 'socks-buffer buffer)
        (process-put proc 'socks-host host)
        (process-put proc 'socks-service service)
        (set-process-filter proc nil)
        (set-process-buffer proc (if buffer (get-buffer-create buffer)))
        proc))))

;; Authentication modules go here
\f
;; Basic username/password authentication, ala RFC 1929
(socks-register-authentication-method 2 "Username/Password"
				      'socks-username/password-auth)

(defconst socks-username/password-auth-version 1)

(defun socks-username/password-auth-filter (proc str)
  (or (process-get proc 'socks)
      (error "socks-filter called on non-SOCKS connection %S" proc))
  (cl-callf (lambda (s) (concat s str))
      (process-get proc 'socks-scratch))
  (if (< (length (process-get proc 'socks-scratch)) 2)
      nil
    (process-put proc 'socks-password-auth-status
                 (aref (process-get proc 'socks-scratch) 1))
    (process-put proc 'socks-state socks-state-authenticated)))

(defun socks-username/password-auth (proc)
  (let ((state (process-get proc 'socks-state)))
    (if (not socks-password)
	(setq socks-password (read-passwd
			      (format "Password for %s@%s: "
				      socks-username
				      (process-get proc 'socks-server-name)))))
    (process-put proc 'socks-scratch "")
    (set-process-filter proc #'socks-username/password-auth-filter)
    (process-send-string proc
			 (format "%c%c%s%c%s"
				 socks-username/password-auth-version
				 (length socks-username)
				 socks-username
				 (length socks-password)
				 socks-password))
    (socks-wait-for-state-change proc state)
    (= (process-get proc 'socks-password-auth-status) 0)))

\f
;; More advanced GSS/API stuff, not yet implemented - volunteers?
;; (socks-register-authentication-method 1 "GSS/API" 'socks-gssapi-auth)

(defun socks-gssapi-auth (_proc)
  nil)

\f
;; CHAP stuff
;; (socks-register-authentication-method 3 "CHAP" 'socks-chap-auth)
(defun socks-chap-auth (_proc)
  nil)

\f
;; CRAM stuff
;; (socks-register-authentication-method 5 "CRAM" 'socks-cram-auth)
(defun socks-cram-auth (_proc)
  nil)

\f
(defcustom socks-nslookup-program "nslookup"
  "If non-nil then a string naming the nslookup program."
  :type '(choice (const :tag "None" :value nil) string))

(defun socks-nslookup-host (host)
  "Attempt to resolve the given HOSTNAME using nslookup if possible."
  (interactive "sHost:  ")
  (if socks-nslookup-program
      (let ((proc (start-process " *nslookup*" " *nslookup*"
				 socks-nslookup-program host))
	    (res host))
	(set-process-query-on-exit-flag proc nil)
	(with-current-buffer (process-buffer proc)
	  (while (progn
		   (accept-process-output proc)
		   (memq (process-status proc) '(run open))))
	  (goto-char (point-min))
	  (if (re-search-forward "Name:.*\nAddress\\(es\\)?: *\\([0-9.]+\\)$" nil t)
	      (progn
		(setq res (buffer-substring (match-beginning 2)
					    (match-end 2))
		      res (mapcar #'string-to-number
				  (split-string res "\\.")))))
	  (kill-buffer (current-buffer)))
	res)
    host))

(defun socks--extract-resolve-response (proc)
  "Parse response for PROC and maybe return destination IP address."
  (when-let ((response (process-get proc 'socks-response)))
    (pcase (process-get proc 'socks-server-protocol)
      (4 ; https://www.openssh.com/txt/socks4a.protocol
       (and-let* (((zerop (process-get proc 'socks-reply)))
                  ((eq (aref response 1) 90)) ; #x5a request granted
                  (a (substring response 4)) ; ignore port for now
                  ((not (string-empty-p a)))
                  ((not (string= a "\0\0\0\0"))))
         a))
      (5 ; https://tools.ietf.org/html/rfc1928
       (cl-assert (eq 5 (aref response 0)) t)
       (pcase (aref response 3) ; ATYP
         (1 (and-let* ((a (substring response 4 8))
                       ((not (string= a "\0\0\0\0")))
                       a)))
         ;; No reason to support RESOLVE_PTR [F1] extension, right?
         (3 (let ((len (1- (aref response 4))))
              (substring response 5 (+ 5 len))))
         (4 (substring response 4 20)))))))

(declare-function puny-encode-domain "puny" (domain))

(defun socks--tor-resolve (name &optional _family _flags)
  (condition-case err
      (if-let ((socks-password (or socks-password ""))
               (route (socks-find-route name nil))
               (proc (socks-send-command (socks-open-connection route)
                                         socks-resolve-command
                                         socks-address-type-name
                                         name
                                         0))
               (ip (prog1 (socks--extract-resolve-response proc)
                     (delete-process proc))))
          (list (vconcat ip [0]))
        (error "Failed to resolve %s" name))
    (error
     (unless (member (cadr err)
                     '("SOCKS: Host unreachable" "SOCKS: Rejected or failed"))
       (signal (car err) (cdr err))))))

(defvar socks--tor-resolve-cache nil)

(defun socks-tor-resolve (name &optional _family _flags)
  "Return list with a single IPv4 address for domain NAME.
Return nil on failure.

See `network-lookup-address-info' for format of return value.  As
of 0.4.8.9, TOR's resolution service does not support IPv6.
SOCKS server must support the Tor RESOLVE command.  Note that
this function exists for novelty purposes only.  Using it in
place of `network-lookup-address-info' or similar may not prevent
DNS leaks."
  (unless (string-match (rx bot (+ ascii) eot) name)
    (require 'puny)
    (setq name (puny-encode-domain name)))
  ;; FIXME use some kind of LRU here.  Currently resets at 5 min.
  (if socks--tor-resolve-cache
      (when (time-less-p (car socks--tor-resolve-cache) (current-time))
        (clrhash (cdr socks--tor-resolve-cache)))
    (setq socks--tor-resolve-cache (cons (time-add (* 60 5) (current-time))
                                         (make-hash-table :test #'equal))))
  (with-memoization (gethash name (cdr socks--tor-resolve-cache))
    (socks--tor-resolve name)))

(provide 'socks)

;;; socks.el ends here

debug log:

solving b93a114a198 ...
found b93a114a198 in https://yhetil.org/emacs-bugs/87ldzss6j5.fsf@neverwas.me/
found ecbac7e2345 in https://git.savannah.gnu.org/cgit/emacs.git
preparing index
index prepared:
100644 ecbac7e2345e5f727b82119a92d2154a9321254e	lisp/net/socks.el

applying [1/1] https://yhetil.org/emacs-bugs/87ldzss6j5.fsf@neverwas.me/
diff --git a/lisp/net/socks.el b/lisp/net/socks.el
index ecbac7e2345..b93a114a198 100644

Checking patch lisp/net/socks.el...
Applied patch lisp/net/socks.el cleanly.

index at:
100644 b93a114a198e93f128c96b60016b4c33736dd001	lisp/net/socks.el

(*) Git path names are given by the tree(s) the blob belongs to.
    Blobs themselves have no identifier aside from the hash of its contents.^

Code repositories for project(s) associated with this public inbox

	https://git.savannah.gnu.org/cgit/emacs.git

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).