@matheusbsbs / matheus-bagliano / commits / 2dbc887eaa
Fork 0

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 user@example.com can invoke a command by ssh user@example.com $command Signed-off-by: Greg Brockman <gdb@mit.edu> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Greg Brockman committed Jul 28, 2010 at 17:31 UTC 2dbc887eaa6fbd787edfc9472b86b0faeb54e2ae
1 file changed +42 -2
shell.c
+42 -2
@@ -3,6 +3,8 @@
3 #include "exec_cmd.h"
4 #include "strbuf.h"
5
6 +#define COMMAND_DIR "git-shell-commands"
7 +
8 static int do_generic_cmd(const char *me, char *arg)
9 {
10 const char *my_argv[4];
@@ -33,6 +35,29 @@ static int do_cvs_cmd(const char *me, char *arg)
35 return execv_git_cmd(cvsserver_argv);
36 }
37
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 +}
61
62 static struct commands {
63 const char *name;
@@ -48,6 +73,7 @@ static struct commands {
73 int main(int argc, char **argv)
74 {
75 char *prog;
76 + const char **user_argv;
77 struct commands *cmd;
78 int devnull_fd;
79
@@ -76,7 +102,7 @@ int main(int argc, char **argv)
102 else if (argc != 3 || strcmp(argv[1], "-c"))
103 die("What do you think I am? A shell?");
104
79 - prog = argv[2];
105 + prog = xstrdup(argv[2]);
106 if (!strncmp(prog, "git", 3) && isspace(prog[3]))
107 /* Accept "git foo" as if the caller said "git-foo". */
108 prog[3] = '-';
@@ -99,5 +125,19 @@ int main(int argc, char **argv)
125 }
126 exit(cmd->exec(cmd->name, arg));
127 }
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 + }
143 }