File: crypt_log_usage.c

package info (click to toggle)
cryptsetup 2%3A2.8.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 20,312 kB
  • sloc: ansic: 65,883; sh: 17,680; cpp: 994; xml: 920; makefile: 495; perl: 486
file content (81 lines) | stat: -rw-r--r-- 2,177 bytes parent folder | download
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
// SPDX-License-Identifier: LGPL-2.1-or-later
/*
 * libcryptsetup API log example
 *
 * Copyright (C) 2011-2025 Red Hat, Inc. All rights reserved.
 */

#include <stdio.h>
#include <sys/types.h>
#include <syslog.h>
#include <unistd.h>
#include <libcryptsetup.h>

/*
 * This is an example of crypt_set_log_callback API callback.
 *
 */
static void simple_syslog_wrapper(int level, const char *msg, void *usrptr)
{
	const char *prefix = (const char *)usrptr;
	int priority;

	switch(level) {
		case CRYPT_LOG_NORMAL:  priority = LOG_NOTICE; break;
		case CRYPT_LOG_ERROR:   priority = LOG_ERR;    break;
		case CRYPT_LOG_VERBOSE: priority = LOG_INFO;   break;
		case CRYPT_LOG_DEBUG:   priority = LOG_DEBUG;  break;
		default:
			fprintf(stderr, "Unsupported log level requested!\n");
			return;
	}

	if (prefix)
		syslog(priority, "%s:%s", prefix, msg);
	else
		syslog(priority, "%s", msg);
}

int main(void)
{
	struct crypt_device *cd;
	char usrprefix[] = "cslog_example";
	int r;

	if (geteuid()) {
		printf("Using of libcryptsetup requires super user privileges.\n");
		return 1;
	}

	openlog("cryptsetup", LOG_CONS | LOG_PID, LOG_USER);

	/* Initialize empty crypt device context */
	r = crypt_init(&cd, NULL);
	if (r < 0) {
		printf("crypt_init() failed.\n");
		return 2;
	}

	/* crypt_set_log_callback() - register a log callback for crypt context */
	crypt_set_log_callback(cd, &simple_syslog_wrapper, (void *)usrprefix);

	/* send messages ithrough the crypt_log() interface */
	crypt_log(cd, CRYPT_LOG_NORMAL, "This is normal log message");
	crypt_log(cd, CRYPT_LOG_ERROR, "This is error log message");
	crypt_log(cd, CRYPT_LOG_VERBOSE, "This is verbose log message");
	crypt_log(cd, CRYPT_LOG_DEBUG, "This is debug message");

	/* release crypt context */
	crypt_free(cd);

	/* Initialize default (global) log callback */
	crypt_set_log_callback(NULL, &simple_syslog_wrapper, NULL);

	crypt_log(NULL, CRYPT_LOG_NORMAL, "This is normal log message");
	crypt_log(NULL, CRYPT_LOG_ERROR, "This is error log message");
	crypt_log(NULL, CRYPT_LOG_VERBOSE, "This is verbose log message");
	crypt_log(NULL, CRYPT_LOG_DEBUG, "This is debug message");

	closelog();
	return 0;
}