Code auditing weekend results and fixes committing.
[silc.git] / lib / silcutil / silcutil.c
1 /*
2
3   silcutil.c
4
5   Author: Pekka Riikonen <priikone@poseidon.pspt.fi>
6
7   Copyright (C) 1997 - 2000 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; either version 2 of the License, or
12   (at your option) any later version.
13   
14   This program is distributed in the hope that it will be useful,
15   but WITHOUT ANY WARRANTY; without even the implied warranty of
16   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   GNU General Public License for more details.
18
19 */
20 /*
21  * These are general utility functions that doesn't belong to any specific
22  * group of routines.
23  */
24 /* $Id$ */
25
26 #include "silcincludes.h"
27
28 /* Reads a file to a buffer. The allocated buffer is returned. Length of
29    the file read is returned to the return_len argument. */
30
31 char *silc_file_read(const char *filename, int *return_len)
32 {
33   int fd;
34   char *buffer;
35   int filelen;
36
37   fd = open(filename, O_RDONLY);
38   if (fd < 0) {
39     SILC_LOG_ERROR(("Cannot open file %s: %s", filename, strerror(errno)));
40     return NULL;
41   }
42
43   filelen = lseek(fd, (off_t)0L, SEEK_END);
44   if (filelen < 0)
45     return NULL;
46   if (lseek(fd, (off_t)0L, SEEK_SET) < 0)
47     return NULL;
48
49   if (filelen < 0) {
50     SILC_LOG_ERROR(("Cannot open file %s: %s", filename, strerror(errno)));
51     return NULL;
52   }
53   
54   buffer = silc_calloc(filelen + 1, sizeof(char));
55   
56   if ((read(fd, buffer, filelen)) == -1) {
57     memset(buffer, 0, sizeof(buffer));
58     close(fd);
59     SILC_LOG_ERROR(("Cannot read from file %s: %s", filename,
60                     strerror(errno)));
61     return NULL;
62   }
63
64   close(fd);
65   buffer[filelen] = EOF;
66
67   if (return_len)
68     *return_len = filelen;
69
70   return buffer;
71 }
72
73 /* Writes a buffer to the file. */
74
75 int silc_file_write(const char *filename, const char *buffer, int len)
76 {
77   int fd;
78         
79   if ((fd = creat(filename, 0644)) == -1) {
80     SILC_LOG_ERROR(("Cannot open file %s for writing: %s", strerror(errno)));
81     return -1;
82   }
83   
84   if ((write(fd, buffer, len)) == -1) {
85     SILC_LOG_ERROR(("Cannot write to file %s: %s", strerror(errno)));
86     return -1;
87   }
88
89   close(fd);
90   
91   return 0;
92 }
93
94 /* Writes a buffer to the file.  If the file is created specific mode is
95    set to the file. */
96
97 int silc_file_write_mode(const char *filename, const char *buffer, 
98                          int len, int mode)
99 {
100   int fd;
101         
102   if ((fd = creat(filename, mode)) == -1) {
103     SILC_LOG_ERROR(("Cannot open file %s for writing: %s", strerror(errno)));
104     return -1;
105   }
106   
107   if ((write(fd, buffer, len)) == -1) {
108     SILC_LOG_ERROR(("Cannot write to file %s: %s", strerror(errno)));
109     return -1;
110   }
111
112   close(fd);
113   
114   return 0;
115 }
116
117 /* Gets line from a buffer. Stops reading when a newline or EOF occurs.
118    This doesn't remove the newline sign from the destination buffer. The
119    argument begin is returned and should be passed again for the function. */
120
121 int silc_gets(char *dest, int destlen, const char *src, int srclen, int begin)
122 {
123   static int start = 0;
124   int i;
125   
126   memset(dest, 0, destlen);
127   
128   if (begin != start)
129     start = 0;
130   
131   i = 0;
132   for ( ; start <= srclen; i++, start++) {
133     if (i > destlen)
134       return -1;
135     
136     dest[i] = src[start];
137     
138     if (dest[i] == EOF) 
139       return EOF;
140     
141     if (dest[i] == '\n') 
142       break;
143   }
144   start++;
145   
146   return start;
147 }
148
149 /* Checks line for illegal characters. Return -1 when illegal character
150    were found. This is used to check for bad lines when reading data from
151    for example a configuration file. */
152
153 int silc_check_line(char *buf) 
154 {
155   /* Illegal characters in line */
156   if (strchr(buf, '#')) return -1;
157   if (strchr(buf, '\'')) return -1;
158   if (strchr(buf, '\\')) return -1;
159   if (strchr(buf, '\r')) return -1;
160   if (strchr(buf, '\a')) return -1;
161   if (strchr(buf, '\b')) return -1;
162   if (strchr(buf, '\f')) return -1;
163   
164   /* Empty line */
165   if (buf[0] == '\n')
166     return -1;
167   
168   return 0;
169 }
170
171 /* Returns current time as string. */
172
173 char *silc_get_time()
174 {
175   time_t curtime;
176   char *return_time;
177
178   curtime = time(NULL);
179   return_time = ctime(&curtime);
180   return_time[strlen(return_time) - 1] = '\0';
181
182   return return_time;
183 }
184
185 /* Converts string to capital characters */
186
187 char *silc_to_upper(char *string)
188 {
189   int i;
190   char *ret = silc_calloc(strlen(string) + 1, sizeof(char));
191
192   for (i = 0; i < strlen(string); i++)
193     ret[i] = toupper(string[i]);
194
195   return ret;
196 }
197
198 /* Compares two strings. Strings may include wildcards * and ?.
199    Returns TRUE if strings match. */
200
201 int silc_string_compare(char *string1, char *string2)
202 {
203   int i;
204   int slen1 = strlen(string1);
205   int slen2 = strlen(string2);
206   char *tmpstr1, *tmpstr2;
207
208   if (!string1 || !string2)
209     return FALSE;
210
211   /* See if they are same already */
212   if (!strncmp(string1, string2, strlen(string2)))
213     return TRUE;
214
215   if (slen2 < slen1)
216     if (!strchr(string1, '*'))
217       return FALSE;
218   
219   /* Take copies of the original strings as we will change them */
220   tmpstr1 = silc_calloc(slen1 + 1, sizeof(char));
221   memcpy(tmpstr1, string1, slen1);
222   tmpstr2 = silc_calloc(slen2 + 1, sizeof(char));
223   memcpy(tmpstr2, string2, slen2);
224   
225   for (i = 0; i < slen2; i++) {
226     
227     /* * wildcard. Only one * wildcard is possible. */
228     if (tmpstr1[i] == '*')
229       if (!strncmp(tmpstr1, tmpstr2, i)) {
230         memset(tmpstr2, 0, slen2);
231         strncpy(tmpstr2, tmpstr1, i);
232         break;
233       }
234     
235     /* ? wildcard */
236     if (tmpstr1[i] == '?') {
237       if (!strncmp(tmpstr1, tmpstr2, i)) {
238         if (!(slen1 < i + 1))
239           if (tmpstr1[i + 1] != '?' &&
240               tmpstr1[i + 1] != tmpstr2[i + 1])
241             continue;
242         
243         if (!(slen1 < slen2))
244           tmpstr2[i] = '?';
245       }
246 #if 0
247     } else {
248       if (strncmp(tmpstr1, tmpstr2, i))
249         strncpy(tmpstr2, string2, slen2);
250 #endif
251     }
252   }
253   
254   /* if using *, remove it */
255   if (strchr(tmpstr1, '*'))
256     *strchr(tmpstr1, '*') = 0;
257   
258   if (!strcmp(tmpstr1, tmpstr2)) {
259     memset(tmpstr1, 0, slen1);
260     memset(tmpstr2, 0, slen2);
261     silc_free(tmpstr1);
262     silc_free(tmpstr2);
263     return TRUE;
264   }
265   
266   memset(tmpstr1, 0, slen1);
267   memset(tmpstr2, 0, slen2);
268   silc_free(tmpstr1);
269   silc_free(tmpstr2);
270   return FALSE;
271 }
272
273 static unsigned char pem_enc[64] =
274 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
275
276 /* Encodes data into PEM encoding. Returns NULL terminated PEM encoded
277    data string. Note: This is originally public domain code and is 
278    still PD. */
279
280 char *silc_encode_pem(unsigned char *data, unsigned int len)
281 {
282   int i, j;
283   unsigned int bits, c, char_count;
284   char *pem;
285
286   char_count = 0;
287   bits = 0;
288   j = 0;
289
290   pem = silc_calloc(((len * 8 + 5) / 6) + 5, sizeof(*pem));
291
292   for (i = 0; i < len; i++) {
293     c = data[i];
294     bits += c;
295     char_count++;
296
297     if (char_count == 3) {
298       pem[j++] = pem_enc[bits  >> 18];
299       pem[j++] = pem_enc[(bits >> 12) & 0x3f];
300       pem[j++] = pem_enc[(bits >> 6)  & 0x3f];
301       pem[j++] = pem_enc[bits & 0x3f];
302       bits = 0;
303       char_count = 0;
304     } else {
305       bits <<= 8;
306     }
307   }
308
309   if (char_count != 0) {
310     bits <<= 16 - (8 * char_count);
311     pem[j++] = pem_enc[bits >> 18];
312     pem[j++] = pem_enc[(bits >> 12) & 0x3f];
313
314     if (char_count == 1) {
315       pem[j++] = '=';
316       pem[j] = '=';
317     } else {
318       pem[j++] = pem_enc[(bits >> 6) & 0x3f];
319       pem[j] = '=';
320     }
321   }
322
323   return pem;
324 }
325
326 /* Same as above but puts newline ('\n') every 72 characters. */
327
328 char *silc_encode_pem_file(unsigned char *data, unsigned int data_len)
329 {
330   int i, j;
331   unsigned int len, cols;
332   char *pem, *pem2;
333
334   pem = silc_encode_pem(data, data_len);
335   len = strlen(pem);
336
337   pem2 = silc_calloc(len + (len / 72) + 1, sizeof(*pem2));
338
339   for (i = 0, j = 0, cols = 1; i < len; i++, cols++) {
340     if (cols == 72) {
341       pem2[i] = '\n';
342       cols = 0;
343       len++;
344       continue;
345     }
346
347     pem2[i] = pem[j++];
348   }
349
350   return pem2;
351 }
352
353 /* Decodes PEM into data. Returns the decoded data. Note: This is
354    originally public domain code and is still PD. */
355
356 unsigned char *silc_decode_pem(unsigned char *pem, unsigned int pem_len,
357                                unsigned int *ret_len)
358 {
359   int i, j;
360   unsigned int len, c, char_count, bits;
361   unsigned char *data;
362   static char ialpha[256], decoder[256];
363
364   for (i = 64 - 1; i >= 0; i--) {
365     ialpha[pem_enc[i]] = 1;
366     decoder[pem_enc[i]] = i;
367   }
368
369   char_count = 0;
370   bits = 0;
371   j = 0;
372
373   if (!pem_len)
374     len = strlen(pem);
375   else
376     len = pem_len;
377
378   data = silc_calloc(((len * 6) / 8), sizeof(*data));
379
380   for (i = 0; i < len; i++) {
381     c = pem[i];
382
383     if (c == '=')
384       break;
385
386     if (c > 127 || !ialpha[c])
387       continue;
388
389     bits += decoder[c];
390     char_count++;
391
392     if (char_count == 4) {
393       data[j++] = bits >> 16;
394       data[j++] = (bits >> 8) & 0xff;
395       data[j++] = bits & 0xff;
396       bits = 0;
397       char_count = 0;
398     } else {
399       bits <<= 6;
400     }
401   }
402
403   switch(char_count) {
404   case 1:
405     silc_free(data);
406     return NULL;
407     break;
408   case 2:
409     data[j++] = bits >> 10;
410     break;
411   case 3:
412     data[j++] = bits >> 16;
413     data[j++] = (bits >> 8) & 0xff;
414     break;
415   }
416
417   if (ret_len)
418     *ret_len = j;
419
420   return data;
421 }
422
423 /* Parse nickname string. The format may be <num>!<nickname>@<server> to
424    support multiple same nicknames. The <num> is the final unifier if same
425    nickname is on same server. Note, this is only local format and server
426    does not know anything about these. */
427
428 int silc_parse_nickname(char *string, char **nickname, char **server,
429                         unsigned int *num)
430 {
431   unsigned int tlen;
432   char tmp[256];
433
434   if (!string)
435     return FALSE;
436
437   if (strchr(string, '!')) {
438     tlen = strcspn(string, "!");
439     memset(tmp, 0, sizeof(tmp));
440     memcpy(tmp, string, tlen);
441
442     if (num)
443       *num = atoi(tmp);
444
445     if (tlen >= strlen(string))
446       return FALSE;
447
448     string += tlen + 1;
449   }
450
451   if (strchr(string, '@')) {
452     tlen = strcspn(string, "@");
453     
454     if (nickname) {
455       *nickname = silc_calloc(tlen + 1, sizeof(char));
456       memcpy(*nickname, string, tlen);
457     }
458     
459     if (server) {
460       *server = silc_calloc((strlen(string) - tlen) + 1, sizeof(char));
461       memcpy(*server, string + tlen + 1, strlen(string) - tlen - 1);
462     }
463   } else {
464     if (nickname)
465       *nickname = strdup(string);
466   }
467
468   return TRUE;
469 }
470
471 /* Parses command line. At most `max_args' is taken. Rest of the line
472    will be allocated as the last argument if there are more than `max_args'
473    arguments in the line. Note that the command name is counted as one
474    argument and is saved. */
475
476 void silc_parse_command_line(unsigned char *buffer, 
477                              unsigned char ***parsed,
478                              unsigned int **parsed_lens,
479                              unsigned int **parsed_types,
480                              unsigned int *parsed_num,
481                              unsigned int max_args)
482 {
483   int i, len = 0;
484   int argc = 0;
485   const char *cp = buffer;
486
487   *parsed = silc_calloc(1, sizeof(**parsed));
488   *parsed_lens = silc_calloc(1, sizeof(**parsed_lens));
489
490   /* Get the command first */
491   len = strcspn(cp, " ");
492   (*parsed)[0] = silc_to_upper((char *)cp);
493   (*parsed_lens)[0] = len;
494   cp += len + 1;
495   argc++;
496
497   /* Parse arguments */
498   if (strchr(cp, ' ') || strlen(cp) != 0) {
499     for (i = 1; i < max_args; i++) {
500
501       if (i != max_args - 1)
502         len = strcspn(cp, " ");
503       else
504         len = strlen(cp);
505       
506       *parsed = silc_realloc(*parsed, sizeof(**parsed) * (argc + 1));
507       *parsed_lens = silc_realloc(*parsed_lens, 
508                                   sizeof(**parsed_lens) * (argc + 1));
509       (*parsed)[argc] = silc_calloc(len + 1, sizeof(char));
510       memcpy((*parsed)[argc], cp, len);
511       (*parsed_lens)[argc] = len;
512       argc++;
513
514       cp += len;
515       if (strlen(cp) == 0)
516         break;
517       else
518         cp++;
519     }
520   }
521
522   /* Save argument types. Protocol defines all argument types but
523      this implementation makes sure that they are always in correct
524      order hence this simple code. */
525   *parsed_types = silc_calloc(argc, sizeof(**parsed_types));
526   for (i = 0; i < argc; i++)
527     (*parsed_types)[i] = i;
528
529   *parsed_num = argc;
530 }
531
532 /* Formats arguments to a string and returns it after allocating memory
533    for it. It must be remembered to free it later. */
534
535 char *silc_format(char *fmt, ...)
536 {
537   va_list args;
538   static char buf[8192];
539
540   memset(buf, 0, sizeof(buf));
541   va_start(args, fmt);
542   vsnprintf(buf, sizeof(buf) - 1, fmt, args);
543   va_end(args);
544
545   return strdup(buf);
546 }
547
548 /* Renders ID to suitable to print for example to log file. */
549
550 static char rid[256];
551
552 char *silc_id_render(void *id, unsigned short type)
553 {
554   char tmp[100];
555   unsigned char tmps[2];
556
557   memset(rid, 0, sizeof(rid));
558   switch(type) {
559   case SILC_ID_SERVER:
560     {
561       SilcServerID *server_id = (SilcServerID *)id;
562       strcat(rid, inet_ntoa(server_id->ip));
563       memset(tmp, 0, sizeof(tmp));
564       snprintf(tmp, sizeof(tmp), ",%d,", ntohs(server_id->port));
565       strcat(rid, tmp);
566       SILC_PUT16_MSB(server_id->rnd, tmps);
567       memset(tmp, 0, sizeof(tmp));
568       snprintf(tmp, sizeof(tmp), "[%02x %02x]", tmps[0], tmps[1]);
569       strcat(rid, tmp);
570     }
571     break;
572   case SILC_ID_CLIENT:
573     {
574       SilcClientID *client_id = (SilcClientID *)id;
575       strcat(rid, inet_ntoa(client_id->ip));
576       memset(tmp, 0, sizeof(tmp));
577       snprintf(tmp, sizeof(tmp), ",%02x,", client_id->rnd);
578       strcat(rid, tmp);
579       memset(tmp, 0, sizeof(tmp));
580       snprintf(tmp, sizeof(tmp), "[%02x %02x %02x %02x...]", 
581                client_id->hash[0], client_id->hash[1],
582                client_id->hash[2], client_id->hash[3]);
583       strcat(rid, tmp);
584     }
585     break;
586   case SILC_ID_CHANNEL:
587     {
588       SilcChannelID *channel_id = (SilcChannelID *)id;
589       strcat(rid, inet_ntoa(channel_id->ip));
590       memset(tmp, 0, sizeof(tmp));
591       snprintf(tmp, sizeof(tmp), ",%d,", ntohs(channel_id->port));
592       strcat(rid, tmp);
593       SILC_PUT16_MSB(channel_id->rnd, tmps);
594       memset(tmp, 0, sizeof(tmp));
595       snprintf(tmp, sizeof(tmp), "[%02x %02x]", tmps[0], tmps[1]);
596       strcat(rid, tmp);
597     }
598     break;
599   }
600
601   return rid;
602 }