Imported Upstream version 1.8.7
[debian/sudo] / plugins / sudoers / hexchar.c
1 /*
2  * Copyright (c) 2013 Todd C. Miller <Todd.Miller@courtesan.com>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16
17 #include <config.h>
18
19 #include <sys/types.h>
20 #include <stdio.h>
21
22 #include "missing.h"
23 #include "sudo_debug.h"
24 #include "error.h"
25
26 int
27 hexchar(const char *s)
28 {
29     unsigned char result[2];
30     int i;
31     debug_decl(hexchar, SUDO_DEBUG_UTIL)
32
33     for (i = 0; i < 2; i++) {
34         switch (s[i]) {
35         case '0':
36             result[i] = 0;
37             break;
38         case '1':
39             result[i] = 1;
40             break;
41         case '2':
42             result[i] = 2;
43             break;
44         case '3':
45             result[i] = 3;
46             break;
47         case '4':
48             result[i] = 4;
49             break;
50         case '5':
51             result[i] = 5;
52             break;
53         case '6':
54             result[i] = 6;
55             break;
56         case '7':
57             result[i] = 7;
58             break;
59         case '8':
60             result[i] = 8;
61             break;
62         case '9':
63             result[i] = 9;
64             break;
65         case 'A':
66         case 'a':
67             result[i] = 10;
68             break;
69         case 'B':
70         case 'b':
71             result[i] = 11;
72             break;
73         case 'C':
74         case 'c':
75             result[i] = 12;
76             break;
77         case 'D':
78         case 'd':
79             result[i] = 13;
80             break;
81         case 'E':
82         case 'e':
83             result[i] = 14;
84             break;
85         case 'F':
86         case 'f':
87             result[i] = 15;
88             break;
89         default:
90             /* Should not happen. */
91             fatalx("internal error, \\x%s not in proper hex format", s);
92         }
93     }
94     debug_return_int((result[0] << 4) | result[1]);
95 }