forked from lastpass/lastpass-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlpass.c
121 lines (105 loc) · 2.37 KB
/
lpass.c
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
/*
* Copyright (c) 2014 LastPass. All Rights Reserved.
*
*
*/
#include "process.h"
#include "cmd.h"
#include "string.h"
#include "util.h"
#include "config.h"
#include "terminal.h"
#include "version.h"
#include <sys/stat.h>
#include <getopt.h>
#define CMD(name) { #name, cmd_##name##_usage, cmd_##name }
static struct {
const char *name;
const char *usage;
int (*cmd)(int, char**);
} commands[] = {
CMD(login),
CMD(logout),
CMD(show),
CMD(ls),
CMD(edit),
CMD(generate),
CMD(duplicate),
CMD(rm),
CMD(sync)
};
#undef CMD
static void version(void)
{
terminal_printf(TERMINAL_FG_CYAN TERMINAL_BOLD "LastPass CLI v" LASTPASS_CLI_VERSION TERMINAL_RESET "\n");
}
static void help(void)
{
terminal_printf(TERMINAL_FG_YELLOW TERMINAL_BOLD "Usage" TERMINAL_RESET ":\n");
printf(" %s {--help|--version}\n", ARGV[0]);
for (size_t i = 0; i < ARRAY_SIZE(commands); ++i)
printf(" %s %s\n", ARGV[0], commands[i].usage);
}
static int global_options(int argc, char *argv[])
{
static struct option long_options[] = {
{"version", no_argument, NULL, 'v'},
{"help", no_argument, NULL, 'h'},
{0, 0, 0, 0}
};
char option;
int option_index;
while ((option = getopt_long(argc, argv, "vh", long_options, &option_index)) != -1) {
switch (option) {
case 'v':
version();
return 0;
case 'h':
version();
printf("\n");
case '?':
help();
return option == 'h';
}
}
help();
return 1;
}
static int process_command(int argc, char *argv[])
{
for (size_t i = 0; i < ARRAY_SIZE(commands); ++i) {
if (!strcmp(argv[0], commands[i].name))
return commands[i].cmd(argc, argv);
}
help();
return 1;
}
static void load_saved_environment(void)
{
_cleanup_free_ char *env = NULL;
env = config_read_string("env");
if (!env)
return;
for (char *tok = strtok(env, "\n"); tok; tok = strtok(NULL, "\n")) {
char *equals = strchr(tok, '=');
if (!equals || !*equals) {
warn("The environment line '%s' is invalid.", tok);
continue;
}
*equals = '\0';
if (setenv(tok, equals + 1, true))
warn_errno("The environment line '%s' is invalid.", tok);
}
}
int main(int argc, char *argv[])
{
/* For process.h to function. */
ARGC = argc;
ARGV = argv;
/* Do not remove this umask. Always keep at top. */
umask(0077);
load_saved_environment();
if (argc >= 2 && argv[1][0] != '-')
return process_command(argc - 1, argv + 1);
return global_options(argc, argv);
}