LRN loves slist: Use stack allocation for slist iterator
[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 the len characters long character sequence
175  * given in input that is in the given charset
176  * to UTF-8.
177  * @return the converted string (0-terminated),
178  *  if conversion fails, a copy of the orignal
179  *  string is returned.
180  */
181 char *
182 GNUNET_STRINGS_to_utf8 (const char *input, size_t len, const char *charset)
183 {
184   char *ret;
185
186 #if ENABLE_NLS && HAVE_ICONV
187   size_t tmpSize;
188   size_t finSize;
189   char *tmp;
190   char *itmp;
191   iconv_t cd;
192
193   cd = iconv_open ("UTF-8", charset);
194   if (cd == (iconv_t) - 1)
195     {
196       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "iconv_open");
197       LOG (GNUNET_ERROR_TYPE_WARNING,
198            _("Character set requested was `%s'\n"), charset);
199       ret = GNUNET_malloc (len + 1);
200       memcpy (ret, input, len);
201       ret[len] = '\0';
202       return ret;
203     }
204   tmpSize = 3 * len + 4;
205   tmp = GNUNET_malloc (tmpSize);
206   itmp = tmp;
207   finSize = tmpSize;
208   if (iconv (cd,
209 #if FREEBSD || DARWIN || WINDOWS
210              (const char **) &input,
211 #else
212              (char **) &input,
213 #endif
214              &len, &itmp, &finSize) == SIZE_MAX)
215     {
216       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "iconv");
217       iconv_close (cd);
218       GNUNET_free (tmp);
219       ret = GNUNET_malloc (len + 1);
220       memcpy (ret, input, len);
221       ret[len] = '\0';
222       return ret;
223     }
224   ret = GNUNET_malloc (tmpSize - finSize + 1);
225   memcpy (ret, tmp, tmpSize - finSize);
226   ret[tmpSize - finSize] = '\0';
227   GNUNET_free (tmp);
228   if (0 != iconv_close (cd))
229     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "iconv_close");
230   return ret;
231 #else
232   ret = GNUNET_malloc (len + 1);
233   memcpy (ret, input, len);
234   ret[len] = '\0';
235   return ret;
236 #endif
237 }
238
239
240 /**
241  * Complete filename (a la shell) from abbrevition.
242  * @param fil the name of the file, may contain ~/ or
243  *        be relative to the current directory
244  * @returns the full file name,
245  *          NULL is returned on error
246  */
247 char *
248 GNUNET_STRINGS_filename_expand (const char *fil)
249 {
250   char *buffer;
251
252 #ifndef MINGW
253   size_t len;
254   size_t n;
255   char *fm;
256   const char *fil_ptr;
257 #else
258   char *fn;
259   long lRet;
260 #endif
261
262   if (fil == NULL)
263     return NULL;
264
265 #ifndef MINGW
266   if (fil[0] == DIR_SEPARATOR)
267     /* absolute path, just copy */
268     return GNUNET_strdup (fil);
269   if (fil[0] == '~')
270     {
271       fm = getenv ("HOME");
272       if (fm == NULL)
273         {
274           LOG (GNUNET_ERROR_TYPE_WARNING,
275                _
276                ("Failed to expand `$HOME': environment variable `HOME' not set"));
277           return NULL;
278         }
279       fm = GNUNET_strdup (fm);
280       /* do not copy '~' */
281       fil_ptr = fil + 1;
282
283       /* skip over dir seperator to be consistent */
284       if (fil_ptr[0] == DIR_SEPARATOR)
285         fil_ptr++;
286     }
287   else
288     {
289       /* relative path */
290       fil_ptr = fil;
291       len = 512;
292       fm = NULL;
293       while (1)
294         {
295           buffer = GNUNET_malloc (len);
296           if (getcwd (buffer, len) != NULL)
297             {
298               fm = buffer;
299               break;
300             }
301           if ((errno == ERANGE) && (len < 1024 * 1024 * 4))
302             {
303               len *= 2;
304               GNUNET_free (buffer);
305               continue;
306             }
307           GNUNET_free (buffer);
308           break;
309         }
310       if (fm == NULL)
311         {
312           LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "getcwd");
313           buffer = getenv ("PWD");      /* alternative */
314           if (buffer != NULL)
315             fm = GNUNET_strdup (buffer);
316         }
317       if (fm == NULL)
318         fm = GNUNET_strdup ("./");      /* give up */
319     }
320   n = strlen (fm) + 1 + strlen (fil_ptr) + 1;
321   buffer = GNUNET_malloc (n);
322   GNUNET_snprintf (buffer, n, "%s%s%s", fm,
323                    (fm[strlen (fm) - 1] ==
324                     DIR_SEPARATOR) ? "" : DIR_SEPARATOR_STR, fil_ptr);
325   GNUNET_free (fm);
326   return buffer;
327 #else
328   fn = GNUNET_malloc (MAX_PATH + 1);
329
330   if ((lRet = plibc_conv_to_win_path (fil, fn)) != ERROR_SUCCESS)
331     {
332       SetErrnoFromWinError (lRet);
333       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "plibc_conv_to_win_path");
334       return NULL;
335     }
336   /* is the path relative? */
337   if ((strncmp (fn + 1, ":\\", 2) != 0) && (strncmp (fn, "\\\\", 2) != 0))
338     {
339       char szCurDir[MAX_PATH + 1];
340
341       lRet = GetCurrentDirectory (MAX_PATH + 1, szCurDir);
342       if (lRet + strlen (fn) + 1 > (MAX_PATH + 1))
343         {
344           SetErrnoFromWinError (ERROR_BUFFER_OVERFLOW);
345           LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetCurrentDirectory");
346           return NULL;
347         }
348       buffer = GNUNET_malloc (MAX_PATH + 1);
349       GNUNET_snprintf (buffer, MAX_PATH + 1, "%s\\%s", szCurDir, fn);
350       GNUNET_free (fn);
351       fn = buffer;
352     }
353
354   return fn;
355 #endif
356 }
357
358
359 /**
360  * Give relative time in human-readable fancy format.
361  *
362  * @param delta time in milli seconds
363  * @return time as human-readable string
364  */
365 char *
366 GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative delta)
367 {
368   const char *unit = _( /* time unit */ "ms");
369   char *ret;
370   uint64_t dval = delta.rel_value;
371
372   if (delta.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value)
373     return GNUNET_strdup (_("eternity"));
374   if (dval > 5 * 1000)
375     {
376       dval = dval / 1000;
377       unit = _( /* time unit */ "s");
378       if (dval > 5 * 60)
379         {
380           dval = dval / 60;
381           unit = _( /* time unit */ "m");
382           if (dval > 5 * 60)
383             {
384               dval = dval / 60;
385               unit = _( /* time unit */ "h");
386               if (dval > 5 * 24)
387                 {
388                   dval = dval / 24;
389                   unit = _( /* time unit */ " days");
390                 }
391             }
392         }
393     }
394   GNUNET_asprintf (&ret, "%llu %s", dval, unit);
395   return ret;
396 }
397
398
399 /**
400  * "man ctime_r", except for GNUnet time; also, unlike ctime, the
401  * return value does not include the newline character.
402  *
403  * @param t time to convert
404  * @return absolute time in human-readable format
405  */
406 char *
407 GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t)
408 {
409   time_t tt;
410   char *ret;
411
412   if (t.abs_value == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value)
413     return GNUNET_strdup (_("end of time"));
414   tt = t.abs_value / 1000;
415 #ifdef ctime_r
416   ret = ctime_r (&tt, GNUNET_malloc (32));
417 #else
418   ret = GNUNET_strdup (ctime (&tt));
419 #endif
420   ret[strlen (ret) - 1] = '\0';
421   return ret;
422 }
423
424
425
426 /* end of strings.c */