-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathftpd.cl
1886 lines (1602 loc) · 55.8 KB
/
ftpd.cl
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
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;; This software is Copyright (c) Franz Inc., 2001-2012.
;; Franz Inc. grants you the rights to distribute
;; and use this software as governed by the terms
;; of the Lisp Lesser GNU Public License
;; (http://opensource.franz.com/preamble.html),
;; known as the LLGPL.
(in-package :user)
(defvar *ftpd-version* "1.1.3")
(eval-when (compile)
(proclaim '(optimize (safety 1) (space 1) (speed 3) (debug 2))))
(eval-when (compile eval load)
;; upload errors indicate this is needed
(require :disasm)
(require :regexp)
(require :efmacs)
(require :osi)
(use-package :excl.osi)
;; Needed for proper error reporting.
(setf excl::*strict-probe-file* t))
(eval-when (compile)
(if (shadow-passwd-supported-p)
(push :shadow-passwd-supported-p *features*)))
;; Location of the configuration files (which one can use to
;; override the rest of these parameters).
(defparameter *configfile* "/etc/aftpd.cl")
(eval-when (compile load eval)
(defparameter *extra-files* '("ipaddr")))
(eval-when (compile)
(dolist (source *extra-files*)
(compile-file-if-needed
(concatenate 'string source ".cl"))))
(eval-when (compile load eval)
(dolist (file *extra-files*)
(load (concatenate 'string file ".fasl")))
(require :acldns))
(eval-when (compile load eval)
(defparameter *extfcrlf*
(find-composed-external-format :e-crlf (crlf-base-ef :latin1))))
(defmacro with-umask ((newumask) &body body)
(let ((oldumasksym (gensym)))
`(let ((,oldumasksym (umask ,newumask)))
(unwind-protect
(progn ,@body)
(umask ,oldumasksym)))))
(defclass client ()
((sock :initarg :sock :reader client-sock)
(type :initform :ascii-nonprint :accessor client-type)
(mode :initform :stream)
(stru :initform :file)
(logged-in :initform nil :accessor logged-in)
(attempts :initform 0 :accessor attempts)
(user :initform nil :accessor user)
(pwent :initform nil :accessor pwent)
(anonymous :initform nil :accessor anonymous)
(pwd :accessor pwd)
(addr :initform nil :accessor dataport-addr)
(port :initform nil :accessor dataport-port)
(pasv :initform nil :accessor pasv) ;; holds pasv server socket
(open :initform nil :accessor dataport-open)
(dsock :initform nil :accessor dataport-sock) ;; holds a connected socket
(restart :initform 0 :accessor client-restart)
(umask :initform *default-umask* :accessor client-umask)
(rename-from :initform nil :accessor rename-from)
(message-seen :initform (make-hash-table :test #'equal)
:accessor message-seen)
(restricted :initform nil :accessor restricted)))
(defstruct cmd
command
implemented
must-be-logged-in
handler)
(defparameter *cmds* (make-hash-table :test #'equalp))
(dolist (entry
'(;; Login
("user" t nil cmd-user)
("pass" t nil cmd-pass)
("acct" nil nil nil)
;; Logout
("rein" nil nil nil)
("quit" t nil cmd-quit)
;; Transfer parameters
("port" t t cmd-port)
("pasv" t t cmd-pasv)
("mode" t t cmd-mode)
("type" t t cmd-type)
("stru" t t cmd-stru)
;; File action commands
("allo" t t cmd-allo)
("rest" t t cmd-rest)
("stor" t t cmd-stor)
("stou" nil t nil)
("retr" t t cmd-retr)
("list" t t cmd-list)
("nlst" t t cmd-nlst)
("appe" t t cmd-appe)
("rnfr" t t cmd-rnfr)
("rnto" t t cmd-rnto)
("dele" t t cmd-dele)
("rmd" t t cmd-rmd)
("xrmd" t t cmd-rmd)
("mkd" t t cmd-mkd)
("xmkd" t t cmd-mkd)
("pwd" t t cmd-pwd)
("xpwd" t t cmd-pwd)
("abor" t t cmd-abor)
("cwd" t t cmd-cwd)
("xcwd" t t cmd-cwd)
("cdup" t t cmd-cdup)
("xcup" t t cmd-cdup)
("smnt" nil nil nil)
("mdtm" t t cmd-mdtm)
("size" t t cmd-size)
;; Informational commands
("syst" t t cmd-syst)
("stat" t t cmd-stat)
("help" t t cmd-help)
;; Miscellaneous commands
("site" t t cmd-site)
("noop" t t cmd-noop)))
(setf (gethash (first entry) *cmds*)
(make-cmd
:command (first entry)
:implemented (second entry)
:must-be-logged-in (third entry)
:handler (fourth entry))))
(defparameter *sitecmds*
'(("chmod" . site-chmod)
("umask" . site-umask)
("utime" . site-utime)))
(defparameter *logstream* nil)
(defparameter *xferlogstream* nil)
(defun main-loop ()
(let ((serv (socket:make-socket :connect :passive
:local-host *interface*
:local-port *ftpport*
:reuse-address t)))
(setq socket:*dns-mode* '(:acldns))
(socket:configure-dns :auto t)
(unwind-protect
(loop
(let ((client (handler-case (socket:accept-connection serv)
(interrupt-signal () (exit))
(error () nil))))
(when client (spawn-client client serv))))
;; cleanup forms
(close serv))))
(defmacro with-fork (pidsym parent-form child-form)
`(let ((,pidsym (fork)))
(cond
((< ,pidsym 0) (error "fork failed!"))
((> ,pidsym 0) ;; parent
,parent-form)
((= ,pidsym 0) ;; child
,child-form))))
;; In case I can't get a decent SIGCHLD handler.
(defmacro with-orphaned-child (&body body)
(let ((pidsym (gensym))
(pidsym2 (gensym)))
`(with-fork ,pidsym
;; parent form
(waitpid ,pidsym) ;; reap child
;; child form
(with-fork ,pidsym2
;; parent exits to orphan child. (init will reap it)
(exit t :no-unwind t :quiet t)
;; child does what it needs to do.
(progn
,@body
(exit t :no-unwind t :quiet t))))))
(defun spawn-client (sock serv)
(with-orphaned-child
(close serv) ;; child doesn't need it.
(add-pid)
(unwind-protect
(ftpd-main sock)
(ignore-errors (close sock :abort t))))
;; child never gets here. Parent does.
;; main ftp server doesn't need this
(close sock))
(defmacro with-pids-file ((stream-sym pids-list-sym) &body body)
`(with-open-file (,stream-sym *pidsfile*
:if-exists :overwrite
:if-does-not-exist :create
:direction :io)
(with-stream-lock (,stream-sym)
(let ((,pids-list-sym (read ,stream-sym nil nil)))
,@body
(file-position ,stream-sym 0)
(format ,stream-sym "~A~%" ,pids-list-sym)))))
(defun add-pid ()
(with-pids-file (f pids)
(pushnew (getpid) pids)))
;; returns the number of active pids.
;; also updates the pids file w/ the active list.
(defun probe-pids-file ()
(let (active)
(with-pids-file (f pids)
(dolist (pid pids)
(when (handler-case (kill pid 0)
(error () nil))
(push pid active)))
(setf pids active))
(length active)))
;;; Logging
(defconstant *log-open-flags*
(logior *o-wronly* *o-append* *o-creat*))
(defun open-logs ()
(setf *logstream*
(if* *debug*
then *standard-output*
else (os-open *logfile* *log-open-flags* #o600)))
(setf *xferlogstream*
(if* *debug*
then *standard-output*
else (os-open *xferlog* *log-open-flags* #o0600))))
(defun close-logs ()
(when (not *debug*)
(close *logstream*)
(close *xferlogstream*)))
(defmacro with-open-logs (() &body body)
`(progn
(open-logs)
(unwind-protect (progn ,@body)
(ignore-errors (close-logs)))))
(defun ftp-log (&rest args)
(format *logstream* "~A [~D]: ~?"
(ctime)
(getpid)
(first args)
(rest args))
(force-output *logstream*))
(defun ftp-log-client (client format &rest args)
(apply #'ftp-log
(concatenate 'string "~a: " format)
(socket:ipaddr-to-dotted (socket:remote-host (client-sock client)))
args))
(defun xfer-log (client fullpath direction bytes)
(format *xferlogstream*
"(~A ~A ~S ~S ~D ~S) ;; ~A ~A ~%"
(get-universal-time)
(socket:remote-host (client-sock client))
fullpath
direction
bytes
(if (anonymous client)
(anonymous client)
(user client))
(socket:ipaddr-to-dotted (socket:remote-host (client-sock client)))
(ctime))
(force-output *xferlogstream*))
;;;
(defparameter *outlinestream* 'outlinestream-not-bound)
;; never call outline w/ a first argument that is anything
;; but a format string. This macro checks for that situation
;; to be safe.
(defmacro outline (format-string &rest args)
(let ((ressym (gensym)))
(when (not (stringp format-string))
(error "Crikey, format-string is not a string constant: ~s."
format-string))
`(let ((,ressym (format nil ,format-string ,@args)))
(if (eq *debug* :verbose)
(ftp-log "~A~%" ,ressym))
(write-string ,ressym *outlinestream*)
(write-char #\return *outlinestream*)
(write-char #\newline *outlinestream*)
(force-output *outlinestream*))))
;;;
(defun spawn-command (cmdvec &key env)
(if (not (vectorp cmdvec))
(error "Ack!! non-vector passed to spawn-command"))
(multiple-value-bind (stdout stderr pid)
(run-shell-command cmdvec
:input "/dev/null"
:output :stream
:error-output :stream
:environment env
:wait nil)
(mp:process-run-function "stderr reader" 'stderr-reader stderr)
(values stdout pid)))
(defun stderr-reader (stderr)
(unwind-protect
(let (line)
(while (setf line (read-line stderr nil nil))
(ftp-log "~A~%" line)))
(ignore-errors (close stderr))))
(defmacro with-external-command ((streamvar cmdvec &key env) &body body)
(let ((pidvar (gensym)))
`(multiple-value-bind (,streamvar ,pidvar)
(spawn-command ,cmdvec :env ,env)
(unwind-protect (progn ,@body)
(close ,streamvar)
(sys:reap-os-subprocess :pid ,pidvar)))))
;;;
(defconstant *telnetIAC* 255)
;;(defconstant *telnetIP* 244)
;;(defconstant *telnetSynch* 242)
(defparameter *maxline* 5000)
(defun get-request (client)
(let ((sock (client-sock client))
(buffer (make-string *maxline*))
(pos 0)
lastchar
gotiac
longline
char)
(mp:with-timeout (*idletimeout* :timeout)
(loop
(if (>= pos *maxline*)
(progn
(setf longline t)
(setf pos 0)))
(setf char
(handler-case (read-char sock)
(error ()
nil)))
(if (null char)
(return :eof))
(if (and (char= char #\newline) (eq lastchar #\return))
(return (if longline
:line-too-long
(subseq buffer 0 (1- pos)))))
;;; XXX -- telnet sequences. Stripped and ignored.
;;; XXX -- (two-byte sequences, only)
(if* gotiac
then
(setf gotiac nil)
(if (= (char-code char) *telnetIAC*)
(progn
;; escaped #xff
(setf (schar buffer pos) char)
(incf pos)
(setf lastchar char)))
else
(if (= (char-code char) *telnetIAC*)
(setf gotiac t)
(progn
;; Regular stuff
(setf (schar buffer pos) char)
(incf pos)
(setf lastchar char))))))))
(defun ftpd-main (sock)
;; Load latest configuration
(load-config-file)
;; Freshen log stream (to allow for log rotation).
(close-logs)
(with-open-logs ()
;; Each connection should have its own random state (used by
;; the PASV command to generate port numbers.
(make-random-state t)
(let ((client (make-instance 'client :sock sock))
(*outlinestream* sock)
(*locale* (find-locale :c))
(*print-pretty* nil))
(ftp-log-client client "Connected~%")
(handler-bind
;; FIXME: Don't backtrace on socket errors
((error #'(lambda (e)
(let ((backtrace
(with-output-to-string (s)
(format s "Unhandled error: ~a~%" e)
(format s "Backtrace:~%")
(top-level.debug:zoom s :count nil :all t))))
(ftp-log-client client "~a~%" backtrace))
(return-from ftpd-main))))
(umask (client-umask client))
(outline "220 ~A" *banner*)
(loop
(let ((req (get-request client)))
(if (eq req :eof)
(return (cleanup client "Disconnected")))
(if* (eq req :timeout)
then
(ignore-errors ;; in case the connection disappeared
(outline "421 Timeout: closing control connection."))
(return (cleanup client "Timeout")))
(if (eq req :line-too-long)
(outline "500 Command line too long! Request ignored")
(if (eq (dispatch-cmd client req) :quit)
(return (cleanup client "QUIT"))))))))))
(defun dispatch-cmd (client cmdstring)
(block nil
(let ((spacepos (position #\space cmdstring))
cmdname
entry)
(if (null spacepos)
(setf cmdname cmdstring)
(setf cmdname (subseq cmdstring 0 spacepos)))
(if (and (not (anonymous client))
(equalp cmdname "pass"))
(ftp-log-client client "PASS XXXXXX~%")
(ftp-log-client client "~A~%" cmdstring))
(setf entry (gethash cmdname *cmds*))
(if (null entry)
(return (outline "500 '~A': command not understood." cmdstring)))
(if (not (cmd-implemented entry))
(return (outline "502 ~A command not implemented." cmdname)))
(if (and (cmd-must-be-logged-in entry)
(not (logged-in client)))
(return (outline "530 Please login with USER and PASS.")))
(funcall (cmd-handler entry) client
(if spacepos
(subseq cmdstring (1+ spacepos))
"")))))
(defun cleanup (client reason)
(ftp-log-client client "Disconnected (~a).~%" reason)
(cleanup-data-connection client))
(defmacro with-root-privs (() &body body)
(let ((oldidsym (gensym)))
`(let ((,oldidsym (geteuid)))
(seteuid 0)
(unwind-protect
(progn ,@body)
(seteuid ,oldidsym)))))
(defun ftp-chdir (dir)
(handler-case (setq *default-pathname-defaults* (pathname (chdir dir)))
(error (c)
(ftp-log "chdir ~s failed: ~a~%" dir c)
nil)))
(defun cmd-quit (client cmdtail)
(declare (ignore cmdtail client))
(outline "221 Goodbye.")
:quit)
(defun cmd-user (client user)
(block nil
(if (logged-in client)
(return (outline "530 Already logged in.")))
(setf (anonymous client) nil)
(if (and (member user *anonymous-ftp-names* :test #'equalp)
(lookup-account *anonymous-ftp-account*))
(progn
(setf user *anonymous-ftp-account*)
(setf (anonymous client) t)))
(setf (user client) user)
(setf (pwent client) (lookup-account user))
;; XXX - Doesn't allow no-password logins.
(if (anonymous client)
(outline
"331 Guest login ok, send your complete e-mail address as password.")
(outline "331 Password required for ~A." user))))
(defun lookup-account (user)
(block nil
(let ((pwent (getpwnam user)))
(if (null pwent)
(return nil))
#+shadow-passwd-supported-p
(if (string= (pwent-passwd pwent) "x")
(let ((spent (getspnam user)))
(if spent
(setf (pwent-passwd pwent) (spwd-passwd spent)))))
pwent)))
(defun cmd-pass (client pass)
(block nil
(let ((pwent (pwent client))
(numclients (probe-pids-file)))
(if (logged-in client)
(return (outline "530 Already logged in.")))
(if (null (user client))
(return (outline "503 Login with USER first.")))
(if* (and *maxusers* (> numclients *maxusers*))
then
(dump-msg client "530" *toomanymsg*)
(outline "530 Connection limit exceeded.")
(ftp-log-client client "Connection limit (~D) exceeded.~%" *maxusers*)
(return :quit))
(if* (anonymous client)
then (setf (anonymous client) pass)
elseif (or (null pwent) ;; unknown user
;; or not in test mode and password doesn't check out
(and (not *test*)
;; FIXME: Add PAM support
(not (string= (pwent-passwd pwent)
(crypt pass (pwent-passwd pwent))))))
then (ftp-log-client client "Login failed for user ~s~%" (user client))
(setf (user client) nil)
(setf (pwent client) nil)
(sleep *badpwdelay*)
(outline "530 Login incorrect.")
(incf (attempts client))
(return (if (>= (attempts client) *max-password-attempts*) :quit)))
;; Good to go
;; Successful authentication
(ftp-log-client client "Login successful for user ~s~%" (user client))
(setf (pwd client) (pwent-dir pwent))
(if* (anonymous client)
then (anonymous-setup client)
else ;; If *restricted-users* is 't', then all users are
;; restricted except for those in the *unrestricted-users*
;; list. Otherwise, a user is restricted if he/she is
;; listed in *restricted-users*.
(if* (eq *restricted-users* t)
then (if (member (user client) *unrestricted-users*
:test #'string=)
(setf (restricted client) nil)
(setf (restricted client) t))
else (if (member (user client) *restricted-users*
:test #'string=)
(setf (restricted client) t))))
(when (not *test*)
;; Set up
(handler-case (setegid (pwent-gid pwent))
(error (c)
(ftp-log-client client "Failed to setegid(~D): ~a~%" (pwent-gid pwent) c)
(outline "421 Local configuration error.")
(return :quit)))
(handler-case (initgroups (user client) (pwent-gid pwent))
(error (c)
(ftp-log-client client "Failed to initgroups (~a)~%" c)
(outline "421 Local configuration error.")
(return :quit)))
(handler-case (seteuid (pwent-uid pwent))
(error (c)
(ftp-log-client client "Failed to seteuid(~D): ~a~%" (pwent-uid pwent) c)
(outline "421 Local configuration error.")
(return :quit))))
(when (null (ftp-chdir (pwent-dir pwent)))
(ftp-log-client client "Failed to chdir(~A)~%" (pwent-dir pwent))
;; Anonymous/restricted users have no alternative
(when (or (anonymous client) (restricted client))
(outline "421 Local configuration error.")
(return :quit))
(if* (not (ftp-chdir "/"))
then (ftp-log-client client "Failed to chdir(/)~%")
(outline "421 Local configuration error.")
(return :quit)
else (setf (pwent-dir pwent) "/")
(outline "230-No directory! Logging in with home=/")))
(setf (logged-in client) t)
(cleanup-data-connection client)
(dump-msg client "230" *welcome-msg-file*)
(outline "230 User ~A logged in." (user client)))))
(defun anonymous-setup (client)
(block nil
(let ((pwent (pwent client)))
(if (null (ftp-chdir (pwent-dir pwent)))
(progn
(ftp-log-client client "Failed to chdir(~A)~%" (pwent-dir pwent))
(outline "421 Local configuration error.")
(return nil)))
(handler-case (chroot (pwent-dir pwent))
(error (c)
(ftp-log-client client "Failed to chroot(~a): ~a~%" (pwent-dir pwent) c)
(outline "421 Local configuration error.")
(return nil)))
(setf (pwent-dir pwent) "/")
(setf (pwd client) "/")
t)))
(defmacro ftp-with-open-file ((streamsym errsym path &rest rest) &body body)
`(let (,errsym)
(declare (ignore-if-unused ,errsym))
(let ((,streamsym
(handler-case (open ,path ,@rest)
(file-error (c)
(setf ,errsym (excl::syscall-error-errno c))
nil))))
(unwind-protect (progn ,@body)
(if ,streamsym
(close ,streamsym))))))
(defun dump-msg (client code file)
(declare (ignore client))
(block nil
(if (or (null file)
(null (probe-file file)))
(return))
(ftp-with-open-file
(f errno file)
(if f
(let (line)
(while (setf line (read-line f nil nil))
(outline "~A-~A" code line)))))))
(defun cmd-pwd (client cmdtail)
(declare (ignore cmdtail))
(outline "257 \"~A\" is current directory."
(pwd client)))
(defun cmd-noop (client cmdtail)
(declare (ignore client cmdtail))
(outline "200 NOOP command successful."))
(defun cmd-port (client cmdtail)
(block nil
(multiple-value-bind (matched whole a b c d e f)
(match-regexp
"\\([0-9]+\\),\\([0-9]+\\),\\([0-9]+\\),\\([0-9]+\\),\\([0-9]+\\),\\([0-9]+\\)"
cmdtail)
(declare (ignore whole))
(if (not matched)
(return (outline "500 'PORT ~A': command not understood." cmdtail)))
(setf a (parse-integer a))
(setf b (parse-integer b))
(setf c (parse-integer c))
(setf d (parse-integer d))
(setf e (parse-integer e))
(setf f (parse-integer f))
(let ((addr (logior (ash a 24) (ash b 16) (ash c 8) d))
(port (logior (ash e 8) f)))
(if (or (not (= addr (socket:remote-host (client-sock client))))
(< port 1024))
(return
(progn
(ftp-log-client client "Tried to set PORT ~A:~A~%"
(socket:ipaddr-to-dotted addr)
port)
(outline "500 Illegal PORT Command"))))
(cleanup-data-connection client)
(setf (dataport-addr client) addr)
(setf (dataport-port client) port)
(setf (pasv client) nil)
(outline "200 PORT command successful.")))))
(defun cmd-pasv (client cmdtail)
(declare (ignore cmdtail))
(cleanup-data-connection client)
(let (port sock)
(while (null sock)
;; XXX -- this could theoretically loop forever. Need a loop limiter
(setf port
(+ (car *pasvrange*)
(random (1+ (- (cdr *pasvrange*) (car *pasvrange*))))))
(handler-case (setf sock (socket:make-socket
:type :hiper
:connect :passive
:local-host (socket:local-host (client-sock client))
:local-port port))
(socket-error (c)
(if (not (eq (stream-error-identifier c) :address-in-use))
(signal c)
nil))))
(setf (pasv client) sock)
(let ((addr (get-passive-ip-addr client)))
(outline "227 Entering Passive Mode (~D,~D,~D,~D,~D,~D)"
(logand (ash addr -24) #xff)
(logand (ash addr -16) #xff)
(logand (ash addr -8) #xff)
(logand addr #xff)
(logand (ash port -8) #xff)
(logand port #xff)))))
(defun get-passive-ip-addr (client)
(let ((net (best-network-match (socket:remote-host (client-sock client))
(mapcar #'car *pasvipaddrs*))))
(if (null net)
(socket:local-host (client-sock client))
(cdr (assoc net *pasvipaddrs* :test #'eq)))))
(defun cmd-type (client cmdtail)
(block nil
(let ((params (delimited-string-to-list cmdtail " ")))
(cond
((or (equalp cmdtail "i") (equalp cmdtail "image"))
(setf (client-type client) :image)
(outline "200 Type set to I."))
((equalp cmdtail "e")
(outline "504 Type E not implemented."))
((or (equalp (first params) "a") (equalp (first params) "ascii"))
(if (and (second params)
(not (equalp (second params) "n")))
(return (outline "504 Form must be N.")))
(setf (client-type client) :ascii-nonprint)
(outline "200 Type set to A."))
((equalp (first params) "l")
(if (and (second params)
(not (string= (second params) "8")))
(return (outline "504 Byte size must be 8.")))
(setf (client-type client) :local)
(outline "200 Type set to L (byte size 8)."))
(t
(outline "500 'TYPE ~A': command not understood." cmdtail))))))
(defun cmd-stru (client cmdtail)
(declare (ignore client))
(if (not (member cmdtail '("f" "r" "p") :test #'equalp))
(outline "500 'STRU ~A': command not understood." cmdtail)
(if (not (equalp cmdtail "f"))
(outline "504 Unimplemented STRU type.")
(outline "200 STRU F ok."))))
(defun cmd-mode (client cmdtail)
(declare (ignore client))
(if (not (member cmdtail '("s" "b" "c") :test #'equalp))
(outline "500 'MODE ~A': command not understood." cmdtail)
(if (not (equalp cmdtail "s"))
(outline "504 Unimplemented MODE type.")
(outline "200 MODE S ok."))))
(defun cmd-rest (client cmdtail)
(block nil
(let ((point (ignore-errors (parse-integer cmdtail))))
(if (null point)
(return (outline "500 'REST ~A: command not understood." cmdtail)))
(if (< point 0)
(return (outline "501 'REST ~A: invalid parameter." cmdtail)))
(setf (client-restart client) point)
(outline "350 Restarting at ~D. Send STOR or RETR to initiate transfer."
point))))
(defun cmd-allo (client cmdtail)
(declare (ignore client cmdtail))
(outline "202 ALLO command ignored."))
;; XXX -- pretty useless since asynchronous requests aren't supported.
(defun cmd-abor (client cmdtail)
(declare (ignore cmdtail))
(cleanup-data-connection client)
(outline "225 ABOR command successful."))
(defun data-connection-prepared-p (client)
(or (dataport-addr client)
(pasv client)))
(defun cleanup-data-connection (client)
(when (dataport-open client)
(ignore-errors (close (dataport-sock client)))
(setf (dataport-sock client) nil)
(setf (dataport-open client) nil))
(when (pasv client)
(ignore-errors (close (pasv client)))
(setf (pasv client) nil))
(setf (dataport-addr client) nil)
(setf (dataport-port client) nil))
;; Drops connections made by other hosts.
(defun accept-pasv-connection-from-client (client)
(loop
(let ((newsock (ignore-errors (socket:accept-connection (pasv client)))))
(if newsock
(if (not (= (socket:remote-host newsock)
(socket:remote-host (client-sock client))))
(progn
(ftp-log
"Non-client connection to PASV port ~A:~A made by ~A.~%"
(socket:ipaddr-to-dotted
(socket:local-host (client-sock client)))
(socket:local-port (pasv client))
(socket:ipaddr-to-dotted
(socket:remote-host newsock)))
(ignore-errors (close newsock)))
(return newsock))))))
;; This is covered by the with-timeout in establish-data-connection
(defun make-active-connection (client)
(handler-case
(with-root-privs ()
(socket:make-socket :remote-host (dataport-addr client)
:remote-port (dataport-port client)
:local-host (socket:local-host (client-sock client))
:local-port *ftpdataport*
:reuse-address t
:type :hiper))
(error (c)
(ftp-log-client client "make-active-connection: make-socket failed; ~A~%" c)
nil)))
(defun establish-data-connection (client)
(block nil
(setf (dataport-sock client)
(mp:with-timeout (*connecttimeout* :timeout)
(if (pasv client)
(accept-pasv-connection-from-client client)
(make-active-connection client))))
(if (null (dataport-sock client))
(progn
(outline "425 Can't open data connection.")
(return nil)))
(if (eq (dataport-sock client) :timeout)
(progn
(outline "425 Can't open data connection. Timed out.")
(return nil)))
(socket:socket-control
(dataport-sock client)
:read-timeout *transfertimeout*
:write-timeout *transfertimeout*)
(setf (dataport-open client) t)))
(defun cmd-retr (client file)
(block nil
(let ((fullpath (make-full-path (pwd client) file)))
(if (and (restricted client)
(out-of-bounds-p client fullpath))
(return (outline "550 ~A: Permission denied." file)))
(if (null (data-connection-prepared-p client))
(return (outline "452 No data connection has been prepared.")))
(if (not (probe-file fullpath))
(multiple-value-bind (conv realname)
(conversion-match file)
(if conv
(return (start-conversion client conv realname)))
(return (outline "550 ~A: No such file or directory." file))))
(if (not (eq :file (excl::filesys-type fullpath)))
(return (outline "550 ~A: not a plain file." file)))
(ftp-with-open-file
(f errno fullpath)
(if (null f)
(return (outline "550 ~A: ~A" file (strerror errno))))
;; XXX -- this is only correct for binary files.
(let ((res (ignore-errors
(file-position f (client-restart client)))))
(setf (client-restart client) 0)
(if (null res)
(return (outline "550 ~A: RETR (with REST) failed." file))))
(transmit-stream client f fullpath)))))
;; This should be called after 'path' has been verified not to exist.
(defun conversion-match (path)
(let ((pathlen (length path))
ext
extlen)
(dolist (extcons *conversions*)
(setf ext (car extcons))
(setf extlen (length ext))
(if (and (> pathlen extlen)
(string= (subseq path (- pathlen extlen)) ext))
(return (values (cdr extcons)
(subseq path 0 (- pathlen extlen))))))))
(defun start-conversion (client conversionvec file)
(block nil
(if (not (eq (client-type client) :image))
(return
(outline "~
550 This is a BINARY file, using ASCII mode to transfer will corrupt it.")))
(if (not (= 0 (client-restart client)))
(return
(outline "550 REST not allowed with conversions.")))
(let ((cmdvec (concatenate 'vector
(vector (aref conversionvec 0)) ;; duplicate first entry
conversionvec
(vector file))))
(with-external-command (stream cmdvec)
(transmit-stream client stream (aref cmdvec 0))))))
(defun transmit-stream (client stream name)
(block nil
(if (null (establish-data-connection client))
(return))
(outline "150 Opening ~A mode data connection for ~A."
(if (eq (client-type client) :image)
"BINARY" "ASCII")
name)
(if (handler-case (dump-file client stream)
(socket-error (c)
(if (or (eq (stream-error-identifier c) :read-timeout)
(eq (stream-error-identifier c) :write-timeout))
(outline "426 Data transfer timeout.")
(outline "426 Data connection: Broken pipe."))
nil)
(error (c)
(let ((*print-pretty* nil))
(outline "426 Error: ~A"
(substitute #\space #\newline (format nil "~A" c))))
nil))
(outline "226 Transfer complete."))
(xfer-log client name :retr
(excl::socket-bytes-written (dataport-sock client)))
(cleanup-data-connection client)))
(defun dump-file (client f)
(if (eq (client-type client) :ascii-nonprint)
(dump-file-ascii client f)
(dump-file-binary client f))
t)
(defun dump-file-ascii (client f)
(let ((inbuffer (make-string 32768))
(outbuffer (make-array 65536 :element-type '(unsigned-byte 8)))
(sock (dataport-sock client))
got)
(while (not (= 0 (setf got (read-sequence inbuffer f :partial-fill t))))
(multiple-value-bind (ignore count)
(string-to-octets inbuffer
:null-terminate nil
:mb-vector outbuffer
:end got
:external-format *extfcrlf*)
(declare (ignore ignore))
(write-complete-vector outbuffer count sock))))
t)
(defun dump-file-binary (client f)
(let ((buffer (make-array 65536 :element-type '(unsigned-byte 8)))
(sock (dataport-sock client))
got)
(while (/= 0 (setf got (read-vector buffer f)))
(write-complete-vector buffer got sock)))
t)
(defun write-complete-vector (vec end stream)
(let ((pos 0)
newpos)
(while (< pos end)