| 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 | |
| 19 | #include <algorithm> |
| 20 | #include <cstdio> |
| 21 | #include <cstdlib> |
| 22 | #include <cstring> |
| 23 | #include <cstdarg> |
| 24 | #include <cerrno> |
| 25 | #include <cctype> |
| 26 | #include <filesystem> |
| 27 | #include <map> |
| 28 | #include <memory> |
| 29 | #include <vector> |
| 30 | |
| 31 | #if !defined(POSIX) |
| 32 | // Non-Linux Build Includes |
| 33 | #include <io.h> |
| 34 | #else |
| 35 | // Linux Build Includes |
| 36 | #include "linux_fix.h" |
| 37 | #endif |
| 38 | |
| 39 | #include "byteswap.h" |
| 40 | #include "pserror.h" |
| 41 | #include "ddio.h" |
| 42 | #include "psglob.h" |
| 43 | #include "cfile.h" |
| 44 | #include "hogfile.h" //info about library file |
| 45 | #include "mem.h" |
| 46 | |
| 47 | // Library structures |
| 48 | struct library_entry { |
| 49 | char name[PSFILENAME_LEN + 1]; // just the filename part |
| 50 | uint32_t offset; // offset into library file |
| 51 | uint32_t length; // length of this file |
| 52 | uint32_t timestamp; // time and date of file |
| 53 | uint32_t flags; // misc flags |
| 54 | }; |
| 55 | |
| 56 | struct library { |
| 57 | std::filesystem::path name; // includes path + filename |
| 58 | uint32_t nfiles = 0; |
| 59 | std::vector<std::unique_ptr<library_entry>> entries; |
| 60 | std::shared_ptr<library> next; |
| 61 | int handle = 0; // identifier for this lib |
| 62 | FILE *file = nullptr; // pointer to file for this lib, if no one using it |
| 63 | }; |
| 64 | |
| 65 | // Map of paths. If value of entry is true, path is only for specific extensions |
| 66 | std::map<std::filesystem::path, bool> paths; |
| 67 | |
| 68 | // Map of extensions <=> relevant paths |
| 69 | std::map<std::filesystem::path, std::filesystem::path> extensions; |
| 70 | |
| 71 | std::shared_ptr<library> Libraries; |
| 72 | int lib_handle = 0; |
| 73 | |
| 74 | // Structure thrown on disk error |
| 75 | cfile_error cfe; |
| 76 | // The message for unexpected end of file |
| 77 | const char *eof_error = "Unexpected end of file"; |
| 78 | |
| 79 | // Generates a cfile error |
| 80 | void ThrowCFileError(int type, CFILE *file, const char *msg) { |
| 81 | cfe.read_write = type; |
| 82 | cfe.msg = msg; |
| 83 | cfe.file = file; |
| 84 | throw &cfe; |
| 85 | } |
| 86 | |
| 87 | static void cf_Close(); |
| 88 | |
| 89 | // searches through the open HOG files, and opens a file if it finds it in any of the libs |
| 90 | static CFILE *open_file_in_lib(const char *filename); |
| 91 | |
| 92 | // Opens a HOG file. Future calls to cfopen(), etc. will look in this HOG. |
| 93 | // Parameters: libname - the path & filename of the HOG file |
| 94 | // NOTE: libname must be valid for the entire execution of the program. Therefore, it should either |
| 95 | // be a fully-specified path name, or the current directory must not change. |
| 96 | // Returns: 0 if error, else library handle that can be used to close the library |
| 97 | int cf_OpenLibrary(const std::filesystem::path &libname) { |
| 98 | FILE *fp; |
| 99 | int i; |
| 100 | uint32_t offset; |
| 101 | static int first_time = 1; |
| 102 | tHogHeader header{}; |
| 103 | tHogFileEntry entry{}; |
| 104 | |
| 105 | // allocation library structure |
| 106 | std::shared_ptr<library> lib = std::make_shared<library>(); |
| 107 | |
| 108 | // resolve library name |
| 109 | std::filesystem::path resolve_dir = libname.parent_path(); |
| 110 | std::filesystem::path resolve_name = libname; |
| 111 | |
| 112 | if (!resolve_dir.empty()) { |
| 113 | resolve_name = libname.filename(); |
| 114 | } |
| 115 | |
| 116 | std::filesystem::path t_out = cf_FindRealFileNameCaseInsensitive(resolve_name, resolve_dir); |
| 117 | if (t_out.empty()) { |
| 118 | return 0; // CF_NO_FILE |
| 119 | } |
| 120 | // re-assemble |
| 121 | if (!resolve_dir.empty()) |
| 122 | lib->name = resolve_dir / t_out; |
| 123 | else |
| 124 | lib->name = t_out; |
| 125 | |
| 126 | fp = fopen(lib->name.u8string().c_str(), "rb"); |
| 127 | if (fp == nullptr) { |
| 128 | return 0; // CF_NO_FILE; |
| 129 | } |
| 130 | // check if this if first library opened |
| 131 | if (first_time) { |
| 132 | atexit(cf_Close); |
| 133 | first_time = 0; |
| 134 | } |
| 135 | // read HOG header |
| 136 | if (!ReadHogHeader(fp, &header)) { |
| 137 | fclose(fp); |
| 138 | return 0; // CF_BAD_LIB; |
| 139 | } |
| 140 | lib->nfiles = header.nfiles; |
| 141 | // allocate CFILE hog info. |
| 142 | lib->entries.reserve(lib->nfiles); |
| 143 | lib->next = Libraries; |
| 144 | Libraries = lib; |
| 145 | // set data offset of first file |
| 146 | offset = header.file_data_offset; |
| 147 | // Go to index start |
| 148 | fseek(fp, HOG_HDR_SIZE, SEEK_SET); |
| 149 | |
| 150 | // read in index table |
| 151 | for (i = 0; i < lib->nfiles; i++) { |
| 152 | if (!ReadHogEntry(fp, &entry)) { |
| 153 | fclose(fp); |
| 154 | return 0; |
| 155 | } |
| 156 | // Make sure files are in order |
| 157 | ASSERT((i == 0) || (stricmp(entry.name, lib->entries[i - 1]->name) >= 0)); |
| 158 | // Copy into table |
| 159 | std::unique_ptr<library_entry> lib_entry = std::make_unique<library_entry>(); |
| 160 | strcpy(lib_entry->name, entry.name); |
| 161 | lib_entry->flags = entry.flags; |
| 162 | lib_entry->length = entry.len; |
| 163 | lib_entry->offset = offset; |
| 164 | lib_entry->timestamp = entry.timestamp; |
| 165 | lib->entries.push_back(std::move(lib_entry)); |
| 166 | |
| 167 | offset += entry.len; |
| 168 | } |
| 169 | // assign a handle |
| 170 | lib->handle = ++lib_handle; |
| 171 | // Save the file pointer |
| 172 | lib->file = fp; |
| 173 | // Success. Return the handle |
| 174 | return lib->handle; |
| 175 | } |
| 176 | |
| 177 | /** |
| 178 | * Closes a library file. |
| 179 | * @param handle the handle returned by cf_OpenLibrary() |
| 180 | */ |
| 181 | void cf_CloseLibrary(int handle) { |
| 182 | std::shared_ptr<library> lib, prev; |
| 183 | for (lib = Libraries; lib; prev = lib, lib = lib->next) { |
| 184 | if (lib->handle == handle) { |
| 185 | if (prev) |
| 186 | prev->next = lib->next; |
| 187 | else |
| 188 | Libraries = lib->next; |
| 189 | if (lib->file) |
| 190 | fclose(lib->file); |
| 191 | return; // successful close |
| 192 | } |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | // Closes down the CFILE system, freeing up all data, etc. |
| 197 | void cf_Close() { |
| 198 | std::shared_ptr<library> next; |
| 199 | while (Libraries) { |
| 200 | next = Libraries->next; |
| 201 | Libraries = next; |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | bool cf_SetSearchPath(const std::filesystem::path &path, const std::vector<std::filesystem::path> &ext_list) { |
| 206 | // Don't add non-existing path into search paths |
| 207 | if (!std::filesystem::is_directory(path)) |
| 208 | return false; |
| 209 | // Get & store full path |
| 210 | paths.insert_or_assign(std::filesystem::absolute(path), !ext_list.empty()); |
| 211 | // Set extensions for this path |
| 212 | if (!ext_list.empty()) { |
| 213 | for (auto const &ext : ext_list) { |
| 214 | if (!ext.empty()) { |
| 215 | extensions.insert_or_assign(ext, path); |
| 216 | } |
| 217 | } |
| 218 | } |
| 219 | return true; |
| 220 | } |
| 221 | |
| 222 | /** |
| 223 | * Removes all search paths that have been added by cf_SetSearchPath |
| 224 | */ |
| 225 | void cf_ClearAllSearchPaths() { |
| 226 | paths.clear(); |
| 227 | extensions.clear(); |
| 228 | } |
| 229 | |
| 230 | /** |
| 231 | * Opens a file for reading in a library, given the library id |
| 232 | * @param filename |
| 233 | * @param libhandle |
| 234 | * @return |
| 235 | */ |
| 236 | CFILE *cf_OpenFileInLibrary(const std::filesystem::path &filename, int libhandle) { |
| 237 | if (libhandle <= 0) |
| 238 | return nullptr; |
| 239 | |
| 240 | std::shared_ptr<library> lib = Libraries; |
| 241 | |
| 242 | // find the library that we want to use |
| 243 | while (lib) { |
| 244 | if (lib->handle == libhandle) |
| 245 | break; |
| 246 | lib = lib->next; |
| 247 | } |
| 248 | |
| 249 | if (nullptr == lib) { |
| 250 | // couldn't find the library handle |
| 251 | return nullptr; |
| 252 | } |
| 253 | |
| 254 | // now do a binary search for the file entry |
| 255 | int i, first = 0, last = lib->nfiles - 1, c; |
| 256 | bool found = false; |
| 257 | |
| 258 | do { |
| 259 | i = (first + last) / 2; |
| 260 | c = stricmp(filename.u8string().c_str(), lib->entries[i]->name); // compare to current |
| 261 | if (c == 0) { |
| 262 | found = true; |
| 263 | break; |
| 264 | } |
| 265 | if (first >= last) // exhausted search |
| 266 | break; |
| 267 | if (c > 0) // search key after check key |
| 268 | first = i + 1; |
| 269 | else // search key before check key |
| 270 | last = i - 1; |
| 271 | } while (true); |
| 272 | |
| 273 | if (!found) |
| 274 | return nullptr; // file not in library |
| 275 | |
| 276 | // open the file for reading |
| 277 | FILE *fp; |
| 278 | int r; |
| 279 | // See if there's an available FILE |
| 280 | if (lib->file) { |
| 281 | fp = lib->file; |
| 282 | lib->file = nullptr; |
| 283 | } else { |
| 284 | fp = fopen(lib->name.u8string().c_str(), "rb"); |
| 285 | if (!fp) { |
| 286 | mprintf(1, "Error opening library <%s> when opening file <%s>; errno=%d.", |
| 287 | lib->name.u8string().c_str(), filename.u8string().c_str(), errno); |
| 288 | Int3(); |
| 289 | return nullptr; |
| 290 | } |
| 291 | } |
| 292 | CFILE *cfile = (CFILE *)mem_malloc(sizeof(*cfile)); |
| 293 | if (!cfile) |
| 294 | Error("Out of memory in cf_OpenFileInLibrary()"); |
| 295 | cfile->name = lib->entries[i]->name; |
| 296 | cfile->file = fp; |
| 297 | cfile->lib_handle = lib->handle; |
| 298 | cfile->size = lib->entries[i]->length; |
| 299 | cfile->lib_offset = lib->entries[i]->offset; |
| 300 | cfile->position = 0; |
| 301 | cfile->flags = 0; |
| 302 | r = fseek(fp, cfile->lib_offset, SEEK_SET); |
| 303 | ASSERT(r == 0); |
| 304 | return cfile; |
| 305 | } |
| 306 | |
| 307 | // searches through the open HOG files, and opens a file if it finds it in any of the libs |
| 308 | CFILE *open_file_in_lib(const char *filename) { |
| 309 | CFILE *cfile; |
| 310 | std::shared_ptr<library> lib = Libraries; |
| 311 | while (lib) { |
| 312 | int i; |
| 313 | // Do binary search for the file |
| 314 | int first = 0, last = lib->nfiles - 1, c, found = 0; |
| 315 | do { |
| 316 | i = (first + last) / 2; |
| 317 | c = stricmp(filename, lib->entries[i]->name); // compare to current |
| 318 | if (c == 0) { // found it |
| 319 | found = 1; |
| 320 | break; |
| 321 | } |
| 322 | if (first >= last) // exhausted search |
| 323 | break; |
| 324 | if (c > 0) // search key after check key |
| 325 | first = i + 1; |
| 326 | else // search key before check key |
| 327 | last = i - 1; |
| 328 | } while (true); |
| 329 | if (found) { |
| 330 | FILE *fp; |
| 331 | int r; |
| 332 | // See if there's an available FILE |
| 333 | if (lib->file) { |
| 334 | fp = lib->file; |
| 335 | lib->file = nullptr; |
| 336 | } else { |
| 337 | fp = fopen(lib->name.u8string().c_str(), "rb"); |
| 338 | if (!fp) { |
| 339 | mprintf(1, "Error opening library <%s> when opening file <%s>; errno=%d.", lib->name.u8string().c_str(), |
| 340 | filename, errno); |
| 341 | Int3(); |
| 342 | return nullptr; |
| 343 | } |
| 344 | } |
| 345 | cfile = (CFILE *)mem_malloc(sizeof(*cfile)); |
| 346 | if (!cfile) |
| 347 | Error("Out of memory in open_file_in_lib()"); |
| 348 | cfile->name = lib->entries[i]->name; |
| 349 | cfile->file = fp; |
| 350 | cfile->lib_handle = lib->handle; |
| 351 | cfile->size = lib->entries[i]->length; |
| 352 | cfile->lib_offset = lib->entries[i]->offset; |
| 353 | cfile->position = 0; |
| 354 | cfile->flags = 0; |
| 355 | r = fseek(fp, cfile->lib_offset, SEEK_SET); |
| 356 | ASSERT(r == 0); |
| 357 | return cfile; |
| 358 | } |
| 359 | lib = lib->next; |
| 360 | } |
| 361 | return nullptr; |
| 362 | } |
| 363 | |
| 364 | std::filesystem::path cf_FindRealFileNameCaseInsensitive(const std::filesystem::path &fname, |
| 365 | const std::filesystem::path &directory) { |
| 366 | // Dumb check, maybe there already all ok? |
| 367 | if (exists((directory / fname))) { |
| 368 | return fname.filename(); |
| 369 | } |
| 370 | |
| 371 | std::filesystem::path result, search_path, search_file; |
| 372 | |
| 373 | search_path = directory / fname.parent_path(); |
| 374 | search_file = fname.filename(); |
| 375 | |
| 376 | // If directory does not exist, nothing to search. |
| 377 | if (!std::filesystem::is_directory(search_path) || search_file.empty()) { |
| 378 | return {}; |
| 379 | } |
| 380 | |
| 381 | |
| 382 | // Search component in search_path |
| 383 | auto const &it = std::filesystem::directory_iterator(search_path); |
| 384 | |
| 385 | auto found = std::find_if(it, end(it), [&search_file, &search_path, &result](const auto& dir_entry) { |
| 386 | return stricmp(dir_entry.path().filename().u8string().c_str(), search_file.u8string().c_str()) == 0; |
| 387 | }); |
| 388 | |
| 389 | if (found != end(it)) { |
| 390 | // Match, append to result |
| 391 | result = found->path(); |
| 392 | search_path = result; |
| 393 | } else { |
| 394 | // Component not found, mission failed |
| 395 | return {}; |
| 396 | } |
| 397 | |
| 398 | return result.filename(); |
| 399 | } |
| 400 | |
| 401 | // look for the file in the specified directory |
| 402 | static CFILE *open_file_in_directory(const std::filesystem::path &filename, const char *mode, |
| 403 | const std::filesystem::path &directory); |
| 404 | |
| 405 | // look for the file in the specified directory |
| 406 | CFILE *open_file_in_directory(const std::filesystem::path &filename, const char *mode, |
| 407 | const std::filesystem::path &directory) { |
| 408 | FILE *fp; |
| 409 | CFILE *cfile; |
| 410 | std::filesystem::path using_filename; |
| 411 | char tmode[3] = "rb"; |
| 412 | if (std::filesystem::is_directory(directory)) { |
| 413 | // Make a full path |
| 414 | using_filename = directory / filename; |
| 415 | } else { |
| 416 | // no directory specified, so just use filename passed |
| 417 | using_filename = filename; |
| 418 | } |
| 419 | |
| 420 | // set read or write mode |
| 421 | tmode[0] = mode[0]; |
| 422 | // if mode is "w", then open in text or binary as requested. If "r", always open in "rb" |
| 423 | tmode[1] = (mode[0] == 'w') ? mode[1] : 'b'; |
| 424 | // try to open file |
| 425 | fp = fopen(using_filename.u8string().c_str(), tmode); |
| 426 | |
| 427 | if (!fp) { |
| 428 | #if defined(POSIX) |
| 429 | // If we tried to open file for reading, assume there maybe case-sensitive files |
| 430 | if (tmode[0] == 'r') { |
| 431 | // Try different cases of the filename |
| 432 | using_filename = cf_FindRealFileNameCaseInsensitive(filename, directory); |
| 433 | if (using_filename.empty()) { |
| 434 | // just give up |
| 435 | return nullptr; |
| 436 | } |
| 437 | |
| 438 | if (std::filesystem::is_directory(directory)) { |
| 439 | // Make a full path |
| 440 | using_filename = directory / using_filename; |
| 441 | } |
| 442 | |
| 443 | fp = fopen(using_filename.u8string().c_str(), tmode); |
| 444 | if (!fp) { |
| 445 | // no dice |
| 446 | return nullptr; |
| 447 | } |
| 448 | } else { |
| 449 | // Error on writing file |
| 450 | return nullptr; |
| 451 | } |
| 452 | #else |
| 453 | // We on incase-sensitive filesystem, no file means no file. |
| 454 | return nullptr; |
| 455 | #endif |
| 456 | } else { |
| 457 | using_filename = filename; |
| 458 | } |
| 459 | |
| 460 | // found the file, open it |
| 461 | cfile = (CFILE *)mem_malloc(sizeof(*cfile)); |
| 462 | if (!cfile) |
| 463 | Error("Out of memory in open_file_in_directory()"); |
| 464 | cfile->name = (char *)mem_malloc(sizeof(char) * (strlen(using_filename.u8string().c_str()) + 1)); |
| 465 | if (!cfile->name) |
| 466 | Error("Out of memory in open_file_in_directory()"); |
| 467 | strcpy(cfile->name, using_filename.u8string().c_str()); |
| 468 | cfile->file = fp; |
| 469 | cfile->lib_handle = -1; |
| 470 | cfile->size = ddio_GetFileLength(fp); |
| 471 | cfile->lib_offset = 0; // 0 means on disk, not in HOG |
| 472 | cfile->position = 0; |
| 473 | cfile->flags = 0; |
| 474 | return cfile; |
| 475 | } |
| 476 | |
| 477 | // Opens a file for reading or writing |
| 478 | // If a path is specified, will try to open the file only in that path. |
| 479 | // If no path is specified, will look through search directories and library files. |
| 480 | // Parameters: filename - the name if the file, with or without a path |
| 481 | // mode - the standard C mode string |
| 482 | // Returns: the CFile handle, or NULL if file not opened |
| 483 | CFILE *cfopen(const std::filesystem::path &filename, const char *mode) { |
| 484 | CFILE *cfile; |
| 485 | |
| 486 | // Check for valid mode |
| 487 | ASSERT((mode[0] == 'r') || (mode[0] == 'w')); |
| 488 | ASSERT((mode[1] == 'b') || (mode[1] == 't')); |
| 489 | // get the parts of the pathname |
| 490 | std::filesystem::path path = filename.parent_path(); |
| 491 | std::filesystem::path fname = filename.stem(); |
| 492 | std::filesystem::path ext = filename.extension(); |
| 493 | |
| 494 | // if there is a path specified, use it instead of the libraries, search dirs, etc. |
| 495 | // if the file is writable, just open it, instead of looking in libs, etc. |
| 496 | if (!path.empty() || (mode[0] == 'w')) { |
| 497 | // use path specified with file |
| 498 | cfile = open_file_in_directory(filename, mode, std::filesystem::path()); |
| 499 | goto got_file; // don't look in libs, etc. |
| 500 | } |
| 501 | |
| 502 | // First look in the directories for this file's extension |
| 503 | for (auto const &entry : extensions) { |
| 504 | if (!strnicmp(entry.first.u8string().c_str(), ext.u8string().c_str(), _MAX_EXT)) { |
| 505 | // found ext |
| 506 | cfile = open_file_in_directory(filename, mode, entry.second); |
| 507 | if (cfile) { |
| 508 | goto got_file; |
| 509 | } |
| 510 | } |
| 511 | } |
| 512 | |
| 513 | // Next look in the general directories |
| 514 | for (auto const &entry : paths) { |
| 515 | if (!entry.second) { |
| 516 | cfile = open_file_in_directory(filename, mode, entry.first); |
| 517 | if (cfile) |
| 518 | goto got_file; |
| 519 | } |
| 520 | } |
| 521 | // Lastly, try the hog files |
| 522 | cfile = open_file_in_lib(filename.u8string().c_str()); |
| 523 | got_file:; |
| 524 | if (cfile) { |
| 525 | if (mode[0] == 'w') |
| 526 | cfile->flags |= CFF_WRITING; |
| 527 | if (mode[1] == 't') |
| 528 | cfile->flags |= CFF_TEXT; |
| 529 | } |
| 530 | return cfile; |
| 531 | } |
| 532 | |
| 533 | // Returns the length of the specified file |
| 534 | // Parameters: cfp - the file pointer returned by cfopen() |
| 535 | uint32_t cfilelength(CFILE *cfp) { return cfp->size; } |
| 536 | |
| 537 | // Closes an open CFILE. |
| 538 | // Parameters: cfile - the file pointer returned by cfopen() |
| 539 | void cfclose(CFILE *cfp) { |
| 540 | // Either give the file back to the library, or close it |
| 541 | if (cfp->lib_handle != -1) { |
| 542 | std::shared_ptr<library> lib; |
| 543 | for (lib = Libraries; lib; lib = lib->next) { |
| 544 | if (lib->handle == cfp->lib_handle) { // found the library |
| 545 | // if library doesn't already have a file, give it this one |
| 546 | if (lib->file == nullptr) { |
| 547 | lib->file = cfp->file; |
| 548 | cfp->file = nullptr; |
| 549 | } |
| 550 | break; |
| 551 | } |
| 552 | } |
| 553 | } |
| 554 | // If the file handle wasn't given back to library, close the file |
| 555 | if (cfp->file) |
| 556 | fclose(cfp->file); |
| 557 | // free the name, if allocated |
| 558 | if (!cfp->lib_offset) |
| 559 | mem_free(cfp->name); |
| 560 | // free the cfile struct |
| 561 | mem_free(cfp); |
| 562 | } |
| 563 | |
| 564 | // Just like stdio fgetc(), except works on a CFILE |
| 565 | // Returns a char or EOF |
| 566 | int cfgetc(CFILE *cfp) { |
| 567 | int c; |
| 568 | static uint8_t ch[3] = "\0\0"; |
| 569 | if (cfp->position >= cfp->size) |
| 570 | return EOF; |
| 571 | |
| 572 | fread(ch, sizeof(char), 1, cfp->file); |
| 573 | c = ch[0]; |
| 574 | // c = getc( cfp->file ); |
| 575 | if (cfeof(cfp)) |
| 576 | c = EOF; |
| 577 | if (c != EOF) { |
| 578 | cfp->position++; |
| 579 | // do special newline handling for text files: |
| 580 | // if CR or LF by itself, return as newline |
| 581 | // if CR/LF pair, return as newline |
| 582 | if (cfp->flags & CFF_TEXT) { |
| 583 | if (c == 10) // return LF as newline |
| 584 | c = '\n'; |
| 585 | else if (c == 13) { // check for CR/LF pair |
| 586 | fread(ch, sizeof(char), 1, cfp->file); |
| 587 | int cc = ch[0]; // getc(cfp->file); |
| 588 | // if (cc != EOF) { |
| 589 | if (!cfeof(cfp)) { |
| 590 | if (cc == 10) // line feed? |
| 591 | cfp->position++; //..yes, so swallow it |
| 592 | else { |
| 593 | // ungetc(cc,cfp->file); //..no, so put it back |
| 594 | fseek(cfp->file, -1, SEEK_CUR); |
| 595 | } |
| 596 | } |
| 597 | c = '\n'; // return CR or CR/LF pair as newline |
| 598 | } |
| 599 | } |
| 600 | } |
| 601 | return c; |
| 602 | } |
| 603 | // Just like stdio fseek(), except works on a CFILE |
| 604 | int cfseek(CFILE *cfp, long offset, int where) { |
| 605 | int c; |
| 606 | long goal_position; |
| 607 | switch (where) { |
| 608 | case SEEK_SET: |
| 609 | goal_position = offset; |
| 610 | break; |
| 611 | case SEEK_CUR: |
| 612 | goal_position = cfp->position + offset; |
| 613 | break; |
| 614 | case SEEK_END: |
| 615 | goal_position = cfp->size + offset; |
| 616 | break; |
| 617 | default: |
| 618 | return 1; |
| 619 | } |
| 620 | c = fseek(cfp->file, cfp->lib_offset + goal_position, SEEK_SET); |
| 621 | cfp->position = ftell(cfp->file) - cfp->lib_offset; |
| 622 | return c; |
| 623 | } |
| 624 | |
| 625 | // Just like stdio ftell(), except works on a CFILE |
| 626 | long cftell(CFILE *cfp) { return cfp->position; } |
| 627 | |
| 628 | // Returns true if at EOF |
| 629 | int cfeof(CFILE *cfp) { return (cfp->position >= cfp->size); } |
| 630 | |
| 631 | // Tells if the file exists |
| 632 | // Returns non-zero if file exists. Also tells if the file is on disk |
| 633 | // or in a hog - See return values in cfile.h |
| 634 | int cfexist(const std::filesystem::path &filename) { |
| 635 | CFILE *cfp; |
| 636 | int ret; |
| 637 | |
| 638 | cfp = cfopen(filename, "rb"); |
| 639 | if (!cfp) { // Didn't get file. Why? |
| 640 | if (errno == EACCES) // File exists, but couldn't open it |
| 641 | return CFES_ON_DISK; // so say it exists on the disk |
| 642 | |
| 643 | return CFES_NOT_FOUND; // Say we didn't find the file |
| 644 | } |
| 645 | ret = cfp->lib_offset ? CFES_IN_LIBRARY : CFES_ON_DISK; |
| 646 | cfclose(cfp); |
| 647 | return ret; |
| 648 | } |
| 649 | // Reads the specified number of bytes from a file into the buffer |
| 650 | // DO NOT USE THIS TO READ STRUCTURES. This function is for byte |
| 651 | // data, such as a string or a bitmap of 8-bit pixels. |
| 652 | // Returns the number of bytes read. |
| 653 | // Throws an exception of type (cfile_error *) if the OS returns an error on read |
| 654 | int cf_ReadBytes(uint8_t *buf, int count, CFILE *cfp) { |
| 655 | int i; |
| 656 | const char *error_msg = eof_error; // default error |
| 657 | ASSERT(!(cfp->flags & CFF_TEXT)); |
| 658 | if (cfp->position + count <= cfp->size) { |
| 659 | i = fread(buf, 1, count, cfp->file); |
| 660 | if (i == count) { |
| 661 | cfp->position += i; |
| 662 | return i; |
| 663 | } |
| 664 | // if not EOF, then get the error message |
| 665 | if (!feof(cfp->file)) |
| 666 | error_msg = strerror(errno); |
| 667 | } |
| 668 | mprintf(1, "Error reading %d bytes from position %d of file <%s>; errno=%d.", count, cfp->position, cfp->name, errno); |
| 669 | return 0; |
| 670 | } |
| 671 | // The following functions read numeric vales from a CFILE. All values are |
| 672 | // stored in the file in Intel (little-endian) format. These functions |
| 673 | // will convert to big-endian if required. |
| 674 | // These funtions will exit the program with an error if the value |
| 675 | // cannot be read, so do not call these if you don't require the data |
| 676 | // to be present. |
| 677 | // Read and return an integer (32 bits) |
| 678 | // Throws an exception of type (cfile_error *) if the OS returns an error on read |
| 679 | int32_t cf_ReadInt(CFILE *cfp, bool little_endian) { |
| 680 | int32_t i; |
| 681 | cf_ReadBytes((uint8_t *)&i, sizeof(i), cfp); |
| 682 | return little_endian ? D3::convert_le(i) : D3::convert_be(i); |
| 683 | } |
| 684 | // Read and return a int16_t (16 bits) |
| 685 | // Throws an exception of type (cfile_error *) if the OS returns an error on read |
| 686 | int16_t cf_ReadShort(CFILE *cfp, bool little_endian) { |
| 687 | int16_t i; |
| 688 | cf_ReadBytes((uint8_t *)&i, sizeof(i), cfp); |
| 689 | return little_endian ? D3::convert_le(i) : D3::convert_be(i); |
| 690 | } |
| 691 | // Read and return a byte (8 bits) |
| 692 | // Throws an exception of type (cfile_error *) if the OS returns an error on read |
| 693 | int8_t cf_ReadByte(CFILE *cfp) { |
| 694 | int8_t i; |
| 695 | cf_ReadBytes((uint8_t *)&i, sizeof(i), cfp); |
| 696 | return i; |
| 697 | } |
| 698 | // Read and return a float (32 bits) |
| 699 | // Throws an exception of type (cfile_error *) if the OS returns an error on read |
| 700 | float cf_ReadFloat(CFILE *cfp) { |
| 701 | float f; |
| 702 | cf_ReadBytes((uint8_t *)&f, sizeof(f), cfp); |
| 703 | return INTEL_FLOAT(f); |
| 704 | } |
| 705 | // Read and return a double (64 bits) |
| 706 | // Throws an exception of type (cfile_error *) if the OS returns an error on read |
| 707 | double cf_ReadDouble(CFILE *cfp) { |
| 708 | double f; |
| 709 | cf_ReadBytes((uint8_t *)&f, sizeof(f), cfp); |
| 710 | return D3::convert_le<double>(f); |
| 711 | } |
| 712 | // Reads a string from a CFILE. If the file is type binary, this |
| 713 | // function reads until a NULL or EOF is found. If the file is text, |
| 714 | // the function reads until a newline or EOF is found. The string is always |
| 715 | // written to the destination buffer null-terminated, without the newline. |
| 716 | // Parameters: buf - where the string is written |
| 717 | // n - the maximum string length, including the terminating 0 |
| 718 | // cfp - the CFILE pointer |
| 719 | // Returns the number of bytes in the string, before the terminator |
| 720 | // Does not generate an exception on EOF |
| 721 | int cf_ReadString(char *buf, size_t n, CFILE *cfp) { |
| 722 | int c; |
| 723 | int count; |
| 724 | char *bp; |
| 725 | if (n == 0) |
| 726 | return -1; |
| 727 | bp = buf; |
| 728 | for (count = 0;; count++) { |
| 729 | c = cfgetc(cfp); |
| 730 | if (c == EOF) { |
| 731 | if (!cfeof(cfp)) // not actually at EOF, so must be error |
| 732 | ThrowCFileError(CFE_READING, cfp, strerror(errno)); |
| 733 | break; |
| 734 | } |
| 735 | |
| 736 | if ((!(cfp->flags & CFF_TEXT) && (c == 0)) || ((cfp->flags & CFF_TEXT) && (c == '\n'))) |
| 737 | break; // end-of-string |
| 738 | if (count < n - 1) // store char if room in buffer |
| 739 | *bp++ = c; |
| 740 | } |
| 741 | *bp = 0; // write terminator |
| 742 | return count; |
| 743 | } |
| 744 | // Writes the specified number of bytes from a file into the buffer |
| 745 | // DO NOT USE THIS TO WRITE STRUCTURES. This function is for byte |
| 746 | // data, such as a string or a bitmap of 8-bit pixels. |
| 747 | // Returns the number of bytes written. |
| 748 | // Throws an exception of type (cfile_error *) if the OS returns an error on write |
| 749 | int cf_WriteBytes(const uint8_t *buf, int count, CFILE *cfp) { |
| 750 | int i; |
| 751 | if (!(cfp->flags & CFF_WRITING)) |
| 752 | return 0; |
| 753 | ASSERT(count > 0); |
| 754 | i = fwrite(buf, 1, count, cfp->file); |
| 755 | cfp->position += i; |
| 756 | if (i != count) |
| 757 | ThrowCFileError(CFE_WRITING, cfp, strerror(errno)); |
| 758 | return i; |
| 759 | } |
| 760 | // Writes a null-terminated string to a file. If the file is type binary, |
| 761 | // the string is terminated in the file with a null. If the file is type |
| 762 | // text, the string is terminated with a newline. |
| 763 | // Parameters: buf - pointer to the string |
| 764 | // cfp = the CFILE pointer |
| 765 | // Returns the number of bytes written |
| 766 | // Throws an exception of type (cfile_error *) if the OS returns an error on write |
| 767 | int cf_WriteString(CFILE *cfp, const char *buf) { |
| 768 | int len; |
| 769 | len = strlen(buf); |
| 770 | if (len != 0) // write string |
| 771 | cf_WriteBytes((uint8_t *)buf, len, cfp); |
| 772 | // Terminate with newline (text file) or NULL (binary file) |
| 773 | cf_WriteByte(cfp, (cfp->flags & CFF_TEXT) ? '\n' : 0); |
| 774 | return len + 1; |
| 775 | } |
| 776 | |
| 777 | // Just like stdio fprintf(), except works on a CFILE |
| 778 | int cfprintf(CFILE *cfp, const char *format, ...) { |
| 779 | va_list args; |
| 780 | int count; |
| 781 | va_start(args, format); |
| 782 | count = vfprintf(cfp->file, format, args); |
| 783 | va_end(args); |
| 784 | cfp->position += count + 1; // count doesn't include terminator |
| 785 | return count; |
| 786 | } |
| 787 | |
| 788 | // The following functions write numeric vales to a CFILE. All values are |
| 789 | // stored to the file in Intel (little-endian) format. |
| 790 | // All these throw an exception if there's an error on write. |
| 791 | // Write an integer (32 bits) |
| 792 | // Throws an exception of type (cfile_error *) if the OS returns an error on write |
| 793 | void cf_WriteInt(CFILE *cfp, int32_t i) { |
| 794 | int t = INTEL_INT(i); |
| 795 | cf_WriteBytes((uint8_t *)&t, sizeof(t), cfp); |
| 796 | } |
| 797 | |
| 798 | // Write a int16_t (16 bits) |
| 799 | // Throws an exception of type (cfile_error *) if the OS returns an error on write |
| 800 | void cf_WriteShort(CFILE *cfp, int16_t s) { |
| 801 | int16_t t = INTEL_SHORT(s); |
| 802 | cf_WriteBytes((uint8_t *)&t, sizeof(t), cfp); |
| 803 | } |
| 804 | |
| 805 | // Write a byte (8 bits). |
| 806 | // Throws an exception of type (cfile_error *) if the OS returns an error on write |
| 807 | void cf_WriteByte(CFILE *cfp, int8_t b) { |
| 808 | if (fputc(b, cfp->file) == EOF) |
| 809 | ThrowCFileError(CFE_WRITING, cfp, strerror(errno)); |
| 810 | cfp->position++; |
| 811 | // If text file & writing newline, increment again for LF |
| 812 | if ((cfp->flags & CFF_TEXT) && (b == '\n')) // check for text mode newline |
| 813 | cfp->position++; |
| 814 | } |
| 815 | |
| 816 | // Write a float (32 bits) |
| 817 | // Throws an exception of type (cfile_error *) if the OS returns an error on write |
| 818 | void cf_WriteFloat(CFILE *cfp, float f) { |
| 819 | float t = INTEL_FLOAT(f); |
| 820 | cf_WriteBytes((uint8_t *)&t, sizeof(t), cfp); |
| 821 | } |
| 822 | |
| 823 | // Write a double (64 bits) |
| 824 | // Throws an exception of type (cfile_error *) if the OS returns an error on write |
| 825 | void cf_WriteDouble(CFILE *cfp, double d) { |
| 826 | auto t = D3::convert_le<double>(d); |
| 827 | cf_WriteBytes((uint8_t *)&t, sizeof(t), cfp); |
| 828 | } |
| 829 | |
| 830 | // Copies a file. Returns TRUE if copied ok. Returns FALSE if error opening either file. |
| 831 | // Throws an exception of type (cfile_error *) if the OS returns an error on read or write |
| 832 | bool cf_CopyFile(const std::filesystem::path &dest, const std::filesystem::path &src, int copytime) { |
| 833 | CFILE *infile, *outfile; |
| 834 | if (!stricmp(dest.u8string().c_str(), src.u8string().c_str())) |
| 835 | return true; // don't copy files if they are the same |
| 836 | infile = (CFILE *)cfopen(src, "rb"); |
| 837 | if (!infile) |
| 838 | return false; |
| 839 | outfile = (CFILE *)cfopen(dest, "wb"); |
| 840 | if (!outfile) { |
| 841 | cfclose(infile); |
| 842 | return false; |
| 843 | } |
| 844 | int progress = 0; |
| 845 | int readcount = 0; |
| 846 | #define COPY_CHUNK_SIZE 5000 |
| 847 | uint8_t copybuf[COPY_CHUNK_SIZE]; |
| 848 | while (!cfeof(infile)) { |
| 849 | // uint8_t c; |
| 850 | |
| 851 | if (progress + COPY_CHUNK_SIZE <= infile->size) { |
| 852 | readcount = COPY_CHUNK_SIZE; |
| 853 | } else { |
| 854 | readcount = infile->size - progress; |
| 855 | } |
| 856 | cf_ReadBytes(copybuf, readcount, infile); |
| 857 | cf_WriteBytes(copybuf, readcount, outfile); |
| 858 | progress += readcount; |
| 859 | // c=cf_ReadByte (infile); |
| 860 | // cf_WriteByte (outfile,c); |
| 861 | } |
| 862 | cfclose(infile); |
| 863 | cfclose(outfile); |
| 864 | if (!infile->lib_offset && copytime) { |
| 865 | cf_CopyFileTime(dest, src); |
| 866 | } |
| 867 | return true; |
| 868 | } |
| 869 | |
| 870 | // Checks to see if two files are different. |
| 871 | // Returns TRUE if the files are different, or FALSE if they are the same. |
| 872 | bool cf_Diff(const std::filesystem::path &a, const std::filesystem::path &b) { return (ddio_FileDiff(a, b)); } |
| 873 | |
| 874 | // Copies the file time from one file to another |
| 875 | void cf_CopyFileTime(const std::filesystem::path &dest, const std::filesystem::path &src) { |
| 876 | ddio_CopyFileTime(dest, src); |
| 877 | } |
| 878 | |
| 879 | // Changes a files attributes (ie read/write only) |
| 880 | void cf_ChangeFileAttributes(const char *name, int attr) { |
| 881 | if (_chmod(name, attr) == -1) |
| 882 | Int3(); // Get Jason or Matt, file not found! |
| 883 | } |
| 884 | |
| 885 | // rewinds cfile position |
| 886 | void cf_Rewind(CFILE *fp) { |
| 887 | if (fp->lib_offset) { |
| 888 | int r = fseek(fp->file, fp->lib_offset, SEEK_SET); |
| 889 | ASSERT(r == 0); |
| 890 | } else { |
| 891 | rewind(fp->file); |
| 892 | } |
| 893 | fp->position = 0; |
| 894 | } |
| 895 | |
| 896 | // Calculates a 32-bit CRC for the specified file. a return code of -1 means file note found |
| 897 | #define CRC32_POLYNOMIAL 0xEDB88320L |
| 898 | #define CRC_BUFFER_SIZE 5000 |
| 899 | |
| 900 | uint32_t cf_CalculateFileCRC(CFILE *infile) { |
| 901 | int i, j; |
| 902 | uint8_t crcbuf[CRC_BUFFER_SIZE]; |
| 903 | static bool Cfile_crc_calculated = false; |
| 904 | static uint32_t CRCTable[256]; |
| 905 | uint32_t crc; |
| 906 | uint32_t temp1; |
| 907 | uint32_t temp2; |
| 908 | uint32_t readlen; |
| 909 | |
| 910 | // Only make the lookup table once |
| 911 | if (!Cfile_crc_calculated) { |
| 912 | Cfile_crc_calculated = true; |
| 913 | |
| 914 | for (i = 0; i <= 255; i++) { |
| 915 | crc = i; |
| 916 | for (j = 8; j > 0; j--) { |
| 917 | if (crc & 1) |
| 918 | crc = (crc >> 1) ^ CRC32_POLYNOMIAL; |
| 919 | else |
| 920 | crc >>= 1; |
| 921 | } |
| 922 | CRCTable[i] = crc; |
| 923 | } |
| 924 | } |
| 925 | |
| 926 | crc = 0xffffffffl; |
| 927 | while (!cfeof(infile)) { |
| 928 | if ((infile->size - infile->position) < CRC_BUFFER_SIZE) |
| 929 | readlen = infile->size - infile->position; |
| 930 | else |
| 931 | readlen = CRC_BUFFER_SIZE; |
| 932 | if (!cf_ReadBytes(crcbuf, readlen, infile)) { |
| 933 | // Doh, error time! |
| 934 | Int3(); |
| 935 | return 0xFFFFFFFF; |
| 936 | } |
| 937 | for (uint32_t a = 0; a < readlen; a++) { |
| 938 | temp1 = (crc >> 8) & 0x00FFFFFFL; |
| 939 | temp2 = CRCTable[((int)crc ^ crcbuf[a]) & 0xff]; |
| 940 | crc = temp1 ^ temp2; |
| 941 | } |
| 942 | } |
| 943 | |
| 944 | return crc ^ 0xffffffffl; |
| 945 | } |
| 946 | |
| 947 | uint32_t cf_GetfileCRC(const std::filesystem::path &src) { |
| 948 | CFILE *infile = cfopen(src, "rb"); |
| 949 | if (!infile) |
| 950 | return 0xFFFFFFFF; |
| 951 | |
| 952 | uint32_t crc = cf_CalculateFileCRC(infile); |
| 953 | cfclose(infile); |
| 954 | |
| 955 | return crc; |
| 956 | } |
| 957 | |
| 958 | char cfile_search_wildcard[256]; |
| 959 | std::shared_ptr<library> cfile_search_library; |
| 960 | int cfile_search_curr_index = 0; |
| 961 | bool cfile_search_ispattern = false; |
| 962 | // the following cf_LibraryFind function are similar to the ddio_Find functions as they look |
| 963 | // for files that match the wildcard passed in, however, this is to be used for hog files. |
| 964 | bool cf_LibraryFindFirst(int handle, const char *wildcard, char *buffer) { |
| 965 | ASSERT(wildcard); |
| 966 | ASSERT(buffer); |
| 967 | if (!wildcard || !buffer) |
| 968 | return false; |
| 969 | *buffer = '\0'; |
| 970 | if (cfile_search_library) |
| 971 | cf_LibraryFindClose(); |
| 972 | // find the library |
| 973 | cfile_search_library = Libraries; |
| 974 | while (cfile_search_library && cfile_search_library->handle != handle) { |
| 975 | cfile_search_library = cfile_search_library->next; |
| 976 | } |
| 977 | if (!cfile_search_library) |
| 978 | return false; |
| 979 | // now find the first matching file |
| 980 | strncpy(cfile_search_wildcard, wildcard, 255); |
| 981 | cfile_search_wildcard[255] = '\0'; |
| 982 | cfile_search_ispattern = (bool)(PSGlobHasPattern(cfile_search_wildcard) != 0); |
| 983 | cfile_search_curr_index = 0; |
| 984 | |
| 985 | while (cfile_search_curr_index < cfile_search_library->nfiles) { |
| 986 | if (cfile_search_ispattern) { |
| 987 | if (PSGlobMatch(cfile_search_wildcard, cfile_search_library->entries[cfile_search_curr_index]->name, 0, 0)) { |
| 988 | // it's a match |
| 989 | strcpy(buffer, cfile_search_library->entries[cfile_search_curr_index]->name); |
| 990 | cfile_search_curr_index++; |
| 991 | return true; |
| 992 | } |
| 993 | } else { |
| 994 | if (!stricmp(cfile_search_library->entries[cfile_search_curr_index]->name, cfile_search_wildcard)) { |
| 995 | strcpy(buffer, cfile_search_library->entries[cfile_search_curr_index]->name); |
| 996 | cfile_search_curr_index++; |
| 997 | return true; |
| 998 | } |
| 999 | } |
| 1000 | cfile_search_curr_index++; |
| 1001 | } |
| 1002 | // we didn't find a match |
| 1003 | return false; |
| 1004 | } |
| 1005 | |
| 1006 | bool cf_LibraryFindNext(char *buffer) { |
| 1007 | while (cfile_search_curr_index < cfile_search_library->nfiles) { |
| 1008 | if (cfile_search_ispattern) { |
| 1009 | if (PSGlobMatch(cfile_search_wildcard, cfile_search_library->entries[cfile_search_curr_index]->name, 0, 0)) { |
| 1010 | // it's a match |
| 1011 | strcpy(buffer, cfile_search_library->entries[cfile_search_curr_index]->name); |
| 1012 | cfile_search_curr_index++; |
| 1013 | return true; |
| 1014 | } |
| 1015 | } else { |
| 1016 | if (!stricmp(cfile_search_library->entries[cfile_search_curr_index]->name, cfile_search_wildcard)) { |
| 1017 | strcpy(buffer, cfile_search_library->entries[cfile_search_curr_index]->name); |
| 1018 | cfile_search_curr_index++; |
| 1019 | return true; |
| 1020 | } |
| 1021 | } |
| 1022 | cfile_search_curr_index++; |
| 1023 | } |
| 1024 | return false; |
| 1025 | } |
| 1026 | |
| 1027 | void cf_LibraryFindClose() { |
| 1028 | cfile_search_library = nullptr; |
| 1029 | cfile_search_curr_index = 0; |
| 1030 | cfile_search_ispattern = false; |
| 1031 | } |
| 1032 | |
| 1033 | bool cf_IsFileInHog(const std::filesystem::path &filename, const std::filesystem::path &hogname) { |
| 1034 | std::shared_ptr<library> lib = Libraries; |
| 1035 | |
| 1036 | while (lib) { |
| 1037 | if (stricmp(lib->name.u8string().c_str(), hogname.u8string().c_str()) == 0) { |
| 1038 | // Now look for filename |
| 1039 | CFILE *cf; |
| 1040 | cf = cf_OpenFileInLibrary(filename, lib->handle); |
| 1041 | if (cf) { |
| 1042 | cfclose(cf); |
| 1043 | return true; |
| 1044 | } |
| 1045 | } |
| 1046 | lib = lib->next; |
| 1047 | } |
| 1048 | |
| 1049 | return false; |
| 1050 | } |