aboutsummaryrefslogtreecommitdiff
path: root/modules/csync_sftp.c
blob: edfec72439a7a2cdcc4f949caea3921af0e90676 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
/*
 * libcsync -- a library to sync a directory with another
 *
 * Copyright (c) 2008-2013 by Andreas Schneider <asn@cryptomilk.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <errno.h>
#include <stdio.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <libssh/sftp.h>
#include <libssh/callbacks.h>

#include "c_lib.h"
#include "c_strerror.h"
#include "vio/csync_vio_module.h"
#include "vio/csync_vio_file_stat.h"

#ifdef NDEBUG
#define DEBUG_SFTP(x)
#else
#define DEBUG_SFTP(x) printf x
#endif

ssh_callbacks _ssh_callbacks;
ssh_session _ssh_session;
sftp_session _sftp_session;

csync_auth_callback _authcb;
void *_userdata;
int _connected;

static int _ssh_auth_callback(const char *prompt, char *buf, size_t len,
    int echo, int verify, void *userdata) {
  if (_authcb != NULL) {
    return (*_authcb) (prompt, buf, len, echo, verify, userdata);
  }

  return -1;
}

static int auth_kbdint(ssh_session session, const char *user,
    const char *passwd) {
  const char *name = NULL;
  const char *instruction = NULL;
  const char *prompt = NULL;
  char buffer[256] = {0};
  int err = SSH_AUTH_ERROR;
  int rc;

  err = ssh_userauth_kbdint(session, user, NULL);
  while (err == SSH_AUTH_INFO) {
    int n = 0;
    int i = 0;

    name = ssh_userauth_kbdint_getname(session);
    instruction = ssh_userauth_kbdint_getinstruction(session);
    n = ssh_userauth_kbdint_getnprompts(session);

    if (strlen(name) > 0) {
      printf("%s\n", name);
    }

    if (strlen(instruction) > 0) {
      printf("%s\n", instruction);
    }

    for (i = 0; i < n; ++i) {
      char echo;

      prompt = ssh_userauth_kbdint_getprompt(session, i, &echo);
      if (echo) {
        (*_authcb) (prompt, buffer, sizeof(buffer), 1, 0, NULL);
        rc = ssh_userauth_kbdint_setanswer(session, i, buffer);
        if (rc < 0) {
          return SSH_AUTH_ERROR;
        }
        ZERO_STRUCT(buffer);
      } else {
        if (passwd != NULL) {
          rc = ssh_userauth_kbdint_setanswer(session, i, passwd);
          if (rc < 0) {
            return SSH_AUTH_ERROR;
          }
        } else {
          (*_authcb) ("Password:", buffer, sizeof(buffer), 0, 0, NULL);
          rc = ssh_userauth_kbdint_setanswer(session, i, buffer);
          if (rc < 0) {
            return SSH_AUTH_ERROR;
          }
          ZERO_STRUCT(buffer);
        }
      }
    }
    err = ssh_userauth_kbdint(session, user, NULL);
  }

  return err;
}

static int _sftp_portable_to_errno(int sftp_errno) {
  int rc = 0;

  switch(sftp_errno) {
    case SSH_FX_OK:
      break;
    case SSH_FX_NO_SUCH_FILE:
    case SSH_FX_NO_SUCH_PATH:
      rc = ENOENT;
      break;
    case SSH_FX_PERMISSION_DENIED:
      rc = EACCES;
      break;
    case SSH_FX_FILE_ALREADY_EXISTS:
      rc = EEXIST;
      break;
    case SSH_FX_INVALID_HANDLE:
      rc = EBADF;
      break;
    case SSH_FX_OP_UNSUPPORTED:
    case SSH_FX_BAD_MESSAGE:
      rc = EINVAL;
      break;
    case SSH_FX_FAILURE:
      rc = ENOTEMPTY;
      break;
    default:
      rc = EIO;
      break;
  }

  return rc;
}

static int _sftp_connect(const char *uri) {
  char *scheme = NULL;
  char *user = NULL;
  char *passwd = NULL;
  char *host = NULL;
  unsigned int port = 0;
  unsigned char *hash = NULL;
  size_t hlen = 0;
  int rc = -1;
  int state = SSH_SERVER_ERROR;
  int timeout = 10;
  int method;
  char *verbosity;
  char errbuf[256] = {0};
  ssh_key srv_pubkey;

  if (_connected) {
    return 0;
  }

  rc = c_parse_uri(uri, &scheme, &user, &passwd, &host, &port, NULL);
  if (rc < 0) {
    goto out;
  }

  DEBUG_SFTP(("csync_sftp - conntecting to: %s\n", host));

  /* create the session */
  _ssh_session = ssh_new();
  if (_ssh_session == NULL) {
    c_strerror_r(errno, errbuf, sizeof(errbuf));
    fprintf(stderr, "csync_sftp - error creating new connection: %s\n", errbuf);
    rc = -1;
    goto out;
  }

  rc = ssh_options_set(_ssh_session, SSH_OPTIONS_TIMEOUT, &timeout);
  if (rc < 0) {
    c_strerror_r(errno, errbuf, sizeof(errbuf));
    fprintf(stderr, "csync_sftp - error setting connection timeout: %s\n", errbuf);
    goto out;
  }

  rc = ssh_options_set(_ssh_session, SSH_OPTIONS_COMPRESSION_C_S, "none");
  if (rc < 0) {
    c_strerror_r(errno, errbuf, sizeof(errbuf));
    fprintf(stderr, "csync_sftp - error setting connection compression: %s\n", errbuf);
    goto out;
  }

  rc = ssh_options_set(_ssh_session, SSH_OPTIONS_COMPRESSION_S_C, "none");
  if (rc < 0) {
    c_strerror_r(errno, errbuf, sizeof(errbuf));
    fprintf(stderr, "csync_sftp - error setting connection compression: %s\n", errbuf);
    goto out;
  }

  ssh_options_set(_ssh_session, SSH_OPTIONS_HOST, host);
  if (rc < 0) {
    c_strerror_r(errno, errbuf, sizeof(errbuf));
    fprintf(stderr, "csync_sftp - error setting connection host: %s\n", errbuf);
    goto out;
  }

  if (port) {
    ssh_options_set(_ssh_session, SSH_OPTIONS_PORT, &port);
    if (rc < 0) {
      c_strerror_r(errno, errbuf, sizeof(errbuf));
      fprintf(stderr, "csync_sftp - error setting connection port: %s\n", errbuf);
      goto out;
    }
    DEBUG_SFTP(("csync_sftp - port set to: %d\n", port));
  }

  if (user && *user) {
    ssh_options_set(_ssh_session, SSH_OPTIONS_USER, user);
    if (rc < 0) {
      c_strerror_r(errno, errbuf, sizeof(errbuf));
      fprintf(stderr, "csync_sftp - error setting sftp username: %s\n", errbuf);
      goto out;
    }
    DEBUG_SFTP(("csync_sftp - username set to: %s\n", user));
  }

  verbosity = getenv("CSYNC_SFTP_LOG_VERBOSITY");
  if (verbosity) {
    rc = ssh_options_set(_ssh_session, SSH_OPTIONS_LOG_VERBOSITY_STR, verbosity);
    if (rc < 0) {
      goto out;
    }
  }

  /* read ~/.ssh/config */
  rc = ssh_options_parse_config(_ssh_session, NULL);
  if (rc < 0) {
    goto out;
  }

  _ssh_callbacks = (ssh_callbacks) c_malloc(sizeof(struct ssh_callbacks_struct));
  if (_ssh_callbacks == NULL) {
    rc = -1;
    goto out;
  }
  ZERO_STRUCTP(_ssh_callbacks);

  _ssh_callbacks->userdata = _userdata;
  _ssh_callbacks->auth_function = _ssh_auth_callback;

  ssh_callbacks_init(_ssh_callbacks);

  ssh_set_callbacks(_ssh_session, _ssh_callbacks);

  rc = ssh_connect(_ssh_session);
  if (rc < 0) {
    fprintf(stderr, "csync_sftp - error connecting to the server: %s\n", ssh_get_error(_ssh_session));
    ssh_disconnect(_ssh_session);
    _ssh_session = NULL;
    ssh_finalize();
    goto out;
  }

  rc = ssh_get_publickey(_ssh_session, &srv_pubkey);
  if (rc < 0) {
    fprintf(stderr, "csync_sftp - error connecting to the server: %s\n", ssh_get_error(_ssh_session));
    ssh_disconnect(_ssh_session);
    _ssh_session = NULL;
    ssh_finalize();
    goto out;
  }

  rc = ssh_get_publickey_hash(srv_pubkey,
                              SSH_PUBLICKEY_HASH_SHA1,
                              &hash, &hlen);
  ssh_key_free(srv_pubkey);
  if (rc < 0) {
    fprintf(stderr, "csync_sftp - error connecting to the server: %s\n",
        ssh_get_error(_ssh_session));
    ssh_disconnect(_ssh_session);
    _ssh_session = NULL;
    ssh_finalize();
    goto out;
  }

  /* check the server public key hash */
  state = ssh_is_server_known(_ssh_session);
  switch (state) {
    case SSH_SERVER_KNOWN_OK:
      break;
    case SSH_SERVER_KNOWN_CHANGED:
      fprintf(stderr, "csync_sftp - The host key for this server was "
            "not found, but another type of key exists.\n"
            "An attacker might change the default server key to confuse your "
            "client into thinking the key does not exist.\n"
            "Please contact your system administrator.\n"
            "%s\n", ssh_get_error(_ssh_session));
      ssh_print_hexa("csync_sftp - public key hash", hash, hlen);

      ssh_disconnect(_ssh_session);
      _ssh_session = NULL;
      ssh_finalize();
      rc = -1;
      goto out;
      break;
    case SSH_SERVER_FOUND_OTHER:
      fprintf(stderr, "csync_sftp - the host key for this server was not "
          "found but an other type of key exists.\n");
      fprintf(stderr, "csync_sftp - an attacker might change the default "
          "server key to confuse your client into thinking the key does not "
          "exist\n");
      fprintf(stderr, "The host key for the server %s has changed.\n"
          "This could either mean that DNS SPOOFING is happening or the IP "
          "address for the host and its host key have changed at the same time.\n"
          "The fingerprint for the key sent by the remote host is:\n", host);
          ssh_print_hexa("", hash, hlen);
          fprintf(stderr, "Please contact your system administrator.\n"
          "%s\n", ssh_get_error(_ssh_session));

      ssh_disconnect(_ssh_session);
      _ssh_session = NULL;
      ssh_finalize();
      rc = -1;
      goto out;
      break;
    case SSH_SERVER_NOT_KNOWN:
      if (_authcb) {
        char *hexa;
        char *prompt;
        char buf[4] = {0};

        hexa = ssh_get_hexa(hash, hlen);
        if (hexa == NULL) {
          ssh_disconnect(_ssh_session);
          _ssh_session = NULL;
          ssh_finalize();
          rc = -1;
          goto out;
        }

        if (asprintf(&prompt,
              "The authenticity of host '%s' can't be established.\n"
              "RSA key fingerprint is %s.\n"
              "Are you sure you want to continue connecting (yes/no)?",
              host, hexa) < 0 ) {
          free(hexa);
          ssh_disconnect(_ssh_session);
          _ssh_session = NULL;
          ssh_finalize();
          rc = -1;
          goto out;
        }

        free(hexa);

        if ((*_authcb)(prompt, buf, sizeof(buf), 1, 0, _userdata) < 0) {
          free(prompt);
          ssh_disconnect(_ssh_session);
          _ssh_session = NULL;
          ssh_finalize();
          rc = -1;
          goto out;
        }

        free(prompt);

        if (strncasecmp(buf, "yes", 3) != 0) {
          ssh_disconnect(_ssh_session);
          _ssh_session = NULL;
          ssh_finalize();
          rc = -1;
          goto out;
        }

        if (ssh_write_knownhost(_ssh_session) < 0) {
          ssh_disconnect(_ssh_session);
          _ssh_session = NULL;
          ssh_finalize();
          rc = -1;
          goto out;
        }
      } else {
        fprintf(stderr,"csync_sftp - the server is unknown. Connect manually to "
            "the host to retrieve the public key hash, then try again.\n");
      }
      ssh_disconnect(_ssh_session);
      _ssh_session = NULL;
      ssh_finalize();
      rc = -1;
      goto out;
      break;
    case SSH_SERVER_ERROR:
      fprintf(stderr, "%s\n", ssh_get_error(_ssh_session));

      ssh_disconnect(_ssh_session);
      _ssh_session = NULL;
      ssh_finalize();
      rc = -1;
      goto out;
      break;
    default:
      break;
  }

  /* Try to authenticate */
  rc = ssh_userauth_none(_ssh_session, NULL);
  if (rc == SSH_AUTH_ERROR) {
      ssh_disconnect(_ssh_session);
      _ssh_session = NULL;
      ssh_finalize();
      rc = -1;
      goto out;
  }

#if 0
  /* authenticate with the server */
  if (passwd && *passwd) {
    DEBUG_SFTP(("csync_sftp - authenticating with user/password\n"));
    /*
     * This is tunneled cleartext password authentication and possibly needs
     * to be allowed by the ssh server. Set 'PasswordAuthentication yes'
     */
    auth = ssh_userauth_password(_ssh_session, user, passwd);
  } else {
    DEBUG_SFTP(("csync_sftp - authenticating with pubkey\n"));
    auth = ssh_userauth_autopubkey(_ssh_session, NULL);
  }

  if (auth == SSH_AUTH_ERROR) {
    fprintf(stderr, "csync_sftp - authenticating with pubkey: %s\n",
        ssh_get_error(_ssh_session));
    ssh_disconnect(_ssh_session);
    _ssh_session = NULL;
    ssh_finalize();
    rc = -1;
    goto out;
  }

  if (auth != SSH_AUTH_SUCCESS) {
    if (_authcb != NULL) {
      auth = auth_kbdint(_ssh_session);
      if (auth == SSH_AUTH_ERROR) {
        fprintf(stderr,"csync_sftp - authentication failed: %s\n",
            ssh_get_error(_ssh_session));
        ssh_disconnect(_ssh_session);
        _ssh_session = NULL;
        ssh_finalize();
        rc = -1;
        goto out;
      }
    } else {
      ssh_disconnect(_ssh_session);
      _ssh_session = NULL;
      ssh_finalize();
      rc = -1;
      goto out;
    }
  }


#endif
  method = ssh_auth_list(_ssh_session);

  while (rc != SSH_AUTH_SUCCESS) {
    /* Try to authenticate with public key first */
    if (method & SSH_AUTH_METHOD_PUBLICKEY) {
      rc = ssh_userauth_autopubkey(_ssh_session, NULL);
      if (rc == SSH_AUTH_ERROR) {
        ssh_disconnect(_ssh_session);
        _ssh_session = NULL;
        ssh_finalize();
        rc = -1;
        goto out;
      } else if (rc == SSH_AUTH_SUCCESS) {
        break;
      }
    }

    /* Try to authenticate with keyboard interactive */
    if (method & SSH_AUTH_METHOD_INTERACTIVE) {
      rc = auth_kbdint(_ssh_session, user, passwd);
      if (rc == SSH_AUTH_ERROR) {
        ssh_disconnect(_ssh_session);
        _ssh_session = NULL;
        ssh_finalize();
        rc = -1;
        goto out;
      } else if (rc == SSH_AUTH_SUCCESS) {
        break;
      }
    }

    /* Try to authenticate with password */
    if ((method & SSH_AUTH_METHOD_PASSWORD) && passwd && *passwd) {
      rc = ssh_userauth_password(_ssh_session, user, passwd);
      if (rc == SSH_AUTH_ERROR) {
        ssh_disconnect(_ssh_session);
        _ssh_session = NULL;
        ssh_finalize();
        rc = -1;
        goto out;
      } else if (rc == SSH_AUTH_SUCCESS) {
        break;
      }
    }
  }

  DEBUG_SFTP(("csync_sftp - creating sftp channel...\n"));
  /* start the sftp session */
  _sftp_session = sftp_new(_ssh_session);
  if (_sftp_session == NULL) {
    fprintf(stderr, "csync_sftp - sftp error initialising channel: %s\n", ssh_get_error(_ssh_session));
    rc = -1;
    goto out;
  }

  rc = sftp_init(_sftp_session);
  if (rc < 0) {
    fprintf(stderr, "csync_sftp - error initialising sftp: %s\n", ssh_get_error(_ssh_session));
    goto out;
  }

  DEBUG_SFTP(("csync_sftp - connection established...\n"));
  _connected = 1;
  rc = 0;
out:
  SAFE_FREE(scheme);
  SAFE_FREE(user);
  SAFE_FREE(passwd);
  SAFE_FREE(host);
  ssh_clean_pubkey_hash(&hash);

  return rc;
}

static char *sftp_connect_uri(const char *uri)
{
  char *tmp = NULL;
  char *path;
  int rc;

  rc = _sftp_connect(uri);
  if (rc < 0) {
      return NULL;
  }

  rc = c_parse_uri(uri, NULL, NULL, NULL, NULL, NULL, &tmp);
  if (rc < 0) {
      return NULL;
  }

  path = sftp_canonicalize_path(_sftp_session, tmp);
  SAFE_FREE(tmp);

  return path;
}

/*
 * file functions
 */

static csync_vio_method_handle_t *_sftp_open(const char *uri, int flags, mode_t mode) {
  csync_vio_method_handle_t *mh = NULL;
  char *path;

  path = sftp_connect_uri(uri);
  if (path == NULL) {
    return NULL;
  }

  mh = (csync_vio_method_handle_t *) sftp_open(_sftp_session, path, flags, mode);
  if (mh == NULL) {
    errno = _sftp_portable_to_errno(sftp_get_error(_sftp_session));
  }

  SAFE_FREE(path);
  return mh;
}

static csync_vio_method_handle_t *_sftp_creat(const char *uri, mode_t mode) {
  csync_vio_method_handle_t *mh = NULL;
  char *path;

  path = sftp_connect_uri(uri);
  if (path == NULL) {
    return NULL;
  }

  mh = (csync_vio_method_handle_t *) sftp_open(_sftp_session, path, O_CREAT|O_WRONLY|O_TRUNC, mode);
  if (mh == NULL) {
    errno = _sftp_portable_to_errno(sftp_get_error(_sftp_session));
  }

  SAFE_FREE(path);
  return mh;
}

static int _sftp_close(csync_vio_method_handle_t *fhandle) {
  int rc = -1;

  rc = sftp_close(fhandle);
  if (rc < 0) {
    errno = _sftp_portable_to_errno(sftp_get_error(_sftp_session));
  }

  return rc;
}

static ssize_t _sftp_read(csync_vio_method_handle_t *fhandle, void *buf, size_t count) {
  int rc = -1;

  rc = sftp_read(fhandle, buf, count);
  if (rc < 0) {
    errno = _sftp_portable_to_errno(sftp_get_error(_sftp_session));
  }

  return rc;
}

static ssize_t _sftp_write(csync_vio_method_handle_t *fhandle, const void *buf, size_t count) {
  int rc = -1;

  rc = sftp_write(fhandle, (void *) buf, count);
  if (rc < 0) {
    errno = _sftp_portable_to_errno(sftp_get_error(_sftp_session));
  }

  return rc;
}

static off_t _sftp_lseek(csync_vio_method_handle_t *fhandle, off_t offset, int whence) {
  /* FIXME: really implement seek for lseek? */
  (void) whence;
  sftp_seek(fhandle, offset);
  return 0;
}

/*
 * directory functions
 */

static csync_vio_method_handle_t *_sftp_opendir(const char *uri) {
  csync_vio_method_handle_t *mh = NULL;
  char *path;

  path = sftp_connect_uri(uri);
  if (path == NULL) {
    return NULL;
  }

  mh = (csync_vio_method_handle_t *) sftp_opendir(_sftp_session, path);
  if (mh == NULL) {
    errno = _sftp_portable_to_errno(sftp_get_error(_sftp_session));
  }

  SAFE_FREE(path);
  return mh;
}

static int _sftp_closedir(csync_vio_method_handle_t *dhandle) {
  int rc = -1;

  rc = sftp_closedir(dhandle);
  if (rc < 0) {
    errno = _sftp_portable_to_errno(sftp_get_error(_sftp_session));
  }

  return rc;
}

static csync_vio_file_stat_t *_sftp_readdir(csync_vio_method_handle_t *dhandle) {
  sftp_attributes dirent = NULL;
  csync_vio_file_stat_t *fs = NULL;

  /* TODO: consider adding the _sftp_connect function */
  dirent = sftp_readdir(_sftp_session, dhandle);
  if (dirent == NULL) {
    errno = _sftp_portable_to_errno(sftp_get_error(_sftp_session));
    return NULL;
  }

  fs = c_malloc(sizeof(csync_vio_file_stat_t));
  if (fs == NULL) {
    sftp_attributes_free(dirent);
    return NULL;
  }

  fs->name = c_strdup(dirent->name);
  fs->fields = CSYNC_VIO_FILE_STAT_FIELDS_NONE;

  switch (dirent->type) {
    case SSH_FILEXFER_TYPE_REGULAR:
      fs->fields |= CSYNC_VIO_FILE_STAT_FIELDS_TYPE;
      fs->type = CSYNC_VIO_FILE_TYPE_REGULAR;
      break;
    case SSH_FILEXFER_TYPE_DIRECTORY:
      fs->fields |= CSYNC_VIO_FILE_STAT_FIELDS_TYPE;
      fs->type = CSYNC_VIO_FILE_TYPE_DIRECTORY;
      break;
    case SSH_FILEXFER_TYPE_SYMLINK:
    case SSH_FILEXFER_TYPE_SPECIAL:
    case SSH_FILEXFER_TYPE_UNKNOWN:
      break;
  }

  sftp_attributes_free(dirent);
  return fs;
}

static int _sftp_mkdir(const char *uri, mode_t mode) {
  char *path;
  int rc;

  path = sftp_connect_uri(uri);
  if (path == NULL) {
    return -1;
  }

  rc = sftp_mkdir(_sftp_session, path, mode);
  if (rc < 0) {
    errno = _sftp_portable_to_errno(sftp_get_error(_sftp_session));
  }

  SAFE_FREE(path);
  return rc;
}

static int _sftp_rmdir(const char *uri) {
  char *path;
  int rc;

  path = sftp_connect_uri(uri);
  if (path == NULL) {
    return -1;
  }

  rc = sftp_rmdir(_sftp_session, path);
  if (rc < 0) {
    errno = _sftp_portable_to_errno(sftp_get_error(_sftp_session));
  }

  SAFE_FREE(path);
  return rc;
}

static int _sftp_stat(const char *uri, csync_vio_file_stat_t *buf) {
  sftp_attributes attrs;
  char *path;
  int rc = -1;

  path = sftp_connect_uri(uri);
  if (path == NULL) {
    return -1;
  }

  attrs = sftp_lstat(_sftp_session, path);
  if (attrs == NULL) {
    goto out;
  }

  buf->name = c_basename(path);
  if (buf->name == NULL) {
    csync_vio_file_stat_destroy(buf);
    goto out;
  }
  buf->fields = CSYNC_VIO_FILE_STAT_FIELDS_NONE;

  switch (attrs->type) {
    case SSH_FILEXFER_TYPE_REGULAR:
      buf->type = CSYNC_VIO_FILE_TYPE_REGULAR;
      break;
    case SSH_FILEXFER_TYPE_DIRECTORY:
      buf->type = CSYNC_VIO_FILE_TYPE_DIRECTORY;
      break;
    case SSH_FILEXFER_TYPE_SYMLINK:
      buf->type = CSYNC_VIO_FILE_TYPE_SYMBOLIC_LINK;
      break;
    case SSH_FILEXFER_TYPE_SPECIAL:
    case SSH_FILEXFER_TYPE_UNKNOWN:
      buf->type = CSYNC_VIO_FILE_TYPE_UNKNOWN;
      break;
  }
  buf->fields |= CSYNC_VIO_FILE_STAT_FIELDS_TYPE;

  buf->mode = attrs->permissions;
  buf->fields |= CSYNC_VIO_FILE_STAT_FIELDS_PERMISSIONS;

  if (buf->type == CSYNC_VIO_FILE_TYPE_SYMBOLIC_LINK) {
    /* FIXME: handle symlink */
    buf->flags = CSYNC_VIO_FILE_FLAGS_SYMLINK;
  } else {
    buf->flags = CSYNC_VIO_FILE_FLAGS_NONE;
  }
  buf->fields |= CSYNC_VIO_FILE_STAT_FIELDS_FLAGS;

  buf->uid = attrs->uid;
  buf->fields |= CSYNC_VIO_FILE_STAT_FIELDS_UID;

  buf->uid = attrs->gid;
  buf->fields |= CSYNC_VIO_FILE_STAT_FIELDS_GID;

  buf->size = attrs->size;
  buf->fields |= CSYNC_VIO_FILE_STAT_FIELDS_SIZE;

  buf->atime = attrs->atime;
  buf->fields |= CSYNC_VIO_FILE_STAT_FIELDS_ATIME;

  buf->mtime = attrs->mtime;
  buf->fields |= CSYNC_VIO_FILE_STAT_FIELDS_MTIME;

  buf->ctime = attrs->createtime;
  buf->fields |= CSYNC_VIO_FILE_STAT_FIELDS_CTIME;

  rc = 0;
out:
  if (rc < 0) {
    errno = _sftp_portable_to_errno(sftp_get_error(_sftp_session));
  }
  SAFE_FREE(path);
  sftp_attributes_free(attrs);

  return rc;
}

static int _sftp_rename(const char *olduri, const char *newuri) {
  char *oldpath = NULL;
  char *tmp = NULL;
  char *newpath;
  int rc = -1;

  oldpath = sftp_connect_uri(olduri);
  if (oldpath == NULL) {
    return -1;
  }

  if (c_parse_uri(newuri, NULL, NULL, NULL, NULL, NULL, &tmp) < 0) {
    goto out;
  }

  newpath = sftp_canonicalize_path(_sftp_session, tmp);
  SAFE_FREE(tmp);
  if (newpath == NULL) {
      goto out;
  }

  /* FIXME: workaround cause, sftp_rename can't overwrite */
  sftp_unlink(_sftp_session, newpath);
  rc = sftp_rename(_sftp_session, oldpath, newpath);
  if (rc < 0) {
    errno = _sftp_portable_to_errno(sftp_get_error(_sftp_session));
  }

out:
  SAFE_FREE(oldpath);
  SAFE_FREE(newpath);

  return rc;
}

static int _sftp_unlink(const char *uri) {
  char *path;
  int rc;

  path = sftp_connect_uri(uri);
  if (path == NULL) {
    return -1;
  }

  rc = sftp_unlink(_sftp_session, path);
  if (rc < 0) {
    errno = _sftp_portable_to_errno(sftp_get_error(_sftp_session));
  }

  SAFE_FREE(path);
  return rc;
}

static int _sftp_chmod(const char *uri, mode_t mode) {
  struct sftp_attributes_struct attrs;
  char *path;
  int rc;

  path = sftp_connect_uri(uri);
  if (path == NULL) {
    return -1;
  }

  ZERO_STRUCT(attrs);
  attrs.permissions = mode;
  attrs.flags |= SSH_FILEXFER_ATTR_PERMISSIONS;

  rc = sftp_setstat(_sftp_session, path, &attrs);
  if (rc < 0) {
    errno = _sftp_portable_to_errno(sftp_get_error(_sftp_session));
  }

  SAFE_FREE(path);
  return rc;
}

static int _sftp_chown(const char *uri, uid_t owner, gid_t group) {
  struct sftp_attributes_struct attrs;
  char *path;
  int rc;

  path = sftp_connect_uri(uri);
  if (path == NULL) {
    return -1;
  }

  ZERO_STRUCT(attrs);
  attrs.uid = owner;
  attrs.gid = group;
  attrs.flags |= SSH_FILEXFER_ATTR_OWNERGROUP;

  rc = sftp_setstat(_sftp_session, path, &attrs);
  if (rc < 0) {
    errno = _sftp_portable_to_errno(sftp_get_error(_sftp_session));
  }

  SAFE_FREE(path);
  return rc;
}

static int _sftp_utimes(const char *uri, const struct timeval *times) {
  struct sftp_attributes_struct attrs;
  char *path;
  int rc;

  path = sftp_connect_uri(uri);
  if (path == NULL) {
    return -1;
  }

  ZERO_STRUCT(attrs);
  attrs.atime = times[0].tv_sec;
  attrs.atime_nseconds = times[0].tv_usec;

  attrs.mtime = times[1].tv_sec;
  attrs.mtime_nseconds = times[1].tv_usec;
  attrs.flags |= SSH_FILEXFER_ATTR_ACCESSTIME | SSH_FILEXFER_ATTR_MODIFYTIME;

  rc = sftp_setstat(_sftp_session, path, &attrs);
  if (rc < 0) {
    errno = _sftp_portable_to_errno(sftp_get_error(_sftp_session));
  }

  SAFE_FREE(path);
  return rc;
}

static struct csync_vio_capabilities_s _sftp_capabilities = {
    .atomar_copy_support = false
};

static struct csync_vio_capabilities_s *_sftp_get_capabilities(void)
{
    return &_sftp_capabilities;
}

csync_vio_method_t _method = {
  .method_table_size = sizeof(csync_vio_method_t),
  .get_capabilities = _sftp_get_capabilities,
  .open = _sftp_open,
  .creat = _sftp_creat,
  .close = _sftp_close,
  .read = _sftp_read,
  .write = _sftp_write,
  .lseek = _sftp_lseek,
  .opendir = _sftp_opendir,
  .closedir = _sftp_closedir,
  .readdir = _sftp_readdir,
  .mkdir = _sftp_mkdir,
  .rmdir = _sftp_rmdir,
  .stat = _sftp_stat,
  .rename = _sftp_rename,
  .unlink = _sftp_unlink,
  .chmod = _sftp_chmod,
  .chown = _sftp_chown,
  .utimes = _sftp_utimes
};

csync_vio_method_t *vio_module_init(const char *method_name, const char *args,
    csync_auth_callback cb, void *userdata) {
  DEBUG_SFTP(("csync_sftp - method_name: %s\n", method_name));
  DEBUG_SFTP(("csync_sftp - args: %s\n", args));

  (void) method_name;
  (void) args;

  _authcb = cb;
  _userdata = userdata;

  return &_method;
}

void vio_module_shutdown(csync_vio_method_t *method) {
  (void) method;

  if (_sftp_session) {
    sftp_free(_sftp_session);
  }
  if (_ssh_session) {
    ssh_disconnect(_ssh_session);
  }
  if (_ssh_callbacks) {
    free(_ssh_callbacks);
  }

  ssh_finalize();
}