nodebug
[oweals/gnunet.git] / src / util / strings.c
1 /*
2      This file is part of GNUnet.
3      (C) 2005, 2006 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 2, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file util/strings.c
23  * @brief string functions
24  * @author Nils Durner
25  * @author Christian Grothoff
26  */
27
28 #include "platform.h"
29 #if HAVE_ICONV
30 #include <iconv.h>
31 #endif
32 #include "gnunet_common.h"
33 #include "gnunet_strings_lib.h"
34
35 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
36
37 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
38
39
40 /**
41  * Fill a buffer of the given size with
42  * count 0-terminated strings (given as varargs).
43  * If "buffer" is NULL, only compute the amount of
44  * space required (sum of "strlen(arg)+1").
45  *
46  * Unlike using "snprintf" with "%s", this function
47  * will add 0-terminators after each string.  The
48  * "GNUNET_string_buffer_tokenize" function can be
49  * used to parse the buffer back into individual
50  * strings.
51  *
52  * @param buffer the buffer to fill with strings, can
53  *               be NULL in which case only the necessary
54  *               amount of space will be calculated
55  * @param size number of bytes available in buffer
56  * @param count number of strings that follow
57  * @param ... count 0-terminated strings to copy to buffer
58  * @return number of bytes written to the buffer
59  *         (or number of bytes that would have been written)
60  */
61 size_t
62 GNUNET_STRINGS_buffer_fill (char *buffer, size_t size, unsigned int count,
63                             ...)
64 {
65   size_t needed;
66   size_t slen;
67   const char *s;
68   va_list ap;
69
70   needed = 0;
71   va_start (ap, count);
72   while (count > 0)
73     {
74       s = va_arg (ap, const char *);
75
76       slen = strlen (s) + 1;
77       if (buffer != NULL)
78         {
79           GNUNET_assert (needed + slen <= size);
80           memcpy (&buffer[needed], s, slen);
81         }
82       needed += slen;
83       count--;
84     }
85   va_end (ap);
86   return needed;
87 }
88
89
90 /**
91  * Given a buffer of a given size, find "count"
92  * 0-terminated strings in the buffer and assign
93  * the count (varargs) of type "const char**" to the
94  * locations of the respective strings in the
95  * buffer.
96  *
97  * @param buffer the buffer to parse
98  * @param size size of the buffer
99  * @param count number of strings to locate
100  * @return offset of the character after the last 0-termination
101  *         in the buffer, or 0 on error.
102  */
103 unsigned int
104 GNUNET_STRINGS_buffer_tokenize (const char *buffer, size_t size,
105                                 unsigned int count, ...)
106 {
107   unsigned int start;
108   unsigned int needed;
109   const char **r;
110   va_list ap;
111
112   needed = 0;
113   va_start (ap, count);
114   while (count > 0)
115     {
116       r = va_arg (ap, const char **);
117
118       start = needed;
119       while ((needed < size) && (buffer[needed] != '\0'))
120         needed++;
121       if (needed == size)
122         {
123           va_end (ap);
124           return 0;             /* error */
125         }
126       *r = &buffer[start];
127       needed++;                 /* skip 0-termination */
128       count--;
129     }
130   va_end (ap);
131   return needed;
132 }
133
134
135 /**
136  * Convert a given filesize into a fancy human-readable format.
137  *
138  * @param size number of bytes
139  * @return fancy representation of the size (possibly rounded) for humans
140  */
141 char *
142 GNUNET_STRINGS_byte_size_fancy (unsigned long long size)
143 {
144   const char *unit = _( /* size unit */ "b");
145   char *ret;
146
147   if (size > 5 * 1024)
148     {
149       size = size / 1024;
150       unit = _( /* size unit */ "KiB");
151       if (size > 5 * 1024)
152         {
153           size = size / 1024;
154           unit = _( /* size unit */ "MiB");
155           if (size > 5 * 1024)
156             {
157               size = size / 1024;
158               unit = _( /* size unit */ "GiB");
159               if (size > 5 * 1024)
160                 {
161                   size = size / 1024;
162                   unit = _( /* size unit */ "TiB");
163                 }
164             }
165         }
166     }
167   ret = GNUNET_malloc (32);
168   GNUNET_snprintf (ret, 32, "%llu %s", size, unit);
169   return ret;
170 }
171
172
173 /**
174  * Convert a given fancy human-readable size to bytes.
175  *
176  * @param fancy_size human readable string (i.e. 1 MB)
177  * @param size set to the size in bytes
178  * @return GNUNET_OK on success, GNUNET_SYSERR on error
179  */
180 int
181 GNUNET_STRINGS_fancy_size_to_bytes (const char *fancy_size,
182                                     unsigned long long *size)
183 {
184   struct { 
185     const char *name; 
186     unsigned long long value;
187   } table[] = {
188     { "B", 1 },
189     { "KiB", 1024 },
190     { "kB",  1000 },
191     { "MiB", 1024 * 1024 },
192     { "MB",  1000 * 1000 },
193     { "GiB", 1024 * 1024 * 1024 },
194     { "GB",  1000 * 1000 * 1000 },
195     { "TiB", 1024LL * 1024LL * 1024LL * 1024LL },
196     { "TB",  1000LL * 1000LL * 1000LL * 1024LL },
197     { "PiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL },
198     { "PB",  1000LL * 1000LL * 1000LL * 1024LL * 1000LL},
199     { "EiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL * 1024LL},
200     { "EB",  1000LL * 1000LL * 1000LL * 1024LL * 1000LL * 1000LL },
201     { NULL, 0 }
202   };
203   unsigned long long ret;
204   char *in;
205   const char *tok;
206   unsigned long long last;
207   unsigned int i;
208
209   ret = 0;
210   last = 0;
211   in = GNUNET_strdup (fancy_size);
212   for (tok = strtok (in, " "); tok != NULL; tok = strtok (NULL, " "))
213   {
214     i=0;
215     while ( (table[i].name != NULL) &&
216             (0 != strcasecmp (table[i].name, tok) ) )
217       i++;
218     if (table[i].name != NULL)
219       last *= table[i].value;
220     else
221     {
222       ret += last;
223       last = 0;
224       if (1 != sscanf (tok, "%llu", &last))
225         return GNUNET_SYSERR; /* expected number */
226     }      
227   }
228   ret += last;
229   *size = ret;
230   return GNUNET_OK;
231 }
232
233
234 /**
235  * Convert a given fancy human-readable time to our internal
236  * representation.
237  *
238  * @param fancy_size human readable string (i.e. 1 minute)
239  * @param rtime set to the relative time
240  * @return GNUNET_OK on success, GNUNET_SYSERR on error
241  */
242 int
243 GNUNET_STRINGS_fancy_time_to_relative (const char *fancy_size,
244                                        struct GNUNET_TIME_Relative *rtime)
245 {
246   struct { 
247     const char *name; 
248     unsigned long long value;
249   } table[] = {
250     { "ms", 1 },
251     { "s", 1000 },
252     { "\"", 1000 },
253     { "min",  60 * 1000 },
254     { "minutes", 60 * 1000 },
255     { "'", 60 * 1000 },
256     { "h", 60 * 60 * 1000 },
257     { "d", 24 * 60 * 60 * 1000 },
258     { "a", 31557600 /* year */ },
259     { NULL, 0 }
260   };
261   unsigned long long ret;
262   char *in;
263   const char *tok;
264   unsigned long long last;
265   unsigned int i;
266   
267   if ((0 == strcasecmp (fancy_size, "infinity")) ||
268       (0 == strcasecmp (fancy_size, "forever")))
269     {
270       *rtime = GNUNET_TIME_UNIT_FOREVER_REL;
271       return GNUNET_OK;
272     }
273   ret = 0;
274   last = 0;
275   in = GNUNET_strdup (fancy_size);
276   for (tok = strtok (in, " "); tok != NULL; tok = strtok (NULL, " "))
277   {
278     i=0;
279     while ( (table[i].name != NULL) &&
280             (0 != strcasecmp (table[i].name, tok) ) )
281       i++;
282     if (table[i].name != NULL)
283       last *= table[i].value;
284     else
285     {
286       ret += last;
287       last = 0;
288       if (1 != sscanf (tok, "%llu", &last))
289         return GNUNET_SYSERR; /* expected number */
290     }      
291   }
292   ret += last;
293   rtime->rel_value = (uint64_t) ret;
294   return GNUNET_OK;
295 }
296
297
298 /**
299  * Convert the len characters long character sequence
300  * given in input that is in the given charset
301  * to UTF-8.
302  * @return the converted string (0-terminated),
303  *  if conversion fails, a copy of the orignal
304  *  string is returned.
305  */
306 char *
307 GNUNET_STRINGS_to_utf8 (const char *input, size_t len, const char *charset)
308 {
309   char *ret;
310
311 #if ENABLE_NLS && HAVE_ICONV
312   size_t tmpSize;
313   size_t finSize;
314   char *tmp;
315   char *itmp;
316   iconv_t cd;
317
318   cd = iconv_open ("UTF-8", charset);
319   if (cd == (iconv_t) - 1)
320     {
321       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "iconv_open");
322       LOG (GNUNET_ERROR_TYPE_WARNING,
323            _("Character set requested was `%s'\n"), charset);
324       ret = GNUNET_malloc (len + 1);
325       memcpy (ret, input, len);
326       ret[len] = '\0';
327       return ret;
328     }
329   tmpSize = 3 * len + 4;
330   tmp = GNUNET_malloc (tmpSize);
331   itmp = tmp;
332   finSize = tmpSize;
333   if (iconv (cd,
334 #if FREEBSD || DARWIN || WINDOWS
335              (const char **) &input,
336 #else
337              (char **) &input,
338 #endif
339              &len, &itmp, &finSize) == SIZE_MAX)
340     {
341       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "iconv");
342       iconv_close (cd);
343       GNUNET_free (tmp);
344       ret = GNUNET_malloc (len + 1);
345       memcpy (ret, input, len);
346       ret[len] = '\0';
347       return ret;
348     }
349   ret = GNUNET_malloc (tmpSize - finSize + 1);
350   memcpy (ret, tmp, tmpSize - finSize);
351   ret[tmpSize - finSize] = '\0';
352   GNUNET_free (tmp);
353   if (0 != iconv_close (cd))
354     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "iconv_close");
355   return ret;
356 #else
357   ret = GNUNET_malloc (len + 1);
358   memcpy (ret, input, len);
359   ret[len] = '\0';
360   return ret;
361 #endif
362 }
363
364
365 /**
366  * Complete filename (a la shell) from abbrevition.
367  * @param fil the name of the file, may contain ~/ or
368  *        be relative to the current directory
369  * @returns the full file name,
370  *          NULL is returned on error
371  */
372 char *
373 GNUNET_STRINGS_filename_expand (const char *fil)
374 {
375   char *buffer;
376
377 #ifndef MINGW
378   size_t len;
379   size_t n;
380   char *fm;
381   const char *fil_ptr;
382 #else
383   char *fn;
384   long lRet;
385 #endif
386
387   if (fil == NULL)
388     return NULL;
389
390 #ifndef MINGW
391   if (fil[0] == DIR_SEPARATOR)
392     /* absolute path, just copy */
393     return GNUNET_strdup (fil);
394   if (fil[0] == '~')
395     {
396       fm = getenv ("HOME");
397       if (fm == NULL)
398         {
399           LOG (GNUNET_ERROR_TYPE_WARNING,
400                _
401                ("Failed to expand `$HOME': environment variable `HOME' not set"));
402           return NULL;
403         }
404       fm = GNUNET_strdup (fm);
405       /* do not copy '~' */
406       fil_ptr = fil + 1;
407
408       /* skip over dir seperator to be consistent */
409       if (fil_ptr[0] == DIR_SEPARATOR)
410         fil_ptr++;
411     }
412   else
413     {
414       /* relative path */
415       fil_ptr = fil;
416       len = 512;
417       fm = NULL;
418       while (1)
419         {
420           buffer = GNUNET_malloc (len);
421           if (getcwd (buffer, len) != NULL)
422             {
423               fm = buffer;
424               break;
425             }
426           if ((errno == ERANGE) && (len < 1024 * 1024 * 4))
427             {
428               len *= 2;
429               GNUNET_free (buffer);
430               continue;
431             }
432           GNUNET_free (buffer);
433           break;
434         }
435       if (fm == NULL)
436         {
437           LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "getcwd");
438           buffer = getenv ("PWD");      /* alternative */
439           if (buffer != NULL)
440             fm = GNUNET_strdup (buffer);
441         }
442       if (fm == NULL)
443         fm = GNUNET_strdup ("./");      /* give up */
444     }
445   n = strlen (fm) + 1 + strlen (fil_ptr) + 1;
446   buffer = GNUNET_malloc (n);
447   GNUNET_snprintf (buffer, n, "%s%s%s", fm,
448                    (fm[strlen (fm) - 1] ==
449                     DIR_SEPARATOR) ? "" : DIR_SEPARATOR_STR, fil_ptr);
450   GNUNET_free (fm);
451   return buffer;
452 #else
453   fn = GNUNET_malloc (MAX_PATH + 1);
454
455   if ((lRet = plibc_conv_to_win_path (fil, fn)) != ERROR_SUCCESS)
456     {
457       SetErrnoFromWinError (lRet);
458       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "plibc_conv_to_win_path");
459       return NULL;
460     }
461   /* is the path relative? */
462   if ((strncmp (fn + 1, ":\\", 2) != 0) && (strncmp (fn, "\\\\", 2) != 0))
463     {
464       char szCurDir[MAX_PATH + 1];
465
466       lRet = GetCurrentDirectory (MAX_PATH + 1, szCurDir);
467       if (lRet + strlen (fn) + 1 > (MAX_PATH + 1))
468         {
469           SetErrnoFromWinError (ERROR_BUFFER_OVERFLOW);
470           LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetCurrentDirectory");
471           return NULL;
472         }
473       buffer = GNUNET_malloc (MAX_PATH + 1);
474       GNUNET_snprintf (buffer, MAX_PATH + 1, "%s\\%s", szCurDir, fn);
475       GNUNET_free (fn);
476       fn = buffer;
477     }
478
479   return fn;
480 #endif
481 }
482
483
484 /**
485  * Give relative time in human-readable fancy format.
486  *
487  * @param delta time in milli seconds
488  * @return time as human-readable string
489  */
490 char *
491 GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative delta)
492 {
493   const char *unit = _( /* time unit */ "ms");
494   char *ret;
495   uint64_t dval = delta.rel_value;
496
497   if (delta.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
498     return GNUNET_strdup (_("eternity"));
499   if (dval > 5 * 1000)
500     {
501       dval = dval / 1000;
502       unit = _( /* time unit */ "s");
503       if (dval > 5 * 60)
504         {
505           dval = dval / 60;
506           unit = _( /* time unit */ "m");
507           if (dval > 5 * 60)
508             {
509               dval = dval / 60;
510               unit = _( /* time unit */ "h");
511               if (dval > 5 * 24)
512                 {
513                   dval = dval / 24;
514                   unit = _( /* time unit */ " days");
515                 }
516             }
517         }
518     }
519   GNUNET_asprintf (&ret, "%llu %s", dval, unit);
520   return ret;
521 }
522
523
524 /**
525  * "man ctime_r", except for GNUnet time; also, unlike ctime, the
526  * return value does not include the newline character.
527  *
528  * @param t time to convert
529  * @return absolute time in human-readable format
530  */
531 char *
532 GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t)
533 {
534   time_t tt;
535   char *ret;
536
537   if (t.abs_value == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value)
538     return GNUNET_strdup (_("end of time"));
539   tt = t.abs_value / 1000;
540 #ifdef ctime_r
541   ret = ctime_r (&tt, GNUNET_malloc (32));
542 #else
543   ret = GNUNET_strdup (ctime (&tt));
544 #endif
545   ret[strlen (ret) - 1] = '\0';
546   return ret;
547 }
548
549
550
551 /* end of strings.c */