1 /*
2 * ProFTPD - mod_sftp SCP
3 * Copyright (c) 2008-2020 TJ Saunders
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA.
18 *
19 * As a special exemption, TJ Saunders and other respective copyright holders
20 * give permission to link this program with OpenSSL, and distribute the
21 * resulting executable, without including the source code for OpenSSL in the
22 * source distribution.
23 */
24
25 #include "mod_sftp.h"
26 #include "ssh2.h"
27 #include "packet.h"
28 #include "msg.h"
29 #include "channel.h"
30 #include "scp.h"
31 #include "misc.h"
32 #include "disconnect.h"
33
34 #define SFTP_SCP_ST_MODE_MASK (S_ISUID|S_ISGID|S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO)
35
36 /* Define a maximum limit on the amount of data we buffer when handling
37 * fragmented control messages.
38 */
39 #define SFTP_SCP_MAX_CTL_LEN (PR_TUNABLE_PATH_MAX + 256)
40
41 extern pr_response_t *resp_list, *resp_err_list;
42
43 struct scp_path {
44 char *path;
45
46 /* The original path, as provided in the scp command. */
47 const char *orig_path;
48
49 pr_fh_t *fh;
50
51 /* Points to the parent directory "context" path, if any. For handling
52 * the push/pop approach that SCP uses for receiving directories from
53 * recursive SCP uploads.
54 *
55 * Note: for very wide/deep recursive uploads, the amount of memory used
56 * for these scp_path structs could grow quite a bit. If each struct
57 * was allocated out of its own sub pool, then they could be freed
58 * during the recursive upload. Something to keep in mind.
59 */
60 struct scp_path *parent_dir;
61
62 /* Track state of file metadata we've received. */
63 int checked_errors;
64
65 int have_mode;
66 mode_t st_mode;
67
68 struct timeval times[2];
69 int recvd_timeinfo;
70
71 mode_t perms;
72 off_t filesz;
73 const char *filename;
74 const char *best_path;
75 int recvd_finfo;
76 int recvd_data;
77
78 /* For reading of control messages. */
79 pool *ctl_pool;
80 unsigned char *ctl_data;
81 uint32_t ctl_datalen;
82
83 /* For the reading of bytes of files. */
84 off_t recvlen;
85
86 int wrote_errors;
87
88 /* Track state of how much file metadata we've sent. */
89 int sent_timeinfo;
90 int sent_dirinfo;
91 int sent_finfo;
92 int sent_data;
93
94 /* For sending the bytes of files. */
95 off_t sentlen;
96
97 /* For directories. */
98 void *dirh;
99 struct scp_path *dir_spi;
100
101 /* For supporting the HiddenStores directive. */
102 int hiddenstore;
103
104 /* For indicating whether the file existed prior to being opened/created. */
105 int file_existed;
106 };
107
108 static pool *scp_pool = NULL;
109
110 /* Use a struct to maintain the per-channel SCP-specific values. */
111 struct scp_session {
112 struct scp_session *next, *prev;
113
114 pool *pool;
115 uint32_t channel_id;
116 array_header *paths;
117 unsigned int path_idx;
118 };
119
120 static struct scp_session *scp_session = NULL, *scp_sessions = NULL;
121
122 /* This structure is a container, for holding the paths and index until
123 * the session object for the channel is opened. sftp_scp_set_params(),
124 * which parses out the paths, is called _before_ sftp_scp_open_session(),
125 * hence why we need to track these separately.
126 */
127
128 struct scp_paths {
129 struct scp_paths *next, *prev;
130
131 pool *pool;
132 uint32_t channel_id;
133 array_header *paths;
134 unsigned int path_idx;
135 };
136
137 static struct scp_paths *scp_paths = NULL;
138
139 static unsigned int scp_opts = 0;
140 #define SFTP_SCP_OPT_ISSRC 0x0001
141 #define SFTP_SCP_OPT_ISDST 0x0002
142 #define SFTP_SCP_OPT_DIR 0x0004
143 #define SFTP_SCP_OPT_VERBOSE 0x0008
144 #define SFTP_SCP_OPT_PRESERVE 0x0010
145 #define SFTP_SCP_OPT_RECURSE 0x0020
146
147 /* Boolean flag indicating whether we need to wait for the confirmation
148 * response (byte) from the client before proceeding.
149 */
150 static int need_confirm;
151
152 static const char *trace_channel = "scp";
153
154 static int send_path(pool *, uint32_t, struct scp_path *);
155
scp_timeout_stalled_cb(CALLBACK_FRAME)156 static int scp_timeout_stalled_cb(CALLBACK_FRAME) {
157 pr_event_generate("core.timeout-stalled", NULL);
158
159 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
160 "SCP data transfer stalled timeout (%d secs) reached",
161 pr_data_get_timeout(PR_DATA_TIMEOUT_STALLED));
162 SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_BY_APPLICATION,
163 "data stalled timeout reached");
164
165 return 0;
166 }
167
scp_cmd_alloc(pool * p,const char * name,const char * arg)168 static cmd_rec *scp_cmd_alloc(pool *p, const char *name, const char *arg) {
169 cmd_rec *cmd;
170
171 cmd = pr_cmd_alloc(p, 2, pstrdup(p, name), arg ? arg : "");
172 cmd->arg = (char *) arg;
173
174 return cmd;
175 }
176
scp_destroy_paths(struct scp_paths * paths)177 static int scp_destroy_paths(struct scp_paths *paths) {
178 if (paths == NULL) {
179 return 0;
180 }
181
182 if (paths->next)
183 paths->next->prev = paths->prev;
184
185 if (paths->prev) {
186 paths->prev->next = paths->next;
187
188 } else {
189 scp_paths = paths->next;
190 }
191
192 destroy_pool(paths->pool);
193 return 0;
194 }
195
scp_new_paths(uint32_t channel_id)196 static struct scp_paths *scp_new_paths(uint32_t channel_id) {
197 pool *sub_pool;
198 struct scp_paths *paths, *last;
199
200 /* Check to see if we already have an paths object for this channel ID. */
201 paths = last = scp_paths;
202 while (paths) {
203 pr_signals_handle();
204
205 if (paths->channel_id == channel_id) {
206 errno = EEXIST;
207 return NULL;
208 }
209
210 if (paths->next == NULL) {
211 /* This is the last item in the list. */
212 last = paths;
213 }
214
215 paths = paths->next;
216 }
217
218 /* Looks like we get to allocate a new one. */
219 sub_pool = make_sub_pool(scp_pool);
220 pr_pool_tag(sub_pool, "SCP paths pool");
221
222 paths = pcalloc(sub_pool, sizeof(struct scp_paths));
223 paths->pool = sub_pool;
224 paths->channel_id = channel_id;
225
226 if (last) {
227 last->next = paths;
228 paths->prev = last;
229
230 } else {
231 scp_paths = paths;
232 }
233
234 return paths;
235 }
236
scp_get_paths(uint32_t channel_id)237 static struct scp_paths *scp_get_paths(uint32_t channel_id) {
238 struct scp_paths *paths;
239
240 paths = scp_paths;
241 while (paths) {
242 pr_signals_handle();
243
244 if (paths->channel_id == channel_id) {
245 return paths;
246 }
247
248 paths = paths->next;
249 }
250
251 errno = ENOENT;
252 return NULL;
253 }
254
scp_get_session(uint32_t channel_id)255 static struct scp_session *scp_get_session(uint32_t channel_id) {
256 struct scp_session *sess;
257
258 sess = scp_sessions;
259 while (sess) {
260 pr_signals_handle();
261
262 if (sess->channel_id == channel_id) {
263 return sess;
264 }
265
266 sess = sess->next;
267 }
268
269 errno = ENOENT;
270 return NULL;
271 }
272
reset_path(struct scp_path * sp)273 static void reset_path(struct scp_path *sp) {
274 if (sp->fh) {
275 pr_fsio_close(sp->fh);
276 sp->fh = NULL;
277 }
278
279 /* XXX Should clear/reset the sent fields as well, but this function
280 * is mainly for use when receiving files, not sending files.
281 */
282
283 sp->checked_errors = FALSE;
284
285 sp->st_mode = 0;
286 sp->have_mode = FALSE;
287 sp->recvd_timeinfo = FALSE;
288
289 sp->perms = 0;
290 sp->filesz = 0;
291 sp->filename = NULL;
292 sp->best_path = NULL;
293 sp->recvd_finfo = FALSE;
294 sp->recvd_data = FALSE;
295
296 sp->recvlen = 0;
297 sp->hiddenstore = FALSE;
298 sp->file_existed = FALSE;
299
300 sp->wrote_errors = FALSE;
301 }
302
read_confirm(struct ssh2_packet * pkt,unsigned char ** buf,uint32_t * buflen)303 static int read_confirm(struct ssh2_packet *pkt, unsigned char **buf,
304 uint32_t *buflen) {
305 char code;
306
307 code = sftp_msg_read_byte(pkt->pool, buf, buflen);
308 pr_trace_msg(trace_channel, 9, "recvd confirmation/error code = %d", code);
309
310 switch (code) {
311 case 0:
312 break;
313
314 case 1: {
315 register unsigned int i;
316 char *msg;
317
318 /* Error; message to follow. Since it won't be encoded as an SSH2 string,
319 * we will need to read it character by character. Whee.
320 */
321
322 msg = pcalloc(pkt->pool, *buflen + 1);
323 for (i = 0; *buflen; ) {
324 char c;
325
326 c = sftp_msg_read_byte(pkt->pool, buf, buflen);
327 if (c == '\n') {
328 break;
329 }
330
331 msg[i++] = c;
332 }
333
334 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
335 "error from client: %s", msg);
336 return -1;
337 }
338
339 case 2:
340 /* Fatal error, no message. */
341 return -1;
342 }
343
344 need_confirm = FALSE;
345 return 0;
346 }
347
write_confirm(pool * p,uint32_t channel_id,int code,const char * msg)348 static int write_confirm(pool *p, uint32_t channel_id, int code,
349 const char *msg) {
350 unsigned char *buf, *ptr;
351 uint32_t buflen, bufsz;
352
353 /* XXX Is this big enough? Too big? */
354 buflen = bufsz = 128;
355 buf = ptr = palloc(p, bufsz);
356
357 if (code == 0) {
358 pr_trace_msg(trace_channel, 9, "sending confirmation/error code = %d",
359 code);
360 sftp_msg_write_byte(&buf, &buflen, code);
361
362 } else {
363 char *errstr;
364 size_t errlen;
365
366 pr_trace_msg(trace_channel, 9, "sending confirmation/error code = %d (%s)",
367 code, msg ? msg : "null");
368
369 errstr = pstrcat(p, msg, "\n", NULL);
370 errlen = strlen(errstr);
371
372 sftp_msg_write_byte(&buf, &buflen, code);
373 sftp_msg_write_data(&buf, &buflen, (const unsigned char *) errstr, errlen,
374 FALSE);
375 }
376
377 return sftp_channel_write_data(p, channel_id, ptr, (bufsz - buflen));
378 }
379
380 /* Functions for receiving files from the client. */
381
recv_ctl(uint32_t channel_id,struct scp_path * sp,unsigned char * data,uint32_t datalen,unsigned char ** ctl_data,uint32_t * ctl_datalen)382 static int recv_ctl(uint32_t channel_id, struct scp_path *sp,
383 unsigned char *data, uint32_t datalen,
384 unsigned char **ctl_data, uint32_t *ctl_datalen) {
385 register int i;
386 int have_newline = FALSE;
387 char *tmp;
388 uint32_t tmplen;
389
390 for (i = datalen-1; i >= 0; i--) {
391 if (data[i] == '\n') {
392 have_newline = TRUE;
393 break;
394 }
395 }
396
397 if (sp->ctl_data == NULL) {
398 if (have_newline == TRUE) {
399 *ctl_data = data;
400 *ctl_datalen = datalen;
401
402 return 1;
403 }
404
405 sp->ctl_pool = pr_pool_create_sz(scp_session->pool, 128);
406 sp->ctl_datalen = datalen;
407 sp->ctl_data = palloc(sp->ctl_pool, sp->ctl_datalen);
408 memmove(sp->ctl_data, data, datalen);
409
410 return 0;
411 }
412
413 /* Add the given data to the existing cache of data. */
414 tmplen = sp->ctl_datalen + datalen;
415 tmp = palloc(sp->ctl_pool, tmplen);
416 memmove(tmp, sp->ctl_data, sp->ctl_datalen);
417 memmove(tmp + sp->ctl_datalen, data, datalen);
418
419 sp->ctl_data = (unsigned char *) tmp;
420 sp->ctl_datalen = tmplen;
421
422 /* Now, if we saw a newline, we can return all of the cached data as the
423 * complete control message.
424 */
425 if (have_newline == TRUE) {
426 *ctl_data = sp->ctl_data;
427 *ctl_datalen = sp->ctl_datalen;
428
429 sp->ctl_data = NULL;
430 sp->ctl_datalen = 0;
431 destroy_pool(sp->ctl_pool);
432 sp->ctl_pool = NULL;
433 return 1;
434 }
435
436 if (sp->ctl_datalen >= SFTP_SCP_MAX_CTL_LEN) {
437 write_confirm(sp->ctl_pool, channel_id, 1,
438 "max control message size exceeded");
439 sp->wrote_errors = TRUE;
440 return 1;
441 }
442
443 /* Otherwise, we need to aggregate more data from the client. */
444 return 0;
445 }
446
recv_errors(pool * p,uint32_t channel_id,struct scp_path * sp,unsigned char * data,uint32_t datalen)447 static int recv_errors(pool *p, uint32_t channel_id, struct scp_path *sp,
448 unsigned char *data, uint32_t datalen) {
449
450 /* Check for error messages from the client first. */
451 if (data[0] == '\01') {
452 register unsigned int i;
453 char *msg;
454
455 for (i = 1; i < datalen; i++) {
456 if (data[i] == '\n') {
457 break;
458 }
459 }
460
461 if (i < datalen) {
462 msg = pstrndup(p, (char *) &(data[1]), i + 1);
463
464 } else {
465 msg = pcalloc(p, i + 1);
466 memcpy(msg, &(data[1]), i);
467 }
468
469 pr_trace_msg(trace_channel, 3,
470 "received error '%s' from client while receiving path '%s', skipping",
471 msg, sp->path);
472
473 sp->checked_errors = TRUE;
474 return 1;
475 }
476
477 if (data[0] == '\02') {
478 pr_trace_msg(trace_channel, 3,
479 "received fatal error from client while receiving path '%s', skipping",
480 sp->path);
481
482 sp->checked_errors = TRUE;
483 return 1;
484 }
485
486 sp->checked_errors = TRUE;
487 return 0;
488 }
489
recv_timeinfo(pool * p,uint32_t channel_id,struct scp_path * sp,unsigned char * buf,uint32_t buflen,unsigned char ** remain,uint32_t * remainlen)490 static int recv_timeinfo(pool *p, uint32_t channel_id, struct scp_path *sp,
491 unsigned char *buf, uint32_t buflen, unsigned char **remain,
492 uint32_t *remainlen) {
493 register unsigned int i;
494 unsigned char *data = NULL, *msg, *ptr = NULL;
495 uint32_t datalen = 0;
496 char *tmp = NULL;
497 int res;
498
499 res = recv_ctl(channel_id, sp, buf, buflen, &data, &datalen);
500 if (res != 1) {
501 return res;
502 }
503
504 if (data[0] != 'T') {
505 /* Not a timeinfo message; let someone else process this. */
506 *remain = data;
507 *remainlen = datalen;
508
509 errno = EINVAL;
510 return -1;
511 }
512
513 for (i = 1; i < datalen; i++) {
514 if (data[i] == '\n') {
515 ptr = &data[i++];
516 break;
517 }
518 }
519
520 msg = data + 1;
521
522 if (ptr)
523 *ptr = '\0';
524
525 pr_trace_msg(trace_channel, 5, "'%s' control message: T%s", sp->path, msg);
526
527 sp->times[1].tv_sec = strtoul((char *) msg, &tmp, 10);
528 if (tmp == NULL ||
529 *tmp != ' ') {
530 write_confirm(p, channel_id, 1, "mtime secs not delimited");
531 sp->wrote_errors = TRUE;
532 return 1;
533 }
534
535 msg = ((unsigned char *) tmp) + 1;
536 sp->times[1].tv_usec = strtoul((char *) msg, &tmp, 10);
537 if (tmp == NULL ||
538 *tmp != ' ') {
539 write_confirm(p, channel_id, 1, "mtime usecs not delimited");
540 sp->wrote_errors = TRUE;
541 return 1;
542 }
543
544 msg = ((unsigned char *) tmp) + 1;
545 sp->times[0].tv_sec = strtoul((char *) msg, &tmp, 10);
546 if (tmp == NULL ||
547 *tmp != ' ') {
548 write_confirm(p, channel_id, 1, "atime secs not delimited");
549 sp->wrote_errors = TRUE;
550 return 1;
551 }
552
553 msg = ((unsigned char *) tmp) + 1;
554 sp->times[0].tv_usec = strtoul((char *) msg, &tmp, 10);
555 if (tmp == NULL ||
556 *tmp != '\0') {
557 write_confirm(p, channel_id, 1, "atime usecs not delimited");
558 sp->wrote_errors = TRUE;
559 return 1;
560 }
561
562 sp->recvd_timeinfo = TRUE;
563 write_confirm(p, channel_id, 0, NULL);
564 return 0;
565 }
566
recv_perms(pool * p,uint32_t channel_id,char * mode_str,mode_t * perms)567 static int recv_perms(pool *p, uint32_t channel_id, char *mode_str,
568 mode_t *perms) {
569 register unsigned int i;
570
571 if (strlen(mode_str) < 5) {
572 /* This needs to be at least 5 characters: 4 mode digits, and space. */
573 pr_trace_msg(trace_channel, 2, "mode string too short: '%s'", mode_str);
574 write_confirm(p, channel_id, 1, "bad mode");
575 return -1;
576 }
577
578 for (i = 0; i < 4; i++) {
579 /* Make sure the characters are numeric, and in the octal range. */
580 if (mode_str[i] < '0' ||
581 mode_str[i] > '7') {
582 pr_trace_msg(trace_channel, 2, "non-octal mode character in '%s'",
583 mode_str);
584 *perms = 0;
585 write_confirm(p, channel_id, 1, "bad mode");
586 return -1;
587 }
588
589 *perms = (*perms << 3) | (mode_str[i] - '0');
590 }
591
592 /* Make sure the next character in the string is a space. */
593 if (mode_str[i] != ' ') {
594 pr_trace_msg(trace_channel, 2, "mode not followed by space delimiter");
595 write_confirm(p, channel_id, 1, "mode not delimited");
596 return -1;
597 }
598
599 pr_trace_msg(trace_channel, 8, "client sent file perms: %04o",
600 (unsigned int) *perms);
601 return 0;
602 }
603
recv_filesz(pool * p,uint32_t channel_id,char * size_str,off_t * filesz)604 static int recv_filesz(pool *p, uint32_t channel_id, char *size_str,
605 off_t *filesz) {
606 register unsigned int i;
607
608 /* The file size field could be of arbitrary length. */
609 for (i = 0, *filesz = 0; PR_ISDIGIT(size_str[i]); i++) {
610 pr_signals_handle();
611
612 *filesz = (*filesz * 10) + (size_str[i] - '0');
613 }
614
615 if (size_str[i] != ' ') {
616 pr_trace_msg(trace_channel, 2, "file size not followed by space delimiter");
617 write_confirm(p, channel_id, 1, "file size not delimited");
618 return -1;
619 }
620
621 pr_trace_msg(trace_channel, 8, "client sent file size: %" PR_LU " bytes",
622 (pr_off_t) *filesz);
623 return 0;
624 }
625
recv_filename(pool * p,uint32_t channel_id,char * name_str,struct scp_path * sp)626 static int recv_filename(pool *p, uint32_t channel_id, char *name_str,
627 struct scp_path *sp) {
628
629 if (strchr(name_str, '/') != NULL ||
630 strncmp(name_str, "..", 3) == 0) {
631 pr_trace_msg(trace_channel, 2, "bad filename: '%s'", name_str);
632 write_confirm(p, channel_id, 1,
633 pstrcat(p, "unexpected filename: ", name_str, NULL));
634 return -1;
635 }
636
637 /* name_str contains the name of the source file, on the client machine.
638 * Our task is to determine whether we want use that same filename
639 * for the destination file here or not, and if not, what filename to use
640 * instead.
641 *
642 * sp->path contains the path that the client gaves to us when starting the
643 * SCP session. This path might be a relative or absolute path to a
644 * directory (which may or may not exist), or might be a relative or absolute
645 * path to an actual file. And whether we are chrooted or not might also
646 * factor into things.
647 *
648 * Examples:
649 *
650 * 1. scp src.txt 1.2.3.4:dst.txt
651 *
652 * name_str = "src.txt"
653 * sp->path = "dst.txt"
654 *
655 * 2. scp src.txt 1.2.3.4:dir
656 *
657 * name_str = "src.txt"
658 * sp->path = "dir"
659 *
660 * 3. scp src.txt 1.2.3.4:dir/
661 *
662 * name_str = "src.txt"
663 * sp->path = "dir/"
664 *
665 * 4. scp src.txt 1.2.3.4:dir/dst.txt
666 *
667 * name_str = "src.txt"
668 * sp->path = "dir/dst.txt"
669 *
670 * 5. scp src.txt 1.2.3.4:/dir
671 *
672 * name_str = "src.txt"
673 * sp->path = "/dir"
674 *
675 * 6. scp src.txt 1.2.3.4:/dir/
676 *
677 * name_str = "src.txt"
678 * sp->path = "/dir/"
679 *
680 * 7. scp src.txt 1.2.3.4:/dir/dst.txt
681 *
682 * name_str = "src.txt"
683 * sp->path = "/dir/dst.txt"
684 *
685 * All of the above examples are effectively the same. We need to determine
686 * whether sp->path is a directory or not. The sp->st_mode struct stat can
687 * be used for this. We should not rely on the presence (or not) of a
688 * trailing slash in the sp->path string.
689 *
690 * If we determine that sp->path is a directory, then we need to append
691 * name_str to get the path to the destination file. Otherwise,
692 * we should use sp->path as is, as the path to the destination file.
693 */
694
695 if (sp->parent_dir == NULL) {
696 if (!S_ISDIR(sp->st_mode)) {
697 /* sp->path is not a directory; use it as the destination filename. */
698 sp->filename = pstrdup(scp_pool, sp->path);
699
700 } else {
701 /* sp->path is a directory; append the source filename to it to get the
702 * destination filename.
703 */
704 sp->filename = pdircat(scp_pool, sp->path, name_str, NULL);
705 }
706
707 } else {
708 /* Fortunately, in the case of recursive SCP uploads, we always use the
709 * source filename as the destination file.
710 */
711 sp->filename = pdircat(scp_pool, sp->path, name_str, NULL);
712 }
713
714 if (sp->filename != NULL) {
715 struct stat st;
716
717 sp->best_path = dir_canonical_vpath(scp_pool, sp->filename);
718
719 pr_fs_clear_cache2(sp->best_path);
720 if (pr_fsio_lstat(sp->best_path, &st) == 0) {
721 if (S_ISLNK(st.st_mode)) {
722 char link_path[PR_TUNABLE_PATH_MAX];
723 int len;
724
725 memset(link_path, '\0', sizeof(link_path));
726 len = dir_readlink(scp_pool, sp->best_path, link_path,
727 sizeof(link_path)-1, PR_DIR_READLINK_FL_HANDLE_REL_PATH);
728 if (len > 0) {
729 link_path[len] = '\0';
730 sp->best_path = pstrdup(scp_pool, link_path);
731 }
732 }
733 }
734
735 /* Update the session.xfer.path value with this better, fuller path. */
736 session.xfer.path = pstrdup(session.xfer.p, sp->best_path);
737 }
738
739 pr_trace_msg(trace_channel, 8,
740 "client sent filename '%s' (path '%s')", name_str, sp->best_path);
741 return 0;
742 }
743
recv_finfo(pool * p,uint32_t channel_id,struct scp_path * sp,unsigned char * buf,uint32_t buflen)744 static int recv_finfo(pool *p, uint32_t channel_id, struct scp_path *sp,
745 unsigned char *buf, uint32_t buflen) {
746 register unsigned int i;
747 const char *hiddenstore_path = NULL;
748 struct stat st;
749 unsigned char *data = NULL, *msg;
750 uint32_t datalen = 0;
751 char *ptr = NULL;
752 int have_dir = FALSE, res;
753 cmd_rec *cmd = NULL;
754
755 res = recv_ctl(channel_id, sp, buf, buflen, &data, &datalen);
756 if (res != 1) {
757 return res;
758 }
759
760 switch (data[0]) {
761 case 'C':
762 break;
763
764 case 'D':
765 if (!(scp_opts & SFTP_SCP_OPT_RECURSE)) {
766 pr_trace_msg(trace_channel, 3,
767 "received D control message for '%s' without RECURSE set, "
768 "rejecting", sp->path);
769 write_confirm(p, channel_id, 1,
770 pstrcat(p, sp->path, ": cannot use directory (no -r option)", NULL));
771 sp->wrote_errors = TRUE;
772 return 1;
773 }
774
775 have_dir = TRUE;
776 break;
777
778 default:
779 pr_trace_msg(trace_channel, 3,
780 "expected file info control message for '%s', got '%c'",
781 sp->path, data[0]);
782 write_confirm(p, channel_id, 1,
783 pstrcat(p, sp->path, ": expected control message", NULL));
784 sp->wrote_errors = TRUE;
785 return 1;
786 }
787
788 for (i = 1; i < datalen; i++) {
789 if (data[i] == '\n') {
790 ptr = (char *) &data[i++];
791 break;
792 }
793 }
794
795 msg = data + 1;
796 if (ptr != NULL) {
797 *ptr = '\0';
798 }
799
800 pr_trace_msg(trace_channel, 5, "'%s' control message: %c%s", sp->path,
801 !have_dir ? 'C' : 'D', msg);
802
803 ptr = (char *) msg;
804 if (recv_perms(p, channel_id, ptr, &sp->perms) < 0) {
805 sp->wrote_errors = TRUE;
806 return 1;
807 }
808
809 ptr = strchr(ptr, ' ');
810 if (ptr == NULL) {
811 pr_trace_msg(trace_channel, 3,
812 "bad control message (undelimited mode)");
813 write_confirm(p, channel_id, 1,
814 pstrcat(p, sp->path, ": bad control message (undelimited mode)", NULL));
815 sp->wrote_errors = TRUE;
816 return 1;
817 }
818
819 /* Advance past the space delimiter. */
820 ptr++;
821 if (recv_filesz(p, channel_id, ptr, &sp->filesz) < 0) {
822 sp->wrote_errors = TRUE;
823 return 1;
824 }
825
826 ptr = strchr(ptr, ' ');
827 if (ptr == NULL) {
828 pr_trace_msg(trace_channel, 3,
829 "bad control message (undelimited file size)");
830 write_confirm(p, channel_id, 1,
831 pstrcat(p, sp->path, ": bad control message (undelimited file size)",
832 NULL));
833 sp->wrote_errors = TRUE;
834 return 1;
835 }
836
837 /* Advance past the space delimiter. */
838 ptr++;
839 if (recv_filename(p, channel_id, ptr, sp) < 0) {
840 sp->wrote_errors = TRUE;
841 return 1;
842 }
843
844 sp->recvd_finfo = TRUE;
845
846 if (have_dir) {
847 struct scp_path *parent_sp;
848
849 pr_fs_clear_cache2(sp->filename);
850 if (pr_fsio_stat(sp->filename, &st) < 0) {
851 int xerrno = errno;
852
853 /* We only want to create the directory if it doesn't already exist. */
854 if (xerrno == ENOENT) {
855 pr_trace_msg(trace_channel, 5, "creating directory '%s'", sp->filename);
856
857 /* XXX Dispatch a C_MKD command here? Should <Limit MKD> apply to
858 * recursive directory uploads via SCP?
859 */
860
861 pr_fs_clear_cache2(sp->filename);
862 if (pr_fsio_smkdir(p, sp->filename, 0777, (uid_t) -1, (gid_t) -1) < 0) {
863 xerrno = errno;
864
865 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
866 "scp: error creating directory '%s': %s", sp->filename,
867 strerror(xerrno));
868 write_confirm(p, channel_id, 1,
869 pstrcat(p, sp->filename, ": ", strerror(xerrno), NULL));
870 sp->wrote_errors = TRUE;
871
872 errno = xerrno;
873 return 1;
874 }
875
876 sftp_misc_chown_path(p, sp->filename);
877
878 } else {
879 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
880 "scp: error checking directory '%s': %s", sp->filename,
881 strerror(xerrno));
882 write_confirm(p, channel_id, 1,
883 pstrcat(p, sp->filename, ": ", strerror(xerrno), NULL));
884 sp->wrote_errors = TRUE;
885
886 errno = xerrno;
887 return 1;
888 }
889
890 } else {
891 /* Make sure that the path actually is a directory. */
892 if (!S_ISDIR(st.st_mode)) {
893 pr_trace_msg(trace_channel, 2, "error handling '%s': %s",
894 sp->best_path, strerror(ENOTDIR));
895 write_confirm(p, channel_id, 1,
896 pstrcat(p, sp->filename, ": ", strerror(ENOTDIR), NULL));
897 sp->wrote_errors = TRUE;
898 return 1;
899 }
900 }
901
902 /* At this point, the info in sp is for the parent directory; we can
903 * now expect to receive info for the files/directories contained by
904 * this parent directory.
905 *
906 * So we create a new struct scp_path for this parent directory, copy
907 * the relevant bits, push it onto the stack, and clear sp for the
908 * incoming path.
909 */
910
911 parent_sp = pcalloc(scp_pool, sizeof(struct scp_path));
912 parent_sp->orig_path = pstrdup(scp_pool, sp->orig_path);
913 parent_sp->path = pstrdup(scp_pool, sp->filename);
914 parent_sp->filename = pstrdup(scp_pool, sp->filename);
915 parent_sp->best_path = pstrdup(scp_pool, sp->best_path);
916
917 /* Copy any timeinfo as well. */
918 parent_sp->times[0].tv_sec = sp->times[0].tv_sec;
919 parent_sp->times[0].tv_usec = sp->times[0].tv_usec;
920 parent_sp->times[1].tv_sec = sp->times[1].tv_sec;
921 parent_sp->times[1].tv_usec = sp->times[1].tv_usec;
922 parent_sp->recvd_timeinfo = sp->recvd_timeinfo;
923
924 /* And the perms. */
925 parent_sp->perms = sp->perms;
926 parent_sp->parent_dir = sp->parent_dir;
927
928 /* Reset sp, for re-use for the next file coming in. */
929 reset_path(sp);
930
931 /* Adjust sp->path to account for the directory we just received; the
932 * next file coming in should be relative to the just-received directory.
933 */
934 sp->path = pstrdup(scp_pool, parent_sp->filename);
935 sp->parent_dir = parent_sp;
936
937 write_confirm(p, channel_id, 0, NULL);
938 return 0;
939 }
940
941 pr_scoreboard_entry_update(session.pid,
942 PR_SCORE_CMD, "%s", "scp upload", NULL, NULL);
943 pr_scoreboard_entry_update(session.pid,
944 PR_SCORE_CMD_ARG, "%s", sp->best_path, NULL, NULL);
945
946 cmd = scp_cmd_alloc(p, C_STOR, sp->best_path);
947
948 pr_fs_clear_cache2(sp->best_path);
949 if (exists2(p, sp->best_path)) {
950 if (pr_table_add(cmd->notes, "mod_xfer.file-modified",
951 pstrdup(cmd->pool, "true"), 0) < 0) {
952 if (errno != EEXIST) {
953 pr_log_pri(PR_LOG_NOTICE,
954 "notice: error adding 'mod_xfer.file-modified' note: %s",
955 strerror(errno));
956 }
957 }
958
959 sp->file_existed = TRUE;
960 }
961
962 if (pr_cmd_dispatch_phase(cmd, PRE_CMD, 0) < 0) {
963 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
964 "scp upload to '%s' blocked by '%s' handler", sp->path,
965 (char *) cmd->argv[0]);
966
967 (void) pr_cmd_dispatch_phase(cmd, POST_CMD_ERR, 0);
968 (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0);
969
970 write_confirm(p, channel_id, 1,
971 pstrcat(p, sp->filename, ": ", strerror(EACCES), NULL));
972 sp->wrote_errors = TRUE;
973
974 return 1;
975 }
976
977 if (strcmp(sp->filename, cmd->arg) != 0) {
978 sp->filename = cmd->arg;
979 sp->best_path = dir_canonical_vpath(scp_pool, sp->filename);
980 }
981
982 if (session.xfer.xfer_type == STOR_HIDDEN) {
983 hiddenstore_path = pr_table_get(cmd->notes, "mod_xfer.store-hidden-path",
984 NULL);
985 }
986
987 if (!dir_check(p, cmd, G_WRITE, (char *) sp->best_path, NULL)) {
988 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
989 "scp upload to '%s' blocked by <Limit> configuration", sp->best_path);
990
991 (void) pr_cmd_dispatch_phase(cmd, POST_CMD_ERR, 0);
992 (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0);
993
994 write_confirm(p, channel_id, 1,
995 pstrcat(p, sp->filename, ": ", strerror(EACCES), NULL));
996 sp->wrote_errors = TRUE;
997
998 return 1;
999 }
1000
1001 /* We automatically add the O_NONBLOCK flag to the set of open() flags
1002 * in order to deal with writing to a FIFO whose other end may not be
1003 * open. Then, after a successful open, we return the file to blocking
1004 * mode.
1005 */
1006
1007 sp->fh = pr_fsio_open(hiddenstore_path ? hiddenstore_path : sp->best_path,
1008 O_WRONLY|O_CREAT|O_NONBLOCK|O_TRUNC);
1009 if (sp->fh == NULL) {
1010 int xerrno = errno;
1011
1012 (void) pr_trace_msg("fileperms", 1, "%s, user '%s' (UID %s, GID %s): "
1013 "error opening '%s': %s", "scp upload", session.user,
1014 pr_uid2str(cmd->tmp_pool, session.uid), pr_gid2str(NULL, session.gid),
1015 hiddenstore_path ? hiddenstore_path : sp->best_path, strerror(xerrno));
1016
1017 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1018 "scp: error opening '%s': %s",
1019 hiddenstore_path ? hiddenstore_path : sp->best_path, strerror(xerrno));
1020
1021 (void) pr_cmd_dispatch_phase(cmd, POST_CMD_ERR, 0);
1022 (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0);
1023
1024 write_confirm(p, channel_id, 1,
1025 pstrcat(p, sp->filename, ": ", strerror(xerrno), NULL));
1026 sp->wrote_errors = TRUE;
1027
1028 errno = xerrno;
1029 return 1;
1030
1031 } else {
1032 off_t curr_offset;
1033
1034 /* Stash the offset at which we're writing to this file. */
1035 curr_offset = pr_fsio_lseek(sp->fh, (off_t) 0, SEEK_CUR);
1036 if (curr_offset != (off_t) -1) {
1037 off_t *file_offset;
1038
1039 file_offset = palloc(cmd->pool, sizeof(off_t));
1040 *file_offset = (off_t) curr_offset;
1041 (void) pr_table_add(cmd->notes, "mod_xfer.file-offset", file_offset,
1042 sizeof(off_t));
1043 }
1044 }
1045
1046 if (hiddenstore_path) {
1047 sp->hiddenstore = TRUE;
1048 }
1049
1050 if (pr_fsio_fstat(sp->fh, &st) < 0) {
1051 pr_trace_msg(trace_channel, 3,
1052 "fstat(2) error on '%s': %s", sp->fh->fh_path, strerror(errno));
1053
1054 } else {
1055 /* The path in question might be a FIFO. The FIFO case requires some
1056 * special handling, modulo any IgnoreFIFOs SFTPOption that might be in
1057 * effect.
1058 */
1059 #ifdef S_ISFIFO
1060 if (S_ISFIFO(st.st_mode)) {
1061 if (sftp_opts & SFTP_OPT_IGNORE_FIFOS) {
1062 int xerrno = EPERM;
1063
1064 (void) pr_fsio_close(sp->fh);
1065 sp->fh = NULL;
1066
1067 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1068 "scp: error using FIFO '%s': %s (IgnoreFIFOs SFTPOption in effect)",
1069 hiddenstore_path ? hiddenstore_path : sp->best_path,
1070 strerror(xerrno));
1071
1072 (void) pr_cmd_dispatch_phase(cmd, POST_CMD_ERR, 0);
1073 (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0);
1074
1075 write_confirm(p, channel_id, 1,
1076 pstrcat(p, sp->filename, ": ", strerror(xerrno), NULL));
1077 sp->wrote_errors = TRUE;
1078
1079 errno = xerrno;
1080 return 1;
1081 }
1082 }
1083 #endif /* S_ISFIFO */
1084 }
1085
1086 if (pr_fsio_set_block(sp->fh) < 0) {
1087 pr_trace_msg(trace_channel, 3,
1088 "error setting fd %d (file '%s') as blocking: %s", sp->fh->fh_fd,
1089 sp->fh->fh_path, strerror(errno));
1090 }
1091
1092 sftp_misc_chown_file(p, sp->fh);
1093
1094 write_confirm(p, channel_id, 0, NULL);
1095 return 0;
1096 }
1097
recv_data(pool * p,uint32_t channel_id,struct scp_path * sp,unsigned char * data,uint32_t datalen)1098 static int recv_data(pool *p, uint32_t channel_id, struct scp_path *sp,
1099 unsigned char *data, uint32_t datalen) {
1100 uint32_t writelen;
1101 config_rec *c;
1102 off_t nbytes_max_store = 0;
1103
1104 /* Check MaxStoreFileSize */
1105 c = find_config(get_dir_ctxt(p, sp->fh->fh_path), CONF_PARAM,
1106 "MaxStoreFileSize", FALSE);
1107 if (c != NULL) {
1108 nbytes_max_store = *((off_t *) c->argv[0]);
1109 }
1110
1111 writelen = datalen;
1112 if (writelen > (sp->filesz - sp->recvlen)) {
1113 writelen = (uint32_t) (sp->filesz - sp->recvlen);
1114 }
1115
1116 if (nbytes_max_store > 0) {
1117 if (sp->recvlen > nbytes_max_store) {
1118 #if defined(EFBIG)
1119 int xerrno = EFBIG;
1120 #elif defined(ENOSPC)
1121 int xerrno = ENOSPC;
1122 #else
1123 int xerrno = EIO;
1124 #endif
1125
1126 pr_log_pri(PR_LOG_NOTICE, "MaxStoreFileSize (%" PR_LU " %s) reached: "
1127 "aborting transfer of '%s'", (pr_off_t) nbytes_max_store,
1128 nbytes_max_store != 1 ? "bytes" : "byte", sp->fh->fh_path);
1129
1130 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1131 "error writing %lu bytes to '%s': %s "
1132 "(MaxStoreFileSize %" PR_LU " exceeded)", (unsigned long) writelen,
1133 sp->fh->fh_path, strerror(xerrno), (pr_off_t) nbytes_max_store);
1134
1135 write_confirm(p, channel_id, 1,
1136 pstrcat(p, sp->filename, ": write error: ", strerror(xerrno), NULL));
1137 sp->wrote_errors = TRUE;
1138
1139 /* Note that we do NOT explicitly close the filehandle here; we leave
1140 * that to the calling function, so that it can do e.g. other cleanup.
1141 */
1142
1143 errno = xerrno;
1144 return 1;
1145 }
1146 }
1147
1148 if (writelen > 0) {
1149 while (TRUE) {
1150 int res;
1151
1152 /* XXX Do we need to properly handle short writes here? */
1153 res = pr_fsio_write(sp->fh, (char *) data, writelen);
1154 if ((uint32_t) res != writelen) {
1155 int xerrno = errno;
1156
1157 if (xerrno == EINTR ||
1158 xerrno == EAGAIN) {
1159 pr_signals_handle();
1160 continue;
1161 }
1162
1163 pr_trace_msg(trace_channel, 2, "error writing to '%s': %s",
1164 sp->best_path, strerror(xerrno));
1165 write_confirm(p, channel_id, 1,
1166 pstrcat(p, sp->filename, ": write error: ", strerror(xerrno), NULL));
1167 sp->wrote_errors = TRUE;
1168
1169 /* Note that we do NOT explicitly close the filehandle here; we leave
1170 * that to the calling function, so that it can do e.g. other cleanup.
1171 */
1172
1173 errno = xerrno;
1174 return 1;
1175 }
1176
1177 break;
1178 }
1179
1180 sp->recvlen += writelen;
1181
1182 session.xfer.total_bytes += writelen;
1183 session.total_bytes += writelen;
1184
1185 if (writelen < datalen) {
1186 if (data[writelen] != '\0') {
1187 pr_trace_msg(trace_channel, 2, "expected end-of-data marker when "
1188 "receiving file data, received '%c'", data[writelen]);
1189 }
1190
1191 pr_throttle_pause(sp->recvlen, TRUE);
1192
1193 sp->recvd_data = TRUE;
1194 return 1;
1195 }
1196
1197 pr_throttle_pause(sp->recvlen, FALSE);
1198
1199 } else {
1200 /* We should have just one extra end-of-stream byte. */
1201 if (data[writelen] != '\0') {
1202 pr_trace_msg(trace_channel, 2, "expected end-of-data marker when "
1203 "receiving file data, received '%c'", data[writelen]);
1204 }
1205
1206 pr_throttle_pause(sp->recvlen, TRUE);
1207
1208 sp->recvd_data = TRUE;
1209 return 1;
1210 }
1211
1212 return 0;
1213 }
1214
recv_eod(pool * p,uint32_t channel_id,struct scp_path * sp,unsigned char * buf,uint32_t buflen,unsigned char ** remain,uint32_t * remainlen)1215 static int recv_eod(pool *p, uint32_t channel_id, struct scp_path *sp,
1216 unsigned char *buf, uint32_t buflen, unsigned char **remain,
1217 uint32_t *remainlen) {
1218 struct scp_path *parent_sp;
1219 unsigned char *data = NULL;
1220 uint32_t datalen = 0;
1221 int ok = TRUE, res;
1222
1223 res = recv_ctl(channel_id, sp, buf, buflen, &data, &datalen);
1224 if (res != 1) {
1225 return res;
1226 }
1227
1228 if (data[0] != 'E') {
1229 /* Not an EOD message; let someone else process this. */
1230 *remain = data;
1231 *remainlen = datalen;
1232
1233 errno = EINVAL;
1234 return -1;
1235 }
1236
1237 pr_trace_msg(trace_channel, 5, "'%s' control message: E", sp->path);
1238
1239 parent_sp = sp->parent_dir;
1240
1241 /* If the SFTPOption for ignoring perms for SCP uploads is set, then
1242 * skip the chmod on the upload file.
1243 */
1244 if (!(sftp_opts & SFTP_OPT_IGNORE_SCP_UPLOAD_PERMS)) {
1245 pr_trace_msg(trace_channel, 9, "setting perms %04o on directory '%s'",
1246 (unsigned int) parent_sp->perms, parent_sp->path);
1247 if (pr_fsio_chmod(parent_sp->path, parent_sp->perms) < 0) {
1248 int xerrno = errno;
1249
1250 pr_trace_msg(trace_channel, 2, "error setting mode %04o on '%s': %s",
1251 (unsigned int) parent_sp->perms, parent_sp->path, strerror(xerrno));
1252 write_confirm(p, channel_id, 1,
1253 pstrcat(p, parent_sp->path, ": error setting mode: ", strerror(xerrno),
1254 NULL));
1255 parent_sp->wrote_errors = TRUE;
1256 ok = FALSE;
1257 }
1258
1259 } else {
1260 pr_trace_msg(trace_channel, 7, "SFTPOption 'IgnoreSCPUploadPerms' "
1261 "configured, ignoring perms sent by client");
1262 }
1263
1264 if (parent_sp->recvd_timeinfo) {
1265 pr_trace_msg(trace_channel, 9, "setting times on directory '%s'",
1266 parent_sp->filename);
1267
1268 /* If the SFTPOption for ignoring times for SCP uploads is set, then
1269 * skip the utimes on the upload file.
1270 */
1271 if (!(sftp_opts & SFTP_OPT_IGNORE_SCP_UPLOAD_TIMES)) {
1272 if (pr_fsio_utimes(parent_sp->filename, parent_sp->times) < 0) {
1273 int xerrno = errno;
1274
1275 pr_trace_msg(trace_channel, 2,
1276 "error setting atime %lu, mtime %lu on '%s': %s",
1277 (unsigned long) sp->times[0].tv_sec,
1278 (unsigned long) sp->times[1].tv_sec, parent_sp->filename,
1279 strerror(xerrno));
1280
1281 write_confirm(p, channel_id, 1,
1282 pstrcat(p, parent_sp->filename, ": error setting times: ",
1283 strerror(xerrno), NULL));
1284 parent_sp->wrote_errors = TRUE;
1285 ok = FALSE;
1286 }
1287
1288 } else {
1289 pr_trace_msg(trace_channel, 7, "SFTPOption 'IgnoreSCPUploadTimes' "
1290 "configured, ignoring times sent by client");
1291 }
1292 }
1293
1294 if (ok) {
1295 write_confirm(p, channel_id, 0, NULL);
1296 }
1297
1298 return 1;
1299 }
1300
1301 /* Return 1 when we should skip to the next path in the list, either because
1302 * we have received all the data for this path, or because we can never
1303 * receive it (due to some error).
1304 */
recv_path(pool * p,uint32_t channel_id,struct scp_path * sp,unsigned char * data,uint32_t datalen)1305 static int recv_path(pool *p, uint32_t channel_id, struct scp_path *sp,
1306 unsigned char *data, uint32_t datalen) {
1307 int res;
1308 cmd_rec *cmd = NULL;
1309 char *curr_path = NULL;
1310
1311 if (!sp->checked_errors) {
1312 res = recv_errors(p, channel_id, sp, data, datalen);
1313 if (res == 1) {
1314 return 1;
1315 }
1316 }
1317
1318 if (!sp->have_mode) {
1319 struct stat st;
1320
1321 pr_fs_clear_cache2(sp->path);
1322 res = pr_fsio_stat(sp->path, &st);
1323 if (res == 0) {
1324 sp->st_mode = st.st_mode;
1325 sp->have_mode = TRUE;
1326 }
1327
1328 if (scp_opts & SFTP_SCP_OPT_DIR) {
1329 /* If the path should be a directory, stat it and make sure that
1330 * is the case. If not, we have a problem.
1331 */
1332 if (res == 0) {
1333 if (!S_ISDIR(st.st_mode)) {
1334 write_confirm(p, channel_id, 1,
1335 pstrcat(p, sp->path, ": ", strerror(ENOTDIR), NULL));
1336 sp->wrote_errors = TRUE;
1337 return 1;
1338 }
1339
1340 } else {
1341 write_confirm(p, channel_id, 1,
1342 pstrcat(p, sp->path, ": ", strerror(errno), NULL));
1343 sp->wrote_errors = TRUE;
1344 return 1;
1345 }
1346
1347 } else {
1348 char *ptr;
1349
1350 /* If the given path contains a directory component, make sure that the
1351 * directory exists.
1352 */
1353 ptr = strrchr(sp->path, '/');
1354 if (ptr != NULL) {
1355 *ptr = '\0';
1356
1357 pr_fs_clear_cache2(sp->path);
1358 res = pr_fsio_stat(sp->path, &st);
1359 *ptr = '/';
1360
1361 if (res < 0) {
1362 write_confirm(p, channel_id, 1,
1363 pstrcat(p, sp->path, ": ", strerror(errno), NULL));
1364 sp->wrote_errors = TRUE;
1365 return 1;
1366 }
1367 }
1368 }
1369 }
1370
1371 /* Check for end-of-directory control messages under the following
1372 * conditions:
1373 *
1374 * 1. We can handle an end-of-directory marker, i.e. sp->parent_dir is
1375 * not null.
1376 * 2. We have not already received any file info messages for this path.
1377 * 3. We have not already received any data for this path.
1378 */
1379 if (sp->parent_dir != NULL &&
1380 sp->recvd_finfo == FALSE &&
1381 (sp->recvlen == 0 || sp->recvd_data)) {
1382 unsigned char *remain = NULL;
1383 uint32_t remainlen = 0;
1384
1385 res = recv_eod(p, channel_id, sp, data, datalen, &remain, &remainlen);
1386 if (res == 0) {
1387 return res;
1388 }
1389
1390 if (res == 1) {
1391 struct scp_path *parent_dir = NULL;
1392
1393 if (sp->parent_dir != NULL) {
1394 parent_dir = sp->parent_dir->parent_dir;
1395 }
1396
1397 if (parent_dir != NULL) {
1398 pr_trace_msg(trace_channel, 18,
1399 "received EOD, resetting path from '%s' to '%s'", sp->path,
1400 parent_dir->path);
1401 sp->path = parent_dir->path;
1402
1403 } else {
1404 if (sp->orig_path != NULL) {
1405 sp->path = pstrdup(scp_pool, sp->orig_path);
1406 }
1407
1408 pr_trace_msg(trace_channel, 18,
1409 "received EOD, no parent found for '%s'", sp->path);
1410 }
1411
1412 sp->parent_dir = parent_dir;
1413
1414 /* We return 1 here, and the caller will call reset_path() on the same
1415 * sp pointer. That's OK, since reset_path() does NOT change sp->path or
1416 * sp->parent_dir, which is what we are most concerned with here.
1417 */
1418 return 1;
1419 }
1420
1421 data = remain;
1422 datalen = remainlen;
1423 }
1424
1425 if ((scp_opts & SFTP_SCP_OPT_PRESERVE) &&
1426 !sp->recvd_timeinfo &&
1427 !sp->recvd_finfo) {
1428 unsigned char *remain = NULL;
1429 uint32_t remainlen = 0;
1430
1431 /* It possible that this is not a timeinfo message; we need to be
1432 * prepared for this. PuTTY, for example, when recursively uploading
1433 * a directory with the -p (preserve time) option enabled, does NOT
1434 * send the timeinfo message, whereas OpenSSH's scp(1) does.
1435 */
1436 res = recv_timeinfo(p, channel_id, sp, data, datalen, &remain, &remainlen);
1437 if (res < 0) {
1438 data = remain;
1439 datalen = remainlen;
1440
1441 } else {
1442 return res;
1443 }
1444 }
1445
1446 if (!sp->recvd_finfo) {
1447 return recv_finfo(p, channel_id, sp, data, datalen);
1448 }
1449
1450 if (!sp->recvd_data &&
1451 sp->recvlen != sp->filesz) {
1452 if (cmd == NULL) {
1453 cmd = scp_cmd_alloc(p, C_STOR, sp->best_path);
1454
1455 if (pr_table_add(cmd->notes, "mod_xfer.store-path",
1456 pstrdup(p, sp->best_path), 0) < 0) {
1457 if (errno != EEXIST) {
1458 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1459 "error adding 'mod_xfer.store-path for SCP upload: %s",
1460 strerror(errno));
1461 }
1462 }
1463 }
1464
1465 pr_throttle_init(cmd);
1466
1467 /* recv_data() indicates that it has received all of the data, including
1468 * the end-of-data marker, by returning 1. If that happens, we need
1469 * to continue one to the end-of-path processing.
1470 */
1471 res = recv_data(p, channel_id, sp, data, datalen);
1472 if (res != 1) {
1473 return res;
1474 }
1475 }
1476
1477 if (sp->wrote_errors == FALSE) {
1478 /* The uploaded file may be smaller than an existing file; call
1479 * pr_fsio_truncate() to ensure proper file size.
1480 */
1481 if (S_ISREG(sp->st_mode)) {
1482 pr_trace_msg(trace_channel, 9, "truncating file '%s' to %" PR_LU " bytes",
1483 sp->fh->fh_path, (pr_off_t) sp->filesz);
1484
1485 if (pr_fsio_ftruncate(sp->fh, sp->filesz) < 0) {
1486 int xerrno = errno;
1487
1488 pr_trace_msg(trace_channel, 2, "error truncating '%s' to %" PR_LU
1489 " bytes: %s", sp->best_path, (pr_off_t) sp->filesz, strerror(xerrno));
1490
1491 write_confirm(p, channel_id, 1,
1492 pstrcat(p, sp->filename, ": error truncating file: ",
1493 strerror(xerrno), NULL));
1494 sp->wrote_errors = TRUE;
1495 }
1496 }
1497 }
1498
1499 if (sp->wrote_errors == FALSE) {
1500 /* If the SFTPOption for ignoring perms for SCP uploads is set, then
1501 * skip the chmod on the upload file.
1502 */
1503 if (!(sftp_opts & SFTP_OPT_IGNORE_SCP_UPLOAD_PERMS)) {
1504 pr_trace_msg(trace_channel, 9, "setting perms %04o on file '%s'",
1505 (unsigned int) sp->perms, sp->fh->fh_path);
1506
1507 if (pr_fsio_fchmod(sp->fh, sp->perms) < 0) {
1508 int xerrno = errno;
1509
1510 pr_trace_msg(trace_channel, 2, "error setting mode %04o on '%s': %s",
1511 (unsigned int) sp->perms, sp->best_path, strerror(xerrno));
1512
1513 write_confirm(p, channel_id, 1,
1514 pstrcat(p, sp->filename, ": error setting mode: ", strerror(xerrno),
1515 NULL));
1516 sp->wrote_errors = TRUE;
1517 }
1518
1519 } else {
1520 pr_trace_msg(trace_channel, 7, "SFTPOption 'IgnoreSCPUploadPerms' "
1521 "configured, ignoring perms sent by client");
1522 }
1523 }
1524
1525 if (sp->fh) {
1526 curr_path = pstrdup(scp_pool, sp->fh->fh_path);
1527
1528 /* Set session.curr_cmd, for any FSIO callbacks that might be interested. */
1529 session.curr_cmd = C_STOR;
1530
1531 res = pr_fsio_close(sp->fh);
1532 if (res < 0) {
1533 int xerrno = errno;
1534
1535 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1536 "scp: error closing '%s': %s", sp->best_path, strerror(xerrno));
1537
1538 write_confirm(p, channel_id, 1,
1539 pstrcat(p, sp->filename, ": ", strerror(xerrno), NULL));
1540 sp->wrote_errors = TRUE;
1541 }
1542
1543 sp->fh = NULL;
1544 }
1545
1546 if (sp->hiddenstore == TRUE &&
1547 curr_path != NULL) {
1548 if (sp->wrote_errors == TRUE) {
1549 /* There was an error writing this HiddenStores file; be sure to clean
1550 * things up.
1551 */
1552 pr_trace_msg(trace_channel, 8, "deleting HiddenStores path '%s'",
1553 curr_path);
1554
1555 if (pr_fsio_unlink(curr_path) < 0) {
1556 if (errno != ENOENT) {
1557 pr_log_debug(DEBUG0, MOD_SFTP_VERSION
1558 ": error deleting HiddenStores file '%s': %s", curr_path,
1559 strerror(errno));
1560 }
1561 }
1562
1563 } else {
1564 /* This is a HiddenStores file, and needs to be renamed to the real
1565 * path (i.e. sp->best_path).
1566 */
1567 pr_trace_msg(trace_channel, 8,
1568 "renaming HiddenStores path '%s' to '%s'", curr_path, sp->best_path);
1569
1570 res = pr_fsio_rename(curr_path, sp->best_path);
1571 if (res < 0) {
1572 int xerrno = errno;
1573
1574 pr_log_pri(PR_LOG_WARNING, "Rename of %s to %s failed: %s",
1575 curr_path, sp->best_path, strerror(xerrno));
1576
1577 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1578 "renaming of HiddenStore path '%s' to '%s' failed: %s",
1579 curr_path, sp->best_path, strerror(xerrno));
1580
1581 if (pr_fsio_unlink(curr_path) < 0) {
1582 pr_trace_msg(trace_channel, 1,
1583 "error deleting HiddenStores file '%s': %s", curr_path,
1584 strerror(errno));
1585 }
1586 }
1587 }
1588 }
1589
1590 /* After receiving all the data and metadata, we need to make sure that
1591 * the requested times and mode/perms are enforced on the uploaded file.
1592 */
1593 if (sp->recvd_timeinfo) {
1594 pr_trace_msg(trace_channel, 9, "setting times on file '%s'", sp->filename);
1595
1596 /* If the SFTPOption for ignoring times for SCP uploads is set, then
1597 * skip the utimes on the upload file.
1598 */
1599 if (!(sftp_opts & SFTP_OPT_IGNORE_SCP_UPLOAD_TIMES)) {
1600 if (pr_fsio_utimes(sp->filename, sp->times) < 0) {
1601 int xerrno = errno;
1602
1603 pr_trace_msg(trace_channel, 2,
1604 "error setting atime %lu, mtime %lu on '%s': %s",
1605 (unsigned long) sp->times[0].tv_sec,
1606 (unsigned long) sp->times[1].tv_sec, sp->best_path, strerror(xerrno));
1607
1608 write_confirm(p, channel_id, 1,
1609 pstrcat(p, sp->filename, ": error setting times: ", strerror(xerrno),
1610 NULL));
1611 sp->wrote_errors = TRUE;
1612 }
1613
1614 } else {
1615 pr_trace_msg(trace_channel, 7, "SFTPOption 'IgnoreSCPUploadTimes' "
1616 "configured, ignoring times sent by client");
1617 }
1618 }
1619
1620 if (!sp->wrote_errors) {
1621 /* We only send this if there were no end-of-path handling errors. */
1622 write_confirm(p, channel_id, 0, NULL);
1623
1624 if (cmd == NULL) {
1625 cmd = scp_cmd_alloc(p, C_STOR, sp->best_path);
1626
1627 if (pr_table_add(cmd->notes, "mod_xfer.store-path",
1628 pstrdup(p, sp->best_path), 0) < 0) {
1629 if (errno != EEXIST) {
1630 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1631 "error adding 'mod_xfer.store-path: %s", strerror(errno));
1632 }
1633 }
1634 }
1635
1636 if (sp->file_existed) {
1637 if (pr_table_add(cmd->notes, "mod_xfer.file-modified",
1638 pstrdup(cmd->pool, "true"), 0) < 0) {
1639 if (errno != EEXIST) {
1640 pr_log_pri(PR_LOG_NOTICE,
1641 "notice: error adding 'mod_xfer.file-modified' note: %s",
1642 strerror(errno));
1643 }
1644 }
1645 }
1646
1647 session.xfer.path = sftp_misc_vroot_abs_path(session.xfer.p,
1648 session.xfer.path, FALSE);
1649 (void) pr_cmd_dispatch_phase(cmd, POST_CMD, 0);
1650 (void) pr_cmd_dispatch_phase(cmd, LOG_CMD, 0);
1651
1652 } else {
1653 if (cmd == NULL) {
1654 cmd = scp_cmd_alloc(p, C_STOR, sp->best_path);
1655
1656 if (pr_table_add(cmd->notes, "mod_xfer.store-path",
1657 pstrdup(p, sp->best_path), 0) < 0) {
1658 if (errno != EEXIST) {
1659 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1660 "error adding 'mod_xfer.store-path: %s", strerror(errno));
1661 }
1662 }
1663 }
1664
1665 if (sp->file_existed) {
1666 if (pr_table_add(cmd->notes, "mod_xfer.file-modified",
1667 pstrdup(cmd->pool, "true"), 0) < 0) {
1668 pr_log_pri(PR_LOG_NOTICE,
1669 "notice: error adding 'mod_xfer.file-modified' note: %s",
1670 strerror(errno));
1671 }
1672 }
1673
1674 (void) pr_cmd_dispatch_phase(cmd, POST_CMD_ERR, 0);
1675 (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0);
1676 }
1677
1678 return 1;
1679 }
1680
1681 /* Functions for sending files to the client. */
1682
send_timeinfo(pool * p,uint32_t channel_id,struct scp_path * sp,struct stat * st)1683 static int send_timeinfo(pool *p, uint32_t channel_id, struct scp_path *sp,
1684 struct stat *st) {
1685 int res;
1686 unsigned char ctrl_msg[64];
1687 size_t ctrl_msglen;
1688
1689 memset(ctrl_msg, '\0', sizeof(ctrl_msg));
1690
1691 /* The field of this message are:
1692 *
1693 * T (time info)
1694 * number (mtime, in secs)
1695 * 0 (future proof field for sending mtime usecs)
1696 * number (atime, in secs)
1697 * 0 (future proof field for sending atime usecs)
1698 */
1699
1700 pr_snprintf((char *) ctrl_msg, sizeof(ctrl_msg), "T%lu 0 %lu 0",
1701 (unsigned long) (st->st_mtime > 0 ? st->st_mtime : 0),
1702 (unsigned long) (st->st_atime > 0 ? st->st_atime : 0));
1703
1704 pr_trace_msg(trace_channel, 3, "sending '%s' T (timestamps): %s", sp->path,
1705 ctrl_msg);
1706
1707 ctrl_msg[strlen((char *) ctrl_msg)] = '\n';
1708 ctrl_msglen = strlen((char *) ctrl_msg);
1709
1710 need_confirm = TRUE;
1711
1712 res = sftp_channel_write_data(p, channel_id, ctrl_msg, ctrl_msglen);
1713 if (res < 0)
1714 return -1;
1715
1716 sp->sent_timeinfo = TRUE;
1717 return 0;
1718 }
1719
send_dirinfo(pool * p,uint32_t channel_id,struct scp_path * sp,struct stat * st)1720 static int send_dirinfo(pool *p, uint32_t channel_id, struct scp_path *sp,
1721 struct stat *st) {
1722 int res;
1723 unsigned char ctrl_msg[1536];
1724 size_t ctrl_msglen;
1725 char *tmp;
1726
1727 /* We need to find the last path component, if any; no path separators
1728 * in the control messages.
1729 */
1730 tmp = strrchr(sp->path, '/');
1731 if (tmp == NULL) {
1732 tmp = sp->path;
1733
1734 } else {
1735 tmp++;
1736 }
1737
1738 memset(ctrl_msg, '\0', sizeof(ctrl_msg));
1739 pr_snprintf((char *) ctrl_msg, sizeof(ctrl_msg), "D%04o 0 %.1024s",
1740 (unsigned int) (st->st_mode & SFTP_SCP_ST_MODE_MASK), tmp);
1741
1742 pr_trace_msg(trace_channel, 3, "sending '%s' D (directory): %s", sp->path,
1743 ctrl_msg);
1744
1745 ctrl_msg[strlen((char *) ctrl_msg)] = '\n';
1746 ctrl_msglen = strlen((char *) ctrl_msg);
1747
1748 need_confirm = TRUE;
1749
1750 res = sftp_channel_write_data(p, channel_id, ctrl_msg, ctrl_msglen);
1751 if (res < 0)
1752 return -1;
1753
1754 sp->sent_dirinfo = TRUE;
1755 return 0;
1756 }
1757
send_finfo(pool * p,uint32_t channel_id,struct scp_path * sp,struct stat * st)1758 static int send_finfo(pool *p, uint32_t channel_id, struct scp_path *sp,
1759 struct stat *st) {
1760 int res;
1761 unsigned char ctrl_msg[1536];
1762 size_t ctrl_msglen;
1763 char *tmp;
1764
1765 /* We need to find the last path component, if any; no path separators
1766 * in the control messages.
1767 */
1768 tmp = strrchr(sp->path, '/');
1769 if (tmp == NULL) {
1770 tmp = sp->path;
1771
1772 } else {
1773 tmp++;
1774 }
1775
1776 memset(ctrl_msg, '\0', sizeof(ctrl_msg));
1777 pr_snprintf((char *) ctrl_msg, sizeof(ctrl_msg), "C%04o %" PR_LU " %.1024s",
1778 (unsigned int) (st->st_mode & SFTP_SCP_ST_MODE_MASK),
1779 (pr_off_t) st->st_size, tmp);
1780
1781 pr_trace_msg(trace_channel, 3, "sending '%s' C (info): %s", sp->path,
1782 ctrl_msg);
1783
1784 ctrl_msg[strlen((char *) ctrl_msg)] = '\n';
1785 ctrl_msglen = strlen((char *) ctrl_msg);
1786
1787 need_confirm = TRUE;
1788
1789 res = sftp_channel_write_data(p, channel_id, ctrl_msg, ctrl_msglen);
1790 if (res < 0)
1791 return -1;
1792
1793 sp->sent_finfo = TRUE;
1794 return 0;
1795 }
1796
send_data(pool * p,uint32_t channel_id,struct scp_path * sp,struct stat * st)1797 static int send_data(pool *p, uint32_t channel_id, struct scp_path *sp,
1798 struct stat *st) {
1799 unsigned char *chunk;
1800 size_t chunksz;
1801
1802 /* Include space for one more character, i.e. for the terminating NUL
1803 * character that indicates the last chunk of the file.
1804 */
1805 chunksz = pr_config_get_server_xfer_bufsz(PR_NETIO_IO_WR) + 1;
1806 chunk = palloc(p, chunksz);
1807
1808 /* Keep sending chunks until we have sent the entire file, or until the
1809 * channel window closes.
1810 */
1811 while (TRUE) {
1812 int res, chunklen;
1813
1814 pr_signals_handle();
1815
1816 if (S_ISREG(st->st_mode)) {
1817 /* Seek to where we last left off with this file. */
1818 if (pr_fsio_lseek(sp->fh, sp->sentlen, SEEK_SET) < 0) {
1819 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1820 "error seeking to offset %" PR_LU " in '%s': %s",
1821 (pr_off_t) sp->sentlen, sp->path, strerror(errno));
1822 return 1;
1823 }
1824
1825 pr_trace_msg(trace_channel, 15, "at %.2f%% (%" PR_LU " of %" PR_LU
1826 " bytes) of '%s'",
1827 (float) (((float) sp->sentlen / (float) st->st_size) * 100),
1828 (pr_off_t) sp->sentlen, (pr_off_t) st->st_size, sp->path);
1829 }
1830
1831 chunklen = pr_fsio_read(sp->fh, (char *) chunk, chunksz - 1);
1832 if (chunklen < 0) {
1833 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1834 "error reading from '%s': %s", sp->path, strerror(errno));
1835 return 1;
1836 }
1837
1838 session.xfer.total_bytes += chunklen;
1839 session.total_bytes += chunklen;
1840
1841 /* If this was the last chunk of the file, write one more space
1842 * character.
1843 */
1844 if (sp->sentlen + chunklen == st->st_size) {
1845 chunk[chunklen++] = '\0';
1846 need_confirm = TRUE;
1847
1848 pr_throttle_pause(sp->sentlen, TRUE);
1849
1850 } else {
1851 pr_throttle_pause(sp->sentlen, FALSE);
1852 }
1853
1854 pr_trace_msg(trace_channel, 3, "sending '%s' data (%lu bytes)", sp->path,
1855 need_confirm ? (unsigned long) (chunklen - 1) : (unsigned long) chunklen);
1856
1857 res = sftp_channel_write_data(p, channel_id, chunk, chunklen);
1858 if (res < 0) {
1859 return 1;
1860 }
1861
1862 /* If our channel window has closed, try handling some packets; hopefully
1863 * some of them are WINDOW_ADJUST messages.
1864 *
1865 * XXX I wonder if this can be more efficient by waiting until we
1866 * have a certain amount of data buffered up (N * transfer data size?)
1867 * AND the window is closed before handling incoming packets? That way
1868 * we can handle more WINDOW_ADJUSTS at a whack, at the cost of buffering
1869 * more data in memory. Hmm.
1870 *
1871 * We also need to watch for when rekeying is occurring; handle packets
1872 * until that state clears.
1873 */
1874 while ((sftp_sess_state & SFTP_SESS_STATE_REKEYING) ||
1875 sftp_channel_get_windowsz(channel_id) == 0) {
1876 pr_signals_handle();
1877
1878 if (sftp_ssh2_packet_handle() < 0) {
1879 return 1;
1880 }
1881 }
1882
1883 sp->sentlen += chunklen;
1884 if (sp->sentlen >= st->st_size) {
1885 sp->sent_data = TRUE;
1886 break;
1887 }
1888 }
1889
1890 return 0;
1891 }
1892
send_dir(pool * p,uint32_t channel_id,struct scp_path * sp,struct stat * st)1893 static int send_dir(pool *p, uint32_t channel_id, struct scp_path *sp,
1894 struct stat *st) {
1895 struct dirent *dent;
1896 struct stat link_st;
1897 int res = 0;
1898
1899 if (sp->dirh == NULL) {
1900 sp->dirh = pr_fsio_opendir(sp->path);
1901 if (sp->dirh == NULL) {
1902 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1903 "error reading directory '%s': %s", sp->path, strerror(errno));
1904 return -1;
1905 }
1906
1907 /* If we're a directory, send a D control message. */
1908 if (!sp->sent_dirinfo) {
1909 return send_dirinfo(p, channel_id, sp, st);
1910 }
1911 }
1912
1913 /* If we were already in the middle of sending a path from this
1914 * directory, continue with it. Otherwise, read the next dent from the
1915 * directory handle.
1916 */
1917
1918 if (sp->dir_spi) {
1919 res = send_path(p, channel_id, sp->dir_spi);
1920 if (res <= 0) {
1921 return res;
1922 }
1923
1924 /* Clear out any transfer-specific data. */
1925 if (session.xfer.p) {
1926 destroy_pool(session.xfer.p);
1927 }
1928 memset(&session.xfer, 0, sizeof(session.xfer));
1929
1930 sp->dir_spi = NULL;
1931 return 0;
1932 }
1933
1934 while ((dent = pr_fsio_readdir(sp->dirh)) != NULL) {
1935 struct scp_path *spi;
1936 size_t pathlen;
1937
1938 pr_signals_handle();
1939
1940 /* Skip "." and "..". */
1941 if (strncmp(dent->d_name, ".", 2) == 0 ||
1942 strncmp(dent->d_name, "..", 3) == 0) {
1943 continue;
1944 }
1945
1946 /* Add these to the list of paths that need to be sent. */
1947 spi = pcalloc(scp_pool, sizeof(struct scp_path));
1948 spi->path = pdircat(scp_pool, sp->path, dent->d_name, NULL);
1949 pathlen = strlen(spi->path);
1950
1951 /* Trim any trailing path separators. It's important. */
1952 while (pathlen > 1 &&
1953 spi->path[pathlen-1] == '/') {
1954 pr_signals_handle();
1955 spi->path[pathlen-1] = '\0';
1956 pathlen--;
1957 }
1958
1959 spi->best_path = dir_canonical_vpath(scp_pool, spi->path);
1960
1961 pr_fs_clear_cache2(spi->best_path);
1962 if (pr_fsio_lstat(spi->best_path, &link_st) == 0) {
1963 if (S_ISLNK(link_st.st_mode)) {
1964 char link_path[PR_TUNABLE_PATH_MAX];
1965 int len;
1966
1967 memset(link_path, '\0', sizeof(link_path));
1968 len = dir_readlink(scp_pool, spi->best_path, link_path,
1969 sizeof(link_path)-1, PR_DIR_READLINK_FL_HANDLE_REL_PATH);
1970 if (len > 0) {
1971 link_path[len] = '\0';
1972 spi->best_path = pstrdup(scp_pool, link_path);
1973 }
1974 }
1975 }
1976
1977 if (pathlen > 0) {
1978 sp->dir_spi = spi;
1979
1980 res = send_path(p, channel_id, spi);
1981 if (res == 1) {
1982 /* Clear out any transfer-specific data. */
1983 if (session.xfer.p) {
1984 destroy_pool(session.xfer.p);
1985 }
1986
1987 memset(&session.xfer, 0, sizeof(session.xfer));
1988 }
1989
1990 return res;
1991 }
1992 }
1993
1994 if (sp->dirh) {
1995 pr_fsio_closedir(sp->dirh);
1996 sp->dirh = NULL;
1997
1998 /* Send end-of-directory control message */
1999
2000 need_confirm = TRUE;
2001 res = sftp_channel_write_data(p, channel_id, (unsigned char *) "E\n", 2);
2002 if (res < 0) {
2003 return res;
2004 }
2005 }
2006
2007 return 1;
2008 }
2009
2010 /* Return 1 when the we should skip to the next path in the list, either
2011 * because we have sent all the data for this path, or because we can
2012 * never send it (due to some error).
2013 */
send_path(pool * p,uint32_t channel_id,struct scp_path * sp)2014 static int send_path(pool *p, uint32_t channel_id, struct scp_path *sp) {
2015 int res, is_file = FALSE;
2016 struct stat st;
2017 cmd_rec *cmd = NULL;
2018
2019 if (sp->sent_data) {
2020 /* Already sent everything for this path. */
2021 return 1;
2022 }
2023
2024 pr_scoreboard_entry_update(session.pid,
2025 PR_SCORE_CMD, "%s", "scp download", NULL, NULL);
2026 pr_scoreboard_entry_update(session.pid,
2027 PR_SCORE_CMD_ARG, "%s", sp->path, NULL, NULL);
2028
2029 cmd = scp_cmd_alloc(p, C_RETR, sp->path);
2030 session.curr_cmd_rec = cmd;
2031
2032 /* First, dispatch the command to the PRE_CMD handlers. They might,
2033 * for example, change the path.
2034 */
2035 if (sp->fh == NULL) {
2036 /* Note, however, that SCP also has to deal with directories, which will
2037 * be blocked by the PRE_CMD RETR handler in mod_xfer.
2038 */
2039
2040 if (pr_cmd_dispatch_phase(cmd, PRE_CMD, 0) < 0) {
2041 int xerrno = errno;
2042
2043 if (xerrno != EISDIR) {
2044 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2045 "scp download of '%s' blocked by '%s' handler", sp->path,
2046 (char *) cmd->argv[0]);
2047
2048 (void) pr_cmd_dispatch_phase(cmd, POST_CMD_ERR, 0);
2049 (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0);
2050
2051 destroy_pool(cmd->pool);
2052 session.curr_cmd_rec = NULL;
2053
2054 write_confirm(p, channel_id, 1,
2055 pstrcat(p, sp->path, ": ", strerror(xerrno), NULL));
2056 sp->wrote_errors = TRUE;
2057 return 1;
2058 }
2059 }
2060
2061 if (strcmp(sp->path, cmd->arg) != 0) {
2062 sp->path = pstrdup(scp_session->pool, cmd->arg);
2063 }
2064 }
2065
2066 if (pr_table_add(cmd->notes, "mod_xfer.retr-path",
2067 pstrdup(cmd->pool, sp->path), 0) < 0) {
2068 if (errno != EEXIST) {
2069 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2070 "error adding 'mod_xfer.retr-path' for SCP download: %s",
2071 strerror(errno));
2072 }
2073 }
2074
2075 pr_fs_clear_cache2(sp->path);
2076 if (pr_fsio_lstat(sp->path, &st) == 0) {
2077 if (S_ISLNK(st.st_mode)) {
2078 char link_path[PR_TUNABLE_PATH_MAX];
2079 int len;
2080
2081 memset(link_path, '\0', sizeof(link_path));
2082 len = dir_readlink(scp_pool, sp->path, link_path, sizeof(link_path)-1,
2083 PR_DIR_READLINK_FL_HANDLE_REL_PATH);
2084 if (len > 0) {
2085 link_path[len] = '\0';
2086 sp->path = pstrdup(scp_pool, link_path);
2087 }
2088 }
2089 }
2090
2091 if (pr_fsio_stat(sp->path, &st) < 0) {
2092 int xerrno = errno;
2093
2094 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2095 "error stat'ing '%s': %s", sp->path, strerror(xerrno));
2096
2097 if (sp->fh != NULL) {
2098 /* Set session.curr_cmd, for any FSIO callbacks that might be
2099 * interested.
2100 */
2101 session.curr_cmd = C_RETR;
2102
2103 pr_fsio_close(sp->fh);
2104 sp->fh = NULL;
2105
2106 (void) pr_cmd_dispatch_phase(cmd, POST_CMD_ERR, 0);
2107 (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0);
2108 }
2109
2110 destroy_pool(cmd->pool);
2111 session.curr_cmd_rec = NULL;
2112
2113 write_confirm(p, channel_id, 1,
2114 pstrcat(p, sp->path, ": ", strerror(xerrno), NULL));
2115 sp->wrote_errors = TRUE;
2116 return 1;
2117 }
2118
2119 /* The path in question might be a file, a directory, or a FIFO. The FIFO
2120 * case requires some special handling, modulo any IgnoreFIFOs SFTPOption
2121 * that might be in effect.
2122 */
2123 if (S_ISREG(st.st_mode)) {
2124 is_file = TRUE;
2125
2126 } else {
2127 #ifdef S_ISFIFO
2128 if (S_ISFIFO(st.st_mode)) {
2129 is_file = TRUE;
2130
2131 if (sftp_opts & SFTP_OPT_IGNORE_FIFOS) {
2132 is_file = FALSE;
2133 }
2134 }
2135 #endif /* S_ISFIFO */
2136 }
2137
2138 if (is_file == FALSE) {
2139 if (S_ISDIR(st.st_mode)) {
2140 if (scp_opts & SFTP_SCP_OPT_RECURSE) {
2141 res = send_dir(p, channel_id, sp, &st);
2142 destroy_pool(cmd->pool);
2143 session.curr_cmd_rec = NULL;
2144 return res;
2145 }
2146
2147 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2148 "cannot send directory '%s' (no -r option)", sp->path);
2149
2150 (void) pr_cmd_dispatch_phase(cmd, POST_CMD_ERR, 0);
2151 (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0);
2152
2153 destroy_pool(cmd->pool);
2154 session.curr_cmd_rec = NULL;
2155
2156 write_confirm(p, channel_id, 1,
2157 pstrcat(p, sp->path, ": ", strerror(EPERM), NULL));
2158 sp->wrote_errors = TRUE;
2159 return 1;
2160 }
2161
2162 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2163 "cannot send '%s': Not a regular file", sp->path);
2164
2165 (void) pr_cmd_dispatch_phase(cmd, POST_CMD_ERR, 0);
2166 (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0);
2167
2168 destroy_pool(cmd->pool);
2169 session.curr_cmd_rec = NULL;
2170
2171 write_confirm(p, channel_id, 1,
2172 pstrcat(p, sp->path, ": ", strerror(EPERM), NULL));
2173 sp->wrote_errors = TRUE;
2174 return 1;
2175 }
2176
2177 if (sp->fh == NULL) {
2178 sp->best_path = dir_canonical_vpath(scp_pool, sp->path);
2179
2180 if (!dir_check(p, cmd, G_READ, sp->best_path, NULL)) {
2181 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2182 "scp download of '%s' blocked by <Limit> configuration", sp->best_path);
2183
2184 (void) pr_cmd_dispatch_phase(cmd, POST_CMD_ERR, 0);
2185 (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0);
2186
2187 destroy_pool(cmd->pool);
2188 session.curr_cmd_rec = NULL;
2189
2190 write_confirm(p, channel_id, 1,
2191 pstrcat(p, sp->path, ": ", strerror(EACCES), NULL));
2192 sp->wrote_errors = TRUE;
2193 return 1;
2194 }
2195
2196 sp->fh = pr_fsio_open(sp->best_path, O_RDONLY|O_NONBLOCK);
2197 if (sp->fh == NULL) {
2198 int xerrno = errno;
2199
2200 (void) pr_trace_msg("fileperms", 1, "%s, user '%s' (UID %s, GID %s): "
2201 "error opening '%s': %s", "scp download", session.user,
2202 pr_uid2str(cmd->tmp_pool, session.uid), pr_gid2str(NULL, session.gid),
2203 sp->best_path, strerror(xerrno));
2204
2205 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2206 "error reading '%s': %s", sp->best_path, strerror(xerrno));
2207
2208 (void) pr_cmd_dispatch_phase(cmd, POST_CMD_ERR, 0);
2209 (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0);
2210
2211 destroy_pool(cmd->pool);
2212 session.curr_cmd_rec = NULL;
2213
2214 write_confirm(p, channel_id, 1,
2215 pstrcat(p, sp->path, ": ", strerror(xerrno), NULL));
2216 sp->wrote_errors = TRUE;
2217
2218 errno = xerrno;
2219 return 1;
2220
2221 } else {
2222 off_t curr_offset;
2223
2224 /* Stash the offset at which we're reading from this file. */
2225 curr_offset = pr_fsio_lseek(sp->fh, (off_t) 0, SEEK_CUR);
2226 if (curr_offset != (off_t) -1) {
2227 off_t *file_offset;
2228
2229 file_offset = palloc(cmd->pool, sizeof(off_t));
2230 *file_offset = (off_t) curr_offset;
2231 (void) pr_table_add(cmd->notes, "mod_xfer.file-offset", file_offset,
2232 sizeof(off_t));
2233 }
2234 }
2235 }
2236
2237 if (pr_fsio_set_block(sp->fh) < 0) {
2238 pr_trace_msg(trace_channel, 3,
2239 "error setting fd %d (file '%s') as blocking: %s", sp->fh->fh_fd,
2240 sp->fh->fh_path, strerror(errno));
2241 }
2242
2243 if (session.xfer.p == NULL) {
2244 session.xfer.p = pr_pool_create_sz(scp_pool, 64);
2245 session.xfer.path = pstrdup(session.xfer.p, sp->best_path);
2246 memset(&session.xfer.start_time, 0, sizeof(session.xfer.start_time));
2247 gettimeofday(&session.xfer.start_time, NULL);
2248 session.xfer.direction = PR_NETIO_IO_WR;
2249 }
2250
2251 /* If the PRESERVE flag is set, then we need to send a T control message
2252 * that includes the file timestamps.
2253 */
2254 if ((scp_opts & SFTP_SCP_OPT_PRESERVE) &&
2255 !sp->sent_timeinfo) {
2256 res = send_timeinfo(p, channel_id, sp, &st);
2257 if (res == 1) {
2258 (void) pr_cmd_dispatch_phase(cmd, POST_CMD_ERR, 0);
2259 (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0);
2260 }
2261
2262 destroy_pool(cmd->pool);
2263 session.curr_cmd_rec = NULL;
2264 return res;
2265 }
2266
2267 if (!sp->sent_finfo) {
2268 res = send_finfo(p, channel_id, sp, &st);
2269 if (res == 1) {
2270 (void) pr_cmd_dispatch_phase(cmd, POST_CMD_ERR, 0);
2271 (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0);
2272 }
2273
2274 destroy_pool(cmd->pool);
2275 session.curr_cmd_rec = NULL;
2276 return res;
2277 }
2278
2279 if (!sp->sent_data) {
2280 pr_throttle_init(cmd);
2281
2282 res = send_data(p, channel_id, sp, &st);
2283 if (res == 1) {
2284 (void) pr_cmd_dispatch_phase(cmd, POST_CMD_ERR, 0);
2285 (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0);
2286
2287 destroy_pool(cmd->pool);
2288 session.curr_cmd_rec = NULL;
2289
2290 return res;
2291 }
2292 }
2293
2294 pr_fsio_close(sp->fh);
2295 sp->fh = NULL;
2296
2297 session.xfer.path = sftp_misc_vroot_abs_path(session.xfer.p,
2298 session.xfer.path, FALSE);
2299 (void) pr_cmd_dispatch_phase(cmd, POST_CMD, 0);
2300 (void) pr_cmd_dispatch_phase(cmd, LOG_CMD, 0);
2301
2302 destroy_pool(cmd->pool);
2303 session.curr_cmd_rec = NULL;
2304
2305 return 1;
2306 }
2307
2308 /* Main entry point */
sftp_scp_handle_packet(pool * p,void * ssh2,uint32_t channel_id,unsigned char * data,uint32_t datalen)2309 int sftp_scp_handle_packet(pool *p, void *ssh2, uint32_t channel_id,
2310 unsigned char *data, uint32_t datalen) {
2311 int res = -1;
2312 struct ssh2_packet *pkt;
2313
2314 scp_session = scp_get_session(channel_id);
2315 if (scp_session == NULL) {
2316 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2317 "no existing SCP session for channel ID %lu, rejecting request",
2318 (unsigned long) channel_id);
2319 return -1;
2320 }
2321
2322 pkt = ssh2;
2323
2324 /* This is a bit of a hack, for playing along better with mod_vroot,
2325 * which pays attention to the session.curr_phase value.
2326 *
2327 * I'm not sure which is better here, PRE_CMD vs CMD. Let's go with
2328 * PRE_CMD for now.
2329 */
2330 session.curr_phase = PRE_CMD;
2331
2332 if (pr_data_get_timeout(PR_DATA_TIMEOUT_NO_TRANSFER) > 0) {
2333 pr_timer_reset(PR_TIMER_NOXFER, ANY_MODULE);
2334 }
2335
2336 if (pr_data_get_timeout(PR_DATA_TIMEOUT_STALLED) > 0) {
2337 pr_timer_reset(PR_TIMER_STALLED, ANY_MODULE);
2338 }
2339
2340 pr_response_set_pool(pkt->pool);
2341
2342 if (need_confirm) {
2343 /* Handle the confirmation/response from the client. */
2344 if (read_confirm(pkt, &data, &datalen) < 0) {
2345 return 1;
2346 }
2347 }
2348
2349 if (scp_opts & SFTP_SCP_OPT_ISSRC) {
2350 struct scp_path **paths;
2351
2352 pr_proctitle_set("%s - %s: scp download", session.user,
2353 session.proc_prefix);
2354
2355 if (scp_session->path_idx == scp_session->paths->nelts) {
2356 /* Done sending our paths; need confirmation that the client received
2357 * all of them.
2358 */
2359 return 1;
2360 }
2361
2362 paths = scp_session->paths->elts;
2363
2364 if (scp_session->path_idx < scp_session->paths->nelts) {
2365 pr_signals_handle();
2366
2367 res = send_path(pkt->pool, channel_id, paths[scp_session->path_idx]);
2368 if (res < 0) {
2369 return -1;
2370 }
2371
2372 if (res == 1) {
2373 /* If send_path() returns 1, it means we've finished that path,
2374 * and are ready for another.
2375 */
2376 scp_session->path_idx++;
2377
2378 /* Clear out any transfer-specific data. */
2379 if (session.xfer.p) {
2380 destroy_pool(session.xfer.p);
2381 }
2382 memset(&session.xfer, 0, sizeof(session.xfer));
2383
2384 /* Make sure to clear the response lists of any cruft from previous
2385 * requests.
2386 */
2387 pr_response_clear(&resp_list);
2388 pr_response_clear(&resp_err_list);
2389 }
2390 }
2391
2392 /* We would normally return 1 here, to indicate that we are done with
2393 * the transfer. However, doing so indicates to the channel-handling
2394 * code that the channel is done, and should be closed.
2395 *
2396 * In the case of scp, though, we want the client to close the connection,
2397 * in order ensure that it has received all of the data (see Bug#3544).
2398 *
2399 * If we haven't sent data, but instead have sent an error, then we DO
2400 * want to return 1 here, since it will be us, not the client, which needs
2401 * to close the connection.
2402 */
2403 if (res == 1) {
2404 if (paths[scp_session->path_idx-1]->wrote_errors == TRUE) {
2405 return 1;
2406 }
2407 }
2408
2409 return 0;
2410
2411 } else if (scp_opts & SFTP_SCP_OPT_ISDST) {
2412 struct scp_path **paths;
2413
2414 pr_proctitle_set("%s - %s: scp upload", session.user,
2415 session.proc_prefix);
2416
2417 paths = scp_session->paths->elts;
2418
2419 if (session.xfer.p == NULL) {
2420 session.xfer.p = pr_pool_create_sz(scp_pool, 64);
2421 session.xfer.path = pstrdup(session.xfer.p,
2422 paths[scp_session->path_idx]->path);
2423 memset(&session.xfer.start_time, 0, sizeof(session.xfer.start_time));
2424 gettimeofday(&session.xfer.start_time, NULL);
2425 session.xfer.direction = PR_NETIO_IO_RD;
2426 }
2427
2428 res = recv_path(pkt->pool, channel_id, paths[scp_session->path_idx], data,
2429 datalen);
2430 if (res < 0) {
2431 return -1;
2432 }
2433
2434 if (res == 1) {
2435 /* Clear out any transfer-specific data. */
2436 if (session.xfer.p) {
2437 destroy_pool(session.xfer.p);
2438 }
2439 memset(&session.xfer, 0, sizeof(session.xfer));
2440
2441 /* Make sure to clear the response lists of any cruft from previous
2442 * requests.
2443 */
2444 pr_response_clear(&resp_list);
2445 pr_response_clear(&resp_err_list);
2446
2447 /* Note: we don't increment path_idx here because when we're receiving
2448 * files (i.e. it's an SCP upload), we either receive a single file,
2449 * or a single (recursive) directory. Therefore, there are not
2450 * multiple struct scp_path elements in the scp_session->paths array,
2451 * just one.
2452 */
2453 reset_path(paths[scp_session->path_idx]);
2454 }
2455 }
2456
2457 return 0;
2458 }
2459
sftp_scp_set_params(pool * p,uint32_t channel_id,array_header * req)2460 int sftp_scp_set_params(pool *p, uint32_t channel_id, array_header *req) {
2461 register unsigned int i;
2462 int optc, use_glob = TRUE;
2463 char **reqargv;
2464 const char *opts = "dfprtv";
2465 config_rec *c;
2466 struct scp_paths *paths;
2467
2468 if (!(sftp_services & SFTP_SERVICE_FL_SCP)) {
2469 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2470 "%s", "'scp' exec request denied by Protocols config");
2471 errno = EPERM;
2472 return -1;
2473 }
2474
2475 /* Possible options are:
2476 *
2477 * -d (target should be a directory)
2478 * -f (copying data from the server)
2479 * -p (preserve times, mode using ctrl messages)
2480 * -r (recursive)
2481 * -t (copying data to the server)
2482 * -v (verbose)
2483 */
2484
2485 pr_getopt_reset();
2486
2487 reqargv = (char **) req->elts;
2488 for (i = 0; i < req->nelts; i++) {
2489 if (reqargv[i]) {
2490 pr_trace_msg(trace_channel, 5, "reqargv[%u] = '%s'", i, reqargv[i]);
2491 }
2492 }
2493
2494 c = find_config(main_server->conf, CONF_PARAM, "UseGlobbing", FALSE);
2495 if (c) {
2496 use_glob = *((unsigned char *) c->argv[0]);
2497 }
2498
2499 need_confirm = FALSE;
2500 scp_pool = make_sub_pool(sftp_pool);
2501 pr_pool_tag(scp_pool, "SSH2 SCP Pool");
2502
2503 while ((optc = getopt(req->nelts-1, reqargv, opts)) != -1) {
2504 switch (optc) {
2505 case 'd':
2506 scp_opts |= SFTP_SCP_OPT_DIR;
2507 break;
2508
2509 case 'f':
2510 scp_opts |= SFTP_SCP_OPT_ISSRC;
2511 need_confirm = TRUE;
2512 break;
2513
2514 case 'p':
2515 scp_opts |= SFTP_SCP_OPT_PRESERVE;
2516 break;
2517
2518 case 'r':
2519 scp_opts |= SFTP_SCP_OPT_RECURSE;
2520 break;
2521
2522 case 't':
2523 scp_opts |= SFTP_SCP_OPT_ISDST;
2524 write_confirm(p, channel_id, 0, NULL);
2525 break;
2526
2527 case 'v':
2528 scp_opts |= SFTP_SCP_OPT_VERBOSE;
2529 break;
2530 }
2531 }
2532
2533 /* If we don't have paths, then it's an error. */
2534 if (reqargv[optind] == NULL) {
2535 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2536 "'scp' request provided no paths, ignoring");
2537 errno = EINVAL;
2538 return -1;
2539 }
2540
2541 paths = scp_new_paths(channel_id);
2542 if (paths == NULL) {
2543 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2544 "unable to handle paths for 'scp' request: %s", strerror(errno));
2545 return -1;
2546 }
2547
2548 /* Make a copy of the remaining paths, for later handling. */
2549 paths->paths = make_array(paths->pool, 1, sizeof(struct scp_path *));
2550 paths->path_idx = 0;
2551
2552 for (i = optind; i < req->nelts; i++) {
2553 pr_signals_handle();
2554
2555 if (reqargv[i]) {
2556 struct scp_path *sp;
2557 size_t pathlen;
2558 char *glob_path;
2559
2560 if (use_glob &&
2561 (scp_opts & SFTP_SCP_OPT_ISSRC) &&
2562 strpbrk(reqargv[i], "{[*?") != NULL) {
2563 int res, xerrno;
2564 glob_t gl;
2565
2566 /* Whee, glob characters. Need to expand the pattern to the
2567 * list of matching files, just as the shell would do.
2568 */
2569
2570 memset(&gl, 0, sizeof(gl));
2571
2572 glob_path = pstrdup(paths->pool, reqargv[i]);
2573 pathlen = strlen(glob_path);
2574
2575 /* Remove any enclosing shell quotations, e.g. single and double
2576 * quotation marks. Some SCP clients (i.e. newer libssh2) will
2577 * quote the paths, assuming that the handling server (us) uses
2578 * a shell to handle the command. Sigh.
2579 */
2580 if ((glob_path[0] == '\'' &&
2581 glob_path[pathlen-1] == '\'') ||
2582 (glob_path[0] == '"' &&
2583 glob_path[pathlen-1] == '"')) {
2584 glob_path[pathlen-1] = '\0';
2585 glob_path = (glob_path + 1);
2586 }
2587
2588 res = pr_fs_glob(glob_path, GLOB_NOSORT|GLOB_BRACE, NULL, &gl);
2589 switch (res) {
2590 case 0: {
2591 register unsigned int j;
2592
2593 for (j = 0; j < gl.gl_pathc; j++) {
2594 pr_signals_handle();
2595
2596 sp = pcalloc(paths->pool, sizeof(struct scp_path));
2597 sp->path = pstrdup(paths->pool, gl.gl_pathv[j]);
2598 pathlen = strlen(sp->path);
2599
2600 /* Trim any trailing path separators. It's important. */
2601 while (pathlen > 1 &&
2602 sp->path[pathlen-1] == '/') {
2603 pr_signals_handle();
2604 sp->path[--pathlen] = '\0';
2605 }
2606
2607 sp->orig_path = pstrdup(paths->pool, sp->path);
2608
2609 if (pathlen > 0) {
2610 *((struct scp_path **) push_array(paths->paths)) = sp;
2611 }
2612 }
2613
2614 break;
2615 }
2616
2617 case GLOB_NOSPACE:
2618 xerrno = errno;
2619 pr_trace_msg(trace_channel, 1, "error globbing '%s': Not "
2620 "enough memory (%s)", reqargv[i], strerror(xerrno));
2621 write_confirm(p, channel_id, 1, pstrcat(p, reqargv[i], ": ",
2622 strerror(xerrno), NULL));
2623 errno = xerrno;
2624 return 0;
2625
2626 case GLOB_NOMATCH:
2627 xerrno = ENOENT;
2628 pr_trace_msg(trace_channel, 1, "error globbing '%s': No "
2629 "matches found (%s)", reqargv[i], strerror(xerrno));
2630 write_confirm(p, channel_id, 1, pstrcat(p, reqargv[i], ": ",
2631 strerror(xerrno), NULL));
2632 errno = xerrno;
2633 return 0;
2634 }
2635
2636 pr_fs_globfree(&gl);
2637
2638 } else {
2639 sp = pcalloc(paths->pool, sizeof(struct scp_path));
2640 sp->path = pstrdup(paths->pool, reqargv[i]);
2641 pathlen = strlen(sp->path);
2642
2643 /* Remove any enclosing shell quotations, e.g. single and double
2644 * quotation marks. Some SCP clients (i.e. newer libssh2) will
2645 * quote the paths, assuming that the handling server (us) uses
2646 * a shell to handle the command. Sigh.
2647 */
2648 if ((sp->path[0] == '\'' &&
2649 sp->path[pathlen-1] == '\'') ||
2650 (sp->path[0] == '"' &&
2651 sp->path[pathlen-1] == '"')) {
2652 sp->path[pathlen-1] = '\0';
2653 sp->path = (sp->path + 1);
2654 pathlen -= 2;
2655 }
2656
2657 /* Trim any trailing path separators. It's important. */
2658 while (pathlen > 1 &&
2659 sp->path[pathlen-1] == '/') {
2660 pr_signals_handle();
2661 sp->path[--pathlen] = '\0';
2662 }
2663
2664 sp->orig_path = pstrdup(paths->pool, sp->path);
2665
2666 if (pathlen > 0) {
2667 *((struct scp_path **) push_array(paths->paths)) = sp;
2668 }
2669 }
2670 }
2671 }
2672
2673 /* If we're receiving files, and the client provided more than one
2674 * path, then it's ambiguous -- we don't know which of the files
2675 * the client will be sending should be written to which path.
2676 */
2677 if ((scp_opts & SFTP_SCP_OPT_ISDST) &&
2678 paths->paths->nelts != 1) {
2679 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2680 "'scp' request provided more than one destination path, ignoring");
2681 errno = EINVAL;
2682 return -1;
2683 }
2684
2685 for (i = 0; i < paths->paths->nelts; i++) {
2686 struct scp_path *sp;
2687
2688 sp = ((struct scp_path **) paths->paths->elts)[i];
2689 if (sp) {
2690 pr_trace_msg(trace_channel, 5, "scp_path[%u] = '%s'", i, sp->path);
2691 }
2692 }
2693
2694 return 0;
2695 }
2696
sftp_scp_open_session(uint32_t channel_id)2697 int sftp_scp_open_session(uint32_t channel_id) {
2698 register unsigned int i;
2699 pool *sub_pool;
2700 struct scp_paths *paths;
2701 struct scp_session *sess, *last;
2702 int timeout_stalled;
2703
2704 /* Check to see if we already have an SCP session opened for the given
2705 * channel ID.
2706 */
2707 sess = last = scp_sessions;
2708 while (sess) {
2709 pr_signals_handle();
2710
2711 if (sess->channel_id == channel_id) {
2712 errno = EEXIST;
2713 return -1;
2714 }
2715
2716 if (sess->next == NULL) {
2717 /* This is the last item in the list. */
2718 last = sess;
2719 }
2720
2721 sess = sess->next;
2722 }
2723
2724 paths = scp_get_paths(channel_id);
2725 if (paths == NULL) {
2726 pr_trace_msg(trace_channel, 1, "missing paths for SCP channel ID %lu",
2727 (unsigned long) channel_id);
2728 errno = EACCES;
2729 return -1;
2730 }
2731
2732 /* Looks like we get to allocate a new one. */
2733 sub_pool = make_sub_pool(scp_pool);
2734 pr_pool_tag(sub_pool, "SCP session pool");
2735
2736 sess = pcalloc(sub_pool, sizeof(struct scp_session));
2737 sess->pool = sub_pool;
2738 sess->channel_id = channel_id;
2739
2740 /* Now copy all of the struct scp_path elements from the paths list into
2741 * the session object.
2742 */
2743
2744 sess->paths = make_array(sess->pool, paths->paths->nelts,
2745 sizeof(struct scp_path *));
2746
2747 for (i = 0; i < paths->paths->nelts; i++) {
2748 struct scp_path *src_sp, *dst_sp;
2749
2750 src_sp = ((struct scp_path **) paths->paths->elts)[i];
2751
2752 dst_sp = pcalloc(sess->pool, sizeof(struct scp_path));
2753 dst_sp->orig_path = pstrdup(sess->pool, src_sp->orig_path);
2754 dst_sp->path = pstrdup(sess->pool, src_sp->path);
2755
2756 *((struct scp_path **) push_array(sess->paths)) = dst_sp;
2757 }
2758
2759 sess->path_idx = paths->path_idx;
2760
2761 scp_destroy_paths(paths);
2762
2763 if (last) {
2764 last->next = sess;
2765 sess->prev = last;
2766
2767 } else {
2768 scp_sessions = sess;
2769 }
2770
2771 pr_event_generate("mod_sftp.scp.session-opened", NULL);
2772
2773 pr_timer_remove(PR_TIMER_STALLED, ANY_MODULE);
2774
2775 timeout_stalled = pr_data_get_timeout(PR_DATA_TIMEOUT_STALLED);
2776 if (timeout_stalled > 0) {
2777 pr_timer_add(timeout_stalled, PR_TIMER_STALLED, NULL,
2778 scp_timeout_stalled_cb, "TimeoutStalled");
2779 }
2780
2781 pr_session_set_protocol("scp");
2782
2783 /* Clear any ASCII flags (set by default for FTP sessions. */
2784 session.sf_flags &= ~SF_ASCII;
2785
2786 return 0;
2787 }
2788
sftp_scp_close_session(uint32_t channel_id)2789 int sftp_scp_close_session(uint32_t channel_id) {
2790 struct scp_session *sess;
2791
2792 /* Check to see if we have an SCP session opened for this channel ID. */
2793 sess = scp_sessions;
2794 while (sess) {
2795 pr_signals_handle();
2796
2797 if (sess->channel_id == channel_id) {
2798 pr_timer_remove(PR_TIMER_STALLED, ANY_MODULE);
2799
2800 if (sess->next)
2801 sess->next->prev = sess->prev;
2802
2803 if (sess->prev) {
2804 sess->prev->next = sess->next;
2805
2806 } else {
2807 /* This is the start of the session list. */
2808 scp_sessions = sess->next;
2809 }
2810
2811 /* XXX How to handle dangling directory lists?? */
2812
2813 if (sess->paths != NULL) {
2814 if (sess->paths != NULL &&
2815 sess->paths->nelts > 0) {
2816 register unsigned int i;
2817 int count = 0;
2818 struct scp_path **elts;
2819
2820 elts = sess->paths->elts;
2821 for (i = 0; i < sess->paths->nelts; i++) {
2822 struct scp_path *elt = elts[i];
2823
2824 if (elt->fh != NULL) {
2825 count++;
2826 }
2827 }
2828
2829 if (count > 0) {
2830 config_rec *c;
2831 unsigned char delete_aborted_stores = FALSE;
2832
2833 c = find_config(main_server->conf, CONF_PARAM,
2834 "DeleteAbortedStores", FALSE);
2835 if (c) {
2836 delete_aborted_stores = *((unsigned char *) c->argv[0]);
2837 }
2838
2839 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2840 "aborting %d unclosed file %s", count,
2841 count != 1 ? "handles" : "handle");
2842
2843 for (i = 0; i < sess->paths->nelts; i++) {
2844 struct scp_path *elt = elts[i];
2845
2846 if (elt->fh != NULL) {
2847 char *abs_path, *curr_path;
2848
2849 curr_path = pstrdup(scp_pool, elt->fh->fh_path);
2850
2851 /* Write out an 'incomplete' TransferLog entry for this. */
2852 abs_path = sftp_misc_vroot_abs_path(scp_pool, elt->best_path,
2853 TRUE);
2854
2855 if (elt->recvlen > 0) {
2856 xferlog_write(0, pr_netaddr_get_sess_remote_name(),
2857 elt->recvlen, abs_path, 'b', 'i', 'r', session.user, 'i',
2858 "_");
2859
2860 } else {
2861 xferlog_write(0, pr_netaddr_get_sess_remote_name(),
2862 elt->sentlen, abs_path, 'b', 'o', 'r', session.user, 'i',
2863 "_");
2864 }
2865
2866 if (pr_fsio_close(elt->fh) < 0) {
2867 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2868 "error writing aborted file '%s': %s", elt->best_path,
2869 strerror(errno));
2870 }
2871
2872 elt->fh = NULL;
2873
2874 if (delete_aborted_stores == TRUE &&
2875 elt->recvlen > 0) {
2876 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2877 "removing aborted uploaded file '%s'", curr_path);
2878
2879 if (pr_fsio_unlink(curr_path) < 0) {
2880 (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2881 "error unlinking file '%s': %s", curr_path,
2882 strerror(errno));
2883 }
2884 }
2885 }
2886 }
2887 }
2888 }
2889 }
2890
2891 sess->paths = NULL;
2892 destroy_pool(sess->pool);
2893
2894 pr_session_set_protocol("ssh2");
2895
2896 pr_event_generate("mod_sftp.scp.session-closed", NULL);
2897 return 0;
2898 }
2899
2900 sess = sess->next;
2901 }
2902
2903 errno = ENOENT;
2904 return -1;
2905 }
2906