diff mbox series

[bug#66387] home: services: Fix race condition when detecting first login

Message ID dd990558758d8bec9b4074f126c464e2f8a8ae6f.1697025388.git.carlo@zancanaro.id.au
State New
Headers show
Series [bug#66387] home: services: Fix race condition when detecting first login | expand

Commit Message

Carlo Zancanaro Oct. 11, 2023, 11:57 a.m. UTC
* gnu/home/services.scm (compute-on-first-login-script): Use open to
atomically check whether a file exists and create it if not.
---
 gnu/home/services.scm | 20 +++++++++++++++-----
 1 file changed, 15 insertions(+), 5 deletions(-)


base-commit: 9ad9113fc238ee8de5191a5e15b5153fd149e9fa
diff mbox series

Patch

diff --git a/gnu/home/services.scm b/gnu/home/services.scm
index 8d53f2f4d3..7137925b30 100644
--- a/gnu/home/services.scm
+++ b/gnu/home/services.scm
@@ -2,6 +2,7 @@ 
 ;;; Copyright © 2021-2023 Andrew Tropin <andrew@trop.in>
 ;;; Copyright © 2021 Xinglu Chen <public@yoctocell.xyz>
 ;;; Copyright © 2022-2023 Ludovic Courtès <ludo@gnu.org>
+;;; Copyright © 2023 Carlo Zancanaro <carlo@zancanaro.id.au>
 ;;;
 ;;; This file is part of GNU Guix.
 ;;;
@@ -412,20 +413,29 @@  (define (compute-on-first-login-script _ gexps)
      #~(begin
          (use-modules (guix i18n)
                       (guix diagnostics))
+
+       (define (claim-first-run file-name)
+         (catch #t
+           (lambda ()
+             ;; This incantation will raise an error if the file at
+             ;; flag-file-path already exists, and will create it otherwise.
+             (close (open file-name (logior O_CREAT O_EXCL)))
+             #t)
+           (lambda _
+             #f)))
+
        #$%initialize-gettext
 
        (let* ((xdg-runtime-dir (or (getenv "XDG_RUNTIME_DIR")
                                    (format #f "/run/user/~a" (getuid))))
               (flag-file-path (string-append
-                               xdg-runtime-dir "/on-first-login-executed"))
-              (touch (lambda (file-name)
-                       (call-with-output-file file-name (const #t)))))
+                               xdg-runtime-dir "/on-first-login-executed")))
          ;; XDG_RUNTIME_DIR dissapears on logout, that means such trick
          ;; allows to launch on-first-login script on first login only
          ;; after complete logout/reboot.
          (if (file-exists? xdg-runtime-dir)
-             (unless (file-exists? flag-file-path)
-               (begin #$@gexps (touch flag-file-path)))
+             (when (claim-first-run flag-file-path)
+               #$@gexps)
              ;; TRANSLATORS: 'on-first-login' is the name of a service and
              ;; shouldn't be translated
              (warning (G_ "XDG_RUNTIME_DIR doesn't exists, on-first-login script