httpdate: favor gettimeofday(2) over time(2) for correctness
[unicorn.git] / ext / unicorn_http / httpdate.c
blob27a8f5183a0c1a4f2d0225a8f3269c1f68f38c67
1 #include <ruby.h>
2 #include <sys/time.h>
3 #include <stdio.h>
5 static const size_t buf_capa = sizeof("Thu, 01 Jan 1970 00:00:00 GMT");
6 static VALUE buf;
7 static char *buf_ptr;
8 static const char week[] = "Sun\0Mon\0Tue\0Wed\0Thu\0Fri\0Sat";
9 static const char months[] = "Jan\0Feb\0Mar\0Apr\0May\0Jun\0"
10 "Jul\0Aug\0Sep\0Oct\0Nov\0Dec";
12 /* for people on wonky systems only */
13 #ifndef HAVE_GMTIME_R
14 # warning using fake gmtime_r
15 static struct tm * my_gmtime_r(time_t *now, struct tm *tm)
17 struct tm *global = gmtime(now);
18 if (global)
19 *tm = *global;
20 return tm;
22 # define gmtime_r my_gmtime_r
23 #endif
27 * Returns a string which represents the time as rfc1123-date of HTTP-date
28 * defined by RFC 2616:
30 * day-of-week, DD month-name CCYY hh:mm:ss GMT
32 * Note that the result is always GMT.
34 * This method is identical to Time#httpdate in the Ruby standard library,
35 * except it is implemented in C for performance. We always saw
36 * Time#httpdate at or near the top of the profiler output so we
37 * decided to rewrite this in C.
39 * Caveats: it relies on a Ruby implementation with the global VM lock,
40 * a thread-safe version will be provided when a Unix-only, GVL-free Ruby
41 * implementation becomes viable.
43 static VALUE httpdate(VALUE self)
45 static time_t last;
46 struct timeval now;
47 struct tm tm;
50 * Favor gettimeofday(2) over time(2), as the latter can return the
51 * wrong value in the first 1 .. 2.5 ms of every second(!)
53 * https://lore.kernel.org/git/20230320230507.3932018-1-gitster@pobox.com/
54 * https://inbox.sourceware.org/libc-alpha/20230306160321.2942372-1-adhemerval.zanella@linaro.org/T/
55 * https://sourceware.org/bugzilla/show_bug.cgi?id=30200
57 if (gettimeofday(&now, NULL))
58 rb_sys_fail("gettimeofday");
60 if (last == now.tv_sec)
61 return buf;
62 last = now.tv_sec;
63 gmtime_r(&now.tv_sec, &tm);
65 /* we can make this thread-safe later if our Ruby loses the GVL */
66 snprintf(buf_ptr, buf_capa,
67 "%s, %02d %s %4d %02d:%02d:%02d GMT",
68 week + (tm.tm_wday * 4),
69 tm.tm_mday,
70 months + (tm.tm_mon * 4),
71 tm.tm_year + 1900,
72 tm.tm_hour,
73 tm.tm_min,
74 tm.tm_sec);
76 return buf;
79 void init_unicorn_httpdate(void)
81 VALUE mod = rb_define_module("Unicorn");
82 mod = rb_define_module_under(mod, "HttpResponse");
84 buf = rb_str_new(0, buf_capa - 1);
85 rb_gc_register_mark_object(buf);
86 buf_ptr = RSTRING_PTR(buf);
87 httpdate(Qnil);
89 rb_define_method(mod, "httpdate", httpdate, 0);