chiark / gitweb /
tcl: Update from 8.6.5 to 8.6.6
[termux-packages] / packages / mosh / mosh.cc
1 //   Mosh: the mobile shell
2 //   Copyright 2012 Keith Winstein
3 //
4 //   This program is free software: you can redistribute it and/or modify
5 //   it under the terms of the GNU General Public License as published by
6 //   the Free Software Foundation, either version 3 of the License, or
7 //   (at your option) any later version.
8 //
9 //   This program is distributed in the hope that it will be useful,
10 //   but WITHOUT ANY WARRANTY; without even the implied warranty of
11 //   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 //   GNU General Public License for more details.
13 //
14 //   You should have received a copy of the GNU General Public License
15 //   along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17 #include <limits.h>
18 #include <unistd.h>
19 #include <stdlib.h>
20 #include <stdarg.h>
21 #include <string.h>
22 #include <vector>
23 #include <map>
24 #include <stdio.h>
25 #include <string>
26 #include <sys/socket.h>
27 #include <getopt.h>
28 #include <arpa/inet.h>
29 #include <netdb.h>
30 #include <signal.h>
31 #include <errno.h>
32 #include <sys/ioctl.h>
33 #include <sys/types.h>
34 #include <sys/wait.h>
35 #include <termios.h>
36 #include <pty.h>
37
38 using namespace std;
39
40 inline string shell_quote_string( const string &x )
41 {
42   string result = "'";
43   string rest = x;
44   while ( rest.size() ) {
45     size_t good_part = rest.find( "'" );
46     result += rest.substr( 0, good_part );
47     if ( good_part != string::npos ) {
48       result += "'\\''";
49       rest = rest.substr( good_part + 1 );
50     } else {
51       break;
52     }
53   }
54   return result + "'";
55 }
56
57 template <typename SequenceT>
58 inline string shell_quote( const SequenceT &sequence )
59 {
60   string result;
61   for ( typename SequenceT::const_iterator i = sequence.begin();
62         i != sequence.end();
63         i++ ) {
64     result += shell_quote_string( *i ) + " ";
65   }
66   return result.substr( 0, result.size() - 1 );
67 }
68
69 void die( const char *format, ... ) {
70   va_list args;
71   va_start( args, format );
72   vfprintf( stderr, format, args );
73   va_end( args );
74   fprintf( stderr, "\n" );
75   exit( 255 );
76 }
77
78 static const char *usage_format =
79 "Usage: %s [options] [--] [user@]host [command...]\n"
80 "        --client=PATH        mosh client on local machine\n"
81 "                                (default: \"mosh-client\")\n"
82 "        --server=COMMAND     mosh server on remote machine\n"
83 "                                (default: \"mosh-server\")\n"
84 "\n"
85 "        --predict=adaptive      local echo for slower links [default]\n"
86 "-a      --predict=always        use local echo even on fast links\n"
87 "-n      --predict=never         never use local echo\n"
88 "\n"
89 "-p NUM  --port=NUM           server-side UDP port\n"
90 "\n"
91 "-P NUM  --ssh-port=NUM       ssh server port\n"
92 "                                (default: let the ssh command choose)\n"
93 "\n"
94 "        --ssh=COMMAND        ssh command to run when setting up session\n"
95 "                                (example: \"ssh -p 2222\")\n"
96 "                                (default: \"ssh\")\n"
97 "\n"
98 "        --no-init            do not send terminal initialization string\n"
99 "\n"
100 "        --help               this message\n"
101 "        --version            version and copyright information\n"
102 "\n"
103 "Please report bugs to mosh-devel@mit.edu.\n"
104 "Mosh home page: http://mosh.mit.edu";
105
106 static const char *version_format =
107 "mosh %s\n"
108 "Copyright 2012 Keith Winstein <mosh-devel@mit.edu>\n"
109 "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n"
110 "This is free software: you are free to change and redistribute it.\n"
111 "There is NO WARRANTY, to the extent permitted by law.";
112
113 static const char *key_valid_char_set =
114 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/+";
115
116 static char *argv0;
117
118 void predict_check( const string &predict, bool env_set )
119 {
120   if ( predict != "adaptive" &&
121        predict != "always" &&
122        predict != "never" ) {
123     fprintf( stderr, "%s: Unknown mode \"%s\"%s.\n", argv0, predict.c_str(),
124         env_set ? " (MOSH_PREDICTION_DISPLAY in environment)" : "" );
125     die( usage_format, argv0 );
126   }
127 }
128
129 void cat( int ifd, int ofd )
130 {
131   char buf[4096];
132   ssize_t n;
133   while ( 1 ) {
134     n = read( ifd, buf, sizeof( buf ) );
135     if ( n==-1 ) {
136       if (errno == EINTR ) {
137         continue;
138       }
139       break;
140     }
141     if ( n==0 ) {
142       break;
143     }
144     n = write( ofd, buf, n );
145     if ( n==-1 ) {
146       break;
147     }
148   }
149 }
150
151 bool valid_port(string port) {
152   if ( port.size() ) {
153     return port.find_first_not_of( "0123456789" ) == string::npos &&
154          atoi( port.c_str() ) > 0 &&
155          atoi( port.c_str() ) <= 65535;
156   }
157   return true; // consider no port to be the default value
158 }
159
160 int main( int argc, char *argv[] )
161 {
162   argv0 = argv[0];
163   string client = "mosh-client";
164   string server = "mosh-server";
165   string ssh = "ssh";
166   string predict, port_request, ssh_port;
167   int help=0, version=0, fake_proxy=0, term_init=1;
168
169   static struct option long_options[] =
170   {
171     { "client",      required_argument,  0,              'c' },
172     { "server",      required_argument,  0,              's' },
173     { "no-init",     no_argument,        &term_init,      0  },
174     { "predict",     required_argument,  0,              'r' },
175     { "port",        required_argument,  0,              'p' },
176     { "ssh-port",    required_argument,  0,              'P' },
177     { "ssh",         required_argument,  0,              'S' },
178     { "help",        no_argument,        &help,           1  },
179     { "version",     no_argument,        &version,        1  },
180     { "fake-proxy",  no_argument,        &fake_proxy,     1  },
181     { 0, 0, 0, 0 }
182   };
183   while ( 1 ) {
184     int option_index = 0;
185     int c = getopt_long( argc, argv, "anp:P:",
186         long_options, &option_index );
187     if ( c == -1 ) {
188       break;
189     }
190
191     switch ( c ) {
192       case 0:
193         // flag has been set
194         break;
195       case 'c':
196         client = optarg;
197         break;
198       case 's':
199         server = optarg;
200         break;
201       case 'r':
202         predict = optarg;
203         break;
204       case 'p':
205         port_request = optarg;
206         break;
207       case 'P':
208         ssh_port = optarg;
209         break;
210       case 'S':
211         ssh = optarg;
212         break;
213       case 'a':
214         predict = "always";
215         break;
216       case 'n':
217         predict = "never";
218         break;
219       default:
220         die( usage_format, argv[0] );
221     }
222   }
223
224   if ( help ) {
225     die( usage_format, argv[0] );
226   }
227   if ( version ) {
228     die( version_format, PACKAGE_VERSION );
229   }
230
231   if ( predict.size() ) {
232     predict_check( predict, 0 );
233   } else if ( getenv( "MOSH_PREDICTION_DELAY" ) ) {
234     predict = getenv( "MOSH_PREDICTION_DELAY" );
235     predict_check( predict, 1 );
236   } else {
237     predict = "adaptive";
238     predict_check( predict, 0 );
239   }
240
241   if(!valid_port(port_request)) {
242     die( "%s: Server-side port (%s) must be within valid range [0..65535].",
243         argv[0],
244         port_request.c_str() );
245   }
246
247   if(!valid_port(ssh_port)) {
248     die( "%s: SSH port (%s) must be within valid range [0..65535].",
249         argv[0],
250         ssh_port.c_str() );
251   }
252
253   unsetenv( "MOSH_PREDICTION_DISPLAY" );
254
255   if ( fake_proxy ) {
256     string host = argv[optind++];
257     string port = argv[optind++];
258
259     int sockfd = -1;
260     struct addrinfo hints, *servinfo, *p;
261     int rv;
262
263     memset( &hints, 0, sizeof( hints ) );
264     hints.ai_socktype = SOCK_STREAM;
265
266     if ( ( rv = getaddrinfo( host.c_str(),
267                              port.c_str(),
268                              &hints,
269                              &servinfo ) ) != 0 ) {
270       die( "%s: Could not resolve hostname %s: getaddrinfo: %s",
271            argv[0],
272            host.c_str(),
273            gai_strerror( rv ) );
274     }
275
276     int try_family = AF_INET;
277     // loop through all the results and connect to the first we can
278     for ( p = servinfo; p != NULL || try_family == AF_INET; p = p->ai_next ) {
279       if(p == NULL && try_family == AF_INET) { // start over and try AF_INET6
280         p = servinfo;
281         try_family = AF_INET6;
282       }
283       if(p == NULL) {
284         break; // servinfo == NULL
285       }
286
287       if(p->ai_family != try_family) {
288         continue;
289       }
290
291       if ( ( sockfd = socket( p->ai_family, SOCK_STREAM, IPPROTO_TCP ) ) == -1 ) {
292         continue;
293       }
294
295       if ( connect( sockfd, p->ai_addr, p->ai_addrlen ) == -1 ) {
296         close( sockfd );
297         continue;
298       }
299
300       char host[NI_MAXHOST], service[NI_MAXSERV];
301       if ( getnameinfo( p->ai_addr, p->ai_addrlen,
302             host, NI_MAXHOST,
303             service, NI_MAXSERV,
304             NI_NUMERICSERV | NI_NUMERICHOST ) == -1 ) {
305         die( "Couldn't get host name info" );
306       }
307
308       fprintf( stderr, "MOSH IP %s\n", host );
309       break; // if we get here, we must have connected successfully
310     }
311
312     if ( p == NULL ) {
313       // looped off the end of the list with no connection
314       die( "%s: failed to connect to host %s port %s",
315             argv[0], host.c_str(), port.c_str() );
316     }
317
318     freeaddrinfo( servinfo ); // all done with this structure
319
320     int pid = fork();
321     if ( pid == -1 ) die( "%s: fork: %d", argv[0], errno );
322     if ( pid == 0 ) {
323       close( STDIN_FILENO );
324       cat( sockfd, STDOUT_FILENO );
325       shutdown( sockfd, 0 );
326       exit( 0 );
327     }
328     signal( SIGHUP, SIG_IGN );
329     close( STDOUT_FILENO );
330     cat( STDIN_FILENO, sockfd );
331     shutdown( sockfd, SHUT_WR /* = 1 */ );
332     close( STDIN_FILENO );
333     waitpid( pid, NULL, 0 );
334     exit( 0 );
335   }
336
337   if ( argc - optind < 1 ) {
338     die( usage_format, argv[0] );
339   }
340
341   string userhost = argv[optind++];
342   char **command = &argv[optind];
343   int commands = argc - optind;
344
345   char *buf = NULL;
346   size_t buf_sz = 0;
347   ssize_t n;
348
349   int pty, pty_slave;
350   struct winsize ws;
351   if ( ioctl( 0, TIOCGWINSZ, &ws ) == -1 ) {
352     die( "%s: ioctl: %d", argv[0], errno );
353   }
354
355   if ( openpty( &pty, &pty_slave, NULL, NULL, &ws ) == -1 ) {
356     die( "%s: openpty: %d", argv[0], errno );
357   }
358
359   int pid = fork();
360   if ( pid == -1 ) die( "%s: fork: %d", argv[0], errno );
361   if ( pid == 0 ) {
362     close( pty );
363     if ( -1 == dup2( pty_slave, 1 ) ||
364          -1 == dup2( pty_slave, 2 ) ) {
365       die( "%s: dup2: %d", argv[0], errno );
366     }
367     close( pty_slave );
368
369     vector<string> server_args;
370     server_args.push_back( "new" );
371     server_args.push_back( "-c" );
372     server_args.push_back( "256" );
373     server_args.push_back( "-s" );
374     if ( port_request.size() ) {
375       server_args.push_back( "-p" );
376       server_args.push_back( port_request );
377     }
378
379     for (char const* env_name : {
380         "LANG", "LANGUAGE", "LC_CTYPE", "LC_NUMERIC",
381         "LC_TIME", "LC_COLLATE", "LC_MONETARY", "LC_MESSAGES", "LC_PAPER",
382         "LC_NAME", "LC_ADDRESS", "LC_TELEPHONE", "LC_MEASUREMENT",
383         "LC_IDENTIFICATION", "LC_ALL" }) {
384       char* env_value = getenv(env_name);
385       if (env_value) {
386         server_args.push_back("-l");
387         server_args.push_back(string(env_name) + "=" + env_value);
388       }
389     }
390
391     if ( commands ) {
392       server_args.push_back( "--" );
393       server_args.insert( server_args.end(), command, command + commands );
394     }
395
396     string quoted_self = shell_quote_string( string( argv[0] ) );
397     string quoted_server_args = shell_quote( server_args );
398     fflush( stdout );
399
400     string proxy_arg = "ProxyCommand=" + quoted_self + " --fake-proxy -- %h %p";
401     string ssh_remote_command = server + " " + quoted_server_args;
402
403     vector<string> ssh_args;
404     ssh_args.push_back( "-n" );
405     ssh_args.push_back( "-tt" );
406     ssh_args.push_back( "-S" );
407     ssh_args.push_back( "none" );
408     ssh_args.push_back( "-o" );
409     ssh_args.push_back( proxy_arg );
410     ssh_args.push_back( userhost );
411     if ( ssh_port.size() ) {
412       ssh_args.push_back( "-p" );
413       ssh_args.push_back( ssh_port );
414     }
415     ssh_args.push_back( "--" );
416     ssh_args.push_back( ssh_remote_command );
417
418     string ssh_exec_string = ssh + " " + shell_quote( ssh_args );
419
420     int ret = execlp( "sh", "sh", "-c", ssh_exec_string.c_str(), (char *)NULL );
421     if ( ret == -1 ) {
422       die( "Cannot exec ssh: %d", errno );
423     }
424   }
425
426   close( pty_slave );
427   string ip, port, key;
428
429   FILE *pty_file = fdopen( pty, "r" );
430   string line;
431   while ( ( n = getline( &buf, &buf_sz, pty_file ) ) >= 0 ) {
432     line = string( buf, n );
433     line = line.erase( line.find_last_not_of( "\n" ) );
434     if ( line.compare( 0, 8, "MOSH IP " ) == 0 ) {
435       size_t ip_end = line.find_last_not_of( " \t\n\r" );
436       if ( ip_end != string::npos && ip_end >= 8 ) {
437         ip = line.substr( 8, ip_end + 1 - 8 );
438       }
439     } else if ( line.compare( 0, 13, "MOSH CONNECT " ) == 0 ) {
440       size_t port_end = line.find_first_not_of( "0123456789", 13 );
441       if ( port_end != string::npos && port_end >= 13 ) {
442         port = line.substr( 13, port_end - 13 );
443       }
444       string rest = line.substr( port_end + 1 );
445       size_t key_end = rest.find_last_not_of( " \t\n\r" );
446       size_t key_valid_end = rest.find_last_of( key_valid_char_set );
447       if ( key_valid_end == key_end && key_end + 1 == 22 ) {
448         key = rest.substr( 0, key_end + 1 );
449       }
450       break;
451     } else {
452       printf( "%s\n", line.c_str() );
453     }
454   }
455   waitpid( pid, NULL, 0 );
456
457   if ( !ip.size() ) {
458     die( "%s: Did not find remote IP address (is SSH ProxyCommand disabled?).",
459          argv[0] );
460   }
461
462   if ( !key.size() || !port.size() ) {
463     die( "%s: Did not find mosh server startup message.", argv[0] );
464   }
465
466   setenv( "MOSH_KEY", key.c_str(), 1 );
467   setenv( "MOSH_PREDICTION_DISPLAY", predict.c_str(), 1 );
468   if (!term_init) setenv( "MOSH_NO_TERM_INIT", "1", 1 );
469   execlp( client.c_str(), client.c_str(), ip.c_str(), port.c_str(), (char *)NULL );
470 }