aboutsummaryrefslogtreecommitdiff
path: root/crypt.c
blob: 3d81bdabb8f5ede785acb6c0b3bf94f24d4d5f26 (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
/**
 * Copyright (C) 2015--2017, 2020--2021 Tom Ryder <tom@sanctum.geek.nz>
 *
 * This file is part of crypt.
 *
 * crypt is free software: you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * crypt is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * crypt.  If not, see <https://www.gnu.org/licenses/>.
 */

#define _XOPEN_SOURCE
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h> /* strerror(3) */
#include <unistd.h> /* crypt(3) */

void error(const char *);
void usage(FILE *, int);

int main(int argc, char **argv)
{
	const char *hash, *key, *salt;
	int opt, printed;

	while ((opt = getopt(argc, argv, "h")) != -1) {
		switch (opt) {
		case 'h': /* Help */
			usage(stdout, EXIT_SUCCESS);
			break;
		case '?': /* Unknown option */
			usage(stderr, EXIT_FAILURE);
			break;
		default: /* Shouldn't happen */
			abort();
		}
	}

	/*
	 * If we don't have three arguments left after processing the options,
	 * exit with usage information and error status
	 */
	if (argc != 3) {
		usage(stderr, EXIT_FAILURE);
	}

	key = argv[1];
	salt = argv[2];

	/*
	 * Create the hash, but exit immediately with the system error string
	 * if it returns a null pointer (error condition)
	 */
	if (!(hash = crypt(key, salt))) {
		error(strerror(errno));
	}
	assert(strlen(hash) > 0);

	/*
	 * Print the hash, and ensure we printed all of it
	 */
	if ((printed = printf("%s\n", hash)) < 0) {
		error(strerror(errno));
	}
	assert(printed > 0);
	if ((unsigned) printed < strlen(hash) + 1) { /* +1 for newline */
		error("Incomplete print");
	}

	exit(EXIT_SUCCESS);
}

/*
 * Exit with error message and status
 */
void error(const char *message)
{
	fprintf(stderr, "%s\n", message);
	exit(EXIT_FAILURE);
}

/*
 * Show usage to given stream, and exit with given code
 */
void usage(FILE *stream, const int status)
{
	fputs("USAGE: crypt [-h | KEY SALT]\n", stream);
	exit(status);
}