2 #include "credential.h"
3 #include "string-list.h"
4 #include "parse-options.h"
5 #include "unix-socket.h"
6 #include "run-command.h"
11 static int send_request(const char *socket, const struct strbuf *out)
14 int fd = unix_stream_connect(socket);
19 if (write_in_full(fd, out->buf, out->len) < 0)
20 die_errno("unable to write to cache daemon");
21 shutdown(fd, SHUT_WR);
27 r = read_in_full(fd, in, sizeof(in));
31 die_errno("read error from cache daemon");
32 write_or_die(1, in, r);
38 static void spawn_daemon(const char *socket)
40 struct child_process daemon;
41 const char *argv[] = { NULL, NULL, NULL };
45 memset(&daemon, 0, sizeof(daemon));
46 argv[0] = "git-credential-cache--daemon";
52 if (start_command(&daemon))
53 die_errno("unable to start cache daemon");
54 r = read_in_full(daemon.out, buf, sizeof(buf));
56 die_errno("unable to read result code from cache daemon");
57 if (r != 3 || memcmp(buf, "ok\n", 3))
58 die("cache daemon did not start: %.*s", r, buf);
62 static void do_cache(const char *socket, const char *action, int timeout,
65 struct strbuf buf = STRBUF_INIT;
67 strbuf_addf(&buf, "action=%s\n", action);
68 strbuf_addf(&buf, "timeout=%d\n", timeout);
69 if (flags & FLAG_RELAY) {
70 if (strbuf_read(&buf, 0, 0) < 0)
71 die_errno("unable to relay credential");
74 if (send_request(socket, &buf) < 0) {
75 if (errno != ENOENT && errno != ECONNREFUSED)
76 die_errno("unable to connect to cache daemon");
77 if (flags & FLAG_SPAWN) {
79 if (send_request(socket, &buf) < 0)
80 die_errno("unable to connect to cache daemon");
86 int main(int argc, const char **argv)
88 char *socket_path = NULL;
91 const char * const usage[] = {
92 "git credential-cache [options] <action>",
95 struct option options[] = {
96 OPT_INTEGER(0, "timeout", &timeout,
97 "number of seconds to cache credentials"),
98 OPT_STRING(0, "socket", &socket_path, "path",
99 "path of cache-daemon socket"),
103 argc = parse_options(argc, argv, NULL, options, usage, 0);
105 usage_with_options(usage, options);
109 socket_path = expand_user_path("~/.git-credential-cache/socket");
111 die("unable to find a suitable socket path; use --socket");
113 if (!strcmp(op, "exit"))
114 do_cache(socket_path, op, timeout, 0);
115 else if (!strcmp(op, "get") || !strcmp(op, "erase"))
116 do_cache(socket_path, op, timeout, FLAG_RELAY);
117 else if (!strcmp(op, "store"))
118 do_cache(socket_path, op, timeout, FLAG_RELAY|FLAG_SPAWN);
120 ; /* ignore unknown operation */