openssh: Bump after paths.h ndk patch
[termux-packages] / packages / mosh / mosh.cc
CommitLineData
188d1201
FF
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
38using namespace std;
39
40inline 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
57template <typename SequenceT>
58inline 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
69void 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
78static 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" --help this message\n"
99" --version version and copyright information\n"
100"\n"
101"Please report bugs to mosh-devel@mit.edu.\n"
102"Mosh home page: http://mosh.mit.edu";
103
104static const char *version_format =
105"mosh %s\n"
106"Copyright 2012 Keith Winstein <mosh-devel@mit.edu>\n"
107"License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n"
108"This is free software: you are free to change and redistribute it.\n"
109"There is NO WARRANTY, to the extent permitted by law.";
110
111static const char *key_valid_char_set =
112"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/+";
113
114static char *argv0;
115
116void predict_check( const string &predict, bool env_set )
117{
118 if ( predict != "adaptive" &&
119 predict != "always" &&
120 predict != "never" ) {
121 fprintf( stderr, "%s: Unknown mode \"%s\"%s.\n", argv0, predict.c_str(),
122 env_set ? " (MOSH_PREDICTION_DISPLAY in environment)" : "" );
123 die( usage_format, argv0 );
124 }
125}
126
127void cat( int ifd, int ofd )
128{
129 char buf[4096];
130 ssize_t n;
131 while ( 1 ) {
132 n = read( ifd, buf, sizeof( buf ) );
133 if ( n==-1 ) {
134 if (errno == EINTR ) {
135 continue;
136 }
137 break;
138 }
139 if ( n==0 ) {
140 break;
141 }
142 n = write( ofd, buf, n );
143 if ( n==-1 ) {
144 break;
145 }
146 }
147}
148
149bool valid_port(string port) {
150 if ( port.size() ) {
151 return port.find_first_not_of( "0123456789" ) == string::npos &&
152 atoi( port.c_str() ) > 0 &&
153 atoi( port.c_str() ) <= 65535;
154 }
155 return true; // consider no port to be the default value
156}
157
158int main( int argc, char *argv[] )
159{
160 argv0 = argv[0];
161 string client = "mosh-client";
162 string server = "mosh-server";
163 string ssh = "ssh";
164 string predict, port_request, ssh_port;
165 int help=0, version=0, fake_proxy=0;
166
167 static struct option long_options[] =
168 {
169 { "client", required_argument, 0, 'c' },
170 { "server", required_argument, 0, 's' },
171 { "predict", required_argument, 0, 'r' },
172 { "port", required_argument, 0, 'p' },
173 { "ssh-port", required_argument, 0, 'P' },
174 { "ssh", required_argument, 0, 'S' },
175 { "help", no_argument, &help, 1 },
176 { "version", no_argument, &version, 1 },
177 { "fake-proxy!", no_argument, &fake_proxy, 1 },
178 { 0, 0, 0, 0 }
179 };
180 while ( 1 ) {
181 int option_index = 0;
182 int c = getopt_long( argc, argv, "anp:P:",
183 long_options, &option_index );
184 if ( c == -1 ) {
185 break;
186 }
187
188 switch ( c ) {
189 case 0:
190 // flag has been set
191 break;
192 case 'c':
193 client = optarg;
194 break;
195 case 's':
196 server = optarg;
197 break;
198 case 'r':
199 predict = optarg;
200 break;
201 case 'p':
202 port_request = optarg;
203 break;
204 case 'P':
205 ssh_port = optarg;
206 break;
207 case 'S':
208 ssh = optarg;
209 break;
210 case 'a':
211 predict = "always";
212 break;
213 case 'n':
214 predict = "never";
215 break;
216 default:
217 die( usage_format, argv[0] );
218 }
219 }
220
221 if ( help ) {
222 die( usage_format, argv[0] );
223 }
224 if ( version ) {
225 die( version_format, PACKAGE_VERSION );
226 }
227
228 if ( predict.size() ) {
229 predict_check( predict, 0 );
230 } else if ( getenv( "MOSH_PREDICTION_DELAY" ) ) {
231 predict = getenv( "MOSH_PREDICTION_DELAY" );
232 predict_check( predict, 1 );
233 } else {
234 predict = "adaptive";
235 predict_check( predict, 0 );
236 }
237
238 if(!valid_port(port_request)) {
239 die( "%s: Server-side port (%s) must be within valid range [0..65535].",
240 argv[0],
241 port_request.c_str() );
242 }
243
244 if(!valid_port(ssh_port)) {
245 die( "%s: SSH port (%s) must be within valid range [0..65535].",
246 argv[0],
247 ssh_port.c_str() );
248 }
249
250 unsetenv( "MOSH_PREDICTION_DISPLAY" );
251
252 if ( fake_proxy ) {
253 string host = argv[optind++];
254 string port = argv[optind++];
255
256 int sockfd = -1;
257 struct addrinfo hints, *servinfo, *p;
258 int rv;
259
260 memset( &hints, 0, sizeof( hints ) );
261 hints.ai_socktype = SOCK_STREAM;
262
263 if ( ( rv = getaddrinfo( host.c_str(),
264 port.c_str(),
265 &hints,
266 &servinfo ) ) != 0 ) {
267 die( "%s: Could not resolve hostname %s: getaddrinfo: %s",
268 argv[0],
269 host.c_str(),
270 gai_strerror( rv ) );
271 }
272
273 int try_family = AF_INET;
274 // loop through all the results and connect to the first we can
275 for ( p = servinfo; p != NULL || try_family == AF_INET; p = p->ai_next ) {
276 if(p == NULL && try_family == AF_INET) { // start over and try AF_INET6
277 p = servinfo;
278 try_family = AF_INET6;
279 }
280 if(p == NULL) {
281 break; // servinfo == NULL
282 }
283
284 if(p->ai_family != try_family) {
285 continue;
286 }
287
288 if ( ( sockfd = socket( p->ai_family, SOCK_STREAM, IPPROTO_TCP ) ) == -1 ) {
289 continue;
290 }
291
292 if ( connect( sockfd, p->ai_addr, p->ai_addrlen ) == -1 ) {
293 close( sockfd );
294 continue;
295 }
296
297 char host[NI_MAXHOST], service[NI_MAXSERV];
298 if ( getnameinfo( p->ai_addr, p->ai_addrlen,
299 host, NI_MAXHOST,
300 service, NI_MAXSERV,
301 NI_NUMERICSERV | NI_NUMERICHOST ) == -1 ) {
302 die( "Couldn't get host name info" );
303 }
304
305 fprintf( stderr, "MOSH IP %s\n", host );
306 break; // if we get here, we must have connected successfully
307 }
308
309 if ( p == NULL ) {
310 // looped off the end of the list with no connection
311 die( "%s: failed to connect to host %s port %s",
312 argv[0], host.c_str(), port.c_str() );
313 }
314
315 freeaddrinfo( servinfo ); // all done with this structure
316
317 int pid = fork();
1f87518b 318 if ( pid == -1 ) die( "%s: fork: %d", argv[0], errno );
188d1201 319 if ( pid == 0 ) {
3afa4f34
FF
320 close( STDIN_FILENO );
321 cat( sockfd, STDOUT_FILENO );
188d1201
FF
322 shutdown( sockfd, 0 );
323 exit( 0 );
324 }
325 signal( SIGHUP, SIG_IGN );
3afa4f34
FF
326 close( STDOUT_FILENO );
327 cat( STDIN_FILENO, sockfd );
328 shutdown( sockfd, SHUT_WR /* = 1 */ );
329 close( STDIN_FILENO );
188d1201
FF
330 waitpid( pid, NULL, 0 );
331 exit( 0 );
332 }
333
334 if ( argc - optind < 1 ) {
335 die( usage_format, argv[0] );
336 }
337
338 string userhost = argv[optind++];
339 char **command = &argv[optind];
340 int commands = argc - optind;
341
342 string color_invocation = client + " -c";
343 FILE *color_file = popen( color_invocation.c_str(), "r" );
1f87518b 344 if ( !color_file ) die( "%s: popen: %d", argv[0], errno );
188d1201
FF
345 char *buf = NULL;
346 size_t buf_sz = 0;
347 ssize_t n;
348 if ( ( n = getline( &buf, &buf_sz, color_file ) ) < 0 ) {
349 die( "%s: Can't count colors: %d", argv[0], errno );
350 }
1f87518b
FF
351 // Chomp the trailing newline:
352 if ( n > 0 && buf[n - 1] == '\n' ) n--;
188d1201
FF
353 string colors = string( buf, n );
354 pclose( color_file );
355
356 if ( !colors.size() ||
357 colors.find_first_not_of( "0123456789" ) != string::npos ||
358 atoi( colors.c_str() ) < 0 ) {
359 colors = "0";
360 }
361
362 int pty, pty_slave;
363 struct winsize ws;
364 if ( ioctl( 0, TIOCGWINSZ, &ws ) == -1 ) {
365 die( "%s: ioctl: %d", argv[0], errno );
366 }
367
368 if ( openpty( &pty, &pty_slave, NULL, NULL, &ws ) == -1 ) {
369 die( "%s: openpty: %d", argv[0], errno );
370 }
371
372 int pid = fork();
3afa4f34 373 if ( pid == -1 ) die( "%s: fork: %d", argv[0], errno );
188d1201
FF
374 if ( pid == 0 ) {
375 close( pty );
376 if ( -1 == dup2( pty_slave, 1 ) ||
377 -1 == dup2( pty_slave, 2 ) ) {
378 die( "%s: dup2: %d", argv[0], errno );
379 }
380 close( pty_slave );
381
382 vector<string> server_args;
383 server_args.push_back( "new" );
384 server_args.push_back( "-s" );
385 server_args.push_back( "-c" );
386 server_args.push_back( colors );
387 if ( port_request.size() ) {
388 server_args.push_back( "-p" );
389 server_args.push_back( port_request );
390 }
32144b83
FF
391
392 for (char const* env_name : {
393 "LANG", "LANGUAGE", "LC_CTYPE", "LC_NUMERIC",
394 "LC_TIME", "LC_COLLATE", "LC_MONETARY", "LC_MESSAGES", "LC_PAPER",
395 "LC_NAME", "LC_ADDRESS", "LC_TELEPHONE", "LC_MEASUREMENT",
396 "LC_IDENTIFICATION", "LC_ALL" }) {
397 char* env_value = getenv(env_name);
398 if (env_value) {
399 server_args.push_back("-l");
400 server_args.push_back(string(env_name) + "=" + env_value);
401 }
402 }
403
188d1201
FF
404 if ( commands ) {
405 server_args.insert( server_args.end(), command, command + commands );
406 }
407 string quoted_self = shell_quote_string( string( argv[0] ) );
408 string quoted_server_args = shell_quote( server_args );
409 fflush( stdout );
410
411 string proxy_arg = "ProxyCommand=" + quoted_self + " --fake-proxy -- %h %p";
412 string ssh_remote_command = server + " " + quoted_server_args;
413
414 vector<string> ssh_args;
415 ssh_args.push_back( "-S" );
416 ssh_args.push_back( "none" );
417 ssh_args.push_back( "-o" );
418 ssh_args.push_back( proxy_arg );
419 ssh_args.push_back( "-t" );
420 ssh_args.push_back( userhost );
421 if ( ssh_port.size() ) {
422 ssh_args.push_back( "-p" );
423 ssh_args.push_back( ssh_port );
424 }
425 ssh_args.push_back( "--" );
426 ssh_args.push_back( ssh_remote_command );
427
428 string ssh_exec_string = ssh + " " + shell_quote( ssh_args );
429
430 int ret = execlp( "sh", "sh", "-c", ssh_exec_string.c_str(), (char *)NULL );
431 if ( ret == -1 ) {
432 die( "Cannot exec ssh: %d", errno );
433 }
434 }
435
436 close( pty_slave );
437 string ip, port, key;
438
439 FILE *pty_file = fdopen( pty, "r" );
440 string line;
441 while ( ( n = getline( &buf, &buf_sz, pty_file ) ) >= 0 ) {
442 line = string( buf, n );
443 line = line.erase( line.find_last_not_of( "\n" ) );
444 if ( line.compare( 0, 8, "MOSH IP " ) == 0 ) {
445 size_t ip_end = line.find_last_not_of( " \t\n\r" );
446 if ( ip_end != string::npos && ip_end >= 8 ) {
447 ip = line.substr( 8, ip_end + 1 - 8 );
448 }
449 } else if ( line.compare( 0, 13, "MOSH CONNECT " ) == 0 ) {
450 size_t port_end = line.find_first_not_of( "0123456789", 13 );
451 if ( port_end != string::npos && port_end >= 13 ) {
452 port = line.substr( 13, port_end - 13 );
453 }
454 string rest = line.substr( port_end + 1 );
455 size_t key_end = rest.find_last_not_of( " \t\n\r" );
456 size_t key_valid_end = rest.find_last_of( key_valid_char_set );
457 if ( key_valid_end == key_end && key_end + 1 == 22 ) {
458 key = rest.substr( 0, key_end + 1 );
459 }
460 break;
461 } else {
462 printf( "%s\n", line.c_str() );
463 }
464 }
465 waitpid( pid, NULL, 0 );
466
467 if ( !ip.size() ) {
468 die( "%s: Did not find remote IP address (is SSH ProxyCommand disabled?).",
469 argv[0] );
470 }
471
472 if ( !key.size() || !port.size() ) {
473 die( "%s: Did not find mosh server startup message.", argv[0] );
474 }
475
476 setenv( "MOSH_KEY", key.c_str(), 1 );
477 setenv( "MOSH_PREDICTION_DISPLAY", predict.c_str(), 1 );
478 execlp( client.c_str(), client.c_str(), ip.c_str(), port.c_str(), (char *)NULL );
479}