File: tools.c

package info (click to toggle)
binkd 0.9.5a-4
  • links: PTS
  • area: main
  • in suites: woody
  • size: 1,016 kB
  • ctags: 1,069
  • sloc: ansic: 9,838; makefile: 750; sh: 223; perl: 89
file content (733 lines) | stat: -rw-r--r-- 15,001 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
/*
 *  tools.c -- misc utils
 *
 *  tools.c is a part of binkd project
 *
 *  Copyright (C) 1996-1998  Dima Maloff, 5047/13
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version. See COPYING.
 */

/*
 * $Id: tools.c,v 2.0 2001/01/10 12:12:39 gul Exp $
 *
 * $Log: tools.c,v $
 * Revision 2.0  2001/01/10 12:12:39  gul
 * Binkd is under CVS again
 *
 * Revision 1.18  1998/05/05  04:37:54  mff
 * Now we add trailing '\n' to pids in pidfiles, added 2nd arg to strquote(),
 * added strdequote(), strwipe() does not touch ' ' and 0xff any more,
 * added istic(), ispkt(), isarcmail().
 *
 * Revision 1.17  1997/10/23  03:31:49  mff
 * minor bug fixes in mkpath*() (again!), added mutex into Log(),
 * stricmp() -> STRICMP(), getwordx() moved to getw.c, minor fixes.
 *
 * Revision 1.16  1997/06/16  05:38:21  mff
 * Changed Log() -> syslog() loglevel mapping, fixed endless recursion
 * in Log() when calling assert() from Log()
 *
 * Revision 1.15  1997/05/17  11:18:14  mff
 * + get_os_string()
 *
 * Revision 1.14  1997/05/17  08:40:35  mff
 * assert() in Log() changed a bit
 *
 * Revision 1.13  1997/05/08  05:23:20  mff
 * Fixed syslog feature of Log()
 *
 * Revision 1.12  1997/03/28  06:10:12  mff
 * + ed()
 *
 * Revision 1.11  1997/03/15  05:03:32  mff
 * added touch()
 *
 * Revision 1.10  1997/03/09  07:15:30  mff
 * GWX_*, syslog
 *
 * Revision 1.9  1997/02/07  06:45:52  mff
 * getwordx now handles not only first `#' as comment. Though it can be
 * quoted with "" or \. TODO: bitmapped arg to turn this and var substing off
 *
 * Revision 1.8  1997/01/09  05:33:35  mff
 * Now we don't mkdir("") (Thanks to Mike Malakhov)
 *
 * Revision 1.7  1996/12/29  09:47:42  mff
 * Added: create_empty_sem_file()
 *
 * Revision 1.6  1996/12/14  07:13:51  mff
 * log() is now Log()
 *
 * Revision 1.5  1996/12/05  08:01:11  mff
 * Changed parse_args(), removed free_args()
 *
 * Revision 1.4  1996/12/05  07:24:35  mff
 * Format strings for Log() should have no "\n" at the end
 *
 * Revision 1.3  1996/12/05  04:30:14  mff
 * Now we don't mkdir drives
 */
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#if defined (HAVE_VSYSLOG) && defined (HAVE_FACILITYNAMES)
#include <syslog.h>
#endif

#include "assert.h"
#include "Config.h"
#include "sys.h"
#include "tools.h"
#include "readdir.h"		       /* for [sys/]utime.h */
#include "readcfg.h"
#include "sem.h"

#ifdef WIN32
extern int isService;
#endif

/*
 * Lowercase the string
 */
char *strlower (char *s)
{
  int i;

  for (i = 0; s[i]; ++i)
    s[i] = (char) tolower (s[i]);
  return s;
}

int mkpath0 (const char *path0)
{
  struct stat sb;

  if (stat (path0, &sb) == -1)
  {
    char *path, *s;
    int retval;

    if ((path = strdup (path0)) == NULL)
    {
      errno = ENOMEM;
      return -1;
    }
    if ((s = max (strrchr (path, '\\'), strrchr (path, '/'))) != 0)
    {
      *(s++) = 0;
      if (*path && mkpath0 (path) == -1)
      {
	free (path);
	return -1;
      }
    }
    else
      s = path;

    if (path0[strlen (path0) - 1] == ':')
      retval = 0;		       /* we found the device part of the
				        * path */
    else
      retval = MKDIR (path0);

    free (path);
    return retval;
  }
  else if (sb.st_mode & S_IFDIR)
  {
    return 0;
  }
  else
  {
    errno = ENOTDIR;
    return -1;
  }
}

int mkpath (char *s)
{
  char path[MAXPATHLEN];

  strnzcpy (path, s, MAXPATHLEN);
  if ((s = max (strrchr (path, '\\'), strrchr (path, '/'))) == 0)
    return 0;
  *s = 0;
  return mkpath0 (path);
}

unsigned long rnd ()
{
  static int i;

  if (!i)
  {
    i = 1;
    srand ((unsigned int)time (0));
  }
  return (time (0) + rand ()) & 0xFFFFFFFFul;
}

/*
 * 1 -- created, 0 -- already busy
 */
int create_empty_sem_file (char *name)
{
  int h;

  if ((h = open (name, O_RDWR | O_CREAT | O_EXCL, 0666)) == -1)
    return 0;
  close (h);
  return 1;
}

int create_sem_file (char *name)
{
  int h, i;
  char buf[10];

  if ((h = open (name, O_RDWR | O_CREAT | O_EXCL, 0666)) == -1)
  { Log (5, "Can't create %s: %s", name, strerror(errno));
    return 0;
  }
  sprintf (buf, "%i\n", (int) getpid ());
  if ((i = write(h, buf, strlen(buf))) != (int)strlen(buf))
  { if (i == -1)
      Log (2, "Can't write to %s (handle %d): %s", name, h, strerror(errno));
    else
      Log (2, "Can't write %d bytes to %s, wrote only %d", strlen(buf), name, i);
  }
  close (h);
  Log (5, "created %s", name);
  return 1;
}

#if defined(EMX) || defined(__WATCOMC__)
#include <malloc.h>		       /* for _heapchk() */
#endif

void Log (int lev, char *s,...)
{
#if defined(HAVE_THREADS) || defined(AMIGA)

  static MUTEXSEM LSem;

#endif
#if defined (HAVE_VSYSLOG) && defined (HAVE_FACILITYNAMES)

  extern int syslog_facility;

#endif

  static int first_time = 1;
  char timebuf[60];
  time_t t;
  struct tm *tm;
  va_list ap;
  static const char *marks = "!?+-";
  char ch = (char)((0 <= lev && lev < (int) strlen (marks)) ? marks[lev] : ' ');

  if (first_time == 1)
  {
    InitSem (&LSem);
    first_time = 2;
  }

  time (&t);
  tm = localtime (&t);

  if (lev <= conlog)
  {
    strftime (timebuf, sizeof (timebuf), "%H:%M", tm);
    LockSem (&LSem);
    fprintf (stderr, "%30.30s\r%c %s [%i] ", " ", ch, timebuf, (int) PID ());
    va_start (ap, s);
    vfprintf (stderr, s, ap);
    va_end (ap);
    if (lev >= 0)
      fputc ('\n', stderr);
    ReleaseSem (&LSem);
    if (lev < 0)
      return;
  }

  if (lev <= loglevel && *logpath)
  {
    FILE *logfile = 0;
    int i;

    LockSem (&LSem);
    for (i = 0; logfile == 0 && i < 10; ++i)
    {
      logfile = fopen (logpath, "a");
    }
    if (logfile)
    {
      if (first_time)
      {
	fputc ('\n', logfile);
	first_time = 0;
      }
      strftime (timebuf, sizeof (timebuf), "%d %b %H:%M:%S", tm);
      fprintf (logfile, "%c %s [%i] ", ch, timebuf, (int) PID ());
      va_start (ap, s);
      vfprintf (logfile, s, ap);
      va_end (ap);
      fputc ('\n', logfile);
      fclose (logfile);
    }
    else
      fprintf (stderr, "Cannot open %s: %s!\n", logpath, strerror (errno));
    ReleaseSem (&LSem);
  }
#ifdef WIN32
  if((!lev)&&(isService))
  {
    char tmp[256];
    va_start (ap, s);
    vsprintf (tmp, s, ap);
    va_end (ap);
    MessageBox(NULL, tmp, MYNAME, MB_OK|MB_ICONSTOP|0x00200000L|MB_SYSTEMMODAL|MB_SETFOREGROUND);
  }
#endif

#if defined (HAVE_VSYSLOG) && defined (HAVE_FACILITYNAMES)
  if (lev <= loglevel && syslog_facility >= 0)
  {
    static int opened = 0;
    static int log_levels[] =
    {
      /* Correspondence between binkd's loglevel and syslog's priority */
      LOG_ERR,			       /* 0 */
      LOG_WARNING,		       /* 1 */
      LOG_NOTICE,		       /* 2 */
      LOG_INFO,			       /* 3 */
      LOG_INFO,			       /* 4 */
      LOG_INFO,			       /* 5 */
      LOG_INFO,			       /* 6 */
      LOG_DEBUG			       /* other */
    };

    if (!opened)
    {
      opened = 1;
      openlog ("binkd", LOG_PID, syslog_facility);
    }

    if (lev < 0 || lev >= sizeof log_levels / sizeof (int))
      lev = sizeof log_levels / sizeof (int) - 1;

    va_start (ap, s);
    vsyslog (log_levels[lev], s, ap);
    va_end (ap);

  }
#endif

  if (lev == 0)
    exit (1);

#if defined(EMX) || defined(__WATCOMC__)
/*
  assert (_heapchk () == _HEAPOK || _heapchk () == _HEAPEMPTY);
*/
#endif
}

int o_memicmp (const void *s1, const void *s2, size_t n)
{
  int i;

  for (i = 0; i < (int) n; ++i)
    if (tolower (((char *) s1)[i]) != tolower (((char *) s2)[i]))
      return (tolower (((char *) s1)[i]) - tolower (((char *) s2)[i]));

  return 0;
}

int o_stricmp (const char *s1, const char *s2)
{
  int i;

  for (i = 0;; ++i)
  {
    if (tolower (s1[i]) != tolower (s2[i]))
      return (tolower (s1[i]) - tolower (s2[i]));
    if (!s1[i])
      return 0;
  }
}

int o_strnicmp (const char *s1, const char *s2, size_t n)
{
  int i;

  for (i = 0; i < (int) n; ++i)
  {
    if (tolower (s1[i]) != tolower (s2[i]))
      return (tolower (s1[i]) - tolower (s2[i]));
    if (!s1[i])
      return 0;
  }
  return 0;
}

/*
 * Quotes all special chars. free() it's retval!
 */
char *strquote (char *s, int flags)
{
  char *r = xalloc (strlen (s) * 4 + 1);
  int i;

  for (i = 0; *s; ++s)
  {
    if (((flags & SQ_CNTRL) && iscntrl (*s)) ||
	((flags & SQ_SPACE) && isspace (*s)) ||
	(*s == '\\'))
    {
      sprintf (r + i, "\\x%02x", *(unsigned char *) s);
      i += 4;
    }
    else
      r[i++] = *s;
  }
  r[i] = 0;
  return r;
}

/*
 * Reverse for strquote(), free it's return value!
 */
char *strdequote (char *s)
{
  char *r = xstrdup (s);
  int i = 0;

  while (*s)
  {
    if (s[0] == '\\' && s[1] == 'x' && isxdigit (s[2]) && isxdigit (s[3]))
    {
#define XD(x) (isdigit(x) ? ((x)-'0') : (tolower(x)-'a'+10))
      r[i++] = (char) (XD (s[2]) * 16 + XD (s[3]));
      s += 4;
#undef XD
    }
    else
      r[i++] = *(s++);
  }
  r[i] = 0;
  return r;
}

/*
 * Makes file system-safe names by wiping suspicious chars with '_'
 */
char *strwipe (char *s)
{
  int i;

  for (i = 0; s[i]; ++i)
    if ((iscntrl (s[i]) || s[i] == '\\' || s[i] == '/' || s[i] == ':')
#ifdef WIN32 /* ungly hack */
        && (s[i] & 0x80 == 0)
#endif
       )
      s[i] = '_';
  return s;
}

/*
 * Copyes not more than len chars from src into dst, but, unlike strncpy(),
 * it appends '\0' even if src is longer than len.
 */
char *strnzcpy (char *dst, const char *src, size_t len)
{
  dst[len - 1] = 0;
  return strncpy (dst, src, len - 1);
}

char *strnzcat (char *dst, const char *src, size_t len)
{
  int x = strlen (dst);

  return strnzcpy (dst + x, src, len - x);
}

/*
 * Splits args ASCIIZ string onto argc separate words,
 * saves them as argv[0]...argv[argc-1]. Logs error
 * "ID: cannot parse args", if args containes less than argc words.
 */
int parse_args (int argc, char *argv[], char *src, char *ID)
{
  int i = 0;

  while (i < argc)
  {
    while (*src && isspace (*src))
      ++src;
    if (!*src)
      break;
    argv[i] = src;
    while (*src && !isspace (*src))
      ++src;
    ++i;
    if (!*src)
      break;
    src++[0] = 0;
  }
  if (i < argc)
  {
    Log (1, "%s: cannot parse args", ID, src);
    return 0;
  }
  else
    return 1;
}

/*
 * Set times for a file, 0 == success, -1 == error
 */
int touch (char *file, time_t t)
{
#ifndef OS2
  struct utimbuf utb;

  utb.actime = utb.modtime = t;
  return utime (file, &utb);
#else /* FastEcho deletes *.bsy by ctime :-( */
  APIRET r;
  FILESTATUS3 buf;
  struct stat st;

  if ((r = stat(file, &st)) == 0)
  {
    struct tm *tm;
#ifdef __WATCOMC__
    struct tm stm;
    tm = &stm;
    _localtime(&t, tm);
#else
    tm=localtime(&t);
#endif
    buf.fdateCreation.day=buf.fdateLastAccess.day=buf.fdateLastWrite.day=
        tm->tm_mday;
    buf.fdateCreation.month=buf.fdateLastAccess.month=buf.fdateLastWrite.month=
        tm->tm_mon+1;
    buf.fdateCreation.year=buf.fdateLastAccess.year=buf.fdateLastWrite.year=
        tm->tm_year-80;
    buf.ftimeCreation.twosecs=buf.ftimeLastAccess.twosecs=buf.ftimeLastWrite.twosecs=
        tm->tm_sec/2;
    buf.ftimeCreation.minutes=buf.ftimeLastAccess.minutes=buf.ftimeLastWrite.minutes=
        tm->tm_min;
    buf.ftimeCreation.hours=buf.ftimeLastAccess.hours=buf.ftimeLastWrite.hours=
        tm->tm_hour;
    buf.cbFile = buf.cbFileAlloc = st.st_size;
    buf.attrFile = FILE_ARCHIVED | FILE_NORMAL;
    r=DosSetPathInfo(file, FIL_STANDARD, &buf, sizeof(buf), 0);
    if (r == 32)
      r = 0; /* Can't touch opened *.bsy */
    if (r)
      Log (1, "touch: DosSetPathInfo(%s) retcode %d", file, r);
  }
  return (r!=0);
#endif
}

/*
 * Replaces all entries of a in s for b, returns edited line.
 * Returned value must be free()'d. Ignores case.
 * size parameter can be used only if "s" was created by malloc()
 */
char *ed (char *s, char *a, char *b, unsigned int *size)
{
   int i, j;
   unsigned int sz;
   int len_a=a?strlen(a):0;
   int len_b=b?strlen(b):0;
   char *r=s;
   
   if((!len_a)||(!s)) return r;
   if(!size) 
   {
     sz=strlen(s)+1;
     r=xstrdup(s);
   }
   else sz=*size;
   for(i=j=0;i<(int)strlen(r);i++)
   {
     if(r[i]!=a[j])
     {
       i-=j;
       j=0;
       continue;
     }
     j++;
     if(a[j]) continue;
     if(strlen(r)-len_a+len_b+1>sz)
     {
       if(len_b<64) sz+=64;
       else sz+=len_b;
       r=xrealloc(r, sz);
     }
     i-=len_a-1;
     memmove(r+i+len_b, r+i+len_a, strlen(r+i+len_a)+1);
     if(len_b)
       memcpy(r+i, b, len_b);
     j=0;
     i+=len_b-1;
   }
   if(size) *size=sz;
   return r;
}

/*
 * Remove/trucate a file, log this
 */
int delete (char *path)
{
  int rc;

  if ((rc = unlink (path)) != 0)
    Log (1, "error unlinking `%s': %s", path, strerror (errno));
  else
    Log (5, "unlinked `%s'", path);

  return rc;
}

int trunc (char *path)
{
  int h;

  if ((h = open (path, O_WRONLY | O_TRUNC)) == -1)
  {
    Log (1, "cannot truncate `%s': %s", path, strerror (errno));
    return -1;
  }
  else
  {
    Log (4, "truncated %s", path);
    close (h);
    return 0;
  }
}

/*
 * Get the string with OS name/version
 */
#ifdef HAVE_UNAME
#include <sys/utsname.h>
#endif

char *get_os_string ()
{
  static char os[80];

  strcpy (os, "/");

#ifdef HAVE_UNAME
  {
    struct utsname name;

    if (uname (&name) == 0)
    {
      strnzcat (os, name.sysname, sizeof (os));
      return os;
    }
  }
#endif

#ifdef OS
  strnzcat (os, OS, sizeof (os));
#else
  *os = 0;
#endif

  return os;
}

/*
 * Test netnames against some wildcards
 */
int ispkt (char *s)
{
  return pmatch ("*.[Pp][Kk][Tt]", s);
}

int istic (char *s)
{
  return pmatch ("*.?[Ii][Cc]", s);
}

int isarcmail (char *s)
{
  /* *.su? *.mo? *.tu? *.we? *.th? *.fr? *.sa? */
  return (pmatch ("*.[Ss][Uu]?", s) ||
	  pmatch ("*.[Mm][Oo]?", s) ||
	  pmatch ("*.[Tt][Uu]?", s) ||
	  pmatch ("*.[Ww][Ee]?", s) ||
	  pmatch ("*.[Tt][Hh]?", s) ||
	  pmatch ("*.[Ff][Rr]?", s) ||
	  pmatch ("*.[Ss][Aa]?", s));
}

/*
 * Formats and prints argv into buf (for logging purposes)
 */
void print_args (char *buf, size_t sizeof_buf, int argc, char *argv[])
{
  int i, j, quote;

  assert (sizeof_buf > 5);
  *buf = 0;
  for (i = 0; i < argc; ++i)
  {
    quote = 0;
    if (argv[i][0] == 0)
      quote = 1;
    else
      for (j = 0; argv[i][j]; ++j)
	if (argv[i][j] <= ' ')
	{
	  quote = 1;
	  break;
	}

    strnzcat (buf, " ", sizeof_buf);
    if (quote)
      strnzcat (buf, "\"", sizeof_buf);
    strnzcat (buf, argv[i], sizeof_buf);
    if (quote)
      strnzcat (buf, "\"", sizeof_buf);
  }
}

/*
 * Dup argv
 */
char **mkargv (int argc, char **argv)
{
  int i;
  char **p;

  p = (char **) xalloc ((argc + 1) * sizeof (p));

  for (i = 0; i < argc; i++)
    p[i] = xstrdup (argv[i]);

  p[i] = NULL;

  return p;
}