@@ -2105,6 +2105,30 @@ static bool UtilMoveFile(const char *fromPath, const char *toPath)
2105
2105
#endif
2106
2106
}
2107
2107
2108
+ static bool UtilCreateWritableTempFile (char * outPathBuffer , const char * prefix , const char * path )
2109
+ {
2110
+ #ifdef _WIN32
2111
+ if (GetTempFileNameA (path , prefix , 0 , outPathBuffer ) == 0 ) {
2112
+ return false;
2113
+ }
2114
+ #else
2115
+ int unix_fd = 0 ;
2116
+ mode_t mask = 0 ;
2117
+
2118
+ snprintf (outPathBuffer , PATH_MAX , "%s/%sXXXXXX" , path , prefix );
2119
+ unix_fd = mkstemp (outPathBuffer );
2120
+ if (unix_fd < 0 ) {
2121
+ return NULL ;
2122
+ }
2123
+
2124
+ mask = umask (0 );
2125
+ umask (mask );
2126
+ fchmod (unix_fd , 0644 & ~mask );
2127
+ #endif
2128
+
2129
+ return true;
2130
+ }
2131
+
2108
2132
// Write JSON to file
2109
2133
void writeJsonToFile (const char * file , char * (* generator ) (const char * ,int * ))
2110
2134
{
@@ -2117,33 +2141,13 @@ void writeJsonToFile(const char *file, char * (*generator) (const char *,int*))
2117
2141
if (!Modes .json_dir )
2118
2142
return ;
2119
2143
2120
- #ifdef _WIN32
2121
- if (GetTempFileNameA (Modes .json_dir , file , 0 , tmppath ) == 0 ) {
2144
+ if (!UtilCreateWritableTempFile (tmppath , file , Modes .json_dir ) ||
2145
+ (fd = fopen (tmppath , "wb" )) == NULL ) {
2146
+ //TODO: implement a function to get the last error on windows and linux as a string
2122
2147
ratelimitWriteError ("failed to create %s (while updating %s/%s): %s" , tmppath , Modes .json_dir , file , strerror (errno ));
2123
- return ;
2124
2148
}
2125
2149
2126
- fd = fopen (tmppath , "wb" );
2127
- #else
2128
- int unix_fd = 0 ;
2129
- mode_t mask = 0 ;
2130
- snprintf (tmppath , PATH_MAX , "%s/%sXXXXXX" , Modes .json_dir , file );
2131
- tmppath [PATH_MAX - 1 ] = 0 ;
2132
- unix_fd = mkstemp (tmppath );
2133
- if (unix_fd < 0 ) {
2134
- ratelimitWriteError ("failed to create %s (while updating %s/%s): %s" , tmppath , Modes .json_dir , file , strerror (errno ));
2135
- return ;
2136
- }
2137
-
2138
- mask = umask (0 );
2139
- umask (mask );
2140
- fchmod (unix_fd , 0644 & ~mask );
2141
- fd = fdopen (unix_fd , "wb" );
2142
- #endif
2143
-
2144
2150
snprintf (pathbuf , PATH_MAX , "/data/%s" , file );
2145
- pathbuf [PATH_MAX - 1 ] = 0 ;
2146
-
2147
2151
content = generator (pathbuf , (int * )& len );
2148
2152
2149
2153
if (fwrite (content , 1 , len , fd ) != len || fclose (fd ) != 0 )
@@ -2156,8 +2160,6 @@ void writeJsonToFile(const char *file, char * (*generator) (const char *,int*))
2156
2160
}
2157
2161
2158
2162
snprintf (pathbuf , PATH_MAX , "%s/%s" , Modes .json_dir , file );
2159
- pathbuf [PATH_MAX - 1 ] = 0 ;
2160
-
2161
2163
if (!UtilMoveFile (tmppath , pathbuf )){
2162
2164
ratelimitWriteError ("failed to rename %s to %s: %s" , tmppath , pathbuf , strerror (errno ));
2163
2165
}
0 commit comments