5 Author: Pekka Riikonen <priikone@poseidon.pspt.fi>
7 Copyright (C) 1997 - 2000 Pekka Riikonen
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.
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.
21 * These are general utility functions that doesn't belong to any specific
26 #include "silcincludes.h"
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. */
31 char *silc_file_read(const char *filename, uint32 *return_len)
37 fd = open(filename, O_RDONLY);
39 SILC_LOG_ERROR(("Cannot open file %s: %s", filename, strerror(errno)));
43 filelen = lseek(fd, (off_t)0L, SEEK_END);
46 if (lseek(fd, (off_t)0L, SEEK_SET) < 0)
50 SILC_LOG_ERROR(("Cannot open file %s: %s", filename, strerror(errno)));
54 buffer = silc_calloc(filelen + 1, sizeof(char));
56 if ((read(fd, buffer, filelen)) == -1) {
57 memset(buffer, 0, sizeof(buffer));
59 SILC_LOG_ERROR(("Cannot read from file %s: %s", filename,
65 buffer[filelen] = EOF;
68 *return_len = filelen;
73 /* Writes a buffer to the file. */
75 int silc_file_write(const char *filename, const char *buffer, uint32 len)
79 if ((fd = creat(filename, 0644)) == -1) {
80 SILC_LOG_ERROR(("Cannot open file %s for writing: %s", strerror(errno)));
84 if ((write(fd, buffer, len)) == -1) {
85 SILC_LOG_ERROR(("Cannot write to file %s: %s", strerror(errno)));
94 /* Writes a buffer to the file. If the file is created specific mode is
97 int silc_file_write_mode(const char *filename, const char *buffer,
102 if ((fd = creat(filename, mode)) == -1) {
103 SILC_LOG_ERROR(("Cannot open file %s for writing: %s", strerror(errno)));
107 if ((write(fd, buffer, len)) == -1) {
108 SILC_LOG_ERROR(("Cannot write to file %s: %s", strerror(errno)));
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. */
121 int silc_gets(char *dest, int destlen, const char *src, int srclen, int begin)
123 static int start = 0;
126 memset(dest, 0, destlen);
132 for ( ; start <= srclen; i++, start++) {
136 dest[i] = src[start];
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. */
153 int silc_check_line(char *buf)
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;
171 /* Returns current time as string. */
173 char *silc_get_time()
178 curtime = time(NULL);
179 return_time = ctime(&curtime);
180 return_time[strlen(return_time) - 1] = '\0';
185 /* Converts string to capital characters */
187 char *silc_to_upper(char *string)
190 char *ret = silc_calloc(strlen(string) + 1, sizeof(char));
192 for (i = 0; i < strlen(string); i++)
193 ret[i] = toupper(string[i]);
198 static unsigned char pem_enc[64] =
199 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
201 /* Encodes data into PEM encoding. Returns NULL terminated PEM encoded
202 data string. Note: This is originally public domain code and is
205 char *silc_encode_pem(unsigned char *data, uint32 len)
208 uint32 bits, c, char_count;
215 pem = silc_calloc(((len * 8 + 5) / 6) + 5, sizeof(*pem));
217 for (i = 0; i < len; i++) {
222 if (char_count == 3) {
223 pem[j++] = pem_enc[bits >> 18];
224 pem[j++] = pem_enc[(bits >> 12) & 0x3f];
225 pem[j++] = pem_enc[(bits >> 6) & 0x3f];
226 pem[j++] = pem_enc[bits & 0x3f];
234 if (char_count != 0) {
235 bits <<= 16 - (8 * char_count);
236 pem[j++] = pem_enc[bits >> 18];
237 pem[j++] = pem_enc[(bits >> 12) & 0x3f];
239 if (char_count == 1) {
243 pem[j++] = pem_enc[(bits >> 6) & 0x3f];
251 /* Same as above but puts newline ('\n') every 72 characters. */
253 char *silc_encode_pem_file(unsigned char *data, uint32 data_len)
259 pem = silc_encode_pem(data, data_len);
262 pem2 = silc_calloc(len + (len / 72) + 1, sizeof(*pem2));
264 for (i = 0, j = 0, cols = 1; i < len; i++, cols++) {
278 /* Decodes PEM into data. Returns the decoded data. Note: This is
279 originally public domain code and is still PD. */
281 unsigned char *silc_decode_pem(unsigned char *pem, uint32 pem_len,
285 uint32 len, c, char_count, bits;
287 static char ialpha[256], decoder[256];
289 for (i = 64 - 1; i >= 0; i--) {
290 ialpha[pem_enc[i]] = 1;
291 decoder[pem_enc[i]] = i;
303 data = silc_calloc(((len * 6) / 8), sizeof(*data));
305 for (i = 0; i < len; i++) {
311 if (c > 127 || !ialpha[c])
317 if (char_count == 4) {
318 data[j++] = bits >> 16;
319 data[j++] = (bits >> 8) & 0xff;
320 data[j++] = bits & 0xff;
334 data[j++] = bits >> 10;
337 data[j++] = bits >> 16;
338 data[j++] = (bits >> 8) & 0xff;
348 /* Parse nickname string. The format may be <num>!<nickname>@<server> to
349 support multiple same nicknames. The <num> is the final unifier if same
350 nickname is on same server. Note, this is only local format and server
351 does not know anything about these. */
353 int silc_parse_nickname(char *string, char **nickname, char **server,
362 if (strchr(string, '!')) {
363 tlen = strcspn(string, "!");
364 memset(tmp, 0, sizeof(tmp));
365 memcpy(tmp, string, tlen);
370 if (tlen >= strlen(string))
376 if (strchr(string, '@')) {
377 tlen = strcspn(string, "@");
380 *nickname = silc_calloc(tlen + 1, sizeof(char));
381 memcpy(*nickname, string, tlen);
385 *server = silc_calloc((strlen(string) - tlen) + 1, sizeof(char));
386 memcpy(*server, string + tlen + 1, strlen(string) - tlen - 1);
390 *nickname = strdup(string);
396 /* Parses command line. At most `max_args' is taken. Rest of the line
397 will be allocated as the last argument if there are more than `max_args'
398 arguments in the line. Note that the command name is counted as one
399 argument and is saved. */
401 void silc_parse_command_line(unsigned char *buffer,
402 unsigned char ***parsed,
403 uint32 **parsed_lens,
404 uint32 **parsed_types,
410 const char *cp = buffer;
412 *parsed = silc_calloc(1, sizeof(**parsed));
413 *parsed_lens = silc_calloc(1, sizeof(**parsed_lens));
415 /* Get the command first */
416 len = strcspn(cp, " ");
417 (*parsed)[0] = silc_to_upper((char *)cp);
418 (*parsed_lens)[0] = len;
422 /* Parse arguments */
423 if (strchr(cp, ' ') || strlen(cp) != 0) {
424 for (i = 1; i < max_args; i++) {
426 if (i != max_args - 1)
427 len = strcspn(cp, " ");
431 *parsed = silc_realloc(*parsed, sizeof(**parsed) * (argc + 1));
432 *parsed_lens = silc_realloc(*parsed_lens,
433 sizeof(**parsed_lens) * (argc + 1));
434 (*parsed)[argc] = silc_calloc(len + 1, sizeof(char));
435 memcpy((*parsed)[argc], cp, len);
436 (*parsed_lens)[argc] = len;
447 /* Save argument types. Protocol defines all argument types but
448 this implementation makes sure that they are always in correct
449 order hence this simple code. */
450 *parsed_types = silc_calloc(argc, sizeof(**parsed_types));
451 for (i = 0; i < argc; i++)
452 (*parsed_types)[i] = i;
457 /* Formats arguments to a string and returns it after allocating memory
458 for it. It must be remembered to free it later. */
460 char *silc_format(char *fmt, ...)
463 static char buf[8192];
465 memset(buf, 0, sizeof(buf));
467 vsnprintf(buf, sizeof(buf) - 1, fmt, args);
473 /* Renders ID to suitable to print for example to log file. */
475 static char rid[256];
477 char *silc_id_render(void *id, uint16 type)
480 unsigned char tmps[2];
482 memset(rid, 0, sizeof(rid));
486 SilcServerID *server_id = (SilcServerID *)id;
487 strcat(rid, inet_ntoa(server_id->ip));
488 memset(tmp, 0, sizeof(tmp));
489 snprintf(tmp, sizeof(tmp), ",%d,", ntohs(server_id->port));
491 SILC_PUT16_MSB(server_id->rnd, tmps);
492 memset(tmp, 0, sizeof(tmp));
493 snprintf(tmp, sizeof(tmp), "[%02x %02x]", tmps[0], tmps[1]);
499 SilcClientID *client_id = (SilcClientID *)id;
500 strcat(rid, inet_ntoa(client_id->ip));
501 memset(tmp, 0, sizeof(tmp));
502 snprintf(tmp, sizeof(tmp), ",%02x,", client_id->rnd);
504 memset(tmp, 0, sizeof(tmp));
505 snprintf(tmp, sizeof(tmp), "[%02x %02x %02x %02x...]",
506 client_id->hash[0], client_id->hash[1],
507 client_id->hash[2], client_id->hash[3]);
511 case SILC_ID_CHANNEL:
513 SilcChannelID *channel_id = (SilcChannelID *)id;
514 strcat(rid, inet_ntoa(channel_id->ip));
515 memset(tmp, 0, sizeof(tmp));
516 snprintf(tmp, sizeof(tmp), ",%d,", ntohs(channel_id->port));
518 SILC_PUT16_MSB(channel_id->rnd, tmps);
519 memset(tmp, 0, sizeof(tmp));
520 snprintf(tmp, sizeof(tmp), "[%02x %02x]", tmps[0], tmps[1]);
529 /* Compares two strings. Strings may include wildcards * and ?.
530 Returns TRUE if strings match. */
532 int silc_string_compare(char *string1, char *string2)
535 int slen1 = strlen(string1);
536 int slen2 = strlen(string2);
537 char *tmpstr1, *tmpstr2;
539 if (!string1 || !string2)
542 /* See if they are same already */
543 if (!strncmp(string1, string2, strlen(string2)))
547 if (!strchr(string1, '*'))
550 /* Take copies of the original strings as we will change them */
551 tmpstr1 = silc_calloc(slen1 + 1, sizeof(char));
552 memcpy(tmpstr1, string1, slen1);
553 tmpstr2 = silc_calloc(slen2 + 1, sizeof(char));
554 memcpy(tmpstr2, string2, slen2);
556 for (i = 0; i < slen2; i++) {
558 /* * wildcard. Only one * wildcard is possible. */
559 if (tmpstr1[i] == '*')
560 if (!strncmp(tmpstr1, tmpstr2, i)) {
561 memset(tmpstr2, 0, slen2);
562 strncpy(tmpstr2, tmpstr1, i);
567 if (tmpstr1[i] == '?') {
568 if (!strncmp(tmpstr1, tmpstr2, i)) {
569 if (!(slen1 < i + 1))
570 if (tmpstr1[i + 1] != '?' &&
571 tmpstr1[i + 1] != tmpstr2[i + 1])
574 if (!(slen1 < slen2))
579 if (strncmp(tmpstr1, tmpstr2, i))
580 strncpy(tmpstr2, string2, slen2);
585 /* if using *, remove it */
586 if (strchr(tmpstr1, '*'))
587 *strchr(tmpstr1, '*') = 0;
589 if (!strcmp(tmpstr1, tmpstr2)) {
590 memset(tmpstr1, 0, slen1);
591 memset(tmpstr2, 0, slen2);
597 memset(tmpstr1, 0, slen1);
598 memset(tmpstr2, 0, slen2);
604 /* Inspects the `string' for wildcards and returns regex string that can
605 be used by the GNU regex library. A comma (`,') in the `string' means
606 that the string is list. */
608 char *silc_string_regexify(const char *string)
613 len = strlen(string);
615 for (i = 0; i < len; i++)
616 if (string[i] == '*' || string[i] == '?')
619 regex = silc_calloc(len + count, sizeof(*regex));
625 for (i = 0; i < len; i++) {
626 if (string[i] == '*' || string[i] == '?') {
629 } else if (string[i] == ',') {
635 regex[count] = string[i];
639 regex[count - 1] = ')';
645 /* Combines two regex strings into one regex string so that they can be
646 used as one by the GNU regex library. The `string2' is combine into
649 char *silc_string_regex_combine(const char *string1, const char *string2)
654 len1 = strlen(string1);
655 len2 = strlen(string2);
657 tmp = silc_calloc(2 + len1 + len2, sizeof(*tmp));
658 strncat(tmp, string1, len1 - 2);
659 strncat(tmp, "|", 1);
660 strncat(tmp, string2 + 1, len2 - 1);
665 /* Matches the two strings and returns TRUE if the strings match. */
667 int silc_string_regex_match(const char *regex, const char *string)
672 if (regcomp(&preg, regex, REG_NOSUB | REG_EXTENDED) < 0)
675 if (regexec(&preg, string, 0, NULL, 0) == 0)
683 /* Do regex match to the two strings `string1' and `string2'. If the
684 `string2' matches the `string1' this returns TRUE. */
686 int silc_string_match(const char *string1, const char *string2)
691 s1 = silc_string_regexify(string1);
692 ret = silc_string_regex_match(s1, string2);