Merge branch 'nd/cherry-pick-quit-fix'
[git] / contrib / credential / libsecret / git-credential-libsecret.c
1 /*
2  * Copyright (C) 2011 John Szakmeister <john@szakmeister.net>
3  *               2012 Philipp A. Hartmann <pah@qo.cx>
4  *               2016 Mantas Mikulėnas <grawity@gmail.com>
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 2 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
18  */
19
20 /*
21  * Credits:
22  * - GNOME Keyring API handling originally written by John Szakmeister
23  * - ported to credential helper API by Philipp A. Hartmann
24  */
25
26 #include <stdio.h>
27 #include <string.h>
28 #include <stdlib.h>
29 #include <glib.h>
30 #include <libsecret/secret.h>
31
32 /*
33  * This credential struct and API is simplified from git's credential.{h,c}
34  */
35 struct credential {
36         char *protocol;
37         char *host;
38         unsigned short port;
39         char *path;
40         char *username;
41         char *password;
42 };
43
44 #define CREDENTIAL_INIT { NULL, NULL, 0, NULL, NULL, NULL }
45
46 typedef int (*credential_op_cb)(struct credential *);
47
48 struct credential_operation {
49         char *name;
50         credential_op_cb op;
51 };
52
53 #define CREDENTIAL_OP_END { NULL, NULL }
54
55 /* ----------------- Secret Service functions ----------------- */
56
57 static char *make_label(struct credential *c)
58 {
59         if (c->port)
60                 return g_strdup_printf("Git: %s://%s:%hu/%s",
61                                         c->protocol, c->host, c->port, c->path ? c->path : "");
62         else
63                 return g_strdup_printf("Git: %s://%s/%s",
64                                         c->protocol, c->host, c->path ? c->path : "");
65 }
66
67 static GHashTable *make_attr_list(struct credential *c)
68 {
69         GHashTable *al = g_hash_table_new_full(g_str_hash, g_str_equal, NULL, g_free);
70
71         if (c->username)
72                 g_hash_table_insert(al, "user", g_strdup(c->username));
73         if (c->protocol)
74                 g_hash_table_insert(al, "protocol", g_strdup(c->protocol));
75         if (c->host)
76                 g_hash_table_insert(al, "server", g_strdup(c->host));
77         if (c->port)
78                 g_hash_table_insert(al, "port", g_strdup_printf("%hu", c->port));
79         if (c->path)
80                 g_hash_table_insert(al, "object", g_strdup(c->path));
81
82         return al;
83 }
84
85 static int keyring_get(struct credential *c)
86 {
87         SecretService *service = NULL;
88         GHashTable *attributes = NULL;
89         GError *error = NULL;
90         GList *items = NULL;
91
92         if (!c->protocol || !(c->host || c->path))
93                 return EXIT_FAILURE;
94
95         service = secret_service_get_sync(0, NULL, &error);
96         if (error != NULL) {
97                 g_critical("could not connect to Secret Service: %s", error->message);
98                 g_error_free(error);
99                 return EXIT_FAILURE;
100         }
101
102         attributes = make_attr_list(c);
103         items = secret_service_search_sync(service,
104                                            SECRET_SCHEMA_COMPAT_NETWORK,
105                                            attributes,
106                                            SECRET_SEARCH_LOAD_SECRETS | SECRET_SEARCH_UNLOCK,
107                                            NULL,
108                                            &error);
109         g_hash_table_unref(attributes);
110         if (error != NULL) {
111                 g_critical("lookup failed: %s", error->message);
112                 g_error_free(error);
113                 return EXIT_FAILURE;
114         }
115
116         if (items != NULL) {
117                 SecretItem *item;
118                 SecretValue *secret;
119                 const char *s;
120
121                 item = items->data;
122                 secret = secret_item_get_secret(item);
123                 attributes = secret_item_get_attributes(item);
124
125                 s = g_hash_table_lookup(attributes, "user");
126                 if (s) {
127                         g_free(c->username);
128                         c->username = g_strdup(s);
129                 }
130
131                 s = secret_value_get_text(secret);
132                 if (s) {
133                         g_free(c->password);
134                         c->password = g_strdup(s);
135                 }
136
137                 g_hash_table_unref(attributes);
138                 secret_value_unref(secret);
139                 g_list_free_full(items, g_object_unref);
140         }
141
142         return EXIT_SUCCESS;
143 }
144
145
146 static int keyring_store(struct credential *c)
147 {
148         char *label = NULL;
149         GHashTable *attributes = NULL;
150         GError *error = NULL;
151
152         /*
153          * Sanity check that what we are storing is actually sensible.
154          * In particular, we can't make a URL without a protocol field.
155          * Without either a host or pathname (depending on the scheme),
156          * we have no primary key. And without a username and password,
157          * we are not actually storing a credential.
158          */
159         if (!c->protocol || !(c->host || c->path) ||
160             !c->username || !c->password)
161                 return EXIT_FAILURE;
162
163         label = make_label(c);
164         attributes = make_attr_list(c);
165         secret_password_storev_sync(SECRET_SCHEMA_COMPAT_NETWORK,
166                                     attributes,
167                                     NULL,
168                                     label,
169                                     c->password,
170                                     NULL,
171                                     &error);
172         g_free(label);
173         g_hash_table_unref(attributes);
174
175         if (error != NULL) {
176                 g_critical("store failed: %s", error->message);
177                 g_error_free(error);
178                 return EXIT_FAILURE;
179         }
180
181         return EXIT_SUCCESS;
182 }
183
184 static int keyring_erase(struct credential *c)
185 {
186         GHashTable *attributes = NULL;
187         GError *error = NULL;
188
189         /*
190          * Sanity check that we actually have something to match
191          * against. The input we get is a restrictive pattern,
192          * so technically a blank credential means "erase everything".
193          * But it is too easy to accidentally send this, since it is equivalent
194          * to empty input. So explicitly disallow it, and require that the
195          * pattern have some actual content to match.
196          */
197         if (!c->protocol && !c->host && !c->path && !c->username)
198                 return EXIT_FAILURE;
199
200         attributes = make_attr_list(c);
201         secret_password_clearv_sync(SECRET_SCHEMA_COMPAT_NETWORK,
202                                     attributes,
203                                     NULL,
204                                     &error);
205         g_hash_table_unref(attributes);
206
207         if (error != NULL) {
208                 g_critical("erase failed: %s", error->message);
209                 g_error_free(error);
210                 return EXIT_FAILURE;
211         }
212
213         return EXIT_SUCCESS;
214 }
215
216 /*
217  * Table with helper operation callbacks, used by generic
218  * credential helper main function.
219  */
220 static struct credential_operation const credential_helper_ops[] = {
221         { "get",   keyring_get },
222         { "store", keyring_store },
223         { "erase", keyring_erase },
224         CREDENTIAL_OP_END
225 };
226
227 /* ------------------ credential functions ------------------ */
228
229 static void credential_init(struct credential *c)
230 {
231         memset(c, 0, sizeof(*c));
232 }
233
234 static void credential_clear(struct credential *c)
235 {
236         g_free(c->protocol);
237         g_free(c->host);
238         g_free(c->path);
239         g_free(c->username);
240         g_free(c->password);
241
242         credential_init(c);
243 }
244
245 static int credential_read(struct credential *c)
246 {
247         char *buf;
248         size_t line_len;
249         char *key;
250         char *value;
251
252         key = buf = g_malloc(1024);
253
254         while (fgets(buf, 1024, stdin)) {
255                 line_len = strlen(buf);
256
257                 if (line_len && buf[line_len-1] == '\n')
258                         buf[--line_len] = '\0';
259
260                 if (!line_len)
261                         break;
262
263                 value = strchr(buf, '=');
264                 if (!value) {
265                         g_warning("invalid credential line: %s", key);
266                         g_free(buf);
267                         return -1;
268                 }
269                 *value++ = '\0';
270
271                 if (!strcmp(key, "protocol")) {
272                         g_free(c->protocol);
273                         c->protocol = g_strdup(value);
274                 } else if (!strcmp(key, "host")) {
275                         g_free(c->host);
276                         c->host = g_strdup(value);
277                         value = strrchr(c->host, ':');
278                         if (value) {
279                                 *value++ = '\0';
280                                 c->port = atoi(value);
281                         }
282                 } else if (!strcmp(key, "path")) {
283                         g_free(c->path);
284                         c->path = g_strdup(value);
285                 } else if (!strcmp(key, "username")) {
286                         g_free(c->username);
287                         c->username = g_strdup(value);
288                 } else if (!strcmp(key, "password")) {
289                         g_free(c->password);
290                         c->password = g_strdup(value);
291                         while (*value)
292                                 *value++ = '\0';
293                 }
294                 /*
295                  * Ignore other lines; we don't know what they mean, but
296                  * this future-proofs us when later versions of git do
297                  * learn new lines, and the helpers are updated to match.
298                  */
299         }
300
301         g_free(buf);
302
303         return 0;
304 }
305
306 static void credential_write_item(FILE *fp, const char *key, const char *value)
307 {
308         if (!value)
309                 return;
310         fprintf(fp, "%s=%s\n", key, value);
311 }
312
313 static void credential_write(const struct credential *c)
314 {
315         /* only write username/password, if set */
316         credential_write_item(stdout, "username", c->username);
317         credential_write_item(stdout, "password", c->password);
318 }
319
320 static void usage(const char *name)
321 {
322         struct credential_operation const *try_op = credential_helper_ops;
323         const char *basename = strrchr(name, '/');
324
325         basename = (basename) ? basename + 1 : name;
326         fprintf(stderr, "usage: %s <", basename);
327         while (try_op->name) {
328                 fprintf(stderr, "%s", (try_op++)->name);
329                 if (try_op->name)
330                         fprintf(stderr, "%s", "|");
331         }
332         fprintf(stderr, "%s", ">\n");
333 }
334
335 int main(int argc, char *argv[])
336 {
337         int ret = EXIT_SUCCESS;
338
339         struct credential_operation const *try_op = credential_helper_ops;
340         struct credential cred = CREDENTIAL_INIT;
341
342         if (!argv[1]) {
343                 usage(argv[0]);
344                 exit(EXIT_FAILURE);
345         }
346
347         g_set_application_name("Git Credential Helper");
348
349         /* lookup operation callback */
350         while (try_op->name && strcmp(argv[1], try_op->name))
351                 try_op++;
352
353         /* unsupported operation given -- ignore silently */
354         if (!try_op->name || !try_op->op)
355                 goto out;
356
357         ret = credential_read(&cred);
358         if (ret)
359                 goto out;
360
361         /* perform credential operation */
362         ret = (*try_op->op)(&cred);
363
364         credential_write(&cred);
365
366 out:
367         credential_clear(&cred);
368         return ret;
369 }