File: utils.c

package info (click to toggle)
multitail 4.2.0-1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 660 kB
  • ctags: 812
  • sloc: ansic: 12,046; makefile: 91; sh: 19
file content (740 lines) | stat: -rw-r--r-- 16,124 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
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
#define _LARGEFILE64_SOURCE	/* required for GLIBC to enable stat64 and friends */
#include <errno.h>
#include <signal.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#include <sys/types.h>
#include <regex.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#include <glob.h>
#ifdef _POSIX_PRIORITY_SCHEDULING
#include <sched.h>
#endif
#include <pwd.h>
#include <sys/wait.h>
#include <fcntl.h>
#if defined(sun) || defined(__sun)
#include <sys/loadavg.h>
#endif
#include <dirent.h>

#include "version.h"
#include "error.h"
#include "mem.h"
#include "mt.h"
#include "term.h"
#include "globals.h"
#include "utils.h"


int find_path_max(void)
{
#ifdef PATH_MAX
	int path_max = PATH_MAX;
#else
	int path_max = pathconf("/", _PC_PATH_MAX);
	if (path_max <= 0)
	{
		if (errno) error_exit("find_path_max: pathconf(_PC_PATH_MAX) failed\n");

		path_max = 4096;
	}
	else
		path_max++; /* since its relative to root */
#endif
	if (path_max > 4096)
		path_max = 4096;

	return path_max;
}

int myrand(int max)
{
	return (int)(((double)max * (double)rand()) / (double)RAND_MAX);
}

ssize_t WRITE(int fd, char *whereto, size_t len)
{
	ssize_t cnt=0;

	while(len>0)
	{
		ssize_t rc;

		rc = write(fd, whereto, len);

		if (rc == -1)
		{
			if (errno != EINTR && errno != EAGAIN)
				error_exit("WRITE: Problem writing to filedescriptor\n");
		}
		else if (rc == 0)
		{
			break;
		}
		else
		{
			whereto += rc;
			len -= rc;
			cnt += rc;
		}
	}

	return cnt;
}

void get_load_values(double *v1, double *v2, double *v3)
{
#if !defined(__UCLIBC__) && (defined(__FreeBSD__) || defined(linux) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__) || defined(__GNU__) || defined(__sun) || defined(sun))
#if defined(__GLIBC__) && ( __GLIBC__ < 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 2))
	/* Older glibc doesn't have getloadavg() - use sysinfo() */
	/* thanks to Ville Herva for this code! */
	double scale = 1 << SI_LOAD_SHIFT;
	struct sysinfo si;

	if (sysinfo(&si) == -1)
	{
		/* let's exit: if these kind of system-
		 * calls start to fail, something must be
		 * really wrong
		 */
		error_exit("get_load: sysinfo() failed\n");
	}

	*v1 = (double)si.loads[0] / scale;
	*v2 = (double)si.loads[1] / scale;
	*v3 = (double)si.loads[2] / scale;
#else
	double loadavg[3];
	if (getloadavg(loadavg, 3) == -1)
	{
		/* see comment on sysinfo() */
		error_exit("get_load: getloadavg() failed\n");
	}
	*v1 = loadavg[0];
	*v2 = loadavg[1];
	*v3 = loadavg[2];
#endif
#else
	*v1 = *v2 = *v3 = -1.0;
#endif
}

int get_vmsize(pid_t pid)
{
	int vmsize = -1;
#if defined(linux)
	FILE *fh;
	int path_max = find_path_max();
	char *path = mymalloc(path_max, "path");

	snprintf(path, path_max, "/proc/%d/stat", pid);

	fh = fopen(path, "r");
	if (fh)
	{
		char *dummystr = mymalloc(path_max, "get_vmsize: temp string");
		char dummychar;
		int dummy;

		if (fscanf(fh, "%d %s %c %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d", &dummy, dummystr, &dummychar, &dummy, &dummy, &dummy, &dummy, &dummy, &dummy, &dummy, &dummy, &dummy, &dummy, &dummy, &dummy, &dummy, &dummy, &dummy, &dummy, &dummy, &dummy, &dummy, &vmsize) != 23)
			vmsize = -1;

		fclose(fh);

		myfree(dummystr);
	}

	myfree(path);
#endif

	return vmsize;
}

/** stop_process
 * - in:      int pid  pid of process
 * - returns: nothing
 * this function sends a TERM-signal to the given process, sleeps for 1009 microseconds
 * and then sends a KILL-signal to the given process if it still exists. the TERM signal
 * is send so the process gets the possibility to gracefully exit. if it doesn't do that
 * in 100 microseconds, it is terminated
 */
void stop_process(int pid)
{
	if (pid < 2)
		return;

	if (killpg(pid, SIGTERM) == -1)
	{
		if (errno != ESRCH)
			error_exit("stop_process: problem stopping child-process (%d)!\n", pid);
	}

	usleep(1000);

	/* process still exists? */
	if (killpg(pid, SIGTERM) == 0)
	{
		/* sleep for a millisecond... */
		usleep(1000);

		/* ...and then really terminate the process */
		if (killpg(pid, SIGKILL) == -1)
		{
			if (errno != ESRCH)
				error_exit("stop_process: problem killing child-process (%d)!\n", pid);
		}
	}
	else if (errno != ESRCH)
		error_exit("stop_process: problem stopping child-process (%d)!\n", pid);

	/* wait for the last remainder of the exited process to go away,
	 * otherwhise we'll find zombies on our way
	 */
	if (waitpid(pid, NULL, WNOHANG | WUNTRACED) == -1)
	{
		if (errno != ECHILD)
			error_exit("stop_process: waitpid failed\n");
	}
}

/** delete_array
 * - in:      char **list array of strings to free
 *            int n       number of strings in this array
 * - returns: nothing
 * this function frees an array of strings: all strings are freed and
 * also the pointer-list itself is freed
 */
void delete_array(char **list, int n)
{
	int loop;

	for(loop=n-1; loop>=0; loop--)
		myfree(list[loop]);

	myfree(list);
}

int find_char_offset(char *str, char what)
{
	char *pnt = strchr(str, what);
	if (!pnt)
		return -1;

	return (int)(pnt - str);
}

int file_info(char *filename, off64_t *file_size, time_field_t tft, time_t *ts, mode_t *mode)
{
	struct stat64 buf;

	if (stat64(filename, &buf) == -1)
	{
		if (errno != ENOENT)
			error_exit("file_info: error while doing stat() on file %s\n", filename);

		return -1;
	}

	if (file_size) *file_size = buf.st_size;

	if (ts)
	{
		if (tft == TT_ATIME)
			*ts = buf.st_atime;
		else if (tft == TT_MTIME)
			*ts = buf.st_mtime;
		else if (tft == TT_CTIME)
			*ts = buf.st_ctime;
		else if (tft != 0)
			error_exit("file_info: invalid timefield (%d)\n", (int)tft);
	}

	if (mode) *mode = buf.st_mode;

	return 0;
}

int file_exist(char *filename)
{
	struct stat64 buf;

	return stat64(filename, &buf);
}

char * convert_regexp_error(int error, const regex_t *preg)
{
	/* errors are specified not to be longer then 256 characters */
	char *multitail_string = "MultiTail warning: regular expression failed, reason: ";
	int len = strlen(multitail_string);
	char *error_out = NULL;
	const int max_err_len = 256;

	if (error != 0 && error != REG_NOMATCH)
	{
		error_out = (char *)mymalloc(max_err_len + len + 1, "convert_regexp_error: regexp error string");

		memcpy(error_out, multitail_string, len);

		/* convert regexp error */
		regerror(error, preg, &error_out[len], max_err_len);
	}

	return error_out;
}

/* I'm sorry for this: */
char check_date(void)
{
	time_t now = time(NULL);
	struct tm *ptm = localtime(&now);

	if (ptm -> tm_mon == (4 - 1) && ptm -> tm_mday == 2) /* April the 2nd? */
	{
		return 1;
	}

	return 0;
}

char * amount_to_str(long long int amount)
{
	char *out = mymalloc(AMOUNT_STR_LEN, "amount_to_str: converted amount string");	/* ...XB\0 */

	if (amount >= M_GB)	/* GB */
		snprintf(out, AMOUNT_STR_LEN, "%dGB", (int)((amount + M_GB - 1) / M_GB));
	else if (amount >= M_MB)	/* MB */
		snprintf(out, AMOUNT_STR_LEN, "%dMB", (int)((amount + M_MB - 1) / M_MB));
	else if (amount >= M_KB)	/* KB */
		snprintf(out, AMOUNT_STR_LEN, "%dKB", (int)((amount + M_KB - 1) / M_KB));
	else
		snprintf(out, AMOUNT_STR_LEN, "%d", (int)(amount));

	return out;
}

struct passwd *getuserinfo(void)
{
	struct passwd *pp = getpwuid(geteuid());
	if (!pp)
		error_exit("getuserinfo: failed to get passwdstructure for effective user id %d\n", geteuid());

	return pp;
}

char * getusername(void)
{
	static char username[128] = { 0 };

	if (!username[0])
	{
		strncpy(username, getuserinfo() -> pw_name, sizeof(username));
		username[sizeof(username) - 1] = 0x00;
	}

	return username;
}

/* these are there because AIX/IRIX can return EINTR for those */
int myopen(char *path, int mode)
{
	int fd;

	for(;;)
	{
		fd = open64(path, mode);
		if (fd == -1)
		{
			if (errno == EINTR || errno == EAGAIN) /* for AIX */
				continue;

			return fd;
		}

		break;
	}

	return fd;
}

int myclose(int fd)
{
	for(;;)
	{
		if (close(fd) == -1)
		{
			if (errno == EINTR || errno == EAGAIN) /* for AIX */
				continue;

			return -1;
		}

		return 0;
	}
}

char * shorten_filename(char *in, int max_len)
{
	static char buffer[4096];
	int len = strlen(in);
	int cutlen, dummy;

	if (len <= max_len)
		return in;

	cutlen = (max_len - 3) / 2;

	memcpy(buffer, in, cutlen);
	memcpy(&buffer[cutlen], "...", 3);

	dummy = max_len - (cutlen + 3);
	memcpy(&buffer[cutlen + 3], &in[len - dummy], dummy + 1);

	return buffer;
}

double get_ts(void)
{
	struct timeval ts;
	struct timezone tz;

	if (gettimeofday(&ts, &tz) == -1)
		error_exit("get_ts: gettimeofday failed");

	return (((double)ts.tv_sec) + ((double)ts.tv_usec)/1000000.0);
}

int match_files(char *search_for, char **path, char ***found, char **isdir)
{
	DIR *dir;
	struct dirent *entry;
	char *cur_dir = mymalloc(find_path_max() + 1, "match_files: current file");
	char *fname;
	char **list = NULL;
	int nfound = 0;
	size_t fname_size;
	int path_len;
	int s1, s2;
	char *slash = strrchr(search_for, '/');
	if (slash)
	{
		fname = mystrdup(slash + 1, "match_files: filename");
		*(slash + 1) = 0x00;
		*path = mystrdup(search_for, "match_files: current path");
	}
	else
	{
		*path = mystrdup("./", "match_files: current path");
		fname = mystrdup(search_for, "match_files: filename");
	}
	fname_size = strlen(fname);
	path_len = strlen(*path);

	dir = opendir(*path);
	if (!dir)
	{
		free(cur_dir);
		return 0;
	}

	memcpy(cur_dir, *path, path_len + 1);

	while((entry = readdir(dir)) != NULL)
	{
		if ((fname_size == 0 || strncmp(entry -> d_name, fname, fname_size) == 0) && strcmp(entry -> d_name, ".") != 0 &&
				strcmp(entry -> d_name, "..") != 0)
		{
			struct stat finfo;

			/* get filename */
			list = (char **)myrealloc(list, (nfound + 1) * sizeof(char *), "match_files: directory list");
			list[nfound] = mystrdup(entry -> d_name, "match_files dir entry");

			/* check if the file is a directory */
			*isdir = (char *)myrealloc(*isdir, (nfound + 1) * sizeof(char), "ismatch_files: -dir list");
			strncpy(&cur_dir[path_len], entry -> d_name, max(0,find_path_max() - path_len));
			if (stat(cur_dir, &finfo) == -1)
			{
				if (errno != ENOENT)	/* file did not disappear? then something is very wrong */
					error_exit("match_files: stat error on %s\n", cur_dir);
			}
			(*isdir)[nfound] = S_ISDIR(finfo.st_mode)?1:0;

			nfound++;
		}
	}

	if (closedir(dir) == -1)
		error_exit("match_files: closedir failed\n");

	/*	qsort( (void *)list, (size_t)nfound, sizeof(char *), compare_filenames); */
	for(s1=0; s1<(nfound - 1); s1++)
	{
		for(s2=s1+1; s2<nfound; s2++)
		{
			if (strcasecmp(list[s2], list[s1]) < 0)
			{
				char *fdummy = list[s1], ddummy = (*isdir)[s1];

				list[s1] = list[s2];
				(*isdir)[s1] = (*isdir)[s2];
				list[s2] = fdummy;
				(*isdir)[s2] = ddummy;
			}
		}
	}

	*found = list;

	myfree(fname);
	myfree(cur_dir);

	return nfound;
}

void setup_for_childproc(int fd, char close_fd_0, char *term)
{
	char *dummy = (char *)mymalloc(strlen(term) + 6, "setup_for_childproc: TERM env var");

	if (close_fd_0) if (-1 == myclose(0)) error_exit("setup_for_childproc: close failed\n");
	if (-1 == myclose(1)) error_exit("setup_for_childproc: close failed\n");
	if (-1 == myclose(2)) error_exit("setup_for_childproc: close failed\n");
	if (close_fd_0) if (-1 == dup(fd)) error_exit("setup_for_childproc: dup failed\n");
	if (-1 == dup(fd)) error_exit("setup_for_childproc: dup failed\n");
	if (-1 == dup(fd)) error_exit("setup_for_childproc: dup failed\n");

	/*
	 * not doing this: it also clears the 'PATH'
	 * I could make first do a getenv for PATH and then put it
	 * back after the clearenv, but what would be the point of
	 * doing the clearenv in the first place?
	 *
	 *	if (clearenv() == -1)
	 *	{
	 *		fprintf(stderr, "WARNING: could not clear environment variables: %s (%d)\n", strerror(errno), errno);
	 *		exit(1);
	 *	}
	 */

	/* set terminal */
	sprintf(dummy, "TERM=%s", term);
	if (putenv(dummy) == -1)
		fprintf(stderr, "setup_for_childproc: Could not set TERM environment-variable (%s): %s (%d)\n", dummy, strerror(errno), errno);

	(void)umask(007);
}

int open_null(void)
{
	int fd = myopen("/dev/null", O_RDWR);
	if (fd == -1)
		error_exit("open_null: Failed to open /dev/null\n");

	return fd;
}

void free_re(re *cur_re)
{
	if (cur_re)
	{	
		myfree(cur_re -> regex_str);
		if (cur_re -> use_regex)
			regfree(&cur_re -> regex);

		myfree(cur_re -> cmd);
	}
}

char * find_most_recent_file(char *filespec, char *cur_file)
{
	glob_t files;
	char *selected_file = NULL;
	unsigned int loop;
	time_t prev_ts = (time_t)0;

	LOG("find file for %s\n", filespec);

	/* get timestamp of previous file */
	if (cur_file)
	{
		if (file_info(cur_file, NULL, TT_MTIME, &prev_ts, NULL) == -1)
		{
			LOG("could not get fileinfo for %s\n", cur_file);
			prev_ts = (time_t)0;
		}
	}

	/* get list of files that match */
#if defined(__APPLE__) || defined(__CYGWIN__)
	if (glob(filespec, GLOB_ERR | GLOB_NOSORT, NULL, &files) != 0)
#else
		if (glob(filespec, GLOB_ERR | GLOB_NOSORT | GLOB_NOESCAPE, NULL, &files) != 0)
#endif
		{
			LOG("glob failed %d\n", errno);
			return NULL;
		}

	LOG("number of files found: %d\n", files.gl_pathc);

	/* see if any of them is more recent than the current one */
	for(loop=0; loop<files.gl_pathc; loop++)
	{
		time_t new_ts;

		/* current file? then skip it */
		if (cur_file != NULL && strcmp(cur_file, files.gl_pathv[loop]) == 0)
			continue;

		/* get the modificationtime of this found file */
		if (file_info(files.gl_pathv[loop], NULL, TT_MTIME, &new_ts, NULL) == -1)
		{
			LOG("loop: failed fetching info on file %s: %d\n", files.gl_pathv[loop], errno);
			new_ts = (time_t)0;
		}

		/* more recent? */
		if (new_ts > prev_ts)
		{
			selected_file = files.gl_pathv[loop];
			prev_ts = new_ts;
		}
	}

	/* found a file? then remember the filename */
	if (selected_file != NULL)
	{
		selected_file = mystrdup(selected_file, "find_most_recent_file: new file filename");
	}

	globfree(&files);

	return selected_file;
}

char zerotomin(char c)
{
	if (c == 0)
		return 'n';
	if (c == 1)
		return 'y';

	return c;
}

char *find_next_par(char *start)
{
	char *dummy = strchr(start, ':');
	if (dummy)
	{
		*dummy = 0x00;
		dummy++;
	}

	return dummy;
}

int mydup(int old_fd)
{
	int new_fd = -1;

	for(;;)
	{
		new_fd = dup(old_fd);

		if (new_fd == -1)
		{
			if (errno == EINTR)
				continue;

			error_exit("mydup: dup() failed\n");
		}

		break;
	}

	return new_fd;
}

char * term_t_to_string(term_t term)
{
	switch(term)
	{
		case TERM_ANSI:
			return "ansi";

		case TERM_XTERM:
			return "xterm";
	}

	return "dumb";
}

void get_now_ts(char *format_str, char *dest, int dest_size)
{
	time_t now = time(NULL);
	struct tm *ptm = localtime(&now);
	if (!ptm) error_exit("get_now_ts: localtime() failed\n");

	(void)strftime(dest, dest_size, format_str, ptm);
}

void duplicate_re_array(re *pre_in, int n_rein, re **pre_out, int *n_reout)
{
	int loop, old_n = *n_reout;

	*n_reout += n_rein;
	*pre_out = (re *)myrealloc(*pre_out, (*n_reout) * sizeof(re), "duplicate re array");

	for(loop=0; loop<n_rein; loop++)
	{
		memcpy(&(*pre_out)[loop + old_n], &pre_in[loop], sizeof(re));
		memset(&(*pre_out)[loop + old_n].regex, 0x00, sizeof(regex_t));
		(*pre_out)[loop + old_n].regex_str = mystrdup(pre_in[loop].regex_str, "regex str");
		if (regcomp(&(*pre_out)[loop + old_n].regex, (*pre_out)[loop + old_n].regex_str, REG_EXTENDED))
			error_exit("duplicate_re_array: regex '%s' suddenly failed to compile\n", (*pre_out)[loop + old_n].regex_str);
	}
}

int find_filterscheme(char *name)
{
	int loop;

	for(loop=0; loop<n_fs; loop++)
	{
		if (strcmp(pfs[loop].fs_name, name) == 0)
			return loop;
	}

	return -1;
}

void compile_re(regex_t *whereto, char *what)
{
	/* compile & store regular expression */
	int rc = regcomp(whereto, what, REG_EXTENDED);
	if (rc != 0)
		error_exit("failed to compile regular expression '%s': %s\n", what, convert_regexp_error(rc, whereto));
}

void grow_mem_if_needed(char **what, int *cur_len, int requested_len)
{
	char changed = 0;

	while(*cur_len < requested_len)
	{
		changed = 1;

		if (*cur_len)
			(*cur_len) *= 2;
		else
			*cur_len = 128;
	}

	if (changed)
		*what = myrealloc(*what, *cur_len, "grow_mem_if_needed");
}