[go: up one dir, main page]

File: utils.c

package info (click to toggle)
ima-evm-utils 1.5-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 880 kB
  • sloc: ansic: 4,211; sh: 3,159; awk: 113; makefile: 109
file content (115 lines) | stat: -rw-r--r-- 2,111 bytes parent folder | download | duplicates (2)
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
// SPDX-License-Identifier: GPL-2.0
/*
 * utils: set of common functions
 *
 * Copyright (C) 2020 Patrick Uiterwijk <patrick@puiterwijk.org>
 * Copyright (C) 2010 Cyril Hrubis <chrubis@suse.cz>
 */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#include "utils.h"

#ifndef MIN
# define MIN(a, b) ({ \
	typeof(a) _a = (a); \
	typeof(b) _b = (b); \
	_a < _b ? _a : _b; \
})
#endif /* MIN */

static int file_exist(const char *path)
{
	struct stat st;

	if (!access(path, R_OK) && !stat(path, &st) && S_ISREG(st.st_mode))
		return 1;

	return 0;
}

int get_cmd_path(const char *prog_name, char *buf, size_t buf_len)
{
	const char *path = (const char *)getenv("PATH");
	const char *start = path;
	const char *end;
	size_t size, ret;

	if (path == NULL)
		return -1;

	do {
		end = strchr(start, ':');

		if (end != NULL)
			snprintf(buf, MIN(buf_len, (size_t) (end - start + 1)),
				 "%s", start);
		else
			snprintf(buf, buf_len, "%s", start);

		size = strlen(buf);

		/*
		 * "::" inside $PATH, $PATH ending with ':' or $PATH starting
		 * with ':' should be expanded into current working directory.
		 */
		if (size == 0) {
			snprintf(buf, buf_len, ".");
			size = strlen(buf);
		}

		/*
		 * If there is no '/' ad the end of path from $PATH add it.
		 */
		if (buf[size - 1] != '/')
			ret =
			    snprintf(buf + size, buf_len - size, "/%s",
				     prog_name);
		else
			ret =
			    snprintf(buf + size, buf_len - size, "%s",
				     prog_name);

		if (buf_len - size > ret && file_exist(buf))
			return 0;

		if (end != NULL)
			start = end + 1;

	} while (end != NULL);

	return -1;
}

int hex_to_bin(char ch)
{
	if ((ch >= '0') && (ch <= '9'))
		return ch - '0';
	ch = tolower(ch);
	if ((ch >= 'a') && (ch <= 'f'))
		return ch - 'a' + 10;
	return -1;
}

int hex2bin(void *dst, const char *src, size_t count)
{
	int hi, lo;

	while (count--) {
		if (*src == ' ')
			src++;

		hi = hex_to_bin(*src++);
		lo = hex_to_bin(*src++);

		if ((hi < 0) || (lo < 0))
			return -1;

		*(uint8_t *)dst++ = (hi << 4) | lo;
	}
	return 0;
}