c24649e97a793507220eb1df6b41a87c07112992
[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_H
30 #include <iconv.h>
31 #endif
32 #include "gnunet_common.h"
33 #include "gnunet_strings_lib.h"
34
35
36 /**
37  * Fill a buffer of the given size with
38  * count 0-terminated strings (given as varargs).
39  * If "buffer" is NULL, only compute the amount of
40  * space required (sum of "strlen(arg)+1").
41  *
42  * Unlike using "snprintf" with "%s", this function
43  * will add 0-terminators after each string.  The
44  * "GNUNET_string_buffer_tokenize" function can be
45  * used to parse the buffer back into individual
46  * strings.
47  *
48  * @param buffer the buffer to fill with strings, can
49  *               be NULL in which case only the necessary
50  *               amount of space will be calculated
51  * @param size number of bytes available in buffer
52  * @param count number of strings that follow
53  * @param ... count 0-terminated strings to copy to buffer
54  * @return number of bytes written to the buffer
55  *         (or number of bytes that would have been written)
56  */
57 size_t
58 GNUNET_STRINGS_buffer_fill (char *buffer,
59                             size_t size, unsigned int count, ...)
60 {
61   size_t needed;
62   size_t slen;
63   const char *s;
64   va_list ap;
65
66   needed = 0;
67   va_start (ap, count);
68   while (count > 0)
69     {
70       s = va_arg (ap, const char *);
71       slen = strlen (s) + 1;
72       if (buffer != NULL)
73         {
74           GNUNET_assert (needed + slen <= size);
75           memcpy (&buffer[needed], s, slen);
76         }
77       needed += slen;
78       count--;
79     }
80   va_end (ap);
81   return needed;
82 }
83
84
85 /**
86  * Given a buffer of a given size, find "count"
87  * 0-terminated strings in the buffer and assign
88  * the count (varargs) of type "const char**" to the
89  * locations of the respective strings in the
90  * buffer.
91  *
92  * @param buffer the buffer to parse
93  * @param size size of the buffer
94  * @param count number of strings to locate
95  * @return offset of the character after the last 0-termination
96  *         in the buffer, or 0 on error.
97  */
98 unsigned int
99 GNUNET_STRINGS_buffer_tokenize (const char *buffer,
100                                 size_t size, unsigned int count, ...)
101 {
102   unsigned int start;
103   unsigned int needed;
104   const char **r;
105   va_list ap;
106
107   needed = 0;
108   va_start (ap, count);
109   while (count > 0)
110     {
111       r = va_arg (ap, const char **);
112       start = needed;
113       while ((needed < size) && (buffer[needed] != '\0'))
114         needed++;
115       if (needed == size)
116         {
117           va_end (ap);
118           return 0;             /* error */
119         }
120       *r = &buffer[start];
121       needed++;                 /* skip 0-termination */
122       count--;
123     }
124   va_end (ap);
125   return needed;
126 }
127
128
129 /**
130  * Convert a given filesize into a fancy human-readable format.
131  *
132  * @param size number of bytes
133  * @return fancy representation of the size (possibly rounded) for humans
134  */
135 char *
136 GNUNET_STRINGS_byte_size_fancy (unsigned long long size)
137 {
138   const char *unit = _( /* size unit */ "b");
139   char *ret;
140
141   if (size > 5 * 1024)
142     {
143       size = size / 1024;
144       unit = _( /* size unit */ "KiB");
145       if (size > 5 * 1024)
146         {
147           size = size / 1024;
148           unit = _( /* size unit */ "MiB");
149           if (size > 5 * 1024)
150             {
151               size = size / 1024;
152               unit = _( /* size unit */ "GiB");
153               if (size > 5 * 1024)
154                 {
155                   size = size / 1024;
156                   unit = _( /* size unit */ "TiB");
157                 }
158             }
159         }
160     }
161   ret = GNUNET_malloc (32);
162   GNUNET_snprintf (ret, 32, "%llu%s", size, unit);
163   return ret;
164 }
165
166
167 /**
168  * Convert the len characters long character sequence
169  * given in input that is in the given charset
170  * to UTF-8.
171  * @return the converted string (0-terminated),
172  *  if conversion fails, a copy of the orignal
173  *  string is returned.
174  */
175 char *
176 GNUNET_STRINGS_to_utf8 (const char *input, size_t len, const char *charset)
177 {
178   char *ret;
179 #if ENABLE_NLS && HAVE_ICONV
180   size_t tmpSize;
181   size_t finSize;
182   char *tmp;
183   char *itmp;
184   iconv_t cd;
185
186   cd = iconv_open ("UTF-8", charset);
187   if (cd == (iconv_t) - 1)
188     {
189       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "iconv_open");
190       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
191                   _("Character set requested was `%s'\n"), charset);
192       ret = GNUNET_malloc (len + 1);
193       memcpy (ret, input, len);
194       ret[len] = '\0';
195       return ret;
196     }
197   tmpSize = 3 * len + 4;
198   tmp = GNUNET_malloc (tmpSize);
199   itmp = tmp;
200   finSize = tmpSize;
201   if (iconv (cd, (char **) &input, &len, &itmp, &finSize) == (size_t) - 1)
202     {
203       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "iconv");
204       iconv_close (cd);
205       GNUNET_free (tmp);
206       ret = GNUNET_malloc (len + 1);
207       memcpy (ret, input, len);
208       ret[len] = '\0';
209       return ret;
210     }
211   ret = GNUNET_malloc (tmpSize - finSize + 1);
212   memcpy (ret, tmp, tmpSize - finSize);
213   ret[tmpSize - finSize] = '\0';
214   GNUNET_free (tmp);
215   if (0 != iconv_close (cd))
216     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "iconv_close");
217   return ret;
218 #else
219   ret = GNUNET_malloc (len + 1);
220   memcpy (ret, input, len);
221   ret[len] = '\0';
222   return ret;
223 #endif
224 }
225
226
227 /**
228  * Complete filename (a la shell) from abbrevition.
229  * @param fil the name of the file, may contain ~/ or
230  *        be relative to the current directory
231  * @returns the full file name,
232  *          NULL is returned on error
233  */
234 char *
235 GNUNET_STRINGS_filename_expand (const char *fil)
236 {
237   char *buffer;
238 #ifndef MINGW
239   size_t len;
240   size_t n;
241   char *fm;
242   const char *fil_ptr;
243 #else
244   char *fn;
245   long lRet;
246 #endif
247
248   if (fil == NULL)
249     return NULL;
250
251 #ifndef MINGW
252   if (fil[0] == DIR_SEPARATOR)
253     /* absolute path, just copy */
254     return GNUNET_strdup (fil);
255   if (fil[0] == '~')
256     {
257       fm = getenv ("HOME");
258       if (fm == NULL)
259         {
260           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
261                       _
262                       ("Failed to expand `$HOME': environment variable `HOME' not set"));
263           return NULL;
264         }
265       fm = GNUNET_strdup (fm);
266       /* do not copy '~' */
267       fil_ptr = fil + 1;
268
269       /* skip over dir seperator to be consistent */
270       if (fil_ptr[0] == DIR_SEPARATOR)
271         fil_ptr++;
272     }
273   else
274     {
275       /* relative path */
276       fil_ptr = fil;
277       len = 512;
278       fm = NULL;
279       while (1)
280         {
281           buffer = GNUNET_malloc (len);
282           if (getcwd (buffer, len) != NULL)
283             {
284               fm = buffer;
285               break;
286             }
287           if ((errno == ERANGE) && (len < 1024 * 1024 * 4))
288             {
289               len *= 2;
290               GNUNET_free (buffer);
291               continue;
292             }
293           GNUNET_free (buffer);
294           break;
295         }
296       if (fm == NULL)
297         {
298           GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "getcwd");
299           buffer = getenv ("PWD");      /* alternative */
300           if (buffer != NULL)
301             fm = GNUNET_strdup (buffer);
302         }
303       if (fm == NULL)
304         fm = GNUNET_strdup ("./");      /* give up */
305     }
306   n = strlen (fm) + 1 + strlen (fil_ptr) + 1;
307   buffer = GNUNET_malloc (n);
308   GNUNET_snprintf (buffer, n, "%s%s%s",
309                    fm,
310                    (fm[strlen (fm) - 1] ==
311                     DIR_SEPARATOR) ? "" : DIR_SEPARATOR_STR, fil_ptr);
312   GNUNET_free (fm);
313   return buffer;
314 #else
315   fn = GNUNET_malloc (MAX_PATH + 1);
316
317   if ((lRet = plibc_conv_to_win_path (fil, fn)) != ERROR_SUCCESS)
318     {
319       SetErrnoFromWinError (lRet);
320       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
321                            "plibc_conv_to_win_path");
322       return NULL;
323     }
324   /* is the path relative? */
325   if ((strncmp (fn + 1, ":\\", 2) != 0) && (strncmp (fn, "\\\\", 2) != 0))
326     {
327       char szCurDir[MAX_PATH + 1];
328       lRet = GetCurrentDirectory (MAX_PATH + 1, szCurDir);
329       if (lRet + strlen (fn) + 1 > (MAX_PATH + 1))
330         {
331           SetErrnoFromWinError (ERROR_BUFFER_OVERFLOW);
332           GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
333                                "GetCurrentDirectory");
334           return NULL;
335         }
336       buffer = GNUNET_malloc (MAX_PATH + 1);
337       GNUNET_snprintf (buffer, MAX_PATH + 1, "%s\\%s", szCurDir, fn);
338       GNUNET_free (fn);
339       fn = buffer;
340     }
341
342   return fn;
343 #endif
344 }
345
346
347 /**
348  * Give relative time in human-readable fancy format.
349  *
350  * @param del time in milli seconds
351  * @return time as human-readable string
352  */
353 char *
354 GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative del)
355 {
356   const char *unit = _( /* time unit */ "ms");
357   char *ret;
358   uint64_t delta = del.value;
359
360   if (delta > 5 * 1000)
361     {
362       delta = delta / 1000;
363       unit = _( /* time unit */ "s");
364       if (delta > 5 * 60)
365         {
366           delta = delta / 60;
367           unit = _( /* time unit */ "m");
368           if (delta > 5 * 60)
369             {
370               delta = delta / 60;
371               unit = _( /* time unit */ "h");
372               if (delta > 5 * 24)
373                 {
374                   delta = delta / 24;
375                   unit = _( /* time unit */ " days");
376                 }
377             }
378         }
379     }
380   GNUNET_asprintf (&ret, "%llu%s", delta, unit);
381   return ret;
382 }
383
384
385 /**
386  * "man ctime_r", except for GNUnet time; also, unlike ctime, the
387  * return value does not include the newline character.
388  *
389  * @param t time to convert
390  * @return absolute time in human-readable format
391  */
392 char *
393 GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t)
394 {
395   time_t tt;
396   char *ret;
397
398   tt = t.value / 1000;
399 #ifdef ctime_r
400   ret = ctime_r (&tt, GNUNET_malloc (32));
401 #else
402   ret = GNUNET_strdup (ctime (&tt));
403 #endif
404   ret[strlen (ret) - 1] = '\0';
405   return ret;
406 }
407
408
409
410 /* end of strings.c */