log.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. * Copyright (c) 2004-2005 Sergey Lyubka <valenok@gmail.com>
  3. * All rights reserved
  4. *
  5. * "THE BEER-WARE LICENSE" (Revision 42):
  6. * Sergey Lyubka wrote this file. As long as you retain this notice you
  7. * can do whatever you want with this stuff. If we meet some day, and you think
  8. * this stuff is worth it, you can buy me a beer in return.
  9. */
  10. #include "defs.h"
  11. /*
  12. * Log function
  13. */
  14. void
  15. _shttpd_elog(int flags, struct conn *c, const char *fmt, ...)
  16. {
  17. char date[64], buf[URI_MAX];
  18. int len;
  19. FILE *fp = c == NULL ? NULL : c->ctx->error_log;
  20. va_list ap;
  21. /* Print to stderr */
  22. if (c == NULL || !IS_TRUE(c->ctx, OPT_INETD)) {
  23. va_start(ap, fmt);
  24. (void) vfprintf(stderr, fmt, ap);
  25. (void) fputc('\n', stderr);
  26. va_end(ap);
  27. }
  28. strftime(date, sizeof(date), "%a %b %d %H:%M:%S %Y",
  29. localtime(&_shttpd_current_time));
  30. len = _shttpd_snprintf(buf, sizeof(buf),
  31. "[%s] [error] [client %s] \"%s\" ",
  32. date, c ? inet_ntoa(c->sa.u.sin.sin_addr) : "-",
  33. c && c->request ? c->request : "-");
  34. va_start(ap, fmt);
  35. (void) vsnprintf(buf + len, sizeof(buf) - len, fmt, ap);
  36. va_end(ap);
  37. buf[sizeof(buf) - 1] = '\0';
  38. if (fp != NULL && (flags & (E_FATAL | E_LOG))) {
  39. (void) fprintf(fp, "%s\n", buf);
  40. (void) fflush(fp);
  41. }
  42. if (flags & E_FATAL)
  43. exit(EXIT_FAILURE);
  44. }
  45. void
  46. _shttpd_log_access(FILE *fp, const struct conn *c)
  47. {
  48. static const struct vec dash = {"-", 1};
  49. const struct vec *user = &c->ch.user.v_vec;
  50. const struct vec *referer = &c->ch.referer.v_vec;
  51. const struct vec *user_agent = &c->ch.useragent.v_vec;
  52. char date[64], buf[URI_MAX], *q1 = "\"", *q2 = "\"";
  53. if (user->len == 0)
  54. user = &dash;
  55. if (referer->len == 0) {
  56. referer = &dash;
  57. q1 = "";
  58. }
  59. if (user_agent->len == 0) {
  60. user_agent = &dash;
  61. q2 = "";
  62. }
  63. (void) strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S",
  64. localtime(&c->birth_time));
  65. (void) _shttpd_snprintf(buf, sizeof(buf),
  66. "%s - %.*s [%s %+05d] \"%s\" %d %lu %s%.*s%s %s%.*s%s",
  67. inet_ntoa(c->sa.u.sin.sin_addr), user->len, user->ptr,
  68. date, _shttpd_tz_offset, c->request ? c->request : "-",
  69. c->status, (unsigned long) c->loc.io.total,
  70. q1, referer->len, referer->ptr, q1,
  71. q2, user_agent->len, user_agent->ptr, q2);
  72. if (fp != NULL) {
  73. (void) fprintf(fp, "%s\n", buf);
  74. (void) fflush(fp);
  75. }
  76. }