File: ssh.c

package info (click to toggle)
libguestfs 1%3A1.40.2-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 123,660 kB
  • sloc: ansic: 460,074; ml: 63,059; sh: 14,955; java: 9,512; makefile: 9,133; cs: 6,300; haskell: 5,652; python: 3,856; perl: 3,619; erlang: 2,435; xml: 1,683; ruby: 350; pascal: 255; lex: 135; yacc: 128; cpp: 10
file content (1203 lines) | stat: -rw-r--r-- 35,549 bytes parent folder | download
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
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
/* virt-p2v
 * Copyright (C) 2009-2019 Red Hat 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

/**
 * This file handles the ssh connections to the conversion server.
 *
 * virt-p2v will open several connections over the lifetime of
 * the conversion process.
 *
 * In C<test_connection>, it will first open a connection (to check it
 * is possible) and query virt-v2v on the server to ensure it exists,
 * it is the right version, and so on.  This connection is then
 * closed, because in the GUI case we don't want to deal with keeping
 * it alive in case the administrator has set up an autologout.
 *
 * Once we start conversion, we will open a control connection to send
 * the libvirt configuration data and to start up virt-v2v, and we
 * will open up one data connection per local hard disk.  The data
 * connection(s) have a reverse port forward to the local NBD server
 * which is serving the content of that hard disk.  The remote port
 * for each data connection is assigned by ssh.  See
 * C<open_data_connection> and C<start_remote_conversion>.
 */

#include <config.h>

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <inttypes.h>
#include <unistd.h>
#include <errno.h>
#include <error.h>
#include <locale.h>
#include <assert.h>
#include <libintl.h>
#include <sys/types.h>
#include <sys/wait.h>

#include "ignore-value.h"
#include "getprogname.h"

#include "miniexpect.h"
#include "p2v.h"

#define SSH_TIMEOUT 60          /* seconds */

char *v2v_version = NULL;
char **input_drivers = NULL;
char **output_drivers = NULL;

static char *ssh_error;

static void set_ssh_error (const char *fs, ...)
  __attribute__((format(printf,1,2)));

static void
set_ssh_error (const char *fs, ...)
{
  va_list args;
  char *msg;
  int len;

  va_start (args, fs);
  len = vasprintf (&msg, fs, args);
  va_end (args);

  if (len < 0)
    error (EXIT_FAILURE, errno,
           "vasprintf (original error format string: %s)", fs);

  free (ssh_error);
  ssh_error = msg;
}

const char *
get_ssh_error (void)
{
  return ssh_error;
}

/* Like set_ssh_error, but for errors that aren't supposed to happen. */
#define set_ssh_internal_error(fs, ...)				   \
  set_ssh_error ("%s:%d: internal error: " fs, __FILE__, __LINE__, \
		 ##__VA_ARGS__)
#define set_ssh_mexp_error(fn) \
  set_ssh_internal_error ("%s: %m", fn)
#define set_ssh_pcre_error() \
  set_ssh_internal_error ("pcre error: %d\n", mexp_get_pcre_error (h))

#define set_ssh_unexpected_eof(fs, ...)                               \
  set_ssh_error ("remote server closed the connection unexpectedly, " \
                 "waiting for: " fs, ##__VA_ARGS__)
#define set_ssh_unexpected_timeout(fs, ...)               \
  set_ssh_error ("remote server timed out unexpectedly, " \
                 "waiting for: " fs, ##__VA_ARGS__)

static void compile_regexps (void) __attribute__((constructor));
static void free_regexps (void) __attribute__((destructor));

static pcre *password_re;
static pcre *ssh_message_re;
static pcre *sudo_password_re;
static pcre *prompt_re;
static pcre *version_re;
static pcre *feature_libguestfs_rewrite_re;
static pcre *feature_colours_option_re;
static pcre *feature_input_re;
static pcre *feature_output_re;
static pcre *portfwd_re;

static void
compile_regexps (void)
{
  const char *err;
  int offset;
  int p;

  /* These regexps are always used for partial matching.  In pcre < 8
   * there were limitations on the regexps possible for partial
   * matching, so fail if that is true here.  In pcre >= 8, all
   * regexps can be used in a partial match.
   */
#ifdef PCRE_INFO_OKPARTIAL
#define CHECK_PARTIAL_OK(pattern, re)					\
  do {									\
    pcre_fullinfo ((re), NULL, PCRE_INFO_OKPARTIAL, &p);		\
    if (p != 1) {							\
      fprintf (stderr, "%s: %s:%d: internal error: pattern '%s' cannot be used for partial matching\n", \
	       getprogname (),				\
	       __FILE__, __LINE__, (pattern));				\
      abort ();								\
    }									\
  } while (0)
#else
#define CHECK_PARTIAL_OK(pattern, re) /* skip check */
#endif

#define COMPILE(re,pattern,options)                                     \
  do {                                                                  \
    re = pcre_compile ((pattern), (options), &err, &offset, NULL);      \
    if (re == NULL) {                                                   \
      ignore_value (write (2, err, strlen (err)));                      \
      abort ();                                                         \
    }                                                                   \
    CHECK_PARTIAL_OK ((pattern), re);					\
  } while (0)

  COMPILE (password_re, "password:", 0);
  /* Note that (?:.)* is required in order to work around a problem
   * with partial matching and PCRE in RHEL 5.
   */
  COMPILE (ssh_message_re, "(ssh: (?:.)*)", 0);
  COMPILE (sudo_password_re, "sudo: a password is required", 0);
  /* The magic synchronization strings all match this expression.  See
   * start_ssh function below.
   */
  COMPILE (prompt_re,
	   "###((?:[0123456789abcdefghijklmnopqrstuvwxyz]){8})### ", 0);
  /* Note that (?:.)* is required in order to work around a problem
   * with partial matching and PCRE in RHEL 5.
   */
  COMPILE (version_re,
           "virt-v2v ([1-9](?:.)*)",
	   0);
  COMPILE (feature_libguestfs_rewrite_re, "libguestfs-rewrite", 0);
  COMPILE (feature_colours_option_re, "colours-option", 0);
  /* The input and output regexps must match the same pattern in
   * v2v/modules_list.ml.
   */
  COMPILE (feature_input_re, "input:((?:[-\\w])+)", 0);
  COMPILE (feature_output_re, "output:((?:[-\\w])+)", 0);
  COMPILE (portfwd_re, "Allocated port ((?:\\d)+) for remote forward", 0);
}

static void
free_regexps (void)
{
  pcre_free (password_re);
  pcre_free (ssh_message_re);
  pcre_free (sudo_password_re);
  pcre_free (prompt_re);
  pcre_free (version_re);
  pcre_free (feature_libguestfs_rewrite_re);
  pcre_free (feature_colours_option_re);
  pcre_free (feature_input_re);
  pcre_free (feature_output_re);
  pcre_free (portfwd_re);
}

/**
 * Download URL to local file using the external 'curl' command.
 */
static int
curl_download (const char *url, const char *local_file)
{
  char curl_config_file[] = "/tmp/curl.XXXXXX";
  char error_file[] = "/tmp/curlerr.XXXXXX";
  CLEANUP_FREE char *error_message = NULL;
  int fd, r;
  size_t i, len;
  FILE *fp;
  CLEANUP_FREE char *curl_cmd = NULL;

  fd = mkstemp (error_file);
  if (fd == -1)
    error (EXIT_FAILURE, errno, "mkstemp: %s", error_file);
  close (fd);

  /* Use a secure curl config file because escaping is easier. */
  fd = mkstemp (curl_config_file);
  if (fd == -1)
    error (EXIT_FAILURE, errno, "mkstemp: %s", curl_config_file);
  fp = fdopen (fd, "w");
  if (fp == NULL)
    error (EXIT_FAILURE, errno, "fdopen: %s", curl_config_file);
  fprintf (fp, "url = \"");
  len = strlen (url);
  for (i = 0; i < len; ++i) {
    switch (url[i]) {
    case '\\': fprintf (fp, "\\\\"); break;
    case '"':  fprintf (fp, "\\\""); break;
    case '\t': fprintf (fp, "\\t");  break;
    case '\n': fprintf (fp, "\\n");  break;
    case '\r': fprintf (fp, "\\r");  break;
    case '\v': fprintf (fp, "\\v");  break;
    default:   fputc (url[i], fp);
    }
  }
  fprintf (fp, "\"\n");
  fclose (fp);

  /* Run curl to download the URL to a file. */
  if (asprintf (&curl_cmd, "curl -f -s -S -o %s -K %s 2>%s",
                local_file, curl_config_file, error_file) == -1)
    error (EXIT_FAILURE, errno, "asprintf");

  r = system (curl_cmd);
  /* unlink (curl_config_file); - useful for debugging */
  if (r == -1)
    error (EXIT_FAILURE, errno, "system: %s", curl_cmd);

  /* Did curl subprocess fail? */
  if (WIFEXITED (r) && WEXITSTATUS (r) != 0) {
    if (read_whole_file (error_file, &error_message, NULL) == 0)
      set_ssh_error ("%s: %s", url, error_message);
    else
      set_ssh_error ("%s: curl error %d", url, WEXITSTATUS (r));
    unlink (error_file);
    return -1;
  }
  else if (!WIFEXITED (r)) {
    set_ssh_internal_error ("curl subprocess got a signal (%d)", r);
    unlink (error_file);
    return -1;
  }

  unlink (error_file);
  return 0;
}

/**
 * Re-cache the C<config-E<gt>identity.url> if needed.
 */
static int
cache_ssh_identity (struct config *config)
{
  int fd;

  /* If it doesn't need downloading, return. */
  if (config->auth.identity.url == NULL ||
      !config->auth.identity.file_needs_update)
    return 0;

  /* Generate a random filename. */
  free (config->auth.identity.file);
  config->auth.identity.file = strdup ("/tmp/id.XXXXXX");
  if (config->auth.identity.file == NULL)
    error (EXIT_FAILURE, errno, "strdup");
  fd = mkstemp (config->auth.identity.file);
  if (fd == -1)
    error (EXIT_FAILURE, errno, "mkstemp");
  close (fd);

  /* Curl download URL to file. */
  if (curl_download (config->auth.identity.url, config->auth.identity.file) == -1) {
    free (config->auth.identity.file);
    config->auth.identity.file = NULL;
    config->auth.identity.file_needs_update = 1;
    return -1;
  }

  return 0;
}

/* GCC complains about the argv array in the next function which it
 * thinks might grow to an unbounded size.  Since we control
 * extra_args, this is not in fact a problem.
 */
#if defined(__GNUC__) && GUESTFS_GCC_VERSION >= 40800 /* gcc >= 4.8.0 */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstack-usage="
#endif

/**
 * Start ssh subprocess with the standard arguments and possibly some
 * optional arguments.  Also handles authentication.
 */
static mexp_h *
start_ssh (unsigned spawn_flags, struct config *config,
           char **extra_args, int wait_prompt)
{
  size_t i = 0;
  const size_t MAX_ARGS =
    64 + (extra_args != NULL ? guestfs_int_count_strings (extra_args) : 0);
  const char *argv[MAX_ARGS];
  char port_str[64];
  char connect_timeout_str[128];
  mexp_h *h;
  const int ovecsize = 12;
  int ovector[ovecsize];
  int saved_timeout;
  int using_password_auth;
  size_t count;

  if (cache_ssh_identity (config) == -1)
    return NULL;

  /* Are we using password or identity authentication? */
  using_password_auth = config->auth.identity.file == NULL;

  ADD_ARG (argv, i, "ssh");
  ADD_ARG (argv, i, "-p");      /* Port. */
  snprintf (port_str, sizeof port_str, "%d", config->remote.port);
  ADD_ARG (argv, i, port_str);
  ADD_ARG (argv, i, "-l");      /* Username. */
  ADD_ARG (argv, i, config->auth.username ? config->auth.username : "root");
  ADD_ARG (argv, i, "-o");      /* Host key will always be novel. */
  ADD_ARG (argv, i, "StrictHostKeyChecking=no");
  ADD_ARG (argv, i, "-o");      /* ConnectTimeout */
  snprintf (connect_timeout_str, sizeof connect_timeout_str,
            "ConnectTimeout=%d", SSH_TIMEOUT);
  ADD_ARG (argv, i, connect_timeout_str);
  ADD_ARG (argv, i, "-o");      /* Send ping packets every 5 mins to sshd. */
  ADD_ARG (argv, i, "ServerAliveInterval=300");
  ADD_ARG (argv, i, "-o");
  ADD_ARG (argv, i, "ServerAliveCountMax=6");
  if (using_password_auth) {
    /* Only use password authentication. */
    ADD_ARG (argv, i, "-o");
    ADD_ARG (argv, i, "PreferredAuthentications=keyboard-interactive,password");
  }
  else {
    /* Use identity file (private key). */
    ADD_ARG (argv, i, "-o");
    ADD_ARG (argv, i, "PreferredAuthentications=publickey");
    ADD_ARG (argv, i, "-i");
    ADD_ARG (argv, i, config->auth.identity.file);
  }
  if (extra_args != NULL) {
    for (size_t j = 0; extra_args[j] != NULL; ++j)
      ADD_ARG (argv, i, extra_args[j]);
  }
  ADD_ARG (argv, i, config->remote.server); /* Conversion server. */
  ADD_ARG (argv, i, NULL);

#if DEBUG_STDERR
  fputs ("ssh command: ", stderr);
  for (i = 0; argv[i] != NULL; ++i) {
    if (i > 0) fputc (' ', stderr);
    fputs (argv[i], stderr);
  }
  fputc ('\n', stderr);
#endif

  /* Create the miniexpect handle. */
  h = mexp_spawnvf (spawn_flags, "ssh", (char **) argv);
  if (h == NULL) {
    set_ssh_internal_error ("ssh: mexp_spawnvf: %m");
    return NULL;
  }
#if DEBUG_STDERR
  mexp_set_debug_file (h, stderr);
#endif

  /* We want the ssh ConnectTimeout to be less than the miniexpect
   * timeout, so that if the server is completely unresponsive we
   * still see the error from ssh, not a timeout from miniexpect.  The
   * obvious solution to this is to set ConnectTimeout (above) and to
   * set the miniexpect timeout to be a little bit larger.
   */
  mexp_set_timeout (h, SSH_TIMEOUT + 20);

  if (using_password_auth &&
      config->auth.password && strlen (config->auth.password) > 0) {
    CLEANUP_FREE char *ssh_message = NULL;

    /* Wait for the password prompt. */
  wait_password_again:
    switch (mexp_expect (h,
                         (mexp_regexp[]) {
                           { 100, .re = password_re },
                           { 101, .re = ssh_message_re },
                           { 0 }
                         }, ovector, ovecsize)) {
    case 100:                   /* Got password prompt. */
      if (mexp_printf_password (h, "%s", config->auth.password) == -1 ||
          mexp_printf (h, "\n") == -1) {
        set_ssh_mexp_error ("mexp_printf");
        mexp_close (h);
        return NULL;
      }
      break;

    case 101:
      free (ssh_message);
      ssh_message = strndup (&h->buffer[ovector[2]], ovector[3]-ovector[2]);
      goto wait_password_again;

    case MEXP_EOF:
      /* This is where we get to if the user enters an incorrect or
       * impossible hostname or port number.  Hopefully ssh printed an
       * error message, and we picked it up and put it in
       * 'ssh_message' in case 101 above.  If not we have to print a
       * generic error instead.
       */
      if (ssh_message)
        set_ssh_error ("%s", ssh_message);
      else
        set_ssh_error ("ssh closed the connection without printing an error.");
      mexp_close (h);
      return NULL;

    case MEXP_TIMEOUT:
      set_ssh_unexpected_timeout ("password prompt");
      mexp_close (h);
      return NULL;

    case MEXP_ERROR:
      set_ssh_mexp_error ("mexp_expect");
      mexp_close (h);
      return NULL;

    case MEXP_PCRE_ERROR:
      set_ssh_pcre_error ();
      mexp_close (h);
      return NULL;
    }
  }

  if (!wait_prompt)
    return h;

  /* Ensure we are running bash, set environment variables, and
   * synchronize with the command prompt and set it to a known
   * string.  There are multiple issues being solved here:
   *
   * We cannot control the initial shell prompt.  It would involve
   * changing the remote SSH configuration (AcceptEnv).  However what
   * we can do is to repeatedly send 'export PS1=<magic>' commands
   * until we synchronize with the remote shell.
   *
   * Since we parse error messages, we must set LANG=C.
   *
   * We don't know if the user is using a Bourne-like shell (eg sh,
   * bash) or csh/tcsh.  Setting environment variables works
   * differently.
   *
   * We don't know how command line editing is set up
   * (https://bugzilla.redhat.com/1314244#c9).
   */
  if (mexp_printf (h, "exec bash --noediting --noprofile\n") == -1) {
    set_ssh_mexp_error ("mexp_printf");
    mexp_close (h);
    return NULL;
  }

  saved_timeout = mexp_get_timeout_ms (h);
  mexp_set_timeout (h, 2);

  for (count = 0; count < 30; ++count) {
    char magic[9];
    const char *matched;
    int r;

    if (guestfs_int_random_string (magic, 8) == -1) {
      set_ssh_internal_error ("random_string: %m");
      mexp_close (h);
      return NULL;
    }

    /* The purpose of the '' inside the string is to ensure we don't
     * mistake the command echo for the prompt.
     */
    if (mexp_printf (h, "export LANG=C PS1='###''%s''### '\n", magic) == -1) {
      set_ssh_mexp_error ("mexp_printf");
      mexp_close (h);
      return NULL;
    }

    /* Wait for the prompt. */
  wait_again:
    switch (mexp_expect (h,
                         (mexp_regexp[]) {
                           { 100, .re = password_re },
                           { 101, .re = prompt_re },
                           { 0 }
                         }, ovector, ovecsize)) {
    case 100:                    /* Got password prompt unexpectedly. */
      set_ssh_error ("Login failed.  Probably the username and/or password is wrong.");
      mexp_close (h);
      return NULL;

    case 101:
      /* Got a prompt.  However it might be an earlier prompt.  If it
       * doesn't match the PS1 string we sent, then repeat the expect.
       */
      r = pcre_get_substring (h->buffer, ovector,
                              mexp_get_pcre_error (h), 1, &matched);
      if (r < 0)
        error (EXIT_FAILURE, 0, "pcre error reading substring (%d)", r);
      r = STREQ (magic, matched);
      pcre_free_substring (matched);
      if (!r)
        goto wait_again;
      goto got_prompt;

    case MEXP_EOF:
      set_ssh_unexpected_eof ("the command prompt");
      mexp_close (h);
      return NULL;

    case MEXP_TIMEOUT:
      /* Timeout here is not an error, since ssh may "eat" commands that
       * we send before the shell at the other end is ready.  Just loop.
       */
      break;

    case MEXP_ERROR:
      set_ssh_mexp_error ("mexp_expect");
      mexp_close (h);
      return NULL;

    case MEXP_PCRE_ERROR:
      set_ssh_pcre_error ();
      mexp_close (h);
      return NULL;
    }
  }

  set_ssh_error ("Failed to synchronize with remote shell after 60 seconds.");
  mexp_close (h);
  return NULL;

 got_prompt:
  mexp_set_timeout_ms (h, saved_timeout);

  return h;
}

#if defined(__GNUC__) && GUESTFS_GCC_VERSION >= 40800 /* gcc >= 4.8.0 */
#pragma GCC diagnostic pop
#endif

/**
 * Upload file(s) to remote using L<scp(1)>.
 *
 * Note that the target (directory or file) comes before the list of
 * local files, because the list of local files is a varargs list.
 *
 * This is a simplified version of L</start_ssh> above.
 */
int
scp_file (struct config *config, const char *target, const char *local, ...)
{
  size_t i = 0;
  va_list args;
  const size_t MAX_ARGS = 64;
  const char *argv[MAX_ARGS];
  char port_str[64];
  char connect_timeout_str[128];
  CLEANUP_FREE char *remote = NULL;
  mexp_h *h;
  const int ovecsize = 12;
  int ovector[ovecsize];
  int using_password_auth;

  if (cache_ssh_identity (config) == -1)
    return -1;

  /* Are we using password or identity authentication? */
  using_password_auth = config->auth.identity.file == NULL;

  ADD_ARG (argv, i, "scp");
  ADD_ARG (argv, i, "-P");      /* Port. */
  snprintf (port_str, sizeof port_str, "%d", config->remote.port);
  ADD_ARG (argv, i, port_str);
  ADD_ARG (argv, i, "-o");      /* Host key will always be novel. */
  ADD_ARG (argv, i, "StrictHostKeyChecking=no");
  ADD_ARG (argv, i, "-o");      /* ConnectTimeout */
  snprintf (connect_timeout_str, sizeof connect_timeout_str,
            "ConnectTimeout=%d", SSH_TIMEOUT);
  ADD_ARG (argv, i, connect_timeout_str);
  if (using_password_auth) {
    /* Only use password authentication. */
    ADD_ARG (argv, i, "-o");
    ADD_ARG (argv, i, "PreferredAuthentications=keyboard-interactive,password");
  }
  else {
    /* Use identity file (private key). */
    ADD_ARG (argv, i, "-o");
    ADD_ARG (argv, i, "PreferredAuthentications=publickey");
    ADD_ARG (argv, i, "-i");
    ADD_ARG (argv, i, config->auth.identity.file);
  }

  /* Source files or directories.
   * Strictly speaking this could abort() if the list of files is
   * too long, but that never happens in virt-p2v. XXX
   */
  va_start (args, local);
  do ADD_ARG (argv, i, local);
  while ((local = va_arg (args, const char *)) != NULL);
  va_end (args);

  /* The target file or directory.  We need to rewrite this as
   * "username@server:target".
   */
  if (asprintf (&remote, "%s@%s:%s",
                config->auth.username ? config->auth.username : "root",
                config->remote.server, target) == -1)
    error (EXIT_FAILURE, errno, "asprintf");
  ADD_ARG (argv, i, remote);

  ADD_ARG (argv, i, NULL);

#if DEBUG_STDERR
  fputs ("scp command: ", stderr);
  for (i = 0; argv[i] != NULL; ++i) {
    if (i > 0) fputc (' ', stderr);
    fputs (argv[i], stderr);
  }
  fputc ('\n', stderr);
#endif

  /* Create the miniexpect handle. */
  h = mexp_spawnv ("scp", (char **) argv);
  if (h == NULL) {
    set_ssh_internal_error ("scp: mexp_spawnv: %m");
    return -1;
  }
#if DEBUG_STDERR
  mexp_set_debug_file (h, stderr);
#endif

  /* We want the ssh ConnectTimeout to be less than the miniexpect
   * timeout, so that if the server is completely unresponsive we
   * still see the error from ssh, not a timeout from miniexpect.  The
   * obvious solution to this is to set ConnectTimeout (above) and to
   * set the miniexpect timeout to be a little bit larger.
   */
  mexp_set_timeout (h, SSH_TIMEOUT + 20);

  if (using_password_auth &&
      config->auth.password && strlen (config->auth.password) > 0) {
    CLEANUP_FREE char *ssh_message = NULL;

    /* Wait for the password prompt. */
  wait_password_again:
    switch (mexp_expect (h,
                         (mexp_regexp[]) {
                           { 100, .re = password_re },
                           { 101, .re = ssh_message_re },
                           { 0 }
                         }, ovector, ovecsize)) {
    case 100:                   /* Got password prompt. */
      if (mexp_printf_password (h, "%s", config->auth.password) == -1 ||
          mexp_printf (h, "\n") == -1) {
        set_ssh_mexp_error ("mexp_printf");
        mexp_close (h);
        return -1;
      }
      break;

    case 101:
      free (ssh_message);
      ssh_message = strndup (&h->buffer[ovector[2]], ovector[3]-ovector[2]);
      goto wait_password_again;

    case MEXP_EOF:
      /* This is where we get to if the user enters an incorrect or
       * impossible hostname or port number.  Hopefully scp printed an
       * error message, and we picked it up and put it in
       * 'ssh_message' in case 101 above.  If not we have to print a
       * generic error instead.
       */
      if (ssh_message)
        set_ssh_error ("%s", ssh_message);
      else
        set_ssh_error ("scp closed the connection without printing an error.");
      mexp_close (h);
      return -1;

    case MEXP_TIMEOUT:
      set_ssh_unexpected_timeout ("password prompt");
      mexp_close (h);
      return -1;

    case MEXP_ERROR:
      set_ssh_mexp_error ("mexp_expect");
      mexp_close (h);
      return -1;

    case MEXP_PCRE_ERROR:
      set_ssh_pcre_error ();
      mexp_close (h);
      return -1;
    }
  }

  /* Wait for the scp subprocess to finish. */
  switch (mexp_expect (h, NULL, NULL, 0)) {
  case MEXP_EOF:
    break;

  case MEXP_TIMEOUT:
    set_ssh_unexpected_timeout ("copying (scp) file");
    mexp_close (h);
    return -1;

  case MEXP_ERROR:
    set_ssh_mexp_error ("mexp_expect");
    mexp_close (h);
    return -1;

  case MEXP_PCRE_ERROR:
    set_ssh_pcre_error ();
    mexp_close (h);
    return -1;
  }

  if (mexp_close (h) == -1) {
    set_ssh_internal_error ("scp: mexp_close: %m");
    return -1;
  }

  return 0;
}

static void add_input_driver (const char *name, size_t len);
static void add_output_driver (const char *name, size_t len);
static int compatible_version (const char *v2v_version);

#pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn" /* WTF? */
int
test_connection (struct config *config)
{
  mexp_h *h;
  CLEANUP_FREE char *major_str = NULL, *minor_str = NULL, *release_str = NULL;
  int feature_libguestfs_rewrite = 0;
  int status;
  const int ovecsize = 12;
  int ovector[ovecsize];

  h = start_ssh (0, config, NULL, 1);
  if (h == NULL)
    return -1;

  /* Clear any previous version information since we may be connecting
   * to a different server.
   */
  free (v2v_version);
  v2v_version = NULL;

  /* Send 'virt-v2v --version' command and hope we get back a version string.
   * Note old virt-v2v did not understand -V option.
   */
  if (mexp_printf (h,
                   "%svirt-v2v --version\n",
                   config->auth.sudo ? "sudo -n " : "") == -1) {
    set_ssh_mexp_error ("mexp_printf");
    mexp_close (h);
    return -1;
  }

  for (;;) {
    switch (mexp_expect (h,
                         (mexp_regexp[]) {
                           { 100, .re = version_re },
                           { 101, .re = sudo_password_re },
                           { 102, .re = prompt_re },
                           { 0 }
                         }, ovector, ovecsize)) {
    case 100:                   /* Got version string. */
      free (v2v_version);
      v2v_version = strndup (&h->buffer[ovector[2]], ovector[3]-ovector[2]);
#if DEBUG_STDERR
      fprintf (stderr, "%s: remote virt-v2v version: %s\n",
               getprogname (), v2v_version);
#endif
      break;

    case 101:
      set_ssh_error ("sudo for user \"%s\" requires a password.  Edit /etc/sudoers on the conversion server to ensure the \"NOPASSWD:\" option is set for this user.",
                     config->auth.username);
      mexp_close (h);
      return -1;

    case 102:             /* Got the prompt. */
      goto end_of_version;

    case MEXP_EOF:
      set_ssh_unexpected_eof ("\"virt-v2v --version\" output");
      mexp_close (h);
      return -1;

    case MEXP_TIMEOUT:
      set_ssh_unexpected_timeout ("\"virt-v2v --version\" output");
      mexp_close (h);
      return -1;

    case MEXP_ERROR:
      set_ssh_mexp_error ("mexp_expect");
      mexp_close (h);
      return -1;

    case MEXP_PCRE_ERROR:
      set_ssh_pcre_error ();
      mexp_close (h);
      return -1;
    }
  }
 end_of_version:

  /* Got the prompt but no version number. */
  if (v2v_version == NULL) {
    set_ssh_error ("virt-v2v is not installed on the conversion server, "
                   "or it might be a too old version.");
    mexp_close (h);
    return -1;
  }

  /* Check the version of virt-v2v is compatible with virt-p2v. */
  if (!compatible_version (v2v_version)) {
    mexp_close (h);
    return -1;
  }

  /* Clear any previous driver information since we may be connecting
   * to a different server.
   */
  guestfs_int_free_string_list (input_drivers);
  guestfs_int_free_string_list (output_drivers);
  input_drivers = output_drivers = NULL;

  /* Get virt-v2v features.  See: v2v/cmdline.ml */
  if (mexp_printf (h, "%svirt-v2v --machine-readable\n",
                   config->auth.sudo ? "sudo -n " : "") == -1) {
    set_ssh_mexp_error ("mexp_printf");
    mexp_close (h);
    return -1;
  }

  for (;;) {
    switch (mexp_expect (h,
                         (mexp_regexp[]) {
                           { 100, .re = feature_libguestfs_rewrite_re },
                           { 101, .re = feature_colours_option_re },
                           { 102, .re = feature_input_re },
                           { 103, .re = feature_output_re },
                           { 104, .re = prompt_re },
                           { 0 }
                         }, ovector, ovecsize)) {
    case 100:                   /* libguestfs-rewrite. */
      feature_libguestfs_rewrite = 1;
      break;

    case 101:                   /* virt-v2v supports --colours option */
#if DEBUG_STDERR
  fprintf (stderr, "%s: remote virt-v2v supports --colours option\n",
           getprogname ());
#endif
      feature_colours_option = 1;
      break;

    case 102:
      /* input:<driver-name> corresponds to an -i option in virt-v2v. */
      add_input_driver (&h->buffer[ovector[2]],
                        (size_t) (ovector[3]-ovector[2]));
      break;

    case 103:
      /* output:<driver-name> corresponds to an -o option in virt-v2v. */
      add_output_driver (&h->buffer[ovector[2]],
                         (size_t) (ovector[3]-ovector[2]));
      break;

    case 104:                   /* Got prompt, so end of output. */
      goto end_of_machine_readable;

    case MEXP_EOF:
      set_ssh_unexpected_eof ("\"virt-v2v --machine-readable\" output");
      mexp_close (h);
      return -1;

    case MEXP_TIMEOUT:
      set_ssh_unexpected_timeout ("\"virt-v2v --machine-readable\" output");
      mexp_close (h);
      return -1;

    case MEXP_ERROR:
      set_ssh_mexp_error ("mexp_expect");
      mexp_close (h);
      return -1;

    case MEXP_PCRE_ERROR:
      set_ssh_pcre_error ();
      mexp_close (h);
      return -1;
    }
  }
 end_of_machine_readable:

  if (!feature_libguestfs_rewrite) {
    set_ssh_error ("Invalid output of \"virt-v2v --machine-readable\" command.");
    mexp_close (h);
    return -1;
  }

  /* Test finished, shut down ssh. */
  if (mexp_printf (h, "exit\n") == -1) {
    set_ssh_mexp_error ("mexp_printf");
    mexp_close (h);
    return -1;
  }

  switch (mexp_expect (h, NULL, NULL, 0)) {
  case MEXP_EOF:
    break;

  case MEXP_TIMEOUT:
    set_ssh_unexpected_timeout ("end of ssh session");
    mexp_close (h);
    return -1;

  case MEXP_ERROR:
    set_ssh_mexp_error ("mexp_expect");
    mexp_close (h);
    return -1;

  case MEXP_PCRE_ERROR:
    set_ssh_pcre_error ();
    mexp_close (h);
    return -1;
  }

  status = mexp_close (h);
  if (status == -1) {
    set_ssh_internal_error ("mexp_close: %m");
    return -1;
  }
  if (WIFSIGNALED (status) && WTERMSIG (status) == SIGHUP)
    return 0; /* not an error */
  if (!WIFEXITED (status) || WEXITSTATUS (status) != 0) {
    set_ssh_internal_error ("unexpected close status from ssh subprocess (%d)",
                            status);
    return -1;
  }
  return 0;
}

static void
add_option (const char *type, char ***drivers, const char *name, size_t len)
{
  size_t n;

  if (*drivers == NULL)
    n = 0;
  else
    n = guestfs_int_count_strings (*drivers);

  n++;

  *drivers = realloc (*drivers, (n+1) * sizeof (char *));
  if (*drivers == NULL)
    error (EXIT_FAILURE, errno, "malloc");

  (*drivers)[n-1] = strndup (name, len);
  if ((*drivers)[n-1] == NULL)
    error (EXIT_FAILURE, errno, "strndup");
  (*drivers)[n] = NULL;

#if DEBUG_STDERR
  fprintf (stderr, "%s: remote virt-v2v supports %s driver %s\n",
           getprogname (), type, (*drivers)[n-1]);
#endif
}

static void
add_input_driver (const char *name, size_t len)
{
  add_option ("input", &input_drivers, name, len);
}

static void
add_output_driver (const char *name, size_t len)
{
  /* Ignore the 'vdsm' driver, since that should only be used by VDSM. */
  if (len != 4 || memcmp (name, "vdsm", 4) != 0)
    add_option ("output", &output_drivers, name, len);
}

static int
compatible_version (const char *v2v_version)
{
  unsigned v2v_minor;

  /* The major version must always be 1. */
  if (!STRPREFIX (v2v_version, "1.")) {
    set_ssh_error ("virt-v2v major version is not 1 (\"%s\"), "
                   "this version of virt-p2v is not compatible.",
                   v2v_version);
    return 0;
  }

  /* The version of virt-v2v must be >= 1.28, just to make sure
   * someone isn't (a) using one of the experimental 1.27 releases
   * that we published during development, nor (b) using old virt-v2v.
   * We should remain compatible with any virt-v2v after 1.28.
   */
  if (sscanf (v2v_version, "1.%u", &v2v_minor) != 1) {
    set_ssh_internal_error ("cannot parse virt-v2v version string (\"%s\")",
                            v2v_version);
    return 0;
  }

  if (v2v_minor < 28) {
    set_ssh_error ("virt-v2v version is < 1.28 (\"%s\"), "
                   "you must upgrade to virt-v2v >= 1.28 on "
                   "the conversion server.", v2v_version);
    return 0;
  }

  return 1;                     /* compatible */
}

mexp_h *
open_data_connection (struct config *config,
                      const char *local_ipaddr, int local_port,
                      int *remote_port)
{
  mexp_h *h;
  char remote_arg[32];
  const char *extra_args[] = {
    "-R", remote_arg,
    "-N",
    NULL
  };
  CLEANUP_FREE char *port_str = NULL;
  const int ovecsize = 12;
  int ovector[ovecsize];

  snprintf (remote_arg, sizeof remote_arg, "0:%s:%d", local_ipaddr, local_port);

  h = start_ssh (0, config, (char **) extra_args, 0);
  if (h == NULL)
    return NULL;

  switch (mexp_expect (h,
                       (mexp_regexp[]) {
                         { 100, .re = portfwd_re },
                         { 0 }
                       }, ovector, ovecsize)) {
  case 100:                     /* Ephemeral port. */
    port_str = strndup (&h->buffer[ovector[2]], ovector[3]-ovector[2]);
    if (port_str == NULL) {
      set_ssh_internal_error ("strndup: %m");
      mexp_close (h);
      return NULL;
    }
    if (sscanf (port_str, "%d", remote_port) != 1) {
      set_ssh_internal_error ("cannot extract the port number from '%s'",
                              port_str);
      mexp_close (h);
      return NULL;
    }
    break;

  case MEXP_EOF:
    set_ssh_unexpected_eof ("\"ssh -R\" output");
    mexp_close (h);
    return NULL;

  case MEXP_TIMEOUT:
    set_ssh_unexpected_timeout ("\"ssh -R\" output");
    mexp_close (h);
    return NULL;

  case MEXP_ERROR:
    set_ssh_mexp_error ("mexp_expect");
    mexp_close (h);
    return NULL;

  case MEXP_PCRE_ERROR:
    set_ssh_pcre_error ();
    mexp_close (h);
    return NULL;
  }

  return h;
}

/* Wait for the prompt. */
static int
wait_for_prompt (mexp_h *h)
{
  const int ovecsize = 12;
  int ovector[ovecsize];

  switch (mexp_expect (h,
                       (mexp_regexp[]) {
                         { 100, .re = prompt_re },
                         { 0 }
                       }, ovector, ovecsize)) {
  case 100:                     /* Got the prompt. */
    return 0;

  case MEXP_EOF:
    set_ssh_unexpected_eof ("command prompt");
    return -1;

  case MEXP_TIMEOUT:
    set_ssh_unexpected_timeout ("command prompt");
    return -1;

  case MEXP_ERROR:
    set_ssh_mexp_error ("mexp_expect");
    return -1;

  case MEXP_PCRE_ERROR:
    set_ssh_pcre_error ();
    return -1;
  }

  return 0;
}

mexp_h *
start_remote_connection (struct config *config, const char *remote_dir)
{
  mexp_h *h;

  /* This connection is opened in cooked mode so that we can send ^C
   * if the conversion needs to be cancelled.  However that also means
   * we must be careful not to accidentally send any control
   * characters over this connection at other times.
   */
  h = start_ssh (MEXP_SPAWN_COOKED_MODE, config, NULL, 1);
  if (h == NULL)
    return NULL;

  /* Create the remote directory. */
  if (mexp_printf (h, "mkdir %s\n", remote_dir) == -1) {
    set_ssh_mexp_error ("mexp_printf");
    goto error;
  }

  if (wait_for_prompt (h) == -1)
    goto error;

  /* It's simplest to create the remote 'time' file by running the date
   * command, as that won't send any special control characters.
   */
  if (mexp_printf (h, "date > %s/time\n", remote_dir) == -1) {
    set_ssh_mexp_error ("mexp_printf");
    goto error;
  }

  if (wait_for_prompt (h) == -1)
    goto error;

  return h;

 error:
  mexp_close (h);
  return NULL;
}