sftp-server.c 23.9 KB
Newer Older
1
2
/* sftp-server.c
 *
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 * $Id$
 *
 * The server side of the sftp subsystem. */

/* lsh, an implementation of the ssh protocol
 *
 * Copyright (C) 2001 Niels Mller, Pontus Skld
 *
 * Also includes parts from GNU fileutils, Copyright by Free Software
 * Foundation, Inc.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
27
28
29
30

#include "buffer.h"
#include "sftp.h"

31
32
#include "filemode.h"

33
34
35
36
37
38
39
40
41
42
#include <assert.h>
#include <stdlib.h>
#include <string.h>

#include <errno.h>
#include <fcntl.h>
#include <unistd.h>

#include <sys/stat.h>

43
44
45
46
47
#include <dirent.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>

48
49
50
51
#define SFTP_VERSION 3

#define FATAL(x) do { fputs("sftp-server: " x "\n", stderr); exit(EXIT_FAILURE); } while (0)

52
void sftp_attrib_from_stat( struct stat *st, struct sftp_attrib* a)
53
{
54
55
56
57
58
59
60
61
62
63
64
65
  a->permissions=st->st_mode;
  a->uid=st->st_uid;
  a->gid=st->st_gid;
  a->atime=st->st_atime;
  a->mtime=st->st_mtime;
  a->size=st->st_size;
  a->flags= ( SSH_FILEXFER_ATTR_SIZE ||
	      SSH_FILEXFER_ATTR_UIDGID ||
	      SSH_FILEXFER_ATTR_PERMISSIONS || 
	      SSH_FILEXFER_ATTR_ACMODTIME
	      );
}
66
67

static void
68
sftp_put_longname_mode(struct sftp_output *o, struct stat *st)
69
{
70
71
72
73
74
75
  /* A 10 character modestring and a space */
  UINT8 modes[MODE_STRING_LENGTH];

  filemodestring(st, modes);

  sftp_put_data(o, sizeof(modes), modes);
76
77
}

78
79
80
81
82
83
84
85
86
87
88
89
90
/* FIXME: Replace these dummy functions with the functions from
 * fileutil's lib/idcache.c. */
static const char *
getuser(uid_t uid)
{ return NULL; }

static const char *
getgroup(gid_t gid)
{ return NULL; }

static void
sftp_put_longname(struct sftp_output *o,
		  struct stat *st, UINT8* fname)
91
{
92
93
94
95
96
97
98
99
100
  /* NOTE: The current spec doesn't mandate utf8. */

  /* Where to store the length. */
  UINT32 length_index = sftp_put_reserve_length(o);
  const char *user_name;
  const char *group_name;
  time_t now, when;
  struct tm *when_local;
  const char *time_format;
101
  
102
103
  sftp_put_longname_mode(o, st);
  sftp_put_printf(o, " %3u ", (unsigned) st->st_nlink);
104

105
106
107
108
109
  user_name = getuser(st->st_uid);
  if (user_name)
    sftp_put_printf(o, "%-8.8s ", user_name);
  else
    sftp_put_printf(o, "%-8u ", (unsigned int) st->st_uid);
110

111
112
113
114
115
  group_name = getgroup(st->st_gid);
  if (group_name)
    sftp_put_printf(o, "%-8.8s ", group_name);
  else
    sftp_put_printf(o, "%-8u ", (unsigned) st->st_gid);
116

117
118
  /* FIXME: How to deal with long long sizes? */
  sftp_put_printf(o, "%8lu ", (unsigned long) st->st_size);
119

120
121
  now = time(NULL);
  when = st->st_mtime;
122

123
  when_local = localtime( &st->st_mtime );
124

125
126
127
128
129
130
131
132
133
134
135
136
137
  if ( (now > when + 6L * 30L * 24L * 60L * 60L)	/* Old. */
       || (now < when - 60L * 60L) )		/* In the future. */
    /* The file is fairly old or in the future.
       POSIX says the cutoff is 6 months old;
       approximate this by 6*30 days.
       Allow a 1 hour slop factor for what is considered "the future",
       to allow for NFS server/client clock disagreement.
       Show the year instead of the time of day.  */
    time_format = "%b %e  %Y";
  else
    time_format = "%b %e %H:%M";
      
  sftp_put_strftime(o, 12, time_format, when_local);
138

139
  sftp_put_printf(o, " %s", fname);
140

141
  sftp_put_final_length(o, length_index);
142
143
}

144
145
146
147
static void
sftp_put_filename(struct sftp_output *o,
		  struct stat *st,
		  const char *name)
148
{
149
  struct sftp_attrib a;
150
  
151
152
153
154
155
  sftp_attrib_from_stat( st, &a);
  sftp_put_string(o, strlen(name), name);
  sftp_put_longname(o, st, name);
  sftp_put_attrib(o, &a);
}
156

157
#define SFTP_MAX_HANDLES 200
158

159
160
161
162
struct sftp_handle
{
  enum sftp_handle_type
  { HANDLE_UNUSED = 0, HANDLE_FILE, HANDLE_DIR } type;
163

164
165
166
167
168
169
  union
  {
    int fd;
    DIR *dir;
  } u;
};
170

171
#if 0
172
173
/* A handle is simply an fd */
#define handle_t UINT32
174
175
176
#else
#define handle_t struct sftp_handle *
#endif
177
178
179
180
181
182

struct sftp_ctx
{
  struct sftp_input *i;
  struct sftp_output *o;
  
183
  struct sftp_handle handles[SFTP_MAX_HANDLES];
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
};

void
sftp_init(struct sftp_ctx *ctx, FILE *in, FILE *out)
{
  struct sftp_input *input;
  struct sftp_output *output;
  unsigned i;

  if (!(input = sftp_make_input(stdin)))
    FATAL("sftp_make_input failed");

  if (!(output = sftp_make_output(stdout)))
    FATAL("sftp_make_input failed");

  ctx->i = input;
  ctx->o = output;

202
203
  for (i = 0; i < SFTP_MAX_HANDLES; i++)
    ctx->handles[i].type = HANDLE_UNUSED;
204
205
206
207
208
}

int 
sftp_handle_used(struct sftp_ctx *ctx, handle_t handle)
{
209
210
  return (handle < SFTP_MAX_HANDLES)
    && (ctx->handles[handle].type != HANDLE_UNUSED);
211
212
213
214
215
216
217
}

void
sftp_register_handle(struct sftp_ctx *ctx,
		     UINT32 handle,
		     enum sftp_handle_type type)
{
218
219
  assert(handle < SFTP_MAX_HANDLES);
  assert(ctx->handles[handle].type == HANDLE_UNUSED);
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
  assert(type != HANDLE_UNUSED);

  ctx->handles[handle] = type;
}

int
sftp_get_handle(struct sftp_ctx *ctx, handle_t *handle)
{
  UINT32 length;
  UINT32 value;
  
  if ((sftp_get_uint32(ctx->i, &length))
      && (length == 4)
      && sftp_get_uint32(ctx->i, &value)
      && sftp_handle_used(ctx, value))
    {
      *handle = value;
      return 1;
    }
  return 0;
}

242
void
243
244
sftp_put_handle(struct sftp_ctx *ctx, handle_t handle)
{
245
246
  sftp_put_uint32(ctx->o, 4);
  sftp_put_uint32(ctx->o, handle);
247
248
249
250
251
252
253
254
}

/* NOTE: The status message should be expanded with a human-readable
 * message and a language tag. */
int
sftp_send_status(struct sftp_ctx *ctx, UINT32 status)
{
  sftp_set_msg(ctx->o, SSH_FXP_STATUS);
255
256
  sftp_put_uint32(ctx->o, status);
  return 1;
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
}

int
sftp_send_errno(struct sftp_ctx *ctx)
{
  UINT32 status;
  
  switch(errno)
    {
    case ENOENT:
      status = SSH_FX_NO_SUCH_FILE;
      break;
    case EACCES:
      status = SSH_FX_PERMISSION_DENIED;
      break;
    default:
      status = SSH_FX_FAILURE;
      break;
    }
  return sftp_send_status(ctx, status);
}

int
sftp_bad_message(struct sftp_ctx *ctx)
{
  sftp_send_status(ctx, SSH_FX_BAD_MESSAGE);
  return 0;
}

typedef int sftp_process_func(struct sftp_ctx *ctx);

static int
sftp_process_unsupported(struct sftp_ctx *ctx)
{
  return sftp_bad_message(ctx);
}

/* A filename must not contain any NUL-characters. */
static int
sftp_check_filename(UINT32 length, const UINT8 *data)
{
  return !memchr(data, 0, length);
}

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
static int
sftp_process_opendir(struct sftp_ctx *ctx)
{
  UINT32 length;
  UINT8 *name;
  DIR* dirhandle;

  if ( ! (name = sftp_get_string(ctx->i, &length))
      )
    return sftp_bad_message(ctx);

  if( (! sftp_check_filename(length, name)))
    {
      sftp_free_string(name);
      return sftp_send_status(ctx, SSH_FX_FAILURE);
    }
    
  /* Fixme; Perhaps we should have a sftp_mangle_fname? If not, we
     have to handle an empty filename here */

  dirhandle=opendir(length ? name : ".");

  sftp_free_string(name);
  
  if ( !dirhandle )
    return sftp_send_errno(ctx);

  /* Open successful */

  /* Fixme; we need to redo how handles work, perhaps a struct
     consisting of the type, an int (for an fd) and a DIR* (for a
     directory). I will look into this later (or we could skip using
     opendir/readdir/closedir, but I think that's not better */

  sftp_register_handle(ctx, dirhandle, HANDLE_DIR);
  sftp_put_handle(ctx, dirhandle);
}

static int
sftp_process_readdir(struct sftp_ctx *ctx)
{
  handle_t handle;
  struct dirent* direntry; 
  struct stat st;

  if ( !sftp_get_handle(ctx->i, &handle) ||
       ctx->handles[handle] != HANDLE_DIR
       )
    return sftp_bad_message(ctx);

  direntry=readdir(handle);

  /* Fixme; we need to redo how handles work, perhaps a struct
     consisting of the type, an int (for an fd) and a DIR* (for a
     directory). I will look into this later (or we could skip using
     opendir/readdir/closedir, but I think that's not better */

  if ( !direntry )
    return (errno ? sftp_send_errno(ctx)
	    : sftp_send_status(ctx, SSH_FX_EOF)); 

  /* Fixme; concat name */

  if( lstat(direntry->d_name, &st ) )
    return sftp_send_errno(ctx);

  /* Fixme; we don't have to, but maybe we should be nice and pass
     several at once? It might improve performance quite a lot (or it
     might not) 
     */

  /* Use count == 1 for now. */
  sftp_put_uint32(ctx->o, 1);

  sftp_put_filename(ctx->o, &st, direntry->d_name);

  sftp_set_msg(ctx->o, SSH_FXP_NAME );
  return 1;
}


static int
sftp_process_stat(struct sftp_ctx *ctx)
{
  struct stat st;
  struct sftp_attrib a;
  UINT32 length;
  UINT8 *name;

  if ( ! (name = sftp_get_string(ctx->i, &length))
      )
    return sftp_bad_message(ctx);

  if( (! sftp_check_filename(length, name))
      )
    return sftp_send_status(ctx, SSH_FX_FAILURE);   
    
  /* Fixme; Perhaps we should have a sftp_mangle_fname ? */


  /* Fixme; concat name */

  if ( stat(name, &st ) )
    return sftp_send_errno(ctx);

  sftp_attrib_from_stat( &st, &a);

  sftp_set_msg( ctx->o, SSH_FXP_ATTRS );
  sftp_put_attrib( ctx->o, &a);  

  return 1;
}

static int
sftp_process_lstat(struct sftp_ctx *ctx)
{
  struct stat st;
  struct sftp_attrib a;

  UINT32 length;
  UINT8 *name;

  if ( ! (name = sftp_get_string(ctx->i, &length))
      )
    return sftp_bad_message(ctx);

  if( (! sftp_check_filename(length, name))
      )
    return sftp_send_status(ctx, SSH_FX_FAILURE);   
    
  /* Fixme; Perhaps we should have a sftp_mangle_fname ? */


  /* Fixme; concat name */

  if ( lstat(name, &st ) )
    return sftp_send_errno(ctx);

  sftp_attrib_from_stat( &st, &a );
  sftp_set_msg( ctx->o, SSH_FXP_ATTRS );

  sftp_put_attrib( ctx->o, &a); 

  return 1;
}

static int
sftp_process_fstat(struct sftp_ctx *ctx)
{
  struct stat st;
  struct sftp_attrib a;
  handle_t handle;

  if ( sftp_get_handle(ctx->i, &handle) )
    if ( ctx->handles[handle] == HANDLE_FILE )
	{
	  if ( fstat(handle, &st ) )
	    return sftp_send_errno(ctx);
	  
	  sftp_attrib_from_stat(&st,&a);
	  sftp_set_msg( ctx->o, SSH_FXP_ATTRS );
	  
	  sftp_put_attrib( ctx->o, &a);
	  return 1;
	}

  return sftp_bad_message(ctx);
}


static int
sftp_process_fsetstat(struct sftp_ctx *ctx)
{
  struct sftp_attrib a;
  handle_t handle;

  if ( sftp_get_handle(ctx->i, &handle) &&
       sftp_get_attrib(ctx->i, &a)
       )
    if ( ! (ctx->handles[handle] == HANDLE_FILE ))
      return sftp_bad_message(ctx);

  /* Fixme; set stat */
	  
  if ( a.flags & SSH_FILEXFER_ATTR_UIDGID )
    if ( fchown( handle, a.uid, a.gid ) )
      return sftp_send_errno(ctx);
  
  if ( a.flags & SSH_FILEXFER_ATTR_SIZE )
    if( ftruncate( handle, a.size ) )
      return sftp_send_errno(ctx);
  
  if ( a.flags & SSH_FILEXFER_ATTR_PERMISSIONS )
    if( fchmod( handle, a.permissions ) ) 
                               /* Fixme; Perhaps we should mask it */
      return sftp_send_errno(ctx);
  
  if ( a.flags & SSH_FILEXFER_ATTR_EXTENDED ||
       a.flags & SSH_FILEXFER_ATTR_ACMODTIME ) /* Fixme; how do we? */
    return sftp_send_status(ctx, SSH_FX_OP_UNSUPPORTED );
  
  return sftp_send_status(ctx, SSH_FX_OK);        
}


static int
sftp_process_setstat(struct sftp_ctx *ctx)
{
  struct sftp_attrib a;

  UINT32 length;
  UINT8 *name;

  if ( (! (name = sftp_get_string(ctx->i, &length))) ||
       (!sftp_get_attrib(ctx->i, &a))
       )
    return sftp_bad_message(ctx);

  if( (! sftp_check_filename(length, name))
      )
    return sftp_send_status(ctx, SSH_FX_FAILURE);   
    
  /* Fixme; Perhaps we should have a sftp_mangle_fname ? */

  if ( a.flags & SSH_FILEXFER_ATTR_UIDGID )
    if ( chown( name, a.uid, a.gid ) )
      return sftp_send_errno(ctx);

  if ( a.flags & SSH_FILEXFER_ATTR_SIZE )
    if( truncate( name, a.size ) )
      return sftp_send_errno(ctx);

  if ( a.flags & SSH_FILEXFER_ATTR_PERMISSIONS )
    if( chmod( name, a.permissions ) ) /* Fixme; Perhaps we should mask it */
      return sftp_send_errno(ctx);

  if ( a.flags & SSH_FILEXFER_ATTR_EXTENDED ||
       a.flags & SSH_FILEXFER_ATTR_ACMODTIME ) /* Fixme; how do we? */
    return sftp_send_status(ctx, SSH_FX_OP_UNSUPPORTED );

  return sftp_send_status(ctx, SSH_FX_OK);  
}

static int
sftp_process_remove(struct sftp_ctx *ctx)
{
  UINT32 length;
  UINT8 *name;

  if ( ! (name = sftp_get_string(ctx->i, &length))
      )
    return sftp_bad_message(ctx);

  if( (! sftp_check_filename(length, name))
      )
    return sftp_send_status(ctx, SSH_FX_FAILURE);   
    
  /* Fixme; Perhaps we should have a sftp_mangle_fname ? */
  
  if( ! unlink(name) )
    return sftp_send_errno(ctx);
  else
    return sftp_send_status(ctx, SSH_FX_OK);   
}

static int
sftp_process_mkdir(struct sftp_ctx *ctx)
{
  UINT32 length;
  UINT8 *name;

  if ( ! (name = sftp_get_string(ctx->i, &length))
      )
    return sftp_bad_message(ctx);

  if( (! sftp_check_filename(length, name))
      )
    return sftp_send_status(ctx, SSH_FX_FAILURE);   
    
  /* Fixme; Perhaps we should have a sftp_mangle_fname? If not, we
     have to handle an empty filename here */
  
  if( ! mkdir(name, 0755) ) /* Fixme; default permissions ? */ 
    return sftp_send_errno(ctx);
  else
    return sftp_send_status(ctx, SSH_FX_OK);   
}

static int
sftp_process_rmdir(struct sftp_ctx *ctx)
{
  UINT32 length;
  UINT8 *name;

  if ( ! (name = sftp_get_string(ctx->i, &length))
      )
    return sftp_bad_message(ctx);

  if( (! sftp_check_filename(length, name))
      )
    return sftp_send_status(ctx, SSH_FX_FAILURE);   
    
  /* Fixme; Perhaps we should have a sftp_mangle_fname? If not, we
     need to handle an empty filename here */
  
  if( ! rmdir(name) )
    return sftp_send_errno(ctx);
  else
    return sftp_send_status(ctx, SSH_FX_OK);   
}

static int
sftp_process_realpath(struct sftp_ctx *ctx)
{
  UINT32 length;
  UINT8 *name;
  UINT8 *resolved;
  struct stat st;
  int path_max;

  if ( ! (name = sftp_get_string(ctx->i, &length))
      )
    return sftp_bad_message(ctx);

  if( (! sftp_check_filename(length, name))
      )
    return sftp_send_status(ctx, SSH_FX_FAILURE);   
    
  /* Fixme; Perhaps we should have a sftp_mangle_fname? If not, we
     need to handle an empty filename here */
  
  /* Code below from the manpage for realpath on my debian system */

#ifdef PATH_MAX
  path_max = PATH_MAX;
#else
  path_max = pathconf (path, _PC_PATH_MAX);
  if (path_max <= 0)
    path_max = 4096;
#endif

  resolved=alloca(path_max);
  
  if( ! realpath( name, resolved ) )
    return sftp_send_errno(ctx);
  
  if( lstat(resolved, &st ) )
    return sftp_send_errno(ctx);

  /* Fixme; Should it be supported to call realpath for non-existing
     files?  This code will break (as it tries to stat and will get
     ENOENT). The draft says we should return "just one name and dummy
     attributes", but I figure we might as well pass the real attribs
     */

  sftp_put_uint32(ctx->o, 1); /* Count */  
  sftp_put_filename(ctx->o, &st, resolved);
  sftp_set_msg( ctx->o, SSH_FXP_NAME );
  return 1;
}

static int
sftp_process_rename(struct sftp_ctx *ctx)
{
  UINT32 src_length;
  UINT8 *src_name;

  UINT32 dst_length;
  UINT8 *dst_name;

  if (! ( (src_name = sftp_get_string(ctx->i, &src_length)) &&
	  (dst_name = sftp_get_string(ctx->i, &dst_length)))
      )
    return sftp_bad_message(ctx);
    
  /* Fixme; Perhaps we should have a sftp_mangle_fname ? Otherwise,
     we must handle the case of an empty filename here
     */
  
  if( (! sftp_check_filename(src_length, src_name)) ||
      (! sftp_check_filename(dst_length, dst_name)) 
      )
    return sftp_send_status(ctx, SSH_FX_FAILURE);   
   
  if( ! rename(src_name, dst_name) )
    return sftp_send_errno(ctx);
  else
    return sftp_send_status(ctx, SSH_FX_OK);   
}


692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
static int
sftp_process_open(struct sftp_ctx *ctx)
{
  UINT32 length;
  UINT8 *name;
  UINT32 pflags;
  struct sftp_attrib a;

  if ((name = sftp_get_string(ctx->i, &length))
      && sftp_get_uint32(ctx->i, &pflags)
      && sftp_get_attrib(ctx->i, &a))
    {
      /* Empty name is a synonym to ".", which isn't a file. */
      if (length && sftp_check_filename(length, name))
	{
	  int fd;
	  int mode;
	  struct stat sb;
	  
	  switch (pflags & (SSH_FXF_READ | SSH_FXF_WRITE))
	    {
	    case 0:
714
715
	      sftp_send_status(ctx, SSH_FX_FAILURE);
	      return 1;
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
	    case SSH_FXF_READ:
	      mode = O_RDONLY;
	      break;
	    case SSH_FXF_WRITE:
	      mode = O_WRONLY;
	      break;
	    case SSH_FXF_READ | SSH_FXF_WRITE:
	      mode = O_RDWR;
	      break;
	    default:
	      abort();
	    }
	  if (pflags & SSH_FXF_APPEND)
	    mode |= O_APPEND;

	  if (pflags & SSH_FXF_CREAT)
	    mode |= O_CREAT;
	  else if (pflags & SSH_FXF_EXCL)
	    /* We can't have EXCL without CREAT. */
	    sftp_send_status(ctx, SSH_FX_FAILURE);
	  
	  if (pflags & SSH_FXF_TRUNC)
	    mode |= O_TRUNC;
	  if (pflags & SSH_FXF_EXCL)
	    mode |= O_EXCL;

	  /* Look at the atributes. For now, we care only about the
	   * permission bits. */
	  if (a.flags & SSH_FILEXFER_ATTR_PERMISSIONS)
	    {
	      /* Use the client's permission bits with no umask filtering */
	      mode_t old = umask(0);
	      fd = open(name, mode, a.permissions);
	      umask(old);
	    }
	  else
	    /* Default flags, filtered through our umask */
	    fd = open(name, mode, 0666);

	  if (fd < 0)
	    return sftp_send_errno(ctx);

758
759
760
761
762
763
764
#if 0
	  if (a.flags & SSH_FILEXFER_ATTR_UIDGID)
	    if ( fchown(fd, a.uid, a.gid) )
	      return sftp_send_errno(ctx);
#endif    

	  if (fd > SFTP_MAX_HANDLES)
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
	    {
	      close(fd);
	      return sftp_send_status(ctx, SSH_FX_FAILURE);
	    }

	  if (fstat(fd, &sb) < 0)
	    {
	      close(fd);
	      return sftp_send_errno(ctx);
	    }

	  if (S_ISDIR(sb.st_mode))
	    {
	      close(fd);
	      return sftp_send_status(ctx, SSH_FX_NO_SUCH_FILE);
	    }

	  /* Open successful */
	  sftp_register_handle(ctx, fd, HANDLE_FILE);
	  sftp_put_handle(ctx, fd);
	  return 1;
	}
      else
	return sftp_send_status(ctx, SSH_FX_NO_SUCH_FILE);
    }
  else
    return sftp_bad_message(ctx);
}

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

static int
sftp_process_close(struct sftp_ctx *ctx)
{
  handle_t handle;

  if ( sftp_get_handle(ctx, &handle) )
    {
      if ( ctx->handles[handle] == HANDLE_FILE )
	{
	  if ( !close(handle) )
	    {
	      ctx->handles[handle] = HANDLE_UNUSED;
	      return sftp_send_status(ctx, SSH_FX_OK);
	    }
	  else	
	    return sftp_send_status(ctx, SSH_FX_FAILURE); 
	  /* Fixme: Should we do something on error ?
	   */
	}

      else if ( ctx->handles[handle] == HANDLE_DIR)
	{
	  if ( !closedir(handle) )
	    {
	      ctx->handles[handle] = HANDLE_UNUSED;
	      return sftp_send_status(ctx, SSH_FX_OK);
	    }
	  else	
	    return sftp_send_status(ctx, SSH_FX_FAILURE);
	}
    }
  else
    return sftp_bad_message(ctx); 
/* Fixme; Should we separate cases bad message 
   and illegal handle and return failure for 
   one and bad_message for the other?
   */
}

static int
sftp_process_read(struct sftp_ctx *ctx)
{
  handle_t handle;
  UINT64 offset;
  UINT32 len;
  int readbytes=0;
  static UINT8* readbuf=0; 
  static UINT32 curbuflen=0;

  if ( !sftp_get_handle(ctx, &handle) && 
       ctx->handles[handle] == HANDLE_FILE && 
       sftp_get_uint64(ctx->i, &offset) &&
       sftp_get_uint32(ctx->i, &len)  
       )
    return sftp_bad_message(ctx);

/* Fixme; Should we separate cases bad message
   and illegal handle and return failure 
   for one and bad_message for the other?
   */

  if ( lseek( handle, offset, SEEK_SET) == (off_t) -1 )
    return sftp_send_status(ctx, SSH_FX_FAILURE); 

  /* Fixme; 64-bit support works differently on solaris at least */

  if ( len )                              /* Check so we are to read at all */
    {
      if ( len > curbuflen )             /* Current buffer to small ? */
	{
	  if ( readbuf )                  
	    free( readbuf );             /* Free the existing buffer 
					    (Fixme; Perhaps explicitly set
					    readbuf to NULL, although the 
					    malloc means we shouldn't have to)
					    */


	  readbuf=malloc( len );           /* Allocate the new one */
	  
	  if ( !readbuf )
	    {
	      curbuflen=0;                   /* Failed malloc - we have no 
						buffer 
						*/

	      return sftp_send_status(ctx, SSH_FX_FAILURE); 

	    }
	  else
	    curbuflen=len;
	}

      readbytes=read( handle, readbuf, len );
      
      if ( readbytes == 0 )
	return sftp_send_status( ctx, SSH_FX_EOF ); 
      else if ( readbytes == -1 )
	return sftp_send_status( ctx, SSH_FX_FAILURE ); 
      
    }
 
  sftp_set_msg( ctx->o, SSH_FXP_DATA );
  sftp_put_string( ctx->o, readbytes, readbuf );
  return 1;
}

static int
sftp_process_write(struct sftp_ctx *ctx)
{
  handle_t handle;
  UINT64 offset;

  int writtenbytes=0;
  UINT8 *writebuf; 
  UINT32 length;


  if ( !sftp_get_handle(ctx, &handle) && 
       ctx->handles[handle] == HANDLE_FILE && 
       sftp_get_uint64(ctx->i, &offset) &&
       writebuf=sftp_get_string(ctx->i, &length)  
       )
    return sftp_bad_message(ctx);

/* Fixme; Should we separate cases bad message
   and illegal handle and return failure 
   for one and bad_message for the other?
   */

  if ( lseek( handle, offset, SEEK_SET) == (off_t) -1 )
    return sftp_send_status(ctx, SSH_FX_FAILURE); 

  /* Fixme; 64-bit support works differently on solaris at least */

  /* Nothing happens if length is 0 - hence we need no special test */
    
  if ( write( handle, writebuf, length ) != -1 )
    return sftp_send_status(ctx, SSH_FX_OK); 
  else
    return sftp_send_errno(ctx);
}


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
static void
sftp_process(sftp_process_func **dispatch,
	     struct sftp_ctx *ctx)
{
  UINT8 msg;
  UINT32 id;
  
  int ok;

  switch (sftp_read_packet(ctx->i))
    {
    case 1:
      break;
    case 0:
      exit(EXIT_FAILURE);
    case -1: /* EOF */
      exit(EXIT_SUCCESS);
    }
  
  /* All packets start with a msg byte and a 32-bit id. */
  if (!sftp_get_uint8(ctx->i, &msg))
    FATAL("Invalid packet.");

  if (!sftp_get_uint32(ctx->i, &id))
    FATAL("Invalid packet.");

  /* Every reply starts with the id, so copy it through */
  sftp_set_id(ctx->o, id);
    
  /* Calls FATAL on protocol errors. */
  ok = dispatch[msg](ctx);
    
  /* Every handler should result in at least one message */
  if (!sftp_write_packet(ctx->o))
973
974
    exit(EXIT_FAILURE);
  
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
  if (!ok)
    exit(EXIT_FAILURE);
}  

/* The handshake packets are special, because they don't include any
 * request id. */
int
sftp_handshake(struct sftp_ctx *ctx)
{
  UINT8 msg;
  UINT32 version;
  
  if (sftp_read_packet(ctx->i) <= 0)
    return 0;

  if (sftp_get_uint8(ctx->i, &msg)
      && (msg == SSH_FXP_INIT)
      && sftp_get_uint32(ctx->i, &version))
    {
      while (!sftp_get_eod(ctx->i))
	if (!sftp_skip_extension(ctx->i))
	  return 0;

      if (version < SFTP_VERSION)
	return 0;

      /* The VERSION message puts the version number where
       * the id is usually located. */

      sftp_set_msg(ctx->o, SSH_FXP_VERSION);
      sftp_set_id(ctx->o, SFTP_VERSION);

      return sftp_write_packet(ctx->o);
    }
  return 0;
}

int
main(int argc, char **argv)
{
  unsigned i;
  
  struct sftp_ctx ctx;
  sftp_process_func *dispatch[0x100];

  sftp_init(&ctx, stdin, stdout);

  if (!sftp_handshake(&ctx))
    return EXIT_FAILURE;
  
  for (i = 0; i<0x100; i++)
    dispatch[i] = sftp_process_unsupported;
  
  dispatch[SSH_FXP_OPEN] = sftp_process_open;
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
  dispatch[SSH_FXP_CLOSE] = sftp_process_close;
  dispatch[SSH_FXP_READ] = sftp_process_read;
  dispatch[SSH_FXP_WRITE] = sftp_process_write;
  dispatch[SSH_FXP_LSTAT] = sftp_process_lstat;
  dispatch[SSH_FXP_STAT] = sftp_process_stat;
  dispatch[SSH_FXP_FSTAT] = sftp_process_fstat;
  dispatch[SSH_FXP_SETSTAT] = sftp_process_setstat;
  dispatch[SSH_FXP_FSETSTAT] = sftp_process_fsetstat;  
  dispatch[SSH_FXP_MKDIR] = sftp_process_mkdir;
  dispatch[SSH_FXP_RMDIR] = sftp_process_rmdir;
  dispatch[SSH_FXP_REMOVE] = sftp_process_remove;
  dispatch[SSH_FXP_RENAME] = sftp_process_rename;
  dispatch[SSH_FXP_OPENDIR] = sftp_process_opendir;
  dispatch[SSH_FXP_READDIR] = sftp_process_readdir;
  dispatch[SSH_FXP_REALPATH] = sftp_process_realpath;

1045
1046
1047
  for(;;)
    sftp_process(dispatch, &ctx);
}