Fixed possible crash in silc_parse_userfqdn
[runtime.git] / lib / silcutil / silcutil.c
1 /*
2
3   silcutil.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 1997 - 2008 Pekka Riikonen
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; version 2 of the License.
12
13   This program is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18 */
19 /*
20  * These are general utility functions that doesn't belong to any specific
21  * group of routines.
22  */
23
24 #include "silcruntime.h"
25
26 /* Gets line from a buffer. Stops reading when a newline or EOF occurs.
27    This doesn't remove the newline sign from the destination buffer. The
28    argument begin is returned and should be passed again for the function. */
29
30 int silc_gets(char *dest, int destlen, const char *src, int srclen, int begin)
31 {
32   static int start = 0;
33   int i;
34
35   memset(dest, 0, destlen);
36
37   if (begin != start)
38     start = 0;
39
40   i = 0;
41   for ( ; start <= srclen; i++, start++) {
42     if (i > destlen) {
43       silc_set_errno(SILC_ERR_OVERFLOW);
44       return -1;
45     }
46
47     dest[i] = src[start];
48
49     if (dest[i] == EOF) {
50       silc_set_errno(SILC_ERR_EOF);
51       return EOF;
52     }
53
54     if (dest[i] == '\n')
55       break;
56   }
57   start++;
58
59   return start;
60 }
61
62 /* Converts string to capital characters. */
63
64 SilcBool silc_to_upper(const char *string, char *dest, SilcUInt32 dest_size)
65 {
66   int i;
67
68   if (strlen(string) > dest_size) {
69     silc_set_errno(SILC_ERR_OVERFLOW);
70     return FALSE;
71   }
72
73   for (i = 0; i < strlen(string); i++)
74     dest[i] = (char)toupper((int)string[i]);
75
76   return TRUE;
77 }
78
79 /* Converts string to lower letter characters. */
80
81 SilcBool silc_to_lower(const char *string, char *dest, SilcUInt32 dest_size)
82 {
83   int i;
84
85   if (strlen(string) > dest_size) {
86     silc_set_errno(SILC_ERR_OVERFLOW);
87     return FALSE;
88   }
89
90   for (i = 0; i < strlen(string); i++)
91     dest[i] = (char)tolower((int)string[i]);
92
93   return TRUE;
94 }
95
96 /* Parse userfqdn string which is in user@fqdn format. */
97
98 int silc_parse_userfqdn(const char *string,
99                         char *user, SilcUInt32 user_size,
100                         char *fqdn, SilcUInt32 fqdn_size)
101 {
102   SilcUInt32 tlen;
103
104   if (!user && !fqdn) {
105     silc_set_errno(SILC_ERR_INVALID_ARGUMENT);
106     return 0;
107   }
108
109   if (user)
110     memset(user, 0, user_size);
111   if (fqdn)
112     memset(fqdn, 0, fqdn_size);
113
114   if (!string) {
115     silc_set_errno(SILC_ERR_INVALID_ARGUMENT);
116     return 0;
117   }
118
119   if (string[0] == '@') {
120     if (user)
121       silc_strncat(user, user_size, string, strlen(string));
122
123     return 1;
124   }
125
126   if (strchr(string, '@')) {
127     tlen = strcspn(string, "@");
128
129     if (user)
130       silc_strncat(user, user_size, string, tlen);
131
132     if (fqdn)
133       silc_strncat(fqdn, fqdn_size, string + tlen + 1,
134                    strlen(string) - tlen - 1);
135
136     return 2;
137   }
138
139   if (user)
140     silc_strncat(user, user_size, string, strlen(string));
141
142   return 1;
143 }
144
145 /* Parses command line. At most `max_args' is taken. Rest of the line
146    will be allocated as the last argument if there are more than `max_args'
147    arguments in the line. Note that the command name is counted as one
148    argument and is saved. */
149
150 void silc_parse_command_line(unsigned char *buffer,
151                              unsigned char ***parsed,
152                              SilcUInt32 **parsed_lens,
153                              SilcUInt32 **parsed_types,
154                              SilcUInt32 *parsed_num,
155                              SilcUInt32 max_args)
156 {
157   int i, len = 0;
158   int argc = 0;
159   const char *cp = (const char *)buffer;
160   char *tmp;
161
162   *parsed = silc_calloc(1, sizeof(**parsed));
163   *parsed_lens = silc_calloc(1, sizeof(**parsed_lens));
164
165   /* Get the command first */
166   len = strcspn(cp, " ");
167   tmp = silc_calloc(strlen(cp) + 1, sizeof(*tmp));
168   if (!tmp)
169     return;
170   silc_to_upper(cp, tmp, strlen(cp));
171   (*parsed)[0] = silc_calloc(len + 1, sizeof(char));
172   memcpy((*parsed)[0], tmp, len);
173   silc_free(tmp);
174   (*parsed_lens)[0] = len;
175   cp += len;
176   while (*cp == ' ')
177     cp++;
178   argc++;
179
180   /* Parse arguments */
181   if (strchr(cp, ' ') || strlen(cp) != 0) {
182     for (i = 1; i < max_args; i++) {
183
184       if (i != max_args - 1)
185         len = strcspn(cp, " ");
186       else
187         len = strlen(cp);
188       while (len && cp[len - 1] == ' ')
189         len--;
190       if (!len)
191         break;
192
193       *parsed = silc_realloc(*parsed, sizeof(**parsed) * (argc + 1));
194       *parsed_lens = silc_realloc(*parsed_lens,
195                                   sizeof(**parsed_lens) * (argc + 1));
196       (*parsed)[argc] = silc_calloc(len + 1, sizeof(char));
197       memcpy((*parsed)[argc], cp, len);
198       (*parsed_lens)[argc] = len;
199       argc++;
200
201       cp += len;
202       if (strlen(cp) == 0)
203         break;
204       else
205         while (*cp == ' ')
206           cp++;
207     }
208   }
209
210   /* Save argument types. Protocol defines all argument types but
211      this implementation makes sure that they are always in correct
212      order hence this simple code. */
213   *parsed_types = silc_calloc(argc, sizeof(**parsed_types));
214   for (i = 0; i < argc; i++)
215     (*parsed_types)[i] = i;
216
217   *parsed_num = argc;
218 }
219
220 /* Formats arguments to a string and returns it after allocating memory
221    for it. It must be remembered to free it later. */
222
223 char *silc_format(char *fmt, ...)
224 {
225   va_list args;
226   char buf[8192];
227
228   va_start(args, fmt);
229   silc_vsnprintf(buf, sizeof(buf), fmt, args);
230   va_end(args);
231
232   return silc_strdup(buf);
233 }
234
235 /* Creates fingerprint from data, usually used with SHA1 digests */
236
237 char *silc_fingerprint(const unsigned char *data, SilcUInt32 data_len)
238 {
239   unsigned char *fingerprint, *cp;
240   unsigned int len, blocks, i;
241
242   if (!data || !data_len) {
243     silc_set_errno(SILC_ERR_INVALID_ARGUMENT);
244     return NULL;
245   }
246
247   if (data_len >= 256)
248     data_len = 255;
249
250   /* Align and calculate total length */
251   len = ((data_len + 19) / 20) * 20;
252   blocks = (len / 10);
253   len = (len * 2) + ((blocks - 1) * 2) + (4 * blocks) + 2 + 1;
254
255   cp = fingerprint = silc_calloc(len, sizeof(*fingerprint));
256   if (!cp)
257     return NULL;
258
259   for (i = 0; i < data_len; i++) {
260     silc_snprintf((char *)cp, len, "%02X", data[i]);
261     cp += 2;
262     len -= 2;
263
264     if ((i + 1) % 2 == 0)
265       silc_snprintf((char *)cp++, len--, " ");
266     if ((i + 1) % 10 == 0)
267       silc_snprintf((char *)cp++, len--, " ");
268   }
269   i--;
270   if ((i + 1) % 10 == 0)
271     *(--cp) = '\0';
272   if ((i + 1) % 2 == 0)
273     *(--cp) = '\0';
274
275   return (char *)fingerprint;
276 }
277
278 /* Return TRUE if the `data' is ASCII string. */
279
280 SilcBool silc_string_is_ascii(const unsigned char *data, SilcUInt32 data_len)
281 {
282   int i;
283
284   for (i = 0; i < data_len; i++) {
285     if (!isascii(data[i]))
286       return FALSE;
287   }
288
289   return TRUE;
290 }
291
292 /* Displays input prompt on command line and takes input data from user */
293
294 char *silc_get_input(const char *prompt, SilcBool echo_off)
295 {
296 #ifdef SILC_UNIX
297   int fd;
298   char input[2048];
299
300   if (echo_off) {
301     char *ret = NULL;
302 #ifdef HAVE_TERMIOS_H
303     struct termios to;
304     struct termios to_old;
305
306     fd = open("/dev/tty", O_RDONLY);
307     if (fd < 0) {
308       silc_set_errno_posix(errno);
309       return NULL;
310     }
311
312     signal(SIGINT, SIG_IGN);
313
314     /* Get terminal info */
315     tcgetattr(fd, &to);
316     to_old = to;
317
318     /* Echo OFF, and assure we can prompt and get input */
319     to.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
320     to.c_lflag |= ICANON;
321     to.c_cc[VMIN] = 255;
322     tcsetattr(fd, TCSANOW, &to);
323
324     memset(input, 0, sizeof(input));
325
326     printf("%s", prompt);
327     fflush(stdout);
328
329     if ((read(fd, input, sizeof(input))) < 0) {
330       silc_set_errno_posix(errno);
331       tcsetattr(fd, TCSANOW, &to_old);
332       return NULL;
333     }
334
335     if (strlen(input) <= 1) {
336       tcsetattr(fd, TCSANOW, &to_old);
337       silc_set_errno(SILC_ERR_EOF);
338       return NULL;
339     }
340
341     if (strchr(input, '\n'))
342       *strchr(input, '\n') = '\0';
343
344     /* Restore old terminfo */
345     tcsetattr(fd, TCSANOW, &to_old);
346     signal(SIGINT, SIG_DFL);
347
348     ret = silc_memdup(input, strlen(input));
349     memset(input, 0, sizeof(input));
350 #endif /* HAVE_TERMIOS_H */
351     return ret;
352   } else {
353     fd = open("/dev/tty", O_RDONLY);
354     if (fd < 0) {
355       silc_set_errno_posix(errno);
356       return NULL;
357     }
358
359     memset(input, 0, sizeof(input));
360
361     printf("%s", prompt);
362     fflush(stdout);
363
364     if ((read(fd, input, sizeof(input))) < 0) {
365       silc_set_errno_posix(errno);
366       return NULL;
367     }
368
369     if (strlen(input) <= 1) {
370       silc_set_errno(SILC_ERR_EOF);
371       return NULL;
372     }
373
374     if (strchr(input, '\n'))
375       *strchr(input, '\n') = '\0';
376
377     return silc_strdup(input);
378   }
379 #else
380   return NULL;
381 #endif /* SILC_UNIX */
382 }
383
384 /* Hexdump */
385
386 void silc_hexdump(const unsigned char *data, SilcUInt32 data_len,
387                   FILE *output)
388 {
389   int i, k;
390   int off, pos, count;
391   int len = data_len;
392
393   k = 0;
394   pos = 0;
395   count = 16;
396   off = len % 16;
397   while (1) {
398     if (off) {
399       if ((len - pos) < 16 && (len - pos <= len - off))
400         count = off;
401     } else {
402       if (pos == len)
403         count = 0;
404     }
405     if (off == len)
406       count = len;
407
408     if (count)
409       fprintf(output, "%08X  ", k++ * 16);
410
411     for (i = 0; i < count; i++) {
412       fprintf(output, "%02X ", data[pos + i]);
413
414       if ((i + 1) % 4 == 0)
415         fprintf(output, " ");
416     }
417
418     if (count && count < 16) {
419       int j;
420
421       for (j = 0; j < 16 - count; j++) {
422         fprintf(output, "   ");
423
424         if ((j + count + 1) % 4 == 0)
425           fprintf(output, " ");
426       }
427     }
428
429     for (i = 0; i < count; i++) {
430       char ch;
431
432       if (data[pos] < 32 || data[pos] >= 127)
433         ch = '.';
434       else
435         ch = data[pos];
436
437       fprintf(output, "%c", ch);
438       pos++;
439     }
440
441     if (count)
442       fprintf(output, "\n");
443
444     if (count < 16)
445       break;
446   }
447 }
448
449 /* Convert hex string to data.  Each hex number must have two characters. */
450
451 SilcBool silc_hex2data(const char *hex, unsigned char *data,
452                        SilcUInt32 data_size, SilcUInt32 *ret_data_len)
453 {
454   char *cp = (char *)hex;
455   unsigned char l, h;
456   int i;
457
458   if (data_size < strlen(hex) / 2) {
459     silc_set_errno(SILC_ERR_OVERFLOW);
460     return FALSE;
461   }
462
463   for (i = 0; i < strlen(hex) / 2; i++) {
464     h = *cp++;
465     l = *cp++;
466
467     h -= h < 'A' ? '0' : 'A' - 10;
468     l -= l < 'A' ? '0' : 'A' - 10;
469
470     data[i] = (h << 4) | (l & 0xf);
471   }
472
473   if (ret_data_len)
474     *ret_data_len = i;
475
476   return TRUE;
477 }
478
479 /* Converts binary data to HEX string */
480
481 SilcBool silc_data2hex(const unsigned char *data, SilcUInt32 data_len,
482                        char *hex, SilcUInt32 hex_size)
483 {
484   unsigned char l, h;
485   char *cp = hex;
486   int i;
487
488   if (hex_size - 1 < data_len * 2) {
489     silc_set_errno(SILC_ERR_OVERFLOW);
490     return FALSE;
491   }
492
493   memset(hex, 0, hex_size);
494
495   for (i = 0; i < data_len; i++) {
496     l = data[i];
497     h = l >> 4;
498     l &= 0xf;
499
500     *cp++ = h + (h > 9 ? 'A' - 10 : '0');
501     *cp++ = l + (l > 9 ? 'A' - 10 : '0');
502   }
503
504   return TRUE;
505 }