Skip to content

Commit 2dbc887

Browse files
Greg Brockmangitster
Greg Brockman
authored andcommitted
Allow creation of arbitrary git-shell commands
This provides a mechanism for the server to expose custom functionality to clients. My particular use case is that I would like a way of discovering all repositories available for cloning. A client that clones via git clone [email protected] can invoke a command by ssh [email protected] $command Signed-off-by: Greg Brockman <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 64fdc08 commit 2dbc887

File tree

1 file changed

+42
-2
lines changed

1 file changed

+42
-2
lines changed

shell.c

+42-2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
#include "exec_cmd.h"
44
#include "strbuf.h"
55

6+
#define COMMAND_DIR "git-shell-commands"
7+
68
static int do_generic_cmd(const char *me, char *arg)
79
{
810
const char *my_argv[4];
@@ -33,6 +35,29 @@ static int do_cvs_cmd(const char *me, char *arg)
3335
return execv_git_cmd(cvsserver_argv);
3436
}
3537

38+
static int is_valid_cmd_name(const char *cmd)
39+
{
40+
/* Test command contains no . or / characters */
41+
return cmd[strcspn(cmd, "./")] == '\0';
42+
}
43+
44+
static char *make_cmd(const char *prog)
45+
{
46+
char *prefix = xmalloc((strlen(prog) + strlen(COMMAND_DIR) + 2));
47+
strcpy(prefix, COMMAND_DIR);
48+
strcat(prefix, "/");
49+
strcat(prefix, prog);
50+
return prefix;
51+
}
52+
53+
static void cd_to_homedir(void)
54+
{
55+
const char *home = getenv("HOME");
56+
if (!home)
57+
die("could not determine user's home directory; HOME is unset");
58+
if (chdir(home) == -1)
59+
die("could not chdir to user's home directory");
60+
}
3661

3762
static struct commands {
3863
const char *name;
@@ -48,6 +73,7 @@ static struct commands {
4873
int main(int argc, char **argv)
4974
{
5075
char *prog;
76+
const char **user_argv;
5177
struct commands *cmd;
5278
int devnull_fd;
5379

@@ -76,7 +102,7 @@ int main(int argc, char **argv)
76102
else if (argc != 3 || strcmp(argv[1], "-c"))
77103
die("What do you think I am? A shell?");
78104

79-
prog = argv[2];
105+
prog = xstrdup(argv[2]);
80106
if (!strncmp(prog, "git", 3) && isspace(prog[3]))
81107
/* Accept "git foo" as if the caller said "git-foo". */
82108
prog[3] = '-';
@@ -99,5 +125,19 @@ int main(int argc, char **argv)
99125
}
100126
exit(cmd->exec(cmd->name, arg));
101127
}
102-
die("unrecognized command '%s'", prog);
128+
129+
cd_to_homedir();
130+
if (split_cmdline(prog, &user_argv) != -1) {
131+
if (is_valid_cmd_name(user_argv[0])) {
132+
prog = make_cmd(user_argv[0]);
133+
user_argv[0] = prog;
134+
execv(user_argv[0], (char *const *) user_argv);
135+
}
136+
free(prog);
137+
free(user_argv);
138+
die("unrecognized command '%s'", argv[2]);
139+
} else {
140+
free(prog);
141+
die("invalid command format '%s'", argv[2]);
142+
}
103143
}

0 commit comments

Comments
 (0)