Debian Codegraph @

code/sys/sys_unix.c

raw symbols SCIP
1 /*
2 ===========================================================================
3 Copyright (C) 1999-2005 Id Software, Inc.
4
5 This file is part of Quake III Arena source code.
6
7 Quake III Arena source code is free software; you can redistribute it
8 and/or modify it under the terms of the GNU General Public License as
9 published by the Free Software Foundation; either version 2 of the License,
10 or (at your option) any later version.
11
12 Quake III Arena source code is distributed in the hope that it will be
13 useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Quake III Arena source code; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 ===========================================================================
21 */
22
23 #include "../qcommon/q_shared.h"
24 #include "../qcommon/qcommon.h"
25 #include "sys_local.h"
26
27 #include <signal.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <errno.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <dirent.h>
34 #include <unistd.h>
35 #include <sys/mman.h>
36 #include <sys/time.h>
37 #include <pwd.h>
38 #include <libgen.h>
39 #include <fcntl.h>
40 #include <fenv.h>
41 #include <sys/wait.h>
42 #include <time.h>
43 #include <sys/resource.h>
44
45 qboolean stdinIsATTY;
46
47 static char execBuffer[ 1024 ];
48 static char *execBufferPointer;
49 static char *execArgv[ 16 ];
50 static int execArgc;
51
52 /*
53 ==============
54 Sys_ClearExecBuffer
55 ==============
56 */
57 static void Sys_ClearExecBuffer( void )
58 {
59 execBufferPointer = execBuffer;
60 Com_Memset( execArgv, 0, sizeof( execArgv ) );
61 execArgc = 0;
62 }
63
64 /*
65 ==============
66 Sys_AppendToExecBuffer
67 ==============
68 */
69 static void Sys_AppendToExecBuffer( const char *text )
70 {
71 size_t size = sizeof( execBuffer ) - ( execBufferPointer - execBuffer );
72 int length = strlen( text ) + 1;
73
74 if( length > size || execArgc >= ARRAY_LEN( execArgv ) )
75 return;
76
77 Q_strncpyz( execBufferPointer, text, size );
78 execArgv[ execArgc++ ] = execBufferPointer;
79
80 execBufferPointer += length;
81 }
82
83 /*
84 ==============
85 Sys_Exec
86 ==============
87 */
88 static int Sys_Exec( void )
89 {
90 pid_t pid = fork( );
91
92 if( pid < 0 )
93 return -1;
94
95 if( pid )
96 {
97 // Parent
98 int exitCode;
99
100 wait( &exitCode );
101
102 return WEXITSTATUS( exitCode );
103 }
104 else
105 {
106 // Child
107 execvp( execArgv[ 0 ], execArgv );
108
109 // Failed to execute
110 exit( -1 );
111
112 return -1;
113 }
114 }
115
116 #ifdef __APPLE__
117
118 /*
119 ==================
120 Sys_DefaultHomePath
121 ==================
122 */
123 static char *Sys_DefaultHomePath(void)
124 {
125 static char homePath[ MAX_OSPATH ] = { 0 };
126 char *p;
127
128 if( !*homePath )
129 {
130 if( ( p = getenv( "HOME" ) ) != NULL )
131 {
132 Com_sprintf( homePath, sizeof(homePath), "%s%c%s",
133 p, PATH_SEP, "Library/Application Support/" );
134
135 if( com_homepath && com_homepath->string[0] )
136 Q_strcat(homePath, sizeof(homePath), com_homepath->string);
137 else
138 Q_strcat(homePath, sizeof(homePath), HOMEPATH_NAME);
139 }
140 }
141
142 return homePath;
143 }
144
145 char *Sys_DefaultHomeConfigPath(void) { return Sys_DefaultHomePath(); }
146 char *Sys_DefaultHomeDataPath(void) { return Sys_DefaultHomePath(); }
147 char *Sys_DefaultHomeStatePath(void) { return Sys_DefaultHomePath(); }
148
149 #else // __APPLE__
150
151 /*
152 ==================
153 Sys_HomeConfigPath
154 ==================
155 */
156 char *Sys_HomeConfigPath(void)
157 {
158 static char homeConfigPath[ MAX_OSPATH ] = { 0 };
159 char *p;
160
161 if( !*homeConfigPath )
162 {
163 if( ( p = getenv( "XDG_CONFIG_HOME" ) ) != NULL && *p != '\0' )
164 Com_sprintf(homeConfigPath, sizeof(homeConfigPath), "%s%c", p, PATH_SEP);
165 else if( ( p = getenv( "HOME" ) ) != NULL && *p != '\0' )
166 Com_sprintf(homeConfigPath, sizeof(homeConfigPath), "%s%c.config%c", p, PATH_SEP, PATH_SEP);
167
168 if( *homeConfigPath )
169 {
170 if( com_homepath && com_homepath->string[0] )
171 Q_strcat(homeConfigPath, sizeof(homeConfigPath), com_homepath->string);
172 else
173 Q_strcat(homeConfigPath, sizeof(homeConfigPath), HOMEPATH_NAME);
174 }
175 }
176
177 return homeConfigPath;
178 }
179
180 /*
181 ==================
182 Sys_HomeDataPath
183 ==================
184 */
185 char *Sys_HomeDataPath(void)
186 {
187 static char homeDataPath[ MAX_OSPATH ] = { 0 };
188 char *p;
189
190 if( !*homeDataPath )
191 {
192 if( ( p = getenv( "XDG_DATA_HOME" ) ) != NULL && *p != '\0' )
193 Com_sprintf(homeDataPath, sizeof(homeDataPath), "%s%c", p, PATH_SEP);
194 else if( ( p = getenv( "HOME" ) ) != NULL && *p != '\0' )
195 Com_sprintf(homeDataPath, sizeof(homeDataPath), "%s%c.local%cshare%c", p, PATH_SEP, PATH_SEP, PATH_SEP);
196
197 if( *homeDataPath )
198 {
199 if( com_homepath && com_homepath->string[0] )
200 Q_strcat(homeDataPath, sizeof(homeDataPath), com_homepath->string);
201 else
202 Q_strcat(homeDataPath, sizeof(homeDataPath), HOMEPATH_NAME);
203 }
204 }
205
206 return homeDataPath;
207 }
208
209 /*
210 ==================
211 Sys_HomeStatePath
212 ==================
213 */
214 char *Sys_HomeStatePath(void)
215 {
216 static char homeStatePath[ MAX_OSPATH ] = { 0 };
217 char *p;
218
219 if( !*homeStatePath )
220 {
221 if( ( p = getenv( "XDG_STATE_HOME" ) ) != NULL && *p != '\0' )
222 Com_sprintf(homeStatePath, sizeof(homeStatePath), "%s%c", p, PATH_SEP);
223 else if( ( p = getenv( "HOME" ) ) != NULL && *p != '\0' )
224 Com_sprintf(homeStatePath, sizeof(homeStatePath), "%s%c.local%cstate%c", p, PATH_SEP, PATH_SEP, PATH_SEP);
225
226 if( *homeStatePath )
227 {
228 if( com_homepath && com_homepath->string[0] )
229 Q_strcat(homeStatePath, sizeof(homeStatePath), com_homepath->string);
230 else
231 Q_strcat(homeStatePath, sizeof(homeStatePath), HOMEPATH_NAME);
232 }
233 }
234
235 return homeStatePath;
236 }
237
238 /*
239 ==================
240 Sys_LegacyHomePath
241 ==================
242 */
243 static char *Sys_LegacyHomePath(void)
244 {
245 static char homePath[ MAX_OSPATH ] = { 0 };
246 char *p;
247
248 if( ( p = getenv( "FLATPAK_ID" ) ) != NULL && *p != '\0' )
249 {
250 // Flatpaks always use XDG
251 return "";
252 }
253
254 if( !*homePath )
255 {
256 if( ( p = getenv( "HOME" ) ) != NULL && *p != '\0' )
257 {
258 Com_sprintf(homePath, sizeof(homePath), "%s%c%s",
259 p, PATH_SEP, HOMEPATH_NAME_UNIX_LEGACY);
260 }
261 }
262
263 return homePath;
264 }
265
266 /*
267 ==================
268 Sys_MigrateToXDG
269 ==================
270 */
271 qboolean Sys_MigrateToXDG(void)
272 {
273 const char *scriptTemplate =
274 "#!/bin/sh\n"
275
276 "set -eu\n"
277
278 "legacy_home=\"%s\"\n"
279 "xdg_config_home=\"%s\"\n"
280 "xdg_data_home=\"%s\"\n"
281 "xdg_state_home=\"%s\"\n"
282
283 "xdg_config_pattern=\"*.cfg\"\n"
284 "xdg_data_pattern=\"demos/*.dm_* *.log *.pk3 *.txt \\\n"
285 " screenshots/*.jpg screenshots/*.tga videos/*.avi\"\n"
286 "xdg_state_pattern=\"*.dat q3history q3key\"\n"
287
288 "glob_copy() {\n"
289 " game_dir=${1:+$1/}\n"
290 " dst=\"$2\"\n"
291 " shift 2\n"
292 " for pattern in \"$@\"; do\n"
293 " subdir=$(dirname \"$pattern\")\n"
294 " [ \"$subdir\" = \".\" ] && subdir=\"\"\n"
295 " find \"$legacy_home/$game_dir\" \\\n"
296 " -path \"$legacy_home/$game_dir$pattern\" -type f \\\n"
297 " -exec mkdir -p \"$dst/$game_dir$subdir\" \\; \\\n"
298 " -exec cp -av {} \"$dst/$game_dir$subdir\" \\;\n"
299 " done\n"
300 "}\n"
301
302 "unmatched_copy() {\n"
303 " game_dir=${1:+$1/}\n"
304 " shift\n"
305 " find_args=\"\"\n"
306 " for pattern in \"$@\"; do\n"
307 " find_args=\"$find_args \\\n"
308 " -not -path \\\"$legacy_home/$game_dir$pattern\\\"\"\n"
309 " done\n"
310 " eval \"find '$legacy_home/$game_dir' -type f $find_args\" | \\\n"
311 " while IFS= read -r file; do\n"
312 " dst=\"$xdg_data_home${file#$legacy_home}\"\n"
313 " dst_dir=$(dirname \"$dst\")\n"
314 " mkdir -p \"$dst_dir\"\n"
315 " cp -av \"$file\" \"$dst\"\n"
316 " done\n"
317 "}\n"
318
319 "echo \"Starting XDG migration...\"\n"
320
321 "glob_copy \"\" \"$xdg_state_home\" \"qkey\"\n"
322
323 "for game_dir in \"$legacy_home\"/*; do\n"
324 " [ -d \"$game_dir\" ] || continue\n"
325 " game=$(basename \"$game_dir\")\n"
326 " glob_copy \"$game\" \"$xdg_config_home\" $xdg_config_pattern\n"
327 " glob_copy \"$game\" \"$xdg_data_home\" $xdg_data_pattern\n"
328 " glob_copy \"$game\" \"$xdg_state_home\" $xdg_state_pattern\n"
329 " unmatched_copy \"$game\" \\\n"
330 " $xdg_config_pattern \\\n"
331 " $xdg_data_pattern \\\n"
332 " $xdg_state_pattern\n"
333 "done\n"
334
335 "echo \"XDG migration complete!\"\n";
336
337 char scriptBuffer[2048];
338 int len = Com_sprintf( scriptBuffer, sizeof( scriptBuffer ), scriptTemplate,
339 Sys_LegacyHomePath( ), Sys_HomeConfigPath( ),
340 Sys_HomeDataPath( ), Sys_HomeStatePath( ) );
341
342 if( len < 0 || len >= (int)sizeof( scriptBuffer ) )
343 {
344 Com_Printf( "XDG migration error: substitution failed.\n" );
345 return qfalse;
346 }
347
348 char scriptPath[] = "/tmp/xdgmigrationXXXXXX";
349 int fd = mkstemp( scriptPath );
350 if( fd == -1 )
351 {
352 Com_Printf( "XDG migration error: script creation failed.\n" );
353 return qfalse;
354 }
355
356 if( write( fd, scriptBuffer, len ) != len )
357 {
358 close( fd );
359 unlink( scriptPath );
360 Com_Printf( "XDG migration error: script write failed.\n" );
361 return qfalse;
362 }
363 close( fd );
364
365 if( chmod( scriptPath, 0700 ) == -1 )
366 {
367 unlink( scriptPath );
368 Com_Printf( "XDG migration error: script chmod failed.\n" );
369 return qfalse;
370 }
371
372 Sys_ClearExecBuffer( );
373 Sys_AppendToExecBuffer( scriptPath );
374 int result = Sys_Exec( );
375 unlink( scriptPath );
376
377 return result == 0;
378 }
379
380 /*
381 ==================
382 Sys_ShouldUseLegacyHomePath
383 ==================
384 */
385 static qboolean Sys_ShouldUseLegacyHomePath(void)
386 {
387 if( access( Sys_HomeConfigPath( ), F_OK ) == 0 )
388 {
389 // If the XDG config directory exists, prefer XDG layout, regardless
390 return qfalse;
391 }
392
393 if( ( com_homepath && com_homepath->string[0] ) ||
394 Cvar_VariableString( "fs_homepath" )[0] )
395 {
396 // If a custom homepath has been explicity set then
397 // that strongly implies that migration isn't desired
398 return qfalse;
399 }
400
401 const char *legacyHomePath = Sys_LegacyHomePath();
402
403 if( !*legacyHomePath || access( legacyHomePath, F_OK ) != 0 )
404 {
405 // The legacy home path doesn't exist
406 return qfalse;
407 }
408
409 char migrationRefusedPath[ MAX_OSPATH ];
410 Com_sprintf( migrationRefusedPath, sizeof( migrationRefusedPath ),
411 "%s/.xdgMigrationRefused", legacyHomePath );
412
413 // If the user hasn't already refused, ask if they want to migrate
414 if( access( migrationRefusedPath, F_OK ) != 0 )
415 {
416 dialogResult_t result = Sys_Dialog( DT_YES_NO, va(
417 "Modern games and applications store files in "
418 "directories according to the Free Desktop standard. "
419 "Here's what that would look like for %s:\n\n"
420 "Configuration files:\n %s\n\n"
421 "Data files; pk3s, screenshots, logs, demos, etc.:\n %s\n\n"
422 "Internal runtime files:\n %s\n\n"
423 "At the moment all of these files are found here:\n %s\n\n"
424 "Do you want to copy your files to these new directories?",
425 PRODUCT_NAME,
426 Sys_HomeConfigPath( ), Sys_HomeDataPath( ), Sys_HomeStatePath( ),
427 legacyHomePath ),
428 "Home Directory Files Upgrade" );
429
430 if( result == DR_YES )
431 return !Sys_MigrateToXDG( );
432
433 // Guard against asking again in future
434 fclose( fopen( migrationRefusedPath, "w" ) );
435 }
436
437 return qtrue;
438 }
439
440 /*
441 ==================
442 Sys_DefaultHomeConfigPath
443 ==================
444 */
445 char *Sys_DefaultHomeConfigPath(void)
446 {
447 if( Sys_ShouldUseLegacyHomePath( ) )
448 return Sys_LegacyHomePath( );
449
450 return Sys_HomeConfigPath( );
451 }
452
453 /*
454 ==================
455 Sys_DefaultHomeDataPath
456 ==================
457 */
458 char *Sys_DefaultHomeDataPath(void)
459 {
460 if( Sys_ShouldUseLegacyHomePath( ) )
461 return Sys_LegacyHomePath( );
462
463 return Sys_HomeDataPath( );
464 }
465
466 /*
467 ==================
468 Sys_DefaultHomeStatePath
469 ==================
470 */
471 char *Sys_DefaultHomeStatePath(void)
472 {
473 if( Sys_ShouldUseLegacyHomePath( ) )
474 return Sys_LegacyHomePath( );
475
476 return Sys_HomeStatePath( );
477 }
478
479 #endif
480
481 /*
482 ================
483 Sys_SteamPath
484 ================
485 */
486 char *Sys_SteamPath( void )
487 {
488 // Steam doesn't let you install Quake 3 on Mac/Linux
489 return "";
490 }
491
492 /*
493 ================
494 Sys_GogPath
495 ================
496 */
497 char *Sys_GogPath( void )
498 {
499 // GOG doesn't let you install Quake 3 on Mac/Linux
500 return "";
501 }
502
503 /*
504 ================
505 Sys_MicrosoftStorePath
506 ================
507 */
508 char* Sys_MicrosoftStorePath(void)
509 {
510 // Microsoft Store doesn't exist on Mac/Linux
511 return "";
512 }
513
514
515 /*
516 ================
517 Sys_Milliseconds
518 ================
519 */
520 /* base time in seconds, that's our origin
521 timeval:tv_sec is an int:
522 assuming this wraps every 0x7fffffff - ~68 years since the Epoch (1970) - we're safe till 2038 */
523 unsigned long sys_timeBase = 0;
524 /* current time in ms, using sys_timeBase as origin
525 NOTE: sys_timeBase*1000 + curtime -> ms since the Epoch
526 0x7fffffff ms - ~24 days
527 although timeval:tv_usec is an int, I'm not sure wether it is actually used as an unsigned int
528 (which would affect the wrap period) */
529 int curtime;
530 int Sys_Milliseconds (void)
531 {
532 struct timeval tp;
533
534 gettimeofday(&tp, NULL);
535
536 if (!sys_timeBase)
537 {
538 sys_timeBase = tp.tv_sec;
539 return tp.tv_usec/1000;
540 }
541
542 curtime = (tp.tv_sec - sys_timeBase)*1000 + tp.tv_usec/1000;
543
544 return curtime;
545 }
546
547 /*
548 ==================
549 Sys_RandomBytes
550 ==================
551 */
552 qboolean Sys_RandomBytes( byte *string, int len )
553 {
554 FILE *fp;
555
556 fp = fopen( "/dev/urandom", "r" );
557 if( !fp )
558 return qfalse;
559
560 setvbuf( fp, NULL, _IONBF, 0 ); // don't buffer reads from /dev/urandom
561
562 if( fread( string, sizeof( byte ), len, fp ) != len )
563 {
564 fclose( fp );
565 return qfalse;
566 }
567
568 fclose( fp );
569 return qtrue;
570 }
571
572 /*
573 ==================
574 Sys_GetCurrentUser
575 ==================
576 */
577 char *Sys_GetCurrentUser( void )
578 {
579 struct passwd *p;
580
581 if ( (p = getpwuid( getuid() )) == NULL ) {
582 return "player";
583 }
584 return p->pw_name;
585 }
586
587 #define MEM_THRESHOLD 96*1024*1024
588
589 /*
590 ==================
591 Sys_LowPhysicalMemory
592
593 TODO
594 ==================
595 */
596 qboolean Sys_LowPhysicalMemory( void )
597 {
598 return qfalse;
599 }
600
601 /*
602 ==================
603 Sys_Basename
604 ==================
605 */
606 const char *Sys_Basename( char *path )
607 {
608 return basename( path );
609 }
610
611 /*
612 ==================
613 Sys_Dirname
614 ==================
615 */
616 const char *Sys_Dirname( char *path )
617 {
618 return dirname( path );
619 }
620
621 /*
622 ==============
623 Sys_FOpen
624 ==============
625 */
626 FILE *Sys_FOpen( const char *ospath, const char *mode ) {
627 struct stat buf;
628
629 // check if path exists and is a directory
630 if ( !stat( ospath, &buf ) && S_ISDIR( buf.st_mode ) )
631 return NULL;
632
633 return fopen( ospath, mode );
634 }
635
636 /*
637 ==================
638 Sys_Mkdir
639 ==================
640 */
641 qboolean Sys_Mkdir( const char *path )
642 {
643 int result = mkdir( path, 0750 );
644
645 if( result != 0 )
646 return errno == EEXIST;
647
648 return qtrue;
649 }
650
651 /*
652 ==================
653 Sys_Mkfifo
654 ==================
655 */
656 FILE *Sys_Mkfifo( const char *ospath )
657 {
658 FILE *fifo;
659 int result;
660 int fn;
661 struct stat buf;
662
663 // if file already exists AND is a pipefile, remove it
664 if( !stat( ospath, &buf ) && S_ISFIFO( buf.st_mode ) )
665 FS_Remove( ospath );
666
667 result = mkfifo( ospath, 0600 );
668 if( result != 0 )
669 return NULL;
670
671 fifo = fopen( ospath, "w+" );
672 if( fifo )
673 {
674 fn = fileno( fifo );
675 fcntl( fn, F_SETFL, O_NONBLOCK );
676 }
677
678 return fifo;
679 }
680
681 /*
682 ==================
683 Sys_Cwd
684 ==================
685 */
686 char *Sys_Cwd( void )
687 {
688 static char cwd[MAX_OSPATH];
689
690 char *result = getcwd( cwd, sizeof( cwd ) - 1 );
691 if( result != cwd )
692 return NULL;
693
694 cwd[MAX_OSPATH-1] = 0;
695
696 return cwd;
697 }
698
699 /*
700 ==================
701 Sys_BinaryPathRelative
702 ==================
703 */
704 char *Sys_BinaryPathRelative(const char *relative)
705 {
706 static char resolved[MAX_OSPATH];
707 char combined[MAX_OSPATH];
708
709 snprintf(combined, sizeof(combined), "%s/%s", Sys_BinaryPath(), relative);
710
711 if (!realpath(combined, resolved))
712 return NULL;
713
714 return resolved;
715 }
716
717 /*
718 ==============================================================
719
720 DIRECTORY SCANNING
721
722 ==============================================================
723 */
724
725 #define MAX_FOUND_FILES 0x1000
726
727 /*
728 ==================
729 Sys_ListFilteredFiles
730 ==================
731 */
732 void Sys_ListFilteredFiles( const char *basedir, char *subdirs, char *filter, char **list, int *numfiles )
733 {
734 char search[MAX_OSPATH], newsubdirs[MAX_OSPATH];
735 char filename[MAX_OSPATH];
736 DIR *fdir;
737 struct dirent *d;
738 struct stat st;
739
740 if ( *numfiles >= MAX_FOUND_FILES - 1 ) {
741 return;
742 }
743
744 if ( basedir[0] == '\0' ) {
745 return;
746 }
747
748 if (strlen(subdirs)) {
749 Com_sprintf( search, sizeof(search), "%s/%s", basedir, subdirs );
750 }
751 else {
752 Com_sprintf( search, sizeof(search), "%s", basedir );
753 }
754
755 if ((fdir = opendir(search)) == NULL) {
756 return;
757 }
758
759 while ((d = readdir(fdir)) != NULL) {
760 Com_sprintf(filename, sizeof(filename), "%s/%s", search, d->d_name);
761 if (stat(filename, &st) == -1)
762 continue;
763
764 if (st.st_mode & S_IFDIR) {
765 if (Q_stricmp(d->d_name, ".") && Q_stricmp(d->d_name, "..")) {
766 if (strlen(subdirs)) {
767 Com_sprintf( newsubdirs, sizeof(newsubdirs), "%s/%s", subdirs, d->d_name);
768 }
769 else {
770 Com_sprintf( newsubdirs, sizeof(newsubdirs), "%s", d->d_name);
771 }
772 Sys_ListFilteredFiles( basedir, newsubdirs, filter, list, numfiles );
773 }
774 }
775 if ( *numfiles >= MAX_FOUND_FILES - 1 ) {
776 break;
777 }
778 Com_sprintf( filename, sizeof(filename), "%s/%s", subdirs, d->d_name );
779 if (!Com_FilterPath( filter, filename, qfalse ))
780 continue;
781 list[ *numfiles ] = CopyString( filename );
782 (*numfiles)++;
783 }
784
785 closedir(fdir);
786 }
787
788 /*
789 ==================
790 Sys_ListFiles
791 ==================
792 */
793 char **Sys_ListFiles( const char *directory, const char *extension, char *filter, int *numfiles, qboolean wantsubs )
794 {
795 struct dirent *d;
796 DIR *fdir;
797 qboolean dironly = wantsubs;
798 char search[MAX_OSPATH];
799 int nfiles;
800 char **listCopy;
801 char *list[MAX_FOUND_FILES];
802 int i;
803 struct stat st;
804
805 int extLen;
806
807 if (filter) {
808
809 nfiles = 0;
810 Sys_ListFilteredFiles( directory, "", filter, list, &nfiles );
811
812 list[ nfiles ] = NULL;
813 *numfiles = nfiles;
814
815 if (!nfiles)
816 return NULL;
817
818 listCopy = Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ) );
819 for ( i = 0 ; i < nfiles ; i++ ) {
820 listCopy[i] = list[i];
821 }
822 listCopy[i] = NULL;
823
824 return listCopy;
825 }
826
827 if ( directory[0] == '\0' ) {
828 *numfiles = 0;
829 return NULL;
830 }
831
832 if ( !extension)
833 extension = "";
834
835 if ( extension[0] == '/' && extension[1] == 0 ) {
836 extension = "";
837 dironly = qtrue;
838 }
839
840 extLen = strlen( extension );
841
842 // search
843 nfiles = 0;
844
845 if ((fdir = opendir(directory)) == NULL) {
846 *numfiles = 0;
847 return NULL;
848 }
849
850 while ((d = readdir(fdir)) != NULL) {
851 Com_sprintf(search, sizeof(search), "%s/%s", directory, d->d_name);
852 if (stat(search, &st) == -1)
853 continue;
854 if ((dironly && !(st.st_mode & S_IFDIR)) ||
855 (!dironly && (st.st_mode & S_IFDIR)))
856 continue;
857
858 if (*extension) {
859 if ( strlen( d->d_name ) < extLen ||
860 Q_stricmp(
861 d->d_name + strlen( d->d_name ) - extLen,
862 extension ) ) {
863 continue; // didn't match
864 }
865 }
866
867 if ( nfiles == MAX_FOUND_FILES - 1 )
868 break;
869 list[ nfiles ] = CopyString( d->d_name );
870 nfiles++;
871 }
872
873 list[ nfiles ] = NULL;
874
875 closedir(fdir);
876
877 // return a copy of the list
878 *numfiles = nfiles;
879
880 if ( !nfiles ) {
881 return NULL;
882 }
883
884 listCopy = Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ) );
885 for ( i = 0 ; i < nfiles ; i++ ) {
886 listCopy[i] = list[i];
887 }
888 listCopy[i] = NULL;
889
890 return listCopy;
891 }
892
893 /*
894 ==================
895 Sys_FreeFileList
896 ==================
897 */
898 void Sys_FreeFileList( char **list )
899 {
900 int i;
901
902 if ( !list ) {
903 return;
904 }
905
906 for ( i = 0 ; list[i] ; i++ ) {
907 Z_Free( list[i] );
908 }
909
910 Z_Free( list );
911 }
912
913 /*
914 ==================
915 Sys_Sleep
916
917 Block execution for msec or until input is received.
918 ==================
919 */
920 void Sys_Sleep( int msec )
921 {
922 if( msec == 0 )
923 return;
924
925 if( stdinIsATTY )
926 {
927 fd_set fdset;
928
929 FD_ZERO(&fdset);
930 FD_SET(STDIN_FILENO, &fdset);
931 if( msec < 0 )
932 {
933 select(STDIN_FILENO + 1, &fdset, NULL, NULL, NULL);
934 }
935 else
936 {
937 struct timeval timeout;
938
939 timeout.tv_sec = msec/1000;
940 timeout.tv_usec = (msec%1000)*1000;
941 select(STDIN_FILENO + 1, &fdset, NULL, NULL, &timeout);
942 }
943 }
944 else
945 {
946 struct timespec req;
947
948 // With nothing to select() on, we can't wait indefinitely
949 if( msec < 0 )
950 msec = 10;
951
952 req.tv_sec = msec/1000;
953 req.tv_nsec = (msec%1000)*1000000;
954 nanosleep(&req, NULL);
955 }
956 }
957
958 /*
959 ==============
960 Sys_ErrorDialog
961
962 Display an error message
963 ==============
964 */
965 void Sys_ErrorDialog( const char *error )
966 {
967 char buffer[ 1024 ];
968 unsigned int size;
969 int f = -1;
970 const char *homedatapath = Cvar_VariableString( "fs_homedatapath" );
971 const char *gamedir = Cvar_VariableString( "fs_game" );
972 const char *fileName = "crashlog.txt";
973 char *ospath = FS_BuildOSPath( homedatapath, gamedir, fileName );
974
975 Sys_Print( va( "%s\n", error ) );
976
977 #ifndef DEDICATED
978 Sys_Dialog( DT_ERROR, va( "%s. See \"%s\" for details.", error, ospath ), "Error" );
979 #endif
980
981 // Make sure the write path for the crashlog exists...
982 if( FS_CreatePath( homedatapath ) )
983 {
984 Com_Printf("ERROR: couldn't create path '%s' for crash log.\n", ospath);
985 return;
986 }
987
988 // We might be crashing because we maxed out the Quake MAX_FILE_HANDLES,
989 // which will come through here, so we don't want to recurse forever by
990 // calling FS_FOpenFileWrite()...use the Unix system APIs instead.
991 f = open( ospath, O_CREAT | O_TRUNC | O_WRONLY, 0640 );
992 if( f == -1 )
993 {
994 Com_Printf( "ERROR: couldn't open %s\n", fileName );
995 return;
996 }
997
998 // We're crashing, so we don't care much if write() or close() fails.
999 while( ( size = CON_LogRead( buffer, sizeof( buffer ) ) ) > 0 ) {
1000 if( write( f, buffer, size ) != size ) {
1001 Com_Printf( "ERROR: couldn't fully write to %s\n", fileName );
1002 break;
1003 }
1004 }
1005
1006 close( f );
1007 }
1008
1009 #ifndef __APPLE__
1010 /*
1011 ==============
1012 Sys_ZenityCommand
1013 ==============
1014 */
1015 static void Sys_ZenityCommand( dialogType_t type, const char *message, const char *title )
1016 {
1017 Sys_ClearExecBuffer( );
1018 Sys_AppendToExecBuffer( "zenity" );
1019
1020 switch( type )
1021 {
1022 default:
1023 case DT_INFO: Sys_AppendToExecBuffer( "--info" ); break;
1024 case DT_WARNING: Sys_AppendToExecBuffer( "--warning" ); break;
1025 case DT_ERROR: Sys_AppendToExecBuffer( "--error" ); break;
1026 case DT_YES_NO:
1027 Sys_AppendToExecBuffer( "--question" );
1028 Sys_AppendToExecBuffer( "--ok-label=Yes" );
1029 Sys_AppendToExecBuffer( "--cancel-label=No" );
1030 break;
1031
1032 case DT_OK_CANCEL:
1033 Sys_AppendToExecBuffer( "--question" );
1034 Sys_AppendToExecBuffer( "--ok-label=OK" );
1035 Sys_AppendToExecBuffer( "--cancel-label=Cancel" );
1036 break;
1037 }
1038
1039 Sys_AppendToExecBuffer( va( "--text=%s", message ) );
1040 Sys_AppendToExecBuffer( va( "--title=%s", title ) );
1041 }
1042
1043 /*
1044 ==============
1045 Sys_KdialogCommand
1046 ==============
1047 */
1048 static void Sys_KdialogCommand( dialogType_t type, const char *message, const char *title )
1049 {
1050 Sys_ClearExecBuffer( );
1051 Sys_AppendToExecBuffer( "kdialog" );
1052
1053 switch( type )
1054 {
1055 default:
1056 case DT_INFO: Sys_AppendToExecBuffer( "--msgbox" ); break;
1057 case DT_WARNING: Sys_AppendToExecBuffer( "--sorry" ); break;
1058 case DT_ERROR: Sys_AppendToExecBuffer( "--error" ); break;
1059 case DT_YES_NO: Sys_AppendToExecBuffer( "--warningyesno" ); break;
1060 case DT_OK_CANCEL: Sys_AppendToExecBuffer( "--warningcontinuecancel" ); break;
1061 }
1062
1063 Sys_AppendToExecBuffer( message );
1064 Sys_AppendToExecBuffer( va( "--title=%s", title ) );
1065 }
1066
1067 /*
1068 ==============
1069 Sys_XmessageCommand
1070 ==============
1071 */
1072 static void Sys_XmessageCommand( dialogType_t type, const char *message, const char *title )
1073 {
1074 Sys_ClearExecBuffer( );
1075 Sys_AppendToExecBuffer( "xmessage" );
1076 Sys_AppendToExecBuffer( "-buttons" );
1077
1078 switch( type )
1079 {
1080 default: Sys_AppendToExecBuffer( "OK:0" ); break;
1081 case DT_YES_NO: Sys_AppendToExecBuffer( "Yes:0,No:1" ); break;
1082 case DT_OK_CANCEL: Sys_AppendToExecBuffer( "OK:0,Cancel:1" ); break;
1083 }
1084
1085 Sys_AppendToExecBuffer( "-center" );
1086 Sys_AppendToExecBuffer( message );
1087 }
1088
1089 /*
1090 ==============
1091 Sys_Dialog
1092
1093 Display a *nix dialog box
1094 ==============
1095 */
1096 dialogResult_t Sys_Dialog( dialogType_t type, const char *message, const char *title )
1097 {
1098 typedef enum
1099 {
1100 NONE = 0,
1101 ZENITY,
1102 KDIALOG,
1103 XMESSAGE,
1104 NUM_DIALOG_PROGRAMS
1105 } dialogCommandType_t;
1106 typedef void (*dialogCommandBuilder_t)( dialogType_t, const char *, const char * );
1107
1108 const char *session = getenv( "DESKTOP_SESSION" );
1109 qboolean tried[ NUM_DIALOG_PROGRAMS ] = { qfalse };
1110 dialogCommandBuilder_t commands[ NUM_DIALOG_PROGRAMS ] = { NULL };
1111 dialogCommandType_t preferredCommandType = NONE;
1112 int i;
1113
1114 commands[ ZENITY ] = &Sys_ZenityCommand;
1115 commands[ KDIALOG ] = &Sys_KdialogCommand;
1116 commands[ XMESSAGE ] = &Sys_XmessageCommand;
1117
1118 // This may not be the best way
1119 if( !Q_stricmp( session, "gnome" ) )
1120 preferredCommandType = ZENITY;
1121 else if( !Q_stricmp( session, "kde" ) )
1122 preferredCommandType = KDIALOG;
1123
1124 for( i = NONE + 1; i < NUM_DIALOG_PROGRAMS; i++ )
1125 {
1126 if( preferredCommandType != NONE && preferredCommandType != i )
1127 continue;
1128
1129 if( !tried[ i ] )
1130 {
1131 int exitCode;
1132
1133 commands[ i ]( type, message, title );
1134 exitCode = Sys_Exec( );
1135
1136 if( exitCode >= 0 )
1137 {
1138 switch( type )
1139 {
1140 case DT_YES_NO: return exitCode ? DR_NO : DR_YES;
1141 case DT_OK_CANCEL: return exitCode ? DR_CANCEL : DR_OK;
1142 default: return DR_OK;
1143 }
1144 }
1145
1146 tried[ i ] = qtrue;
1147
1148 // The preference failed, so start again in order
1149 if( preferredCommandType != NONE )
1150 {
1151 preferredCommandType = NONE;
1152 i = NONE + 1;
1153 }
1154 }
1155 }
1156
1157 Com_DPrintf( S_COLOR_YELLOW "WARNING: failed to show a dialog\n" );
1158 return DR_OK;
1159 }
1160 #endif
1161
1162 /*
1163 ==============
1164 Sys_GLimpSafeInit
1165
1166 Unix specific "safe" GL implementation initialisation
1167 ==============
1168 */
1169 void Sys_GLimpSafeInit( void )
1170 {
1171 // NOP
1172 }
1173
1174 /*
1175 ==============
1176 Sys_GLimpInit
1177
1178 Unix specific GL implementation initialisation
1179 ==============
1180 */
1181 void Sys_GLimpInit( void )
1182 {
1183 // NOP
1184 }
1185
1186 void Sys_SetFloatEnv(void)
1187 {
1188 // rounding toward nearest
1189 fesetround(FE_TONEAREST);
1190 }
1191
1192 /*
1193 ==============
1194 Sys_PlatformInit
1195
1196 Unix specific initialisation
1197 ==============
1198 */
1199 void Sys_PlatformInit( void )
1200 {
1201 const char* term = getenv( "TERM" );
1202
1203 signal( SIGHUP, Sys_SigHandler );
1204 signal( SIGQUIT, Sys_SigHandler );
1205 signal( SIGTRAP, Sys_SigHandler );
1206 signal( SIGABRT, Sys_SigHandler );
1207 signal( SIGBUS, Sys_SigHandler );
1208
1209 Sys_SetFloatEnv();
1210
1211 stdinIsATTY = isatty( STDIN_FILENO ) &&
1212 !( term && ( !strcmp( term, "raw" ) || !strcmp( term, "dumb" ) ) );
1213 }
1214
1215 /*
1216 ==============
1217 Sys_PlatformExit
1218
1219 Unix specific deinitialisation
1220 ==============
1221 */
1222 void Sys_PlatformExit( void )
1223 {
1224 }
1225
1226 /*
1227 ==============
1228 Sys_SetEnv
1229
1230 set/unset environment variables (empty value removes it)
1231 ==============
1232 */
1233
1234 void Sys_SetEnv(const char *name, const char *value)
1235 {
1236 if(value && *value)
1237 setenv(name, value, 1);
1238 else
1239 unsetenv(name);
1240 }
1241
1242 /*
1243 ==============
1244 Sys_PID
1245 ==============
1246 */
1247 int Sys_PID( void )
1248 {
1249 return getpid( );
1250 }
1251
1252 /*
1253 ==============
1254 Sys_PIDIsRunning
1255 ==============
1256 */
1257 qboolean Sys_PIDIsRunning( int pid )
1258 {
1259 return kill( pid, 0 ) == 0;
1260 }
1261
1262 /*
1263 =================
1264 Sys_DllExtension
1265
1266 Check if filename should be allowed to be loaded as a DLL.
1267 =================
1268 */
1269 qboolean Sys_DllExtension( const char *name ) {
1270 const char *p;
1271 char c = 0;
1272
1273 if ( COM_CompareExtension( name, DLL_EXT ) ) {
1274 return qtrue;
1275 }
1276
1277 #ifdef __APPLE__
1278 // Allow system frameworks without dylib extensions
1279 // i.e., /System/Library/Frameworks/OpenAL.framework/OpenAL
1280 if ( strncmp( name, "/System/Library/Frameworks/", 27 ) == 0 ) {
1281 return qtrue;
1282 }
1283 #endif
1284
1285 // Check for format of filename.so.1.2.3
1286 p = strstr( name, DLL_EXT "." );
1287
1288 if ( p ) {
1289 p += strlen( DLL_EXT );
1290
1291 // Check if .so is only followed for periods and numbers.
1292 while ( *p ) {
1293 c = *p;
1294
1295 if ( !isdigit( c ) && c != '.' ) {
1296 return qfalse;
1297 }
1298
1299 p++;
1300 }
1301
1302 // Don't allow filename to end in a period. file.so., file.so.0., etc
1303 if ( c != '.' ) {
1304 return qtrue;
1305 }
1306 }
1307
1308 return qfalse;
1309 }
1310
1311 /*
1312 ==============
1313 Sys_OpenFolderInPlatformFileManager
1314 ==============
1315 */
1316 qboolean Sys_OpenFolderInPlatformFileManager( const char *path )
1317 {
1318 Sys_ClearExecBuffer( );
1319
1320 #ifdef __APPLE__
1321 Sys_AppendToExecBuffer( "open" );
1322 #else
1323 Sys_AppendToExecBuffer( "xdg-open" );
1324 #endif
1325
1326 Sys_AppendToExecBuffer( path );
1327
1328 return Sys_Exec( ) == 0;
1329 }
1330
1331 /*
1332 =================
1333 Sys_SetMaxFileLimit
1334 =================
1335 */
1336 qboolean Sys_SetMaxFileLimit( void )
1337 {
1338 #ifdef RLIMIT_NOFILE
1339 struct rlimit limit;
1340
1341 // Get the current open file limit
1342 if( getrlimit( RLIMIT_NOFILE, &limit ) == 0 )
1343 {
1344 // Set the file limit to the maximum
1345 limit.rlim_cur = limit.rlim_max;
1346 if( setrlimit( RLIMIT_NOFILE, &limit ) == 0 )
1347 return qtrue;
1348 else
1349 Com_DPrintf( S_COLOR_YELLOW "WARNING: setrlimit (rlim_max) failed\n" );
1350
1351 #ifdef OPEN_MAX
1352 // On older macOS versions an error can happen trying to set a file limit above
1353 // OPEN_MAX. If we see an error, then try again with OPEN_MAX as the limit.
1354 limit.rlim_cur = OPEN_MAX;
1355 if( setrlimit( RLIMIT_NOFILE, &limit ) == 0 )
1356 return qtrue;
1357 else
1358 Com_DPrintf( S_COLOR_YELLOW "WARNING: setrlimit (OPEN_MAX) failed\n" );
1359 #endif
1360 }
1361 else
1362 Com_DPrintf( S_COLOR_YELLOW "WARNING: getrlimit failed\n" );
1363
1364 #endif // RLIMIT_NOFILE
1365
1366 return qfalse;
1367 }