Debian Codegraph @

engine/stratagus/iolib.cpp

raw
1 // ____ _ __
2 // / __ )____ _____ | | / /___ ___________
3 // / __ / __ \/ ___/ | | /| / / __ `/ ___/ ___/
4 // / /_/ / /_/ (__ ) | |/ |/ / /_/ / / (__ )
5 // /_____/\____/____/ |__/|__/\__,_/_/ /____/
6 //
7 // A futuristic real-time strategy game.
8 // This file is part of Bos Wars.
9 //
10 /**@name iolib.cpp - Compression-IO helper functions. */
11 //
12 // (c) Copyright 2000-2007 by Andreas Arens, Lutz Sammer, and Jimmy Salmon
13 //
14 // This program is free software; you can redistribute it and/or modify
15 // it under the terms of the GNU General Public License as published by
16 // the Free Software Foundation; only version 2 of the License.
17 //
18 // This program is distributed in the hope that it will be useful,
19 // but WITHOUT ANY WARRANTY; without even the implied warranty of
20 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 // GNU General Public License for more details.
22 //
23 // You should have received a copy of the GNU General Public License
24 // along with this program; if not, write to the Free Software
25 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
26 // 02111-1307, USA.
27 //
28
29 //@{
30
31 /*----------------------------------------------------------------------------
32 -- Includes
33 ----------------------------------------------------------------------------*/
34
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <stdarg.h>
38
39 #ifndef _MSC_VER
40 #include <fcntl.h>
41 #endif
42
43 #include "stratagus.h"
44 #include "iocompat.h"
45 #include "iolib.h"
46
47 CFile::CFile()
48 {
49 cl_type = CLF_TYPE_INVALID;
50 }
51
52 CFile::~CFile()
53 {
54 if (cl_type != CLF_TYPE_INVALID) {
55 DebugPrint("File wasn't closed\n");
56 close();
57 }
58 }
59
60
61 #ifndef z_off_t // { ZLIB_VERSION<="1.0.4"
62
63 /**
64 ** Seek on compressed input. (Newer libs support it directly)
65 **
66 ** @param file File
67 ** @param offset Seek position
68 ** @param whence How to seek
69 */
70 static int gzseek(CFile *file, unsigned offset, int whence)
71 {
72 char buf[32];
73
74 while (offset > sizeof(buf)) {
75 gzread(file, buf, sizeof(buf));
76 offset -= sizeof(buf);
77 }
78 return gzread(file, buf, offset);
79 }
80
81 #endif // } ZLIB_VERSION<="1.0.4"
82
83 /**
84 ** CLopen Library file open
85 **
86 ** @param name File name.
87 ** @param openflags Open read, or write and compression options
88 **
89 ** @return 0 on success, -1 on error. The value of errno does not
90 ** reliably indicate the cause of the error.
91 */
92 int CFile::open(const char *name, long openflags)
93 {
94 const char *openstring;
95 std::string namedotgz;
96 unsigned char buf[2];
97
98 if ((openflags & CL_OPEN_READ) && (openflags & CL_OPEN_WRITE)) {
99 openstring = "rwb";
100 } else if (openflags &CL_OPEN_READ) {
101 openstring = "rb";
102 } else if (openflags & CL_OPEN_WRITE) {
103 openstring = "wb";
104 } else {
105 DebugPrint("Bad CLopen flags");
106 Assert(0);
107 return -1;
108 }
109
110 namedotgz = name;
111 namedotgz += ".gz";
112
113 cl_type = CLF_TYPE_INVALID;
114
115 if (openflags & CL_OPEN_WRITE) {
116 if ((openflags & CL_WRITE_GZ) &&
117 (cl_gz = gzopen(namedotgz.c_str(), openstring))) {
118 cl_type = CLF_TYPE_GZIP;
119 } else if ((cl_plain = fopen(name, openstring))) {
120 cl_type = CLF_TYPE_PLAIN;
121 }
122 } else {
123 if (!(cl_plain = fopen(name, openstring))) { // try plain first
124 if ((cl_gz = gzopen(namedotgz.c_str(), "rb"))) {
125 cl_type = CLF_TYPE_GZIP;
126 }
127 } else {
128 cl_type = CLF_TYPE_PLAIN;
129 // Hmm, plain worked, but nevertheless the file may be compressed!
130 if (fread(buf, 2, 1, cl_plain) == 1) {
131 if (buf[0] == 0x1f) { // don't check for buf[1] == 0x8b, so that old compress also works!
132 fclose(cl_plain);
133 if ((cl_gz = gzopen(name, "rb"))) {
134 cl_type = CLF_TYPE_GZIP;
135 } else {
136 if (!(cl_plain = fopen(name, "rb"))) {
137 cl_type = CLF_TYPE_INVALID;
138 }
139 }
140 }
141 }
142 if (cl_type == CLF_TYPE_PLAIN) { // ok, it is not compressed
143 rewind(cl_plain);
144 }
145 }
146 }
147
148 if (cl_type == CLF_TYPE_INVALID) {
149 return -1;
150 }
151
152 return 0;
153 }
154
155 /**
156 ** CLclose Library file close
157 **
158 ** @return 0 on success, nonzero on error. The resulting value of
159 ** errno is best not relied on. Callers that only read
160 ** files, rather than write them, typically ignore the result
161 ** anyway.
162 */
163 int CFile::close()
164 {
165 int tp;
166 int ret;
167
168 ret = EOF;
169
170 if ((tp = cl_type) != CLF_TYPE_INVALID) {
171 if (tp == CLF_TYPE_PLAIN) {
172 // On success, returns 0.
173 // On error, returns EOF and sets errno.
174 ret = fclose(cl_plain);
175 }
176 if (tp == CLF_TYPE_GZIP) {
177 // On success, returns Z_OK=0.
178 // On error, returns a zlib error code, and
179 // sets errno if the code is Z_ERRNO=-1.
180 ret = gzclose(cl_gz);
181 }
182 } else {
183 errno = EBADF;
184 }
185 cl_type = CLF_TYPE_INVALID;
186 return ret;
187 }
188
189 /**
190 ** CLread Library file read
191 **
192 ** @param buf Pointer to read the data to.
193 ** @param len number of bytes to read.
194 */
195 int CFile::read(void *buf, size_t len)
196 {
197 int ret;
198
199 ret = 0;
200
201 if (cl_type != CLF_TYPE_INVALID) {
202 if (cl_type == CLF_TYPE_PLAIN) {
203 ret = fread(buf, 1, len, cl_plain);
204 }
205 if (cl_type == CLF_TYPE_GZIP) {
206 ret = gzread(cl_gz, buf, len);
207 }
208 } else {
209 errno = EBADF;
210 }
211 return ret;
212 }
213
214 void CFile::flush()
215 {
216 if (cl_type != CLF_TYPE_INVALID) {
217 if (cl_type == CLF_TYPE_PLAIN) {
218 fflush(cl_plain);
219 }
220 if (cl_type == CLF_TYPE_GZIP) {
221 gzflush(cl_gz, Z_SYNC_FLUSH);
222 }
223 } else {
224 errno = EBADF;
225 }
226 }
227
228
229 /**
230 ** CLprintf Library file write
231 **
232 ** @param format String Format.
233 ** @param ... Parameter List.
234 */
235 int CFile::printf(const char *format, ...)
236 {
237 int n;
238 int size;
239 int ret;
240 int tp;
241 char *p;
242 va_list ap;
243 char *newp;
244 int oldsize;
245
246 size = 500;
247 ret = -1;
248 if ((p = new char[size]) == NULL) {
249 return -1;
250 }
251 while (1) {
252 // Try to print in the allocated space.
253 va_start(ap, format);
254 n = vsnprintf(p, size, format, ap);
255 va_end(ap);
256 // If that worked, string was processed.
257 if (n > -1 && n < size) {
258 break;
259 }
260 // Else try again with more space.
261 oldsize = size;
262 if (n > -1) { // glibc 2.1
263 size = n + 1; // precisely what is needed
264 } else { /* glibc 2.0, vc++ */
265 size *= 2; // twice the old size
266 }
267 if ((newp = new char[size]) == NULL) {
268 delete[] p;
269 return -1;
270 }
271 memcpy(newp, p, oldsize);
272 delete[] p;
273 p = newp;
274 }
275
276 // Allocate the correct size
277 size = strlen(p);
278
279 if ((tp = cl_type) != CLF_TYPE_INVALID) {
280 if (tp == CLF_TYPE_PLAIN) {
281 ret = fwrite(p, size, 1, cl_plain);
282 }
283 if (tp == CLF_TYPE_GZIP) {
284 ret = gzwrite(cl_gz, p, size);
285 }
286 } else {
287 errno = EBADF;
288 }
289 delete[] p;
290 return ret;
291 }
292
293 /**
294 ** CLseek Library file seek
295 **
296 ** @param offset Seek position
297 ** @param whence How to seek
298 */
299 int CFile::seek(long offset, int whence)
300 {
301 int tp;
302 int ret;
303
304 ret = -1;
305
306 if ((tp = cl_type) != CLF_TYPE_INVALID) {
307 if (tp == CLF_TYPE_PLAIN) {
308 ret = fseek(cl_plain, offset, whence);
309 }
310 if (tp == CLF_TYPE_GZIP) {
311 ret = gzseek(cl_gz, offset, whence);
312 }
313 } else {
314 errno = EBADF;
315 }
316 return ret;
317 }
318
319 /**
320 ** CLtell Library file tell
321 */
322 long CFile::tell()
323 {
324 int tp;
325 int ret;
326
327 ret = -1;
328
329 if ((tp = cl_type) != CLF_TYPE_INVALID) {
330 if (tp == CLF_TYPE_PLAIN) {
331 ret = ftell(cl_plain);
332 }
333 if (tp == CLF_TYPE_GZIP) {
334 ret = gztell(cl_gz);
335 }
336 } else {
337 errno = EBADF;
338 }
339 return ret;
340 }
341
342 /**
343 ** Find a file with its correct extension ("" or ".gz")
344 **
345 ** @param file The string with the file path. Upon success, the string
346 ** is replaced by the full filename witht he correct extension.
347 ** @param filesize Size of the file buffer
348 **
349 ** @return 1 if the file has been found.
350 */
351 static int FindFileWithExtension(char *file, size_t filesize)
352 {
353 char buf[PATH_MAX];
354
355 if (!access(file, R_OK)) {
356 return 1;
357 }
358 sprintf_s(buf, sizeof(buf), "%s.gz", file);
359 if (!access(buf, R_OK)) {
360 strcpy_s(file, filesize, buf);
361 return 1;
362 }
363
364 return 0;
365 }
366
367 /**
368 ** Generate a filename into library.
369 **
370 ** Try current directory, user home directory, global directory.
371 **
372 ** @param file Filename to open.
373 ** @param buffer Allocated buffer for generated filename.
374 ** @param buffersize Size of the buffer
375 **
376 ** @return Pointer to buffer.
377 */
378 char *LibraryFileName(const char *file, char *buffer, size_t buffersize)
379 {
380 // Absolute path or in current directory.
381 strcpy_s(buffer, buffersize, file);
382 if (*buffer == '/') {
383 return buffer;
384 }
385 if (FindFileWithExtension(buffer, buffersize)) {
386 return buffer;
387 }
388
389 // In user home directory
390 sprintf_s(buffer, buffersize, "%s%s", UserDirectory.c_str(), *file == '~' ? file + 1 : file);
391 if (FindFileWithExtension(buffer, buffersize)) {
392 return buffer;
393 }
394
395 // In global shared directory
396 sprintf_s(buffer, buffersize, "%s/%s", StratagusLibPath.c_str(), file);
397 if (FindFileWithExtension(buffer, buffersize)) {
398 return buffer;
399 }
400
401 // Support for graphics in default graphics dir.
402 // They could be anywhere now, but check if they haven't
403 // got full paths.
404 sprintf_s(buffer, buffersize, "%s/graphics/%s", StratagusLibPath.c_str(), file);
405 if (FindFileWithExtension(buffer, buffersize)) {
406 return buffer;
407 }
408
409 // Support for sounds in default sounds dir.
410 // They could be anywhere now, but check if they haven't
411 // got full paths.
412 sprintf_s(buffer, buffersize, "%s/sounds/%s", StratagusLibPath.c_str(), file);
413 if (FindFileWithExtension(buffer, buffersize)) {
414 return buffer;
415 }
416
417 DebugPrint("File `%s' not found\n" _C_ file);
418 strcpy_s(buffer, buffersize, file);
419 return buffer;
420 }
421
422 /**
423 ** Generate a list of files within a specified directory
424 **
425 ** @param dirname Directory to read.
426 ** @param filter Optional xdata-filter function.
427 ** @param fl Filelist pointer.
428 **
429 ** @return the number of entries added to FileList.
430 */
431 int ReadDataDirectory(const char *dirname, int (*filter)(char *, FileList *),
432 std::vector<FileList> &fl)
433 {
434 #ifndef _MSC_VER
435 DIR *dirp;
436 struct dirent *dp;
437 #endif
438 struct stat st;
439 #ifdef _MSC_VER
440 struct _finddata_t fileinfo;
441 long hFile;
442 #endif
443 int n;
444 int isdir = 0; // silence gcc..
445 char *np;
446 char buffer[PATH_MAX];
447 char *filename;
448
449 strcpy_s(buffer, sizeof(buffer), dirname);
450 n = strlen(buffer);
451 if (!n || buffer[n - 1] != '/') {
452 buffer[n++] = '/';
453 buffer[n] = 0;
454 }
455 np = buffer + n;
456
457 #ifndef _MSC_VER
458 dirp = opendir(dirname);
459 #endif
460
461 #ifndef _MSC_VER
462 if (dirp) {
463 while ((dp = readdir(dirp)) != NULL) {
464 filename = dp->d_name;
465 #else
466 strcat_s(buffer, sizeof(buffer), "*.*");
467 hFile = _findfirst(buffer, &fileinfo);
468 if (hFile != -1L) {
469 do {
470 filename = fileinfo.name;
471 #endif
472
473 if (strcmp(filename, ".") == 0) {
474 continue;
475 }
476 if (strcmp(filename, "..") == 0) {
477 continue;
478 }
479
480 strcpy_s(np, sizeof(buffer) - (np - buffer), filename);
481 if (stat(buffer, &st) == 0) {
482 isdir = S_ISDIR(st.st_mode);
483 if (isdir || S_ISREG(st.st_mode)) {
484 FileList nfl;
485 int i;
486 if (isdir) {
487 nfl.name = new_strdup(np);
488 } else {
489 nfl.type = -1;
490 if (filter == NULL) {
491 nfl.name = new_strdup(np);
492 nfl.type = 1;
493 } else if ((*filter)(buffer, &nfl) == 0) {
494 continue;
495 }
496 }
497 for (i = 0; i < (int)fl.size(); ++i) {
498 if (nfl.type == fl[i].type) {
499 if (strcmp(nfl.name, fl[i].name) < 0) {
500 break;
501 }
502 } else {
503 if (fl[i].type - nfl.type > 0) {
504 break;
505 }
506 }
507 }
508 fl.insert(fl.begin() + i, nfl);
509 }
510 }
511 #ifndef _MSC_VER
512 }
513 closedir(dirp);
514 #else
515 } while (_findnext(hFile, &fileinfo) == 0);
516 _findclose(hFile);
517 #endif
518 }
519 return fl.size();
520 }
521
522
523
524 void FileWriter::printf(const char *format, ...)
525 {
526 char static_buf[1024];
527 char *buf = static_buf;
528 int ret;
529 int buf_size = sizeof(static_buf);
530
531 va_list ap;
532 va_start(ap, format);
533 buf[buf_size - 1] = '\0';
534 ret = vsnprintf(buf, buf_size - 1, format, ap);
535 va_end(ap);
536 while (ret == -1 || ret >= buf_size - 1) {
537 if (buf != static_buf) {
538 delete[] buf;
539 }
540 buf_size <<= 1;
541 buf = new char[buf_size];
542 if (!buf) {
543 fprintf(stderr, "Out of memory\n");
544 ExitFatal(-1);
545 }
546 buf[buf_size - 1] = '\0';
547 va_start(ap, format);
548 ret = vsnprintf(buf, buf_size - 1, format, ap);
549 va_end(ap);
550 }
551 write(buf, strlen(buf));
552
553 if (buf != static_buf) {
554 delete[] buf;
555 }
556 }
557
558
559 class RawFileWriter : public FileWriter
560 {
561 FILE *file;
562
563 public:
564 RawFileWriter(const std::string &filename) {
565 file = fopen(filename.c_str(), "wb");
566 if (!file) {
567 fprintf(stderr,"Can't open file '%s' for writing\n", filename.c_str());
568 throw FileException();
569 }
570 }
571
572 virtual ~RawFileWriter() {
573 fclose(file);
574 }
575
576 virtual int write(const char *data, unsigned int size)
577 {
578 return fwrite(data, size, 1, file);
579 }
580 };
581
582 class GzFileWriter : public FileWriter
583 {
584 gzFile file;
585
586 public:
587 GzFileWriter(const std::string &filename) {
588 file = gzopen(filename.c_str(), "wb9");
589 if (!file) {
590 fprintf(stderr,"Can't open file '%s' for writing\n", filename.c_str());
591 throw FileException();
592 }
593 }
594
595 virtual ~GzFileWriter() {
596 gzclose(file);
597 }
598
599 virtual int write(const char *data, unsigned int size)
600 {
601 return gzwrite(file, data, size);
602 }
603 };
604
605 /**
606 ** Create FileWriter
607 */
608 FileWriter *CreateFileWriter(const std::string &filename)
609 {
610 if (strcasestr(filename.c_str(), ".gz")) {
611 return new GzFileWriter(filename);
612 } else {
613 return new RawFileWriter(filename);
614 }
615 }
616
617 //@}