1// SPDX-License-Identifier: GPL-2.0 OR MIT
2/*
3 * Copyright (C) 2015-2020 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
4 */
5
6#include <stddef.h>
7#include <stdio.h>
8#include <string.h>
9
10#include "subcommands.h"
11#include "version.h"
12
13const char *PROG_NAME;
14
15static const struct {
16	const char *subcommand;
17	int (*function)(int, const char**);
18	const char *description;
19} subcommands[] = {
20	{ "show", show_main, "Shows the current configuration and device information" },
21	{ "showconf", showconf_main, "Shows the current configuration of a given WireGuard interface, for use with `setconf'" },
22	{ "set", set_main, "Change the current configuration, add peers, remove peers, or change peers" },
23	{ "setconf", setconf_main, "Applies a configuration file to a WireGuard interface" },
24	{ "addconf", setconf_main, "Appends a configuration file to a WireGuard interface" },
25	{ "syncconf", setconf_main, "Synchronizes a configuration file to a WireGuard interface" },
26	{ "genkey", genkey_main, "Generates a new private key and writes it to stdout" },
27	{ "genpsk", genkey_main, "Generates a new preshared key and writes it to stdout" },
28	{ "pubkey", pubkey_main, "Reads a private key from stdin and writes a public key to stdout" }
29};
30
31static void show_usage(FILE *file)
32{
33	fprintf(file, "Usage: %s <cmd> [<args>]\n\n", PROG_NAME);
34	fprintf(file, "Available subcommands:\n");
35	for (size_t i = 0; i < sizeof(subcommands) / sizeof(subcommands[0]); ++i)
36		fprintf(file, "  %s: %s\n", subcommands[i].subcommand, subcommands[i].description);
37	fprintf(file, "You may pass `--help' to any of these subcommands to view usage.\n");
38}
39
40int main(int argc, const char *argv[])
41{
42	PROG_NAME = argv[0];
43
44	if (argc == 2 && (!strcmp(argv[1], "-v") || !strcmp(argv[1], "--version") || !strcmp(argv[1], "version"))) {
45		printf("wireguard-tools v%s - https://git.zx2c4.com/wireguard-tools/\n", WIREGUARD_TOOLS_VERSION);
46		return 0;
47	}
48	if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help") || !strcmp(argv[1], "help"))) {
49		show_usage(stdout);
50		return 0;
51	}
52
53	if (argc == 1) {
54		static const char *new_argv[] = { "show", NULL };
55		return show_main(1, new_argv);
56	}
57
58	for (size_t i = 0; i < sizeof(subcommands) / sizeof(subcommands[0]); ++i) {
59		if (!strcmp(argv[1], subcommands[i].subcommand))
60			return subcommands[i].function(argc - 1, argv + 1);
61	}
62
63	fprintf(stderr, "Invalid subcommand: `%s'\n", argv[1]);
64	show_usage(stderr);
65	return 1;
66}
67