Merge branch 'bw/commit-partial-from-subdirectory-fix'
[git] / credential-cache--daemon.c
1 #include "cache.h"
2 #include "config.h"
3 #include "tempfile.h"
4 #include "credential.h"
5 #include "unix-socket.h"
6 #include "parse-options.h"
7
8 struct credential_cache_entry {
9         struct credential item;
10         timestamp_t expiration;
11 };
12 static struct credential_cache_entry *entries;
13 static int entries_nr;
14 static int entries_alloc;
15
16 static void cache_credential(struct credential *c, int timeout)
17 {
18         struct credential_cache_entry *e;
19
20         ALLOC_GROW(entries, entries_nr + 1, entries_alloc);
21         e = &entries[entries_nr++];
22
23         /* take ownership of pointers */
24         memcpy(&e->item, c, sizeof(*c));
25         memset(c, 0, sizeof(*c));
26         e->expiration = time(NULL) + timeout;
27 }
28
29 static struct credential_cache_entry *lookup_credential(const struct credential *c)
30 {
31         int i;
32         for (i = 0; i < entries_nr; i++) {
33                 struct credential *e = &entries[i].item;
34                 if (credential_match(c, e))
35                         return &entries[i];
36         }
37         return NULL;
38 }
39
40 static void remove_credential(const struct credential *c)
41 {
42         struct credential_cache_entry *e;
43
44         e = lookup_credential(c);
45         if (e)
46                 e->expiration = 0;
47 }
48
49 static timestamp_t check_expirations(void)
50 {
51         static timestamp_t wait_for_entry_until;
52         int i = 0;
53         timestamp_t now = time(NULL);
54         timestamp_t next = TIME_MAX;
55
56         /*
57          * Initially give the client 30 seconds to actually contact us
58          * and store a credential before we decide there's no point in
59          * keeping the daemon around.
60          */
61         if (!wait_for_entry_until)
62                 wait_for_entry_until = now + 30;
63
64         while (i < entries_nr) {
65                 if (entries[i].expiration <= now) {
66                         entries_nr--;
67                         credential_clear(&entries[i].item);
68                         if (i != entries_nr)
69                                 memcpy(&entries[i], &entries[entries_nr], sizeof(*entries));
70                         /*
71                          * Stick around 30 seconds in case a new credential
72                          * shows up (e.g., because we just removed a failed
73                          * one, and we will soon get the correct one).
74                          */
75                         wait_for_entry_until = now + 30;
76                 }
77                 else {
78                         if (entries[i].expiration < next)
79                                 next = entries[i].expiration;
80                         i++;
81                 }
82         }
83
84         if (!entries_nr) {
85                 if (wait_for_entry_until <= now)
86                         return 0;
87                 next = wait_for_entry_until;
88         }
89
90         return next - now;
91 }
92
93 static int read_request(FILE *fh, struct credential *c,
94                         struct strbuf *action, int *timeout) {
95         static struct strbuf item = STRBUF_INIT;
96         const char *p;
97
98         strbuf_getline_lf(&item, fh);
99         if (!skip_prefix(item.buf, "action=", &p))
100                 return error("client sent bogus action line: %s", item.buf);
101         strbuf_addstr(action, p);
102
103         strbuf_getline_lf(&item, fh);
104         if (!skip_prefix(item.buf, "timeout=", &p))
105                 return error("client sent bogus timeout line: %s", item.buf);
106         *timeout = atoi(p);
107
108         if (credential_read(c, fh) < 0)
109                 return -1;
110         return 0;
111 }
112
113 static void serve_one_client(FILE *in, FILE *out)
114 {
115         struct credential c = CREDENTIAL_INIT;
116         struct strbuf action = STRBUF_INIT;
117         int timeout = -1;
118
119         if (read_request(in, &c, &action, &timeout) < 0)
120                 /* ignore error */ ;
121         else if (!strcmp(action.buf, "get")) {
122                 struct credential_cache_entry *e = lookup_credential(&c);
123                 if (e) {
124                         fprintf(out, "username=%s\n", e->item.username);
125                         fprintf(out, "password=%s\n", e->item.password);
126                 }
127         }
128         else if (!strcmp(action.buf, "exit")) {
129                 /*
130                  * It's important that we clean up our socket first, and then
131                  * signal the client only once we have finished the cleanup.
132                  * Calling exit() directly does this, because we clean up in
133                  * our atexit() handler, and then signal the client when our
134                  * process actually ends, which closes the socket and gives
135                  * them EOF.
136                  */
137                 exit(0);
138         }
139         else if (!strcmp(action.buf, "erase"))
140                 remove_credential(&c);
141         else if (!strcmp(action.buf, "store")) {
142                 if (timeout < 0)
143                         warning("cache client didn't specify a timeout");
144                 else if (!c.username || !c.password)
145                         warning("cache client gave us a partial credential");
146                 else {
147                         remove_credential(&c);
148                         cache_credential(&c, timeout);
149                 }
150         }
151         else
152                 warning("cache client sent unknown action: %s", action.buf);
153
154         credential_clear(&c);
155         strbuf_release(&action);
156 }
157
158 static int serve_cache_loop(int fd)
159 {
160         struct pollfd pfd;
161         timestamp_t wakeup;
162
163         wakeup = check_expirations();
164         if (!wakeup)
165                 return 0;
166
167         pfd.fd = fd;
168         pfd.events = POLLIN;
169         if (poll(&pfd, 1, 1000 * wakeup) < 0) {
170                 if (errno != EINTR)
171                         die_errno("poll failed");
172                 return 1;
173         }
174
175         if (pfd.revents & POLLIN) {
176                 int client, client2;
177                 FILE *in, *out;
178
179                 client = accept(fd, NULL, NULL);
180                 if (client < 0) {
181                         warning_errno("accept failed");
182                         return 1;
183                 }
184                 client2 = dup(client);
185                 if (client2 < 0) {
186                         warning_errno("dup failed");
187                         close(client);
188                         return 1;
189                 }
190
191                 in = xfdopen(client, "r");
192                 out = xfdopen(client2, "w");
193                 serve_one_client(in, out);
194                 fclose(in);
195                 fclose(out);
196         }
197         return 1;
198 }
199
200 static void serve_cache(const char *socket_path, int debug)
201 {
202         int fd;
203
204         fd = unix_stream_listen(socket_path);
205         if (fd < 0)
206                 die_errno("unable to bind to '%s'", socket_path);
207
208         printf("ok\n");
209         fclose(stdout);
210         if (!debug) {
211                 if (!freopen("/dev/null", "w", stderr))
212                         die_errno("unable to point stderr to /dev/null");
213         }
214
215         while (serve_cache_loop(fd))
216                 ; /* nothing */
217
218         close(fd);
219 }
220
221 static const char permissions_advice[] = N_(
222 "The permissions on your socket directory are too loose; other\n"
223 "users may be able to read your cached credentials. Consider running:\n"
224 "\n"
225 "       chmod 0700 %s");
226 static void init_socket_directory(const char *path)
227 {
228         struct stat st;
229         char *path_copy = xstrdup(path);
230         char *dir = dirname(path_copy);
231
232         if (!stat(dir, &st)) {
233                 if (st.st_mode & 077)
234                         die(_(permissions_advice), dir);
235         } else {
236                 /*
237                  * We must be sure to create the directory with the correct mode,
238                  * not just chmod it after the fact; otherwise, there is a race
239                  * condition in which somebody can chdir to it, sleep, then try to open
240                  * our protected socket.
241                  */
242                 if (safe_create_leading_directories_const(dir) < 0)
243                         die_errno("unable to create directories for '%s'", dir);
244                 if (mkdir(dir, 0700) < 0)
245                         die_errno("unable to mkdir '%s'", dir);
246         }
247
248         if (chdir(dir))
249                 /*
250                  * We don't actually care what our cwd is; we chdir here just to
251                  * be a friendly daemon and avoid tying up our original cwd.
252                  * If this fails, it's OK to just continue without that benefit.
253                  */
254                 ;
255
256         free(path_copy);
257 }
258
259 int cmd_main(int argc, const char **argv)
260 {
261         struct tempfile *socket_file;
262         const char *socket_path;
263         int ignore_sighup = 0;
264         static const char *usage[] = {
265                 "git-credential-cache--daemon [opts] <socket_path>",
266                 NULL
267         };
268         int debug = 0;
269         const struct option options[] = {
270                 OPT_BOOL(0, "debug", &debug,
271                          N_("print debugging messages to stderr")),
272                 OPT_END()
273         };
274
275         git_config_get_bool("credentialcache.ignoresighup", &ignore_sighup);
276
277         argc = parse_options(argc, argv, NULL, options, usage, 0);
278         socket_path = argv[0];
279
280         if (!socket_path)
281                 usage_with_options(usage, options);
282
283         if (!is_absolute_path(socket_path))
284                 die("socket directory must be an absolute path");
285
286         init_socket_directory(socket_path);
287         socket_file = register_tempfile(socket_path);
288
289         if (ignore_sighup)
290                 signal(SIGHUP, SIG_IGN);
291
292         serve_cache(socket_path, debug);
293         delete_tempfile(&socket_file);
294
295         return 0;
296 }