You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.3 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /* snprinterr.c */
  2. /* Copyright Gerhard Rieger and contributors (see file CHANGES) */
  3. /* a function similar to vsnprintf() but it just handles %m */
  4. #include "config.h"
  5. #include <stddef.h> /* ptrdiff_t */
  6. #include <ctype.h> /* isdigit() */
  7. #include <stdarg.h>
  8. #include <stdlib.h>
  9. #include <errno.h>
  10. #if HAVE_SYSLOG_H
  11. #include <syslog.h>
  12. #endif
  13. #include <sys/utsname.h>
  14. #include <time.h> /* time_t, strftime() */
  15. #include <sys/time.h> /* gettimeofday() */
  16. #include <stdio.h>
  17. #include <string.h>
  18. #if HAVE_UNISTD_H
  19. #include <unistd.h>
  20. #endif
  21. #include "snprinterr.h"
  22. #define HAVE_STRERROR_R 0
  23. /* replace %m in format with actual strerror() message, write result to *str.
  24. keep other % formats unchanged!
  25. writes at most size chars including the terminating \0 to *str
  26. returns the number of bytes in the output without terminating \0
  27. result is always \0 terminated except when size==0
  28. */
  29. int snprinterr(char *str, size_t size, const char *format) {
  30. char c;
  31. int full = 0; /* 1 means: there is no space left in * str for more data or \0 */
  32. int count = 0;
  33. if (size == 0) return 0;
  34. if (count >= size) full = 1;
  35. while (c = *format++) {
  36. if (c == '%') {
  37. c = *format++;
  38. switch (c) {
  39. case '\0':
  40. ++count; if (!full) { (*str++ = '%'); if (count+1 >= size) full = 1; }
  41. break;
  42. default:
  43. ++count; if (!full) { (*str++ = '%'); if (count+1 >= size) full = 1; }
  44. ++count; if (!full) { (*str++ = c); if (count+1 >= size) full = 1; }
  45. break;
  46. case 'm':
  47. {
  48. #if HAVE_STRERROR_R
  49. # define BUFLEN 64
  50. char buf[BUFLEN] = "";
  51. #endif /* HAVE_STRERROR_R */
  52. char *bufp;
  53. #if !HAVE_STRERROR_R
  54. bufp = strerror(errno);
  55. #else
  56. /* there are two versions floating around... */
  57. # if 1 /* GNU version */
  58. bufp = strerror_r(errno, buf, BUFLEN);
  59. # else /* standard version */
  60. strerror_r(errno, buf, BUFLEN);
  61. bufp = buf;
  62. # endif
  63. #endif /* HAVE_STRERROR_R */
  64. while ((c = *bufp++) != '\0') {
  65. ++count; if (!full) { (*str++ = c); if (count+1 >= size) full = 1; }
  66. }
  67. }
  68. c = ' '; /* not \0 ! */
  69. break;
  70. }
  71. if (c == '\0') break;
  72. } else {
  73. ++count; if (!full) { (*str++ = c); if (count+1 >= size) full = 1; }
  74. }
  75. }
  76. *str++ = '\0'; /* always write terminating \0 */
  77. return count;
  78. #undef BUFLEN
  79. }