A clone of btpd with my configuration changes.

121 строка
2.4 KiB

  1. #include "btpd.h"
  2. #include <stdarg.h>
  3. #include <time.h>
  4. void *
  5. btpd_malloc(size_t size)
  6. {
  7. void *a;
  8. if ((a = malloc(size)) == NULL)
  9. btpd_err("Failed to allocate %d bytes.\n", (int)size);
  10. return a;
  11. }
  12. void *
  13. btpd_calloc(size_t nmemb, size_t size)
  14. {
  15. void *a;
  16. if ((a = calloc(nmemb, size)) == NULL)
  17. btpd_err("Failed to allocate %d bytes.\n", (int)(nmemb * size));
  18. return a;
  19. }
  20. void
  21. btpd_ev_new(struct fdev *ev, int fd, uint16_t flags, evloop_cb_t cb, void *arg)
  22. {
  23. if (fdev_new(ev, fd, flags, cb, arg) != 0)
  24. btpd_err("Failed to add event (%s).\n", strerror(errno));
  25. }
  26. void
  27. btpd_ev_del(struct fdev *ev)
  28. {
  29. if (fdev_del(ev) != 0)
  30. btpd_err("Failed to remove event (%s).\n", strerror(errno));
  31. }
  32. void
  33. btpd_ev_enable(struct fdev *ev, uint16_t flags)
  34. {
  35. if (fdev_enable(ev, flags) != 0)
  36. btpd_err("Failed to enable event (%s).\n", strerror(errno));
  37. }
  38. void
  39. btpd_ev_disable(struct fdev *ev, uint16_t flags)
  40. {
  41. if (fdev_disable(ev, flags) != 0)
  42. btpd_err("Failed to disable event (%s).\n", strerror(errno));
  43. }
  44. void
  45. btpd_timer_add(struct timeout *to, struct timespec *ts)
  46. {
  47. if (timer_add(to, ts) != 0)
  48. btpd_err("Failed to add timeout (%s).\n", strerror(errno));
  49. }
  50. void
  51. btpd_timer_del(struct timeout *to)
  52. {
  53. timer_del(to);
  54. }
  55. static const char *
  56. logtype_str(uint32_t type)
  57. {
  58. if (type & BTPD_L_BTPD)
  59. return "btpd";
  60. else if (type & BTPD_L_ERROR)
  61. return "error";
  62. else if (type & BTPD_L_CONN)
  63. return "conn";
  64. else if (type & BTPD_L_TRACKER)
  65. return "tracker";
  66. else if (type & BTPD_L_MSG)
  67. return "msg";
  68. else
  69. return "";
  70. }
  71. static void
  72. log_common(uint32_t type, const char *fmt, va_list ap)
  73. {
  74. if (type & btpd_logmask) {
  75. char tbuf[20];
  76. time_t tp = time(NULL);
  77. strftime(tbuf, 20, "%b %e %T", localtime(&tp));
  78. printf("%s %s: ", tbuf, logtype_str(type));
  79. vprintf(fmt, ap);
  80. }
  81. }
  82. extern int btpd_daemon_phase;
  83. extern void first_btpd_exit(char);
  84. void
  85. btpd_err(const char *fmt, ...)
  86. {
  87. va_list ap;
  88. va_start(ap, fmt);
  89. if (btpd_daemon_phase > 0) {
  90. vprintf(fmt, ap);
  91. if (btpd_daemon_phase == 1)
  92. first_btpd_exit(1);
  93. exit(1);
  94. } else {
  95. log_common(BTPD_L_ERROR, fmt, ap);
  96. abort();
  97. }
  98. }
  99. void
  100. btpd_log(uint32_t type, const char *fmt, ...)
  101. {
  102. va_list ap;
  103. va_start(ap, fmt);
  104. log_common(type, fmt, ap);
  105. va_end(ap);
  106. }