Debian Codegraph @

ddio/winfile.cpp

raw
1 /*
2 * Descent 3
3 * Copyright (C) 2024 Parallax Software
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18 --- HISTORICAL COMMENTS FOLLOW ---
19
20 * $Logfile: /DescentIII/Main/ddio_win/winfile.cpp $
21 * $Revision: 27 $
22 * $Date: 10/22/99 1:23p $
23 * $Author: Kevin $
24 *
25 * File operations not covered properly in ANSI C
26 *
27 * $Log: /DescentIII/Main/ddio_win/winfile.cpp $
28 *
29 * 27 10/22/99 1:23p Kevin
30 * Made ddio_GetCDDrive return null if the cd isn't found
31 *
32 * 26 7/12/99 6:44p Jeff
33 * added directory lock file API functions
34 *
35 * 25 6/24/99 2:04p Kevin
36 * Fixed bug with 2 CD rom drives & ddio_GetCDDrive
37 *
38 * 24 3/19/99 1:53p Kevin
39 * Fixed a bug with ddio_GetCDDrive
40 *
41 * 23 2/09/99 4:46p Jeff
42 * removed int3 in CopyFileTime
43 *
44 * 22 2/04/99 11:19a Kevin
45 * Added function to find a CD drive letter based on it's volume name
46 *
47 * 21 12/08/98 12:17p Jeff
48 * added 3 functions (similar to ddio_FindFiles) for finding directories
49 * in a path
50 *
51 * 20 11/19/98 5:40p Kevin
52 * Demo system
53 *
54 * 19 10/16/98 11:55a Kevin
55 * Made dlls loadable in a hog
56 *
57 * 18 10/08/98 4:23p Kevin
58 * Changed code to comply with memory library usage. Always use mem_malloc
59 * , mem_free and mem_strdup
60 *
61 * 17 8/19/98 2:18p Jeff
62 * changed ddio_CleanPath
63 *
64 * 16 8/16/98 2:04p Matt
65 * Fixed super-stupid bug
66 *
67 * 15 8/15/98 3:42p Matt
68 * Added new function, ddio_GetFullPath()
69 *
70 * 14 7/29/98 5:38p Jeff
71 * added ddio functions to get parent path, and to clean a path name into
72 * the real path
73 *
74 * 13 7/28/98 6:05p Jeff
75 * added functions to get root directories (aka drives in windows/dos)
76 *
77 * 12 6/01/98 10:34a Matt
78 * If can't copy file time, wait half a second and try again.
79 *
80 * 11 5/26/98 7:35p Jason
81 * took out filetime int 3
82 *
83 * 10 4/06/98 1:24p Samir
84 * support NULL arguments to ddio_SpltPath.
85 *
86 * 9 3/19/98 3:18p Samir
87 * enforce constant char* arguments when needed. done in CFILE and bitmap
88 * libraries as well as ddio.
89 *
90 * 8 2/20/98 3:37p Jason
91 * fixed error message to print out before subsequent file operations
92 * happen
93 *
94 * 7 2/17/98 9:40p Jason
95 * print out error number for copy file time
96 *
97 * 6 2/16/98 11:08a Jason
98 * fixed copyfiletime bug
99 *
100 * 5 2/16/98 1:48a Matt
101 * Added some additional error checking
102 *
103 * 4 9/10/97 12:06p Samir
104 * FIxed FindFile functions.
105 *
106 * 3 8/15/97 6:31p Samir
107 * Added findfile functions.
108 *
109 * 2 7/17/97 3:00p Jason
110 * took out int3 on copy file time
111 *
112 * 10 6/11/97 2:39p Samir
113 * Fixed bools
114 *
115 * 9 5/06/97 4:27p Samir
116 * Added ddio_MakePath
117 *
118 * 8 5/06/97 12:35p Samir
119 * Impllemented DirectoryExists and Save/Restore Working paths.
120 *
121 * 7 4/25/97 6:16p Jason
122 * added ddio_Deletefile function
123 *
124 * 6 4/03/97 4:34p Jason
125 * added CopyFileTime to the cfile, ddio libs
126 *
127 * 5 3/14/97 6:52p Samir
128 * Fixed jeremy bugs.
129 *
130 * 4 3/14/97 6:53 PM Jeremy
131 * added implementation of ddio_GetFileLength, ddio_SplitPath
132 *
133 * 3 3/14/97 6:38p Samir
134 * Added ddio_FileDiff
135 *
136 * 2 3/13/97 11:09a Samir
137 * Moved file stuff from gameos to ddio library
138 *
139 * 1 3/13/97 11:01a Samir
140 * Moved from gameos library
141 *
142 * $NoKeywords: $
143 */
144
145 #include "ddio.h"
146 #include "ddio_win.h"
147 #include "pserror.h"
148 #include "mem.h"
149 #include <stdarg.h>
150 #include <sys/stat.h>
151 #include <io.h>
152 #include <fcntl.h>
153 #include <stdio.h>
154 #include <errno.h>
155
156 // ---------------------------------------------------------------------------
157 // File operations
158
159 // retrieve the current working folder where file operation will occur.
160 void ddio_GetWorkingDir(char *path, int len) { GetCurrentDirectory(len, path); }
161
162 bool ddio_SetWorkingDir(const char *path) { return (SetCurrentDirectory(path)) ? true : false; }
163
164 bool ddio_FileDiff(const std::filesystem::path &path1, const std::filesystem::path &path2) {
165 struct _stat abuf, bbuf;
166
167 if (_stat(path1.u8string().c_str(), &abuf))
168 Int3(); // error getting stat info
169
170 if (_stat(path2.u8string().c_str(), &bbuf))
171 Int3(); // error getting stat info
172
173 if ((abuf.st_size != bbuf.st_size) || (abuf.st_mtime != bbuf.st_mtime))
174 return true;
175
176 return false;
177 }
178
179 // get a file's length
180 int ddio_GetFileLength(FILE *filePtr) { return (filelength(fileno(filePtr))); }
181
182 // Split a pathname into its component parts
183 void ddio_SplitPath(const char *srcPath, char *path, char *filename, char *ext) {
184 char drivename[_MAX_DRIVE], dirname[_MAX_DIR];
185
186 _splitpath(srcPath, drivename, dirname, filename, ext);
187
188 if (path)
189 sprintf(path, "%s%s", drivename, dirname);
190 }
191
192 void ddio_CopyFileTime(const std::filesystem::path &dest, const std::filesystem::path &src) {
193 HANDLE desthandle, srchandle;
194 FILETIME a, b, c;
195 bool first_time = 1;
196
197 try_again:;
198
199 desthandle = CreateFile(dest.u8string().c_str(), GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
200 srchandle = CreateFile(src.u8string().c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
201
202 if (desthandle == INVALID_HANDLE_VALUE || srchandle == INVALID_HANDLE_VALUE) {
203 mprintf(0, "Couldn't copy file time for %s! Error=%d\n", dest.u8string().c_str(), GetLastError());
204
205 if (desthandle != INVALID_HANDLE_VALUE)
206 CloseHandle(desthandle);
207
208 if (srchandle != INVALID_HANDLE_VALUE)
209 CloseHandle(srchandle);
210
211 if (first_time) {
212 first_time = 0;
213 Sleep(500);
214 goto try_again;
215 }
216
217 // JEFF: This Int3 has become really annoying...all we do is blow by it anyway
218 // removed for sanity.
219 //@@Int3(); //Let Matt know if you hit this!
220 return;
221 }
222
223 GetFileTime(srchandle, &a, &b, &c);
224 SetFileTime(desthandle, &a, &b, &c);
225
226 CloseHandle(desthandle);
227 CloseHandle(srchandle);
228 }
229
230 // deletes a file. Returns 1 if successful, 0 on failure
231 int ddio_DeleteFile(const char *name) { return (DeleteFile(name)); }
232
233 // Constructs a path in the local file system's syntax
234 // newPath: stores the constructed path
235 // absolutePathHeader: absolute path on which the sub directories will be appended
236 // (specified in local file system syntax)
237 // takes a variable number of subdirectories which will be concatenated on to the path
238 // the last argument in the list of sub dirs *MUST* be NULL to terminate the list
239 void ddio_MakePath(char *newPath, const char *absolutePathHeader, const char *subDir, ...) {
240 const char delimiter = '\\';
241 va_list args;
242 char *currentDir = NULL;
243 int pathLength = 0;
244
245 assert(newPath);
246 assert(absolutePathHeader);
247 assert(subDir);
248
249 if (newPath != absolutePathHeader) {
250 strcpy(newPath, absolutePathHeader);
251 }
252
253 // Add the first sub directory
254 pathLength = strlen(newPath);
255 if (newPath[pathLength - 1] != delimiter) {
256 newPath[pathLength] = delimiter; // add the delimiter
257 newPath[pathLength + 1] = 0; // terminate the string
258 }
259 strcat(newPath, subDir);
260
261 // Add the additional subdirectories
262 va_start(args, subDir);
263 while ((currentDir = va_arg(args, char *)) != NULL) {
264 pathLength = strlen(newPath);
265 if (newPath[pathLength - 1] != delimiter) {
266 newPath[pathLength] = delimiter; // add the delimiter
267 newPath[pathLength + 1] = 0; // terminate the string
268 }
269 strcat(newPath, currentDir);
270 }
271 va_end(args);
272 }
273
274 bool ddio_GetTempFileName(const char *basedir, const char *prefix, char *filename) {
275
276 if (!GetTempFileName(basedir, prefix, 0, filename))
277 return false;
278 else
279 return true;
280 }
281
282 // These functions allow one to find a file
283 // You use FindFileStart by giving it a wildcard (like *.*, *.txt, u??.*, whatever). It returns
284 // a filename in namebuf.
285 // Use FindNextFile to get the next file found with the wildcard given in FindFileStart.
286 // Use FindFileClose to end your search.
287 static HANDLE hFindFile = INVALID_HANDLE_VALUE;
288 static WIN32_FIND_DATA FindFileData;
289
290 bool ddio_FindFileStart(const char *wildcard, char *namebuf) {
291 if (hFindFile != INVALID_HANDLE_VALUE)
292 ddio_FindFileClose();
293
294 hFindFile = FindFirstFile(wildcard, &FindFileData);
295 if (hFindFile != INVALID_HANDLE_VALUE) {
296 strcpy(namebuf, FindFileData.cFileName);
297 return true;
298 } else {
299 namebuf[0] = 0;
300 return false;
301 }
302 }
303
304 bool ddio_FindNextFile(char *namebuf) {
305
306 if (!hFindFile)
307 return false;
308
309 if (FindNextFile(hFindFile, &FindFileData)) {
310 strcpy(namebuf, FindFileData.cFileName);
311 return true;
312 } else {
313 namebuf[0] = 0;
314 return false;
315 }
316 }
317
318 void ddio_FindFileClose() {
319 if (hFindFile != INVALID_HANDLE_VALUE)
320 FindClose(hFindFile);
321 hFindFile = INVALID_HANDLE_VALUE;
322 }
323
324 // pass in a pathname (could be from ddio_SplitPath), root_path will have the drive name.
325 void ddio_GetRootFromPath(const char *srcPath, char *root_path) {
326 assert(root_path);
327 assert(srcPath);
328
329 // the first char should be drive letter, second char should be a :
330 if ((isalpha(srcPath[0])) && (srcPath[1] == ':')) {
331 // everything is ok
332 strncpy(root_path, srcPath, 2);
333 root_path[2] = '\0';
334 } else {
335 // invalid path (no root)
336 root_path[0] = '\0';
337 }
338 }
339
340 // retrieve root names, free up roots array (allocated with malloc) after use
341 int ddio_GetFileSysRoots(char **roots, int max_roots) {
342 char buffer[100];
343
344 int ret = GetLogicalDriveStrings(100, buffer);
345 if (ret == 0) {
346 // there was an error
347 return 0;
348 }
349
350 if (ret > 100) {
351 // we didn't have enough space
352 return 0;
353 }
354
355 int count = 0;
356 bool done = false;
357 char *strptr = buffer;
358 char *string;
359 int strsize;
360 while ((count < max_roots) && (!done)) {
361 if (*strptr != 0) {
362 strsize = strlen(strptr);
363 string = roots[count] = (char *)mem_malloc(strsize);
364 if (!string)
365 break;
366 // remove the trailing \ from windows
367 strncpy(string, strptr, strsize - 1);
368 string[strsize - 1] = '\0';
369
370 strptr += (strsize + 1);
371
372 count++;
373 } else
374 done = true;
375 }
376 return count;
377 }
378
379 // given a path, it cleans it up (if the path is c:\windows\..\dos it would make it c:\dos)
380 // srcPath is the original path
381 // dest is the finished cleaned path.
382 // dest should be at least _MAX_PATH in size
383 void ddio_CleanPath(char *dest, const char *srcPath) {
384 strcpy(dest, srcPath);
385
386 // break the path into directories
387 char **directories;
388 int dirs;
389 int path_length;
390
391 // make sure the path ends with a \ for sanity
392 path_length = strlen(dest);
393
394 if (dest[path_length - 1] != '\\') {
395 dest[path_length] = '\\';
396 dest[path_length + 1] = '\0';
397 path_length++;
398 }
399
400 // now divide the full path into seperate NULL terminated strings,counting the number
401 // of directories in the process
402 dirs = 0;
403 char *strptr = dest;
404 while (*strptr != '\0') {
405 if (*strptr == '\\') {
406 *strptr = '\0';
407 dirs++;
408 }
409 strptr++;
410 }
411
412 // check to make sure we have a directory, if we don't then return the original path given
413 if (dirs == 0) {
414 strcpy(dest, srcPath);
415 return;
416 }
417
418 // allocate the memory needed for the seperate strings of each directory
419 directories = (char **)mem_malloc(sizeof(char *) * dirs);
420 if (!directories) {
421 strcpy(dest, srcPath);
422 return;
423 }
424
425 // now get all the directories, and place into the individual strings
426 strptr = dest;
427 int count = 0;
428 while (count < dirs) {
429 directories[count] = mem_strdup(strptr);
430 strptr += strlen(strptr) + 1;
431 count++;
432 }
433
434 // now the fun part, figure out the correct order of the directories
435 int *dir_order;
436
437 dir_order = (int *)mem_malloc(sizeof(int) * dirs);
438 if (!dir_order) {
439 strcpy(dest, srcPath);
440 return;
441 }
442
443 for (count = 0; count < dirs; count++)
444 dir_order[count] = -1; // a -1 means the end of the sequence
445
446 // now build the order based on the indicies
447 int curr_index = 0;
448 for (count = 0; count < dirs; count++) {
449
450 if (!stricmp(directories[count], "..")) {
451 // we have to back up a directory
452 curr_index--; // back up
453 if (curr_index < 0)
454 curr_index = 0; // can't go further than root
455 dir_order[curr_index] = -1; // invalidate current slot
456 } else if (stricmp(directories[count], ".")) {
457 // we have a normal directory, add it's index
458 dir_order[curr_index] = count;
459 curr_index++;
460 }
461 }
462
463 // now rebuild the correct path for use, when we hit -1, we're done
464 dest[0] = '\0';
465 for (count = 0; count < dirs; count++) {
466 if (dir_order[count] == -1)
467 break;
468 else {
469 strcat(dest, directories[dir_order[count]]);
470 strcat(dest, "\\");
471 }
472 }
473
474 // now remove trailing \ char
475 path_length = strlen(dest);
476 if ((path_length > 0) && (dest[path_length - 1] == '\\'))
477 dest[path_length - 1] = '\0';
478
479 // free up all the allocated memory and we're done
480 for (count = 0; count < dirs; count++) {
481 if (directories[count])
482 mem_free(directories[count]);
483 }
484 if (directories)
485 mem_free(directories);
486 if (dir_order)
487 mem_free(dir_order);
488 }
489
490 // given a path (with no filename), it will return the parent path
491 // srcPath is the source given path
492 // dest is where the parent path will be placed
493 // returns true on success
494 // dest should be at least _MAX_PATH in length
495 bool ddio_GetParentPath(char *dest, const char *srcPath) {
496 assert(srcPath);
497 assert(dest);
498
499 #define PARENT_DELIM ".."
500 int spath_len = strlen(srcPath);
501 char *temp;
502
503 temp = (char *)mem_malloc(spath_len + strlen(PARENT_DELIM) + 3);
504 if (!temp) {
505 return false;
506 }
507
508 ddio_MakePath(temp, srcPath, PARENT_DELIM, NULL);
509 ddio_CleanPath(dest, temp);
510 mem_free(temp);
511 return true;
512 }
513
514 // Finds a full path from a relative path
515 // Parameters: full_path - filled in with the fully-specified path. Buffer must be at least _MAX_PATH bytes long
516 // rel_path - a path specification, either relative or absolute
517 // Returns TRUE if successful, FALSE if an error
518 bool ddio_GetFullPath(char *full_path, const char *rel_path) {
519 char old_path[_MAX_PATH];
520
521 ddio_GetWorkingDir(old_path, sizeof(old_path)); // save old directory
522
523 if (!ddio_SetWorkingDir(rel_path)) // try switching to new directory
524 return 0; // couldn't switch, so return error
525
526 ddio_GetWorkingDir(full_path, _MAX_PATH); // get path from the OS
527
528 ddio_SetWorkingDir(old_path); // now restore old path
529
530 return 1;
531 }
532
533 bool ddio_CheckProcess(int pid) {
534 HANDLE proc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
535 if (proc) {
536 DWORD obj_ret = WaitForSingleObject(proc, 0);
537 CloseHandle(proc);
538 if (obj_ret == WAIT_TIMEOUT) {
539 // this process exists still
540 return true;
541 }
542 }
543 return false;
544 }
545
546 int ddio_GetPID() {
547 return GetCurrentProcessId();
548 }