git-ssh-push/pull: usability improvements
[git.git] / rsh.c
1 #include "rsh.h"
2
3 #include <string.h>
4 #include <sys/types.h>
5 #include <sys/socket.h>
6
7 #include "cache.h"
8
9 #define COMMAND_SIZE 4096
10
11 int setup_connection(int *fd_in, int *fd_out, const char *remote_prog, 
12                      char *url, int rmt_argc, char **rmt_argv)
13 {
14         char *host;
15         char *path;
16         int sv[2];
17         char command[COMMAND_SIZE];
18         char *posn;
19         int i;
20
21         if (!strcmp(url, "-")) {
22                 *fd_in = 0;
23                 *fd_out = 1;
24                 return 0;
25         }
26
27         host = strstr(url, "//");
28         if (host) {
29                 host += 2;
30                 path = strchr(host, '/');
31         } else {
32                 host = url;
33                 path = strchr(host, ':');
34         }
35         if (!path) {
36                 return error("Bad URL: %s", url);
37         }
38         *(path++) = '\0';
39         /* ssh <host> 'cd /<path>; stdio-pull <arg...> <commit-id>' */
40         snprintf(command, COMMAND_SIZE, 
41                  "%s='/%s' %s",
42                  GIT_DIR_ENVIRONMENT, path, remote_prog);
43         posn = command + strlen(command);
44         for (i = 0; i < rmt_argc; i++) {
45                 *(posn++) = ' ';
46                 strncpy(posn, rmt_argv[i], COMMAND_SIZE - (posn - command));
47                 posn += strlen(rmt_argv[i]);
48                 if (posn - command + 4 >= COMMAND_SIZE) {
49                         return error("Command line too long");
50                 }
51         }
52         strcpy(posn, " -");
53         if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv)) {
54                 return error("Couldn't create socket");
55         }
56         if (!fork()) {
57                 close(sv[1]);
58                 dup2(sv[0], 0);
59                 dup2(sv[0], 1);
60                 execlp("ssh", "ssh", host, command, NULL);
61         }
62         close(sv[0]);
63         *fd_in = sv[1];
64         *fd_out = sv[1];
65         return 0;
66 }