f858d4369558126cca711f77f19f77edff221e67
[platform/upstream/cmake.git] / Utilities / cmcurl / lib / rename.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at https://curl.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  ***************************************************************************/
22
23 #include "rename.h"
24
25 #include "curl_setup.h"
26
27 #if (!defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_COOKIES)) || \
28   !defined(CURL_DISABLE_ALTSVC)
29
30 #include "curl_multibyte.h"
31 #include "timeval.h"
32
33 /* The last 3 #include files should be in this order */
34 #include "curl_printf.h"
35 #include "curl_memory.h"
36 #include "memdebug.h"
37
38 /* return 0 on success, 1 on error */
39 int Curl_rename(const char *oldpath, const char *newpath)
40 {
41 #ifdef WIN32
42   /* rename() on Windows doesn't overwrite, so we can't use it here.
43      MoveFileEx() will overwrite and is usually atomic, however it fails
44      when there are open handles to the file. */
45   const int max_wait_ms = 1000;
46   struct curltime start = Curl_now();
47   TCHAR *tchar_oldpath = curlx_convert_UTF8_to_tchar((char *)oldpath);
48   TCHAR *tchar_newpath = curlx_convert_UTF8_to_tchar((char *)newpath);
49   for(;;) {
50     timediff_t diff;
51     if(MoveFileEx(tchar_oldpath, tchar_newpath, MOVEFILE_REPLACE_EXISTING)) {
52       curlx_unicodefree(tchar_oldpath);
53       curlx_unicodefree(tchar_newpath);
54       break;
55     }
56     diff = Curl_timediff(Curl_now(), start);
57     if(diff < 0 || diff > max_wait_ms) {
58       curlx_unicodefree(tchar_oldpath);
59       curlx_unicodefree(tchar_newpath);
60       return 1;
61     }
62     Sleep(1);
63   }
64 #else
65   if(rename(oldpath, newpath))
66     return 1;
67 #endif
68   return 0;
69 }
70
71 #endif