use putenv instead of setenv for portability
[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   size_t needed;
65   size_t slen;
66   const char *s;
67   va_list ap;
68
69   needed = 0;
70   va_start (ap, count);
71   while (count > 0)
72   {
73     s = va_arg (ap, const char *);
74
75     slen = strlen (s) + 1;
76     if (buffer != NULL)
77     {
78       GNUNET_assert (needed + slen <= size);
79       memcpy (&buffer[needed], s, slen);
80     }
81     needed += slen;
82     count--;
83   }
84   va_end (ap);
85   return needed;
86 }
87
88
89 /**
90  * Given a buffer of a given size, find "count"
91  * 0-terminated strings in the buffer and assign
92  * the count (varargs) of type "const char**" to the
93  * locations of the respective strings in the
94  * buffer.
95  *
96  * @param buffer the buffer to parse
97  * @param size size of the buffer
98  * @param count number of strings to locate
99  * @return offset of the character after the last 0-termination
100  *         in the buffer, or 0 on error.
101  */
102 unsigned int
103 GNUNET_STRINGS_buffer_tokenize (const char *buffer, size_t size,
104                                 unsigned int count, ...)
105 {
106   unsigned int start;
107   unsigned int needed;
108   const char **r;
109   va_list ap;
110
111   needed = 0;
112   va_start (ap, count);
113   while (count > 0)
114   {
115     r = va_arg (ap, const char **);
116
117     start = needed;
118     while ((needed < size) && (buffer[needed] != '\0'))
119       needed++;
120     if (needed == size)
121     {
122       va_end (ap);
123       return 0;                 /* error */
124     }
125     *r = &buffer[start];
126     needed++;                   /* skip 0-termination */
127     count--;
128   }
129   va_end (ap);
130   return needed;
131 }
132
133
134 /**
135  * Convert a given filesize into a fancy human-readable format.
136  *
137  * @param size number of bytes
138  * @return fancy representation of the size (possibly rounded) for humans
139  */
140 char *
141 GNUNET_STRINGS_byte_size_fancy (unsigned long long size)
142 {
143   const char *unit = _( /* size unit */ "b");
144   char *ret;
145
146   if (size > 5 * 1024)
147   {
148     size = size / 1024;
149     unit = "KiB";
150     if (size > 5 * 1024)
151     {
152       size = size / 1024;
153       unit = "MiB";
154       if (size > 5 * 1024)
155       {
156         size = size / 1024;
157         unit = "GiB";
158         if (size > 5 * 1024)
159         {
160           size = size / 1024;
161           unit = "TiB";
162         }
163       }
164     }
165   }
166   ret = GNUNET_malloc (32);
167   GNUNET_snprintf (ret, 32, "%llu %s", size, unit);
168   return ret;
169 }
170
171
172 /**
173  * Convert a given fancy human-readable size to bytes.
174  *
175  * @param fancy_size human readable string (i.e. 1 MB)
176  * @param size set to the size in bytes
177  * @return GNUNET_OK on success, GNUNET_SYSERR on error
178  */
179 int
180 GNUNET_STRINGS_fancy_size_to_bytes (const char *fancy_size,
181                                     unsigned long long *size)
182 {
183   struct
184   {
185     const char *name;
186     unsigned long long value;
187   } table[] =
188   {
189     {
190     "B", 1},
191     {
192     "KiB", 1024},
193     {
194     "kB", 1000},
195     {
196     "MiB", 1024 * 1024},
197     {
198     "MB", 1000 * 1000},
199     {
200     "GiB", 1024 * 1024 * 1024},
201     {
202     "GB", 1000 * 1000 * 1000},
203     {
204     "TiB", 1024LL * 1024LL * 1024LL * 1024LL},
205     {
206     "TB", 1000LL * 1000LL * 1000LL * 1024LL},
207     {
208     "PiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL},
209     {
210     "PB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL},
211     {
212     "EiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL * 1024LL},
213     {
214     "EB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL * 1000LL},
215     {
216     NULL, 0}
217   };
218   unsigned long long ret;
219   char *in;
220   const char *tok;
221   unsigned long long last;
222   unsigned int i;
223
224   ret = 0;
225   last = 0;
226   in = GNUNET_strdup (fancy_size);
227   for (tok = strtok (in, " "); tok != NULL; tok = strtok (NULL, " "))
228   {
229     i = 0;
230     while ((table[i].name != NULL) && (0 != strcasecmp (table[i].name, tok)))
231       i++;
232     if (table[i].name != NULL)
233       last *= table[i].value;
234     else
235     {
236       ret += last;
237       last = 0;
238       if (1 != sscanf (tok, "%llu", &last))
239         return GNUNET_SYSERR;   /* expected number */
240     }
241   }
242   ret += last;
243   *size = ret;
244   return GNUNET_OK;
245 }
246
247
248 /**
249  * Convert a given fancy human-readable time to our internal
250  * representation.
251  *
252  * @param fancy_size human readable string (i.e. 1 minute)
253  * @param rtime set to the relative time
254  * @return GNUNET_OK on success, GNUNET_SYSERR on error
255  */
256 int
257 GNUNET_STRINGS_fancy_time_to_relative (const char *fancy_size,
258                                        struct GNUNET_TIME_Relative *rtime)
259 {
260   struct
261   {
262     const char *name;
263     unsigned long long value;
264   } table[] =
265   {
266     {
267     "ms", 1},
268     {
269     "s", 1000},
270     {
271     "\"", 1000},
272     {
273     "min", 60 * 1000},
274     {
275     "minutes", 60 * 1000},
276     {
277     "'", 60 * 1000},
278     {
279     "h", 60 * 60 * 1000},
280     {
281     "d", 24 * 60 * 60 * 1000},
282     {
283     "a", 31557600 /* year */ },
284     {
285     NULL, 0}
286   };
287   unsigned long long ret;
288   char *in;
289   const char *tok;
290   unsigned long long last;
291   unsigned int i;
292
293   if ((0 == strcasecmp (fancy_size, "infinity")) ||
294       (0 == strcasecmp (fancy_size, "forever")))
295   {
296     *rtime = GNUNET_TIME_UNIT_FOREVER_REL;
297     return GNUNET_OK;
298   }
299   ret = 0;
300   last = 0;
301   in = GNUNET_strdup (fancy_size);
302   for (tok = strtok (in, " "); tok != NULL; tok = strtok (NULL, " "))
303   {
304     i = 0;
305     while ((table[i].name != NULL) && (0 != strcasecmp (table[i].name, tok)))
306       i++;
307     if (table[i].name != NULL)
308       last *= table[i].value;
309     else
310     {
311       ret += last;
312       last = 0;
313       if (1 != sscanf (tok, "%llu", &last))
314         return GNUNET_SYSERR;   /* expected number */
315     }
316   }
317   ret += last;
318   rtime->rel_value = (uint64_t) ret;
319   return GNUNET_OK;
320 }
321
322
323 /**
324  * Convert the len characters long character sequence
325  * given in input that is in the given charset
326  * to UTF-8.
327  * @return the converted string (0-terminated),
328  *  if conversion fails, a copy of the orignal
329  *  string is returned.
330  */
331 char *
332 GNUNET_STRINGS_to_utf8 (const char *input, size_t len, const char *charset)
333 {
334   char *ret;
335
336 #if ENABLE_NLS && HAVE_ICONV
337   size_t tmpSize;
338   size_t finSize;
339   char *tmp;
340   char *itmp;
341   iconv_t cd;
342
343   cd = iconv_open ("UTF-8", charset);
344   if (cd == (iconv_t) - 1)
345   {
346     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "iconv_open");
347     LOG (GNUNET_ERROR_TYPE_WARNING, _("Character set requested was `%s'\n"),
348          charset);
349     ret = GNUNET_malloc (len + 1);
350     memcpy (ret, input, len);
351     ret[len] = '\0';
352     return ret;
353   }
354   tmpSize = 3 * len + 4;
355   tmp = GNUNET_malloc (tmpSize);
356   itmp = tmp;
357   finSize = tmpSize;
358   if (iconv (cd,
359 #if FREEBSD || DARWIN || WINDOWS
360              (const char **) &input,
361 #else
362              (char **) &input,
363 #endif
364              &len, &itmp, &finSize) == SIZE_MAX)
365   {
366     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "iconv");
367     iconv_close (cd);
368     GNUNET_free (tmp);
369     ret = GNUNET_malloc (len + 1);
370     memcpy (ret, input, len);
371     ret[len] = '\0';
372     return ret;
373   }
374   ret = GNUNET_malloc (tmpSize - finSize + 1);
375   memcpy (ret, tmp, tmpSize - finSize);
376   ret[tmpSize - finSize] = '\0';
377   GNUNET_free (tmp);
378   if (0 != iconv_close (cd))
379     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "iconv_close");
380   return ret;
381 #else
382   ret = GNUNET_malloc (len + 1);
383   memcpy (ret, input, len);
384   ret[len] = '\0';
385   return ret;
386 #endif
387 }
388
389
390 /**
391  * Complete filename (a la shell) from abbrevition.
392  * @param fil the name of the file, may contain ~/ or
393  *        be relative to the current directory
394  * @returns the full file name,
395  *          NULL is returned on error
396  */
397 char *
398 GNUNET_STRINGS_filename_expand (const char *fil)
399 {
400   char *buffer;
401
402 #ifndef MINGW
403   size_t len;
404   size_t n;
405   char *fm;
406   const char *fil_ptr;
407 #else
408   char *fn;
409   long lRet;
410 #endif
411
412   if (fil == NULL)
413     return NULL;
414
415 #ifndef MINGW
416   if (fil[0] == DIR_SEPARATOR)
417     /* absolute path, just copy */
418     return GNUNET_strdup (fil);
419   if (fil[0] == '~')
420   {
421     fm = getenv ("HOME");
422     if (fm == NULL)
423     {
424       LOG (GNUNET_ERROR_TYPE_WARNING,
425            _("Failed to expand `$HOME': environment variable `HOME' not set"));
426       return NULL;
427     }
428     fm = GNUNET_strdup (fm);
429     /* do not copy '~' */
430     fil_ptr = fil + 1;
431
432     /* skip over dir seperator to be consistent */
433     if (fil_ptr[0] == DIR_SEPARATOR)
434       fil_ptr++;
435   }
436   else
437   {
438     /* relative path */
439     fil_ptr = fil;
440     len = 512;
441     fm = NULL;
442     while (1)
443     {
444       buffer = GNUNET_malloc (len);
445       if (getcwd (buffer, len) != NULL)
446       {
447         fm = buffer;
448         break;
449       }
450       if ((errno == ERANGE) && (len < 1024 * 1024 * 4))
451       {
452         len *= 2;
453         GNUNET_free (buffer);
454         continue;
455       }
456       GNUNET_free (buffer);
457       break;
458     }
459     if (fm == NULL)
460     {
461       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "getcwd");
462       buffer = getenv ("PWD");  /* alternative */
463       if (buffer != NULL)
464         fm = GNUNET_strdup (buffer);
465     }
466     if (fm == NULL)
467       fm = GNUNET_strdup ("./");        /* give up */
468   }
469   n = strlen (fm) + 1 + strlen (fil_ptr) + 1;
470   buffer = GNUNET_malloc (n);
471   GNUNET_snprintf (buffer, n, "%s%s%s", fm,
472                    (fm[strlen (fm) - 1] ==
473                     DIR_SEPARATOR) ? "" : DIR_SEPARATOR_STR, fil_ptr);
474   GNUNET_free (fm);
475   return buffer;
476 #else
477   fn = GNUNET_malloc (MAX_PATH + 1);
478
479   if ((lRet = plibc_conv_to_win_path (fil, fn)) != ERROR_SUCCESS)
480   {
481     SetErrnoFromWinError (lRet);
482     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "plibc_conv_to_win_path");
483     return NULL;
484   }
485   /* is the path relative? */
486   if ((strncmp (fn + 1, ":\\", 2) != 0) && (strncmp (fn, "\\\\", 2) != 0))
487   {
488     char szCurDir[MAX_PATH + 1];
489
490     lRet = GetCurrentDirectory (MAX_PATH + 1, szCurDir);
491     if (lRet + strlen (fn) + 1 > (MAX_PATH + 1))
492     {
493       SetErrnoFromWinError (ERROR_BUFFER_OVERFLOW);
494       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetCurrentDirectory");
495       return NULL;
496     }
497     buffer = GNUNET_malloc (MAX_PATH + 1);
498     GNUNET_snprintf (buffer, MAX_PATH + 1, "%s\\%s", szCurDir, fn);
499     GNUNET_free (fn);
500     fn = buffer;
501   }
502
503   return fn;
504 #endif
505 }
506
507
508 /**
509  * Give relative time in human-readable fancy format.
510  *
511  * @param delta time in milli seconds
512  * @return time as human-readable string
513  */
514 char *
515 GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative delta)
516 {
517   const char *unit = _( /* time unit */ "ms");
518   char *ret;
519   uint64_t dval = delta.rel_value;
520
521   if (delta.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
522     return GNUNET_strdup (_("eternity"));
523   if (dval > 5 * 1000)
524   {
525     dval = dval / 1000;
526     unit = _( /* time unit */ "s");
527     if (dval > 5 * 60)
528     {
529       dval = dval / 60;
530       unit = _( /* time unit */ "m");
531       if (dval > 5 * 60)
532       {
533         dval = dval / 60;
534         unit = _( /* time unit */ "h");
535         if (dval > 5 * 24)
536         {
537           dval = dval / 24;
538           unit = _( /* time unit */ " days");
539         }
540       }
541     }
542   }
543   GNUNET_asprintf (&ret, "%llu %s", dval, unit);
544   return ret;
545 }
546
547
548 /**
549  * "man ctime_r", except for GNUnet time; also, unlike ctime, the
550  * return value does not include the newline character.
551  *
552  * @param t time to convert
553  * @return absolute time in human-readable format
554  */
555 char *
556 GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t)
557 {
558   time_t tt;
559   char *ret;
560
561   if (t.abs_value == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value)
562     return GNUNET_strdup (_("end of time"));
563   tt = t.abs_value / 1000;
564 #ifdef ctime_r
565   ret = ctime_r (&tt, GNUNET_malloc (32));
566 #else
567   ret = GNUNET_strdup (ctime (&tt));
568 #endif
569   ret[strlen (ret) - 1] = '\0';
570   return ret;
571 }
572
573
574
575 /* end of strings.c */