From e5a6e68c7e03b9112b0429e1849dfbec760a55d7 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?S=C3=A9bastien=20Blin?=
 <sebastien.blin@savoirfairelinux.com>
Date: Thu, 18 May 2023 13:39:28 -0400
Subject: [PATCH] fileutils: fix erase_posix for read-only files

+ Like for windows, add write permissions if possible
+ Rewrite removeAll() condition because it returns an integer.

Change-Id: Id5eb413ed8a6a6345d9208646cdfb13f5c5810bb
---
 src/fileutils.cpp                      | 15 ++++++++-------
 src/jamidht/conversationrepository.cpp |  2 +-
 2 files changed, 9 insertions(+), 8 deletions(-)

diff --git a/src/fileutils.cpp b/src/fileutils.cpp
index 57ace9fc02..43eaef1faa 100644
--- a/src/fileutils.cpp
+++ b/src/fileutils.cpp
@@ -928,16 +928,17 @@ eraseFile_win32(const std::string& path, bool dosync)
 bool
 eraseFile_posix(const std::string& path, bool dosync)
 {
-    int fd = open(path.c_str(), O_WRONLY);
-    if (fd == -1) {
-        JAMI_WARN("Can not open file %s for erasing.", path.c_str());
+    struct stat st;
+    if (stat(path.c_str(), &st) == -1) {
+        JAMI_WARN("Can not erase file %s: fstat() failed.", path.c_str());
         return false;
     }
+    // Remove read-only flag if possible
+    chmod(path.c_str(), st.st_mode | (S_IWGRP+S_IWUSR) );
 
-    struct stat st;
-    if (fstat(fd, &st) == -1) {
-        JAMI_WARN("Can not erase file %s: fstat() failed.", path.c_str());
-        close(fd);
+    int fd = open(path.c_str(), O_WRONLY);
+    if (fd == -1) {
+        JAMI_WARN("Can not open file %s for erasing.", path.c_str());
         return false;
     }
 
diff --git a/src/jamidht/conversationrepository.cpp b/src/jamidht/conversationrepository.cpp
index b26aa7a6f4..18ba622ee2 100644
--- a/src/jamidht/conversationrepository.cpp
+++ b/src/jamidht/conversationrepository.cpp
@@ -2589,7 +2589,7 @@ ConversationRepository::cloneConversation(const std::shared_ptr<JamiAccount>& ac
     if (fileutils::isDirectory(path)) {
         // If a crash occurs during a previous clone, just in case
         JAMI_WARNING("Removing existing directory {} (the dir exists and non empty)", path);
-        if (!fileutils::removeAll(path, true))
+        if (fileutils::removeAll(path, true) != 0)
             return nullptr;
     }
 
-- 
GitLab