File: osutil.c

package info (click to toggle)
nws 2.11-3
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 2,700 kB
  • ctags: 2,820
  • sloc: ansic: 28,849; sh: 3,289; java: 1,205; makefile: 697; perl: 12
file content (684 lines) | stat: -rw-r--r-- 13,503 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
/* $Id: osutil.c,v 1.57 2004/09/16 19:26:01 graziano Exp $ */

#include "config_portability.h"

#include <ctype.h>
#include <errno.h>
#include <pwd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#ifdef HAVE_SYS_WAIT_H
#	include <sys/wait.h> 
#endif
#ifdef HAVE_SYS_UTSNAME_H
#	include <sys/utsname.h>
#endif

#include "osutil.h"

#ifdef HAVE_PTHREAD_H
#	include <pthread.h>
#endif

#include "diagnostic.h"

/* lock for the module */
static void *lock = NULL;


/* global variable of the module */
static char *systemName = NULL;
static char *releaseName = NULL;
static char *machineName = NULL;

/* internal function that fills the data coming from uname. Returns 1 on
 * success, 0 on failure */
static int
CallUname() {
#ifdef HAVE_UNAME
	static struct utsname uts;
	int ret;

	GetNWSLock(&lock);
	ret = uname(&uts);
	if (ret != -1) {
		/* let's fill the fields */
		systemName = uts.sysname;
		releaseName = uts.release;
		machineName = uts.machine;
	}
	ReleaseNWSLock(&lock);

	return (ret != -1);
#else
	return 0;
#endif
}

const char *
GetSystemName() {
	if (systemName == NULL) {
		if (!CallUname()) {
			return NULL;
		}
	}

	return systemName;
}

const char *
GetRelease() {
	if (systemName == NULL) {
		if (!CallUname()) {
			return NULL;
		}
	}

	return releaseName;
}

const char *
GetMachine() {
	if (systemName == NULL) {
		if (!CallUname()) {
			return NULL;
		}
	}

	return machineName;
}


/* 
 * These are defined here only becasue they are not found (sometimes) in
 * the headers but only in libraries. To avoid annoying compilation warnings
 */
#ifdef HAVE_SIGHOLD
int sighold(int sig);
#endif
#ifdef HAVE_SIGRELSE
int sigrelse(int sig);
#endif


int
CPUCount( ) {
	long sysconfCount = 1;
#ifdef HAVE_SYSCONF
#	ifdef SYSCONF_PROCESSOR_COUNT_PARAMETER 
#		undef SYSCONF_PROCESSOR_COUNT_PARAMETER
#	endif
#	ifdef _SC_CRAY_NCPU
#		define SYSCONF_PROCESSOR_COUNT_PARAMETER _SC_CRAY_NCPU
#	elif defined(_SC_NPROC_CONF)
#		define SYSCONF_PROCESSOR_COUNT_PARAMETER _SC_NPROC_CONF
#	elif defined(_SC_NPROCESSORS_CONF)
#		define SYSCONF_PROCESSOR_COUNT_PARAMETER _SC_NPROCESSORS_CONF
#	endif
#	ifdef SYSCONF_PROCESSOR_COUNT_PARAMETER 
	sysconfCount = sysconf(SYSCONF_PROCESSOR_COUNT_PARAMETER);
	if (sysconfCount <= 0) {
		/* remove error and non-sense */
		sysconfCount = 1;
	}
#	endif
#endif
	return (int) sysconfCount;
}

double
InstalledMemory() {
	double mem = -1;
#if defined(HAVE_SYSCONF) && defined(_SC_PHYS_PAGES)
#	ifdef _SC_PAGE_SIZE
	mem = sysconf(_SC_PAGE_SIZE);
#	elif defined(PAGE_SIZE)
	mem = sysconf(PAGE_SIZE);
#	endif
	if (mem > 0) {
		mem *= sysconf(_SC_PHYS_PAGES);
		if (mem < 0) {
			mem = -1;
		}
	}
#endif
	if (mem > 0) {
		mem /= (1024*1024);
	}
	return mem;
}

double
AvailableMemory() {
	double mem = -1;
#if defined(HAVE_SYSCONF) && defined(_SC_AVPHYS_PAGES)
#	ifdef _SC_PAGE_SIZE
	mem = sysconf(_SC_PAGE_SIZE);
#	elif defined(PAGE_SIZE)
	mem = sysconf(PAGE_SIZE);
#	endif
	if (mem > 0) {
		mem *= sysconf(_SC_AVPHYS_PAGES);
		if (mem < 0) {
			mem = -1;
		}
	}
#endif
	if (mem > 0) {
		mem /= (1024*1024);
	}
	return mem;
}


/* It should be thread safe (time should be thread safe) */
double
CurrentTime(void) {
	return((double)time(NULL));
}


char *
GetEnvironmentValue(	const char *name,
			const char *rcDirs,
			const char *rcName,
			const char *defaultValue) {
	const char *dirEnd;
	const char *dirStart;
	const char *homeDir;
	char *from, *to;
	size_t nameLen;
	FILE *rcFile;
	char rcLine[255 + 1], rcPath[255 + 1];
	char *returnValue;
	int i, len;

	/* sanity check */
	if (name == NULL) {
		if (defaultValue != NULL) {
			return strdup(defaultValue);
		} else {
			return NULL;
		}
	}

	returnValue = getenv(name);
	if(returnValue != NULL) {
		/* easy way out: we got the environmental variable */
		return strdup(returnValue);
	}

	if (rcName != NULL && *rcName != '\0') {
		/* we need rcDirs of we are here */
		if (rcDirs == NULL) {
			return NULL;
		}

		nameLen = strlen(name);
		len = sizeof(rcPath);

		for(dirStart = rcDirs, dirEnd = dirStart; dirEnd != NULL; dirStart = dirEnd + 1) {
			/* Construct a file path from the next dir in
			 * rcDirs and rcName. */
			dirEnd = strchr(dirStart, ':');
			if (dirEnd == NULL) {
				i = strlen(dirStart);
			} else {
				i = dirEnd -dirStart;
			}
			if (i >= (len - strlen(rcName) - 1)) {
				/* we wouldn't fit the name anyway */
				continue;
			}
			strncpy(rcPath, dirStart, i);
			rcPath[i] = '\0';

			if ((strcmp(rcPath, "~") == 0) || (strcmp(rcPath, "~/") == 0)) {
				homeDir = getenv("HOME");
				if (homeDir != NULL) {
					strncpy(rcPath, homeDir, len);
					rcPath[len - 1] = '\0';
				}
			}
			strcat(rcPath, "/");
			strcat(rcPath, rcName);
			rcFile = fopen(rcPath, "r");

			if (rcFile == NULL) {
				/* no luck, try the next one */
				continue;
			}

			while(fgets(rcLine, sizeof(rcLine), rcFile) != NULL) {
				/* Test against pattern " *#name# =". */
				for(from = rcLine; (*from != '\0') && isspace((int)*from); from++)
					; /* Nothing more to do. */
				if(strncmp(from, name, nameLen) != 0) {
					continue;
				}
				for(from += nameLen; (*from != '\0') && isspace((int)*from); from++)
					; /* Nothing more to do. */
				if(*from != '=') {
					continue;
				}

				/* We found a line that sets the variable. */
				(void)fclose(rcFile);
				for(from++; (*from != '\0') && isspace((int)*from); from++)
					; /* Nothing more to do. */

				/* Return a single word to allow for
				 * future free-format input. */
				if(*from == '"') {
					returnValue = from + 1;
					for(from++, to = from; (*from != '\0') && (*from != '"'); from++, to++) {
						if(*from == '\\') {
							from++;
							switch(*from) {
							case 'b':
								*to = '\b';
								break;
							case 'f':
								*to = '\f';
								break;
							case 'n':
								*to = '\n';
								break;
							case 'r':
								*to = '\r';
								break;
							case 't':
								*to = '\t';
								break;
							case 'v':
								*to = '\v';
								break;
							default:
								*to = *from;
								break;
							}
						} else {
							*to = *from;
						}
					}
				} else {
					returnValue = from;
					for(to = from; (*to != '\0') && !isspace((int)*to); to++)
						; /* Nothing more to do. */
				}
				*to = '\0';

				if (returnValue != NULL) 
					return strdup(returnValue);
				else 
					break;
			}
		(void)fclose(rcFile);
		}
	}

	/* we didn't find anything: return the default value */
	if (defaultValue != NULL) {
		returnValue = strdup(defaultValue);
	} else {
		returnValue = NULL;
	}

	return returnValue;
}

int
GetUserName(	char *name,
		size_t length) {
	struct passwd *myPasswd;

	GetNWSLock(&lock);
	myPasswd = getpwuid(getuid());
	if(myPasswd != NULL) {
		strncpy(name, myPasswd->pw_name, length);
		name[length - 1] = '\0';
	}
	endpwent();
	ReleaseNWSLock(&lock);

	return(myPasswd != NULL);
}

void
HoldSignal(int sig) {
#ifdef HAVE_SIGHOLD
	sighold(sig);
#else
	sigset_t set, oset;
	sigemptyset(&set);
	sigaddset(&set, sig);
	sigprocmask(SIG_BLOCK, &set, &oset);
#endif
}


int
MakeDirectory(	const char *path,
		mode_t mode,
		int makeEntirePath) {
	const char *endSubPath;
	struct stat pathStat;
	char *subPath;

	if(makeEntirePath) {
		endSubPath = path;  /* This will ignore leading '/' */
		while((endSubPath = strchr(endSubPath + 1, '/')) != NULL) {
			subPath = (char *)MALLOC(endSubPath - path + 1);
			if (subPath == NULL) {
				return 0;
			}
			strncpy(subPath, path, endSubPath - path);
			subPath[endSubPath - path] = '\0';
			if((stat(subPath, &pathStat) == -1) && (errno == ENOENT)) {
				if(mkdir(subPath, mode) == -1) {
					FREE(subPath);
					return 0;
				}
			} else if(!S_ISDIR(pathStat.st_mode)) {
				FREE(subPath);
				return 0;
			}
			FREE(subPath);
		}
	}

	if((stat(path, &pathStat) == -1) && (errno == ENOENT)) {
		return(mkdir(path, mode) != -1);
	} else {
		return(S_ISDIR(pathStat.st_mode));
	}
}


#ifdef HAVE_PTHREAD_H
typedef struct {
	pthread_mutex_t lock;
	pthread_cond_t cond;
	int value;
} nwsLockType;
#endif

int
GetNWSLock(void **Lock) {
#ifdef HAVE_PTHREAD_H
	/* this is the lock for this module. Every other module will use
	 * a void * as a variable as mutex. */
	int ret;
	static pthread_mutex_t nwsLock = PTHREAD_MUTEX_INITIALIZER;
	nwsLockType *thisLock;

	if (Lock == NULL) {
		return 0;
	}
	if (*Lock == NULL) {
		/* let's play it safe: let's do one mutex at the time (in
		 * case multiple threads are running on the same lock */
	 	if (pthread_mutex_lock(&nwsLock) != 0) {
			return 0;
		}
		thisLock = MALLOC(sizeof(nwsLockType));
		if (thisLock == NULL) {
			fprintf(stderr, "GetNWSLock: out of memory\n");
			return 0;
		}
		*Lock = thisLock;		/* save the lock structure */
		pthread_mutex_init(&thisLock->lock, NULL);
		pthread_cond_init(&thisLock->cond, NULL);
		thisLock->value = 0;

	 	if (pthread_mutex_unlock(&nwsLock) != 0) {
			return 0;
		}
	}
	thisLock = *Lock;
	ret = pthread_mutex_lock(&thisLock->lock);
	if (ret != 0) {
		fprintf(stderr, "GetNWSLock: Unable to lock (errno = %d)!\n", ret);
		return 0;
	}
	while (thisLock->value == 1) {
		pthread_cond_wait(&thisLock->cond, &thisLock->lock);
	}
	thisLock->value = 1;
	ret = pthread_mutex_unlock(&thisLock->lock);
	if  (ret != 0) {
		fprintf(stderr, "GetNWSLock: Unable to unlock (errno = %d)!\n", ret);
		return 0;
	}
#endif
	return 1;
}

int 
ReleaseNWSLock(void **Lock) {
#ifdef HAVE_PTHREAD_H
	nwsLockType *thisLock;
	int ret;

	if (Lock == NULL) {
		/* if we don't have lock, there's a problem */
		fprintf(stderr, "ReleaseNWSLock: non-existing lock!\n");
		return 0;
	}
	thisLock = *Lock;
	if (pthread_mutex_lock(&thisLock->lock) != 0) {
		fprintf(stderr, "ReleaseNWSLock: Unable to lock (errno = %d)!\n", errno);
		return 0;
	}
	thisLock->value = 0;
	pthread_cond_signal(&thisLock->cond);
	ret = pthread_mutex_unlock(&thisLock->lock);
	if (ret != 0) {
		fprintf(stderr, "ReleaseNWSLock: Unable to unlock (errno = %d)!\n", ret);
		return 0;
	}
#endif
	return 1;
}

double
MicroTime(void) {
	struct timeval tv;
	double tmp;


	if (gettimeofday(&tv, NULL) == -1) {
		fprintf(stderr, "MicroTime: gettimeofday failed!\n");
		tmp = -1;
	} else {
		tmp = (double)(tv.tv_sec) * 1000000 + (double)tv.tv_usec;
	}

	return tmp;
}


void
ReleaseSignal(int sig) {
#ifdef HAVE_SIGRELSE
	sigrelse(sig);
#else
	sigset_t set, oset;
	sigemptyset(&set);
	sigaddset(&set, sig);
	sigprocmask(SIG_UNBLOCK, &set, &oset);
#endif
}


#ifdef USE_ALARM_SIGNAL
RETSIGTYPE
OsutilTimeOut(int sig) {
	WARN("Send/Receive timeout\n");
}
#endif


/* It should be thread safe (alarm is thread safe) */
void
SetRealTimer(unsigned int numberOfSecs) {
#ifdef USE_ALARM_SIGNAL
	static RETSIGTYPE (*was)(int) = NULL;
	RETSIGTYPE (*tmp)(int);

	if (numberOfSecs > 0) {
#ifdef HAVE_SIGINTERRUPT
		/* just interrupt a system call upon receipt of interrupt */
		siginterrupt(SIGALRM, 1);
#endif
		/* set the signal */
		tmp = signal(SIGALRM, OsutilTimeOut);
		if  (tmp == SIG_ERR) {
			WARN("SetRealTimer: call to signale failed!\n");
		} else {
			GetNWSLock(&lock);
			/* save the old pointer */
			was = tmp;
			ReleaseNWSLock(&lock);
		}
	} else {
		/* reset the signal */
		GetNWSLock(&lock);
		tmp = was;
		was = NULL;
		ReleaseNWSLock(&lock);
		if (tmp != NULL) {
			if (signal(SIGALRM, tmp) == SIG_ERR) {
				WARN("SetRealTimer: call to signale failed!\n");
			}
		}
	}

	alarm(numberOfSecs);
#endif
}


void *
PortabilityRealloc(void *ptr, size_t size) {
	void *tmp;

	/* all of this to be sure that realloc won't choke on NULL or
	 * zero pointers */
	if (size > 0) {
		if (ptr == NULL) {
			/* normal malloc */
			tmp =  malloc(size);
		} else {
			/* normal realloc */
#ifdef HAVE_REALLOC
			tmp =  realloc(ptr, size);
#else
			tmp =  malloc(size);
			memcpy(tmp, ptr, size);
			free(ptr);
#endif

		}
	} else if (size == 0) {
		/* size is 0: free the memory */
		if (ptr != NULL) {
			free(ptr);
		}
		tmp = NULL;
	}

	return tmp;
}

pid_t
WaitChild() {
	pid_t pid = 0;
	int done = 0;

#ifdef HAVE_WAITPID
	do {
		pid = waitpid(-1, NULL, WNOHANG);
		if (pid != -1 || errno != EINTR) {
			done = 1;
		}
	} while (!done);
	
	/* the function ignores the error: we'll have few zombies */
	if (pid < 0) {
		pid = 0;
	}
#else 
	ERROR("WaitChild: waitpid non available on this system!\n");
#endif

	return pid;
}


int
PortabilitySelect(	int n,
			fd_set *readfs,
			fd_set *writefs,
			fd_set *exceptfs,
			struct timeval *timeout,
			int *err) {
	struct timeval tout, *p;
	int ret, tmp;
	double when, now;

#ifndef HAVE_SELECT
	/* what am I supposed to do?? */
	fprintf(stderr, "This system doesn't have select available??\n");
	exit(1);
#endif

	now = MicroTime();
	if (timeout != NULL)  {
		/* save the timeout (at least linux complain that you
		 * cannot trust tout after select returns) */
		when = now + timeout->tv_sec*1000000 + timeout->tv_usec;
		p = &tout;
	} else {
		when = 0;
		p = NULL;
	}

	/* loop through to avoid EINTR */
	do {
		if (timeout != NULL) {
			if (when < now) {
				/* ran out of time */
				ret = 0;
				tmp = ETIMEDOUT;
				break;
			}

			/* set the timeout */
			tout.tv_sec = (unsigned long)(when - now)/1000000;
			tout.tv_usec = (unsigned long)(when - now - (double)tout.tv_sec*1000000);
		}

		ret = select(n, readfs, writefs, exceptfs, p);
		tmp = errno;

		if (ret != -1 || (ret == -1 && tmp != EINTR)) {
			when = -1;
		}
		
		/* new time */
		now = MicroTime();
	} while (when >= now);

	if (err != NULL) {
		*err = tmp;
	}

	return ret;
}