From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on dcvr.yhbt.net X-Spam-Level: X-Spam-ASN: X-Spam-Status: No, score=-4.0 required=3.0 tests=ALL_TRUSTED,AWL,BAYES_00, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF, T_SCC_BODY_TEXT_LINE shortcircuit=no autolearn=ham autolearn_force=no version=3.4.6 Received: from localhost (dcvr.yhbt.net [127.0.0.1]) by dcvr.yhbt.net (Postfix) with ESMTP id B81EB1F542 for ; Mon, 5 Jun 2023 09:15:35 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=yhbt.net; s=selector1; t=1685956535; bh=LXt3nsG39t4gfX9IeBmY15LrUL79OtnEPfleF3fYRPA=; h=From:To:Subject:Date:From; b=uDXLpsJT520N6tyeVTir/CUcfITqRI6dgb2P9+/tD8ZNZ3OGMKYh8+G0ANQls93i+ oULexIXgpEOnvsoYkp96C8kvklHJfKn+ElUJAFG3pOX3rfDxoWh2oqLNwdVO5ODlFL mT540/uy2pr4JudI/QWS8F56la4aUI7oTrlAmIJo= From: Eric Wong To: unicorn-public@yhbt.net Subject: [PATCH] httpdate: favor gettimeofday(2) over time(2) for correctness Date: Mon, 5 Jun 2023 09:15:35 +0000 Message-ID: <20230605091535.296006-1-bofh@yhbt.net> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit List-Id: While scanning the git@vger.kernel.org mailing list, I've learned time(2) may return the wrong value in the first 1 to 2.5 ms of every second. While I'm not sure if the Date: response header matters to anyone, returning the correct time seems prudent. Link: https://lore.kernel.org/git/20230320230507.3932018-1-gitster@pobox.com/ Link: https://inbox.sourceware.org/libc-alpha/20230306160321.2942372-1-adhemerval.zanella@linaro.org/T/ Link: https://sourceware.org/bugzilla/show_bug.cgi?id=30200 --- ext/unicorn_http/httpdate.c | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/ext/unicorn_http/httpdate.c b/ext/unicorn_http/httpdate.c index 3f512dd..27a8f51 100644 --- a/ext/unicorn_http/httpdate.c +++ b/ext/unicorn_http/httpdate.c @@ -1,5 +1,5 @@ #include -#include +#include #include static const size_t buf_capa = sizeof("Thu, 01 Jan 1970 00:00:00 GMT"); @@ -43,13 +43,24 @@ static struct tm * my_gmtime_r(time_t *now, struct tm *tm) static VALUE httpdate(VALUE self) { static time_t last; - time_t now = time(NULL); /* not a syscall on modern 64-bit systems */ + struct timeval now; struct tm tm; - if (last == now) + /* + * Favor gettimeofday(2) over time(2), as the latter can return the + * wrong value in the first 1 .. 2.5 ms of every second(!) + * + * https://lore.kernel.org/git/20230320230507.3932018-1-gitster@pobox.com/ + * https://inbox.sourceware.org/libc-alpha/20230306160321.2942372-1-adhemerval.zanella@linaro.org/T/ + * https://sourceware.org/bugzilla/show_bug.cgi?id=30200 + */ + if (gettimeofday(&now, NULL)) + rb_sys_fail("gettimeofday"); + + if (last == now.tv_sec) return buf; - last = now; - gmtime_r(&now, &tm); + last = now.tv_sec; + gmtime_r(&now.tv_sec, &tm); /* we can make this thread-safe later if our Ruby loses the GVL */ snprintf(buf_ptr, buf_capa,