aboutsummaryrefslogtreecommitdiff
path: root/pass.c
blob: a58276d94b54eef53ba6e9a5acde342f80a5f06c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>

#include "pass_util.h"
#include "util.h"

void print_usage(void);
int cat(const char *path);
int add(const char *path);

void print_usage(void)
{
	printf("Usage: pass COMMAND\n\n"

	       "Commands:\n"
	       "  init key-id/fingerprint\n"
	       "	Initialize new password storage\n"
	       "  ls   [ pass-path ]\n"
	       "	List passwords\n"
	       "  rm   pass-name\n"
	       "	Remove password\n"
	       "  add  pass-name\n"
	       "	Add new password\n"
	       "  gen  pass-name\n"
	       "	Generate new password\n"
	       "  cat  pass-name\n"
	       "	Show encrypted password\n"
	       "  help\n"
	       "	Show this help\n");
}

int cat(const char *path)
{
	int r;

	r = pass_cat(stdout, path);
	if (!r && isatty(STDOUT_FILENO))
		putchar('\n');

	return  r;
}

int add(const char *path)
{
	char *p1 = NULL, *p2 = NULL;
	FILE *in;
	size_t n;
	int r;

	in = fopen("/dev/tty", "r");
	if (!in)
		in = stdin;

	fputs("Password: ", stdout);
	r = pass_getpass(&p1, &n, in);
	if (r < 0) {
		if (in != stdin)
			fclose(in);
		err_die(1, "%d:%s:", errno, strerror(errno));
	}

	fputs("\nRetype password: ", stdout);
	r = pass_getpass(&p2, &n, in);
	putc('\n', stdout);
	if (r < 0) {
		if (in != stdin)
			fclose(in);
		if (p1)
			free(p1);
		err_die(1, "%d:%s:", errno, strerror(errno));
	}

	if (in != stdin)
		fclose(in);

	if (strcmp(p1, p2)) {
		free(p1);
		free(p2);
		err_die(1, "Sorry, passwords do not match");
	}

	free(p1);
	r = pass_add(path, p2, n);

	free(p2);
	return r;
}

int main(int argc, char *argv[])
{
	int r = 0;

	if (!--argc) {
		print_usage();
		exit(EXIT_FAILURE);
	}
	++argv;


	if (!strcmp("help", *argv)) {
		print_usage();
	} else if (!strcmp("init", *argv)) {
		if (!argv[1])
			err_die(1, "invalid usage, try pass help");

		r = pass_init(argv[1]);
	} else if (!strcmp("cat", *argv)) {
		if (!argv[1])
			err_die(1, "invalid usage, try pass help");

		r = cat(argv[1]);
	} else if (!strcmp("add", *argv)) {
		if (!argv[1])
			err_die(1, "invalid usage, try pass help");

		r = add(argv[1]);
	} else {
		r = cat(*argv);
	}

	if (r)
		err_die(r, "Command failed");

	return 0;
}