summaryrefslogtreecommitdiffstats
path: root/contrib/cvs/src/subr.c
blob: 6a97f287d5f404ced36b89088dd5f684fbafb712 (plain)
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
741
742
743
744
745
746
/*
 * Copyright (c) 1992, Brian Berliner and Jeff Polk
 * Copyright (c) 1989-1992, Brian Berliner
 * 
 * You may distribute under the terms of the GNU General Public License as
 * specified in the README file that comes with the CVS source distribution.
 * 
 * Various useful functions for the CVS support code.
 */

#include "cvs.h"
#include "getline.h"

extern char *getlogin ();

/*
 * malloc some data and die if it fails
 */
void *
xmalloc (bytes)
    size_t bytes;
{
    char *cp;

    /* Parts of CVS try to xmalloc zero bytes and then free it.  Some
       systems have a malloc which returns NULL for zero byte
       allocations but a free which can't handle NULL, so compensate. */
    if (bytes == 0)
	bytes = 1;

    cp = malloc (bytes);
    if (cp == NULL)
    {
	char buf[80];
	sprintf (buf, "out of memory; can not allocate %lu bytes",
		 (unsigned long) bytes);
	error (1, 0, buf);
    }
    return (cp);
}

/*
 * realloc data and die if it fails [I've always wanted to have "realloc" do
 * a "malloc" if the argument is NULL, but you can't depend on it.  Here, I
 * can *force* it.
 */
void *
xrealloc (ptr, bytes)
    void *ptr;
    size_t bytes;
{
    char *cp;

    if (!ptr)
	cp = malloc (bytes);
    else
	cp = realloc (ptr, bytes);

    if (cp == NULL)
    {
	char buf[80];
	sprintf (buf, "out of memory; can not reallocate %lu bytes",
		 (unsigned long) bytes);
	error (1, 0, buf);
    }
    return (cp);
}

/* Two constants which tune expand_string.  Having MIN_INCR as large
   as 1024 might waste a bit of memory, but it shouldn't be too bad
   (CVS used to allocate arrays of, say, 3000, PATH_MAX (8192, often),
   or other such sizes).  Probably anything which is going to allocate
   memory which is likely to get as big as MAX_INCR shouldn't be doing
   it in one block which must be contiguous, but since getrcskey does
   so, we might as well limit the wasted memory to MAX_INCR or so
   bytes.

   MIN_INCR and MAX_INCR should both be powers of two and we generally
   try to keep our allocations to powers of two for the most part.
   Most malloc implementations these days tend to like that.  */

#define MIN_INCR 1024
#define MAX_INCR (2*1024*1024)

/* *STRPTR is a pointer returned from malloc (or NULL), pointing to *N
   characters of space.  Reallocate it so that points to at least
   NEWSIZE bytes of space.  Gives a fatal error if out of memory;
   if it returns it was successful.  */
void
expand_string (strptr, n, newsize)
    char **strptr;
    size_t *n;
    size_t newsize;
{
    if (*n < newsize)
    {
	while (*n < newsize)
	{
	    if (*n < MIN_INCR)
		*n = MIN_INCR;
	    else if (*n >= MAX_INCR)
		*n += MAX_INCR;
	    else
	    {
		*n *= 2;
		if (*n > MAX_INCR)
		    *n = MAX_INCR;
	    }
	}
	*strptr = xrealloc (*strptr, *n);
    }
}

/*
 * Duplicate a string, calling xmalloc to allocate some dynamic space
 */
char *
xstrdup (str)
    const char *str;
{
    char *s;

    if (str == NULL)
	return ((char *) NULL);
    s = xmalloc (strlen (str) + 1);
    (void) strcpy (s, str);
    return (s);
}

/* Remove trailing newlines from STRING, destructively. */
void
strip_trailing_newlines (str)
     char *str;
{
    int len;
    len = strlen (str) - 1;

    while (str[len] == '\n')
	str[len--] = '\0';
}

/* Return the number of levels that path ascends above where it starts.
   For example:
   "../../foo" -> 2
   "foo/../../bar" -> 1
   */
/* FIXME: Should be using ISDIRSEP, last_component, or some other
   mechanism which is more general than just looking at slashes,
   particularly for the client.c caller.  The server.c caller might
   want something different, so be careful.  */
int
pathname_levels (path)
    char *path;
{
    char *p;
    char *q;
    int level;
    int max_level;

    max_level = 0;
    p = path;
    level = 0;
    do
    {
	q = strchr (p, '/');
	if (q != NULL)
	    ++q;
	if (p[0] == '.' && p[1] == '.' && (p[2] == '\0' || p[2] == '/'))
	{
	    --level;
	    if (-level > max_level)
		max_level = -level;
	}
	else if (p[0] == '.' && (p[1] == '\0' || p[1] == '/'))
	    ;
	else
	    ++level;
	p = q;
    } while (p != NULL);
    return max_level;
}


/* Free a vector, where (*ARGV)[0], (*ARGV)[1], ... (*ARGV)[*PARGC - 1]
   are malloc'd and so is *ARGV itself.  Such a vector is allocated by
   line2argv or expand_wild, for example.  */
void
free_names (pargc, argv)
    int *pargc;
    char **argv;
{
    register int i;

    for (i = 0; i < *pargc; i++)
    {					/* only do through *pargc */
	free (argv[i]);
    }
    free (argv);
    *pargc = 0;				/* and set it to zero when done */
}

/* Convert LINE into arguments separated by SEPCHARS.  Set *ARGC
   to the number of arguments found, and (*ARGV)[0] to the first argument,
   (*ARGV)[1] to the second, etc.  *ARGV is malloc'd and so are each of
   (*ARGV)[0], (*ARGV)[1], ...  Use free_names() to return the memory
   allocated here back to the free pool.  */
void
line2argv (pargc, argv, line, sepchars)
    int *pargc;
    char ***argv;
    char *line;
    char *sepchars;
{
    char *cp;
    /* Could make a case for size_t or some other unsigned type, but
       we'll stick with int to avoid signed/unsigned warnings when
       comparing with *pargc.  */
    int argv_allocated;

    /* Small for testing.  */
    /* argv_allocated must be at least 3 because at some places
       (e.g. checkout_proc) cvs alters argv[2].  */
    argv_allocated = 4;
    *argv = (char **) xmalloc (argv_allocated * sizeof (**argv));

    *pargc = 0;
    for (cp = strtok (line, sepchars); cp; cp = strtok ((char *) NULL, sepchars))
    {
	if (*pargc == argv_allocated)
	{
	    argv_allocated *= 2;
	    *argv = xrealloc (*argv, argv_allocated * sizeof (**argv));
	}
	(*argv)[*pargc] = xstrdup (cp);
	(*pargc)++;
    }
}

/*
 * Returns the number of dots ('.') found in an RCS revision number
 */
int
numdots (s)
    const char *s;
{
    int dots = 0;

    for (; *s; s++)
    {
	if (*s == '.')
	    dots++;
    }
    return (dots);
}

/* Compare revision numbers REV1 and REV2 by consecutive fields.
   Return negative, zero, or positive in the manner of strcmp.  The
   two revision numbers must have the same number of fields, or else
   compare_revnums will return an inaccurate result. */
int
compare_revnums (rev1, rev2)
    const char *rev1;
    const char *rev2;
{
    const char *s, *sp;
    const char *t, *tp;
    char *snext, *tnext;
    int result = 0;

    sp = s = rev1;
    tp = t = rev2;
    while (result == 0)
    {
	result = strtoul (sp, &snext, 10) - strtoul (tp, &tnext, 10);
	if (*snext == '\0' || *tnext == '\0')
	    break;
	sp = snext + 1;
	tp = tnext + 1;
    }

    return result;
}

char *
increment_revnum (rev)
    const char *rev;
{
    char *newrev, *p;
    int lastfield;
    size_t len = strlen (rev);

    newrev = (char *) xmalloc (len + 2);
    memcpy (newrev, rev, len + 1);
    p = strrchr (newrev, '.');
    if (p == NULL)
    {
	free (newrev);
	return NULL;
    }
    lastfield = atoi (++p);
    sprintf (p, "%d", lastfield + 1);

    return newrev;
}

/* Return the username by which the caller should be identified in
   CVS, in contexts such as the author field of RCS files, various
   logs, etc.  */
char *
getcaller ()
{
#ifndef SYSTEM_GETCALLER
    static char *cache;
    struct passwd *pw;
    uid_t uid;
#endif

    /* If there is a CVS username, return it.  */
#ifdef AUTH_SERVER_SUPPORT
    if (CVS_Username != NULL)
	return CVS_Username;
#endif

#ifdef SYSTEM_GETCALLER
    return SYSTEM_GETCALLER ();
#else
    /* Get the caller's login from his uid.  If the real uid is "root"
       try LOGNAME USER or getlogin(). If getlogin() and getpwuid()
       both fail, return the uid as a string.  */

    if (cache != NULL)
	return cache;

    uid = getuid ();
    if (uid == (uid_t) 0)
    {
	char *name;

	/* super-user; try getlogin() to distinguish */
	if (((name = getlogin ()) || (name = getenv("LOGNAME")) ||
	     (name = getenv("USER"))) && *name)
	{
	    cache = xstrdup (name);
	    return cache;
	}
    }
    if ((pw = (struct passwd *) getpwuid (uid)) == NULL)
    {
	char uidname[20];

	(void) sprintf (uidname, "uid%lu", (unsigned long) uid);
	cache = xstrdup (uidname);
	return cache;
    }
    cache = xstrdup (pw->pw_name);
    return cache;
#endif
}

#ifdef lint
#ifndef __GNUC__
/* ARGSUSED */
time_t
get_date (date, now)
    char *date;
    struct timeb *now;
{
    time_t foo = 0;

    return (foo);
}
#endif
#endif

/* Given two revisions, find their greatest common ancestor.  If the
   two input revisions exist, then rcs guarantees that the gca will
   exist.  */

char *
gca (rev1, rev2)
    const char *rev1;
    const char *rev2;
{
    int dots;
    char *gca;
    const char *p[2];
    int j[2];
    char *retval;

    if (rev1 == NULL || rev2 == NULL)
    {
	error (0, 0, "sanity failure in gca");
	abort();
    }

    /* The greatest common ancestor will have no more dots, and numbers
       of digits for each component no greater than the arguments.  Therefore
       this string will be big enough.  */
    gca = xmalloc (strlen (rev1) + strlen (rev2) + 100);

    /* walk the strings, reading the common parts. */
    gca[0] = '\0';
    p[0] = rev1;
    p[1] = rev2;
    do
    {
	int i;
	char c[2];
	char *s[2];
	
	for (i = 0; i < 2; ++i)
	{
	    /* swap out the dot */
	    s[i] = strchr (p[i], '.');
	    if (s[i] != NULL) {
		c[i] = *s[i];
	    }
	    
	    /* read an int */
	    j[i] = atoi (p[i]);
	    
	    /* swap back the dot... */
	    if (s[i] != NULL) {
		*s[i] = c[i];
		p[i] = s[i] + 1;
	    }
	    else
	    {
		/* or mark us at the end */
		p[i] = NULL;
	    }
	    
	}
	
	/* use the lowest. */
	(void) sprintf (gca + strlen (gca), "%d.",
			j[0] < j[1] ? j[0] : j[1]);

    } while (j[0] == j[1]
	     && p[0] != NULL
	     && p[1] != NULL);

    /* back up over that last dot. */
    gca[strlen(gca) - 1] = '\0';

    /* numbers differ, or we ran out of strings.  we're done with the
       common parts.  */

    dots = numdots (gca);
    if (dots == 0)
    {
	/* revisions differ in trunk major number.  */

	char *q;
	const char *s;

	s = (j[0] < j[1]) ? p[0] : p[1];

	if (s == NULL)
	{
	    /* we only got one number.  this is strange.  */
	    error (0, 0, "bad revisions %s or %s", rev1, rev2);
	    abort();
	}
	else
	{
	    /* we have a minor number.  use it.  */
	    q = gca + strlen (gca);
	    
	    *q++ = '.';
	    for ( ; *s != '.' && *s != '\0'; )
		*q++ = *s++;
	    
	    *q = '\0';
	}
    }
    else if ((dots & 1) == 0)
    {
	/* if we have an even number of dots, then we have a branch.
	   remove the last number in order to make it a revision.  */
	
	char *s;

	s = strrchr(gca, '.');
	*s = '\0';
    }

    retval = xstrdup (gca);
    free (gca);
    return retval;
}

/* Give fatal error if REV is numeric and ARGC,ARGV imply we are
   planning to operate on more than one file.  The current directory
   should be the working directory.  Note that callers assume that we
   will only be checking the first character of REV; it need not have
   '\0' at the end of the tag name and other niceties.  Right now this
   is only called from admin.c, but if people like the concept it probably
   should also be called from diff -r, update -r, get -r, and log -r.  */

void
check_numeric (rev, argc, argv)
    const char *rev;
    int argc;
    char **argv;
{
    if (rev == NULL || !isdigit ((unsigned char) *rev))
	return;

    /* Note that the check for whether we are processing more than one
       file is (basically) syntactic; that is, we don't behave differently
       depending on whether a directory happens to contain only a single
       file or whether it contains more than one.  I strongly suspect this
       is the least confusing behavior.  */
    if (argc != 1
	|| (!wrap_name_has (argv[0], WRAP_TOCVS) && isdir (argv[0])))
    {
	error (0, 0, "while processing more than one file:");
	error (1, 0, "attempt to specify a numeric revision");
    }
}

/*
 *  Sanity checks and any required fix-up on message passed to RCS via '-m'.
 *  RCS 5.7 requires that a non-total-whitespace, non-null message be provided
 *  with '-m'.  Returns a newly allocated, non-empty buffer with whitespace
 *  stripped from end of lines and end of buffer.
 *
 *  TODO: We no longer use RCS to manage repository files, so maybe this
 *  nonsense about non-empty log fields can be dropped.
 */
char *
make_message_rcslegal (message)
     char *message;
{
    char *dst, *dp, *mp;

    if (message == NULL) message = "";

    /* Strip whitespace from end of lines and end of string. */
    dp = dst = (char *) xmalloc (strlen (message) + 1);
    for (mp = message; *mp != '\0'; ++mp)
    {
	if (*mp == '\n')
	{
	    /* At end-of-line; backtrack to last non-space. */
	    while (dp > dst && (dp[-1] == ' ' || dp[-1] == '\t'))
		--dp;
	}
	*dp++ = *mp;
    }

    /* Backtrack to last non-space at end of string, and truncate. */
    while (dp > dst && isspace ((unsigned char) dp[-1]))
	--dp;
    *dp = '\0';

    /* After all that, if there was no non-space in the string,
       substitute a non-empty message. */
    if (*dst == '\0')
    {
	free (dst);
	dst = xstrdup ("*** empty log message ***");
    }

    return dst;
}

/* Does the file FINFO contain conflict markers?  The whole concept
   of looking at the contents of the file to figure out whether there are
   unresolved conflicts is kind of bogus (people do want to manage files
   which contain those patterns not as conflict markers), but for now it
   is what we do.  */
int
file_has_markers (finfo)
    const struct file_info *finfo;
{
    FILE *fp;
    char *line = NULL;
    size_t line_allocated = 0;
    int result;

    result = 0;
    fp = CVS_FOPEN (finfo->file, "r");
    if (fp == NULL)
	error (1, errno, "cannot open %s", finfo->fullname);
    while (getline (&line, &line_allocated, fp) > 0)
    {
	if (strncmp (line, RCS_MERGE_PAT, sizeof RCS_MERGE_PAT - 1) == 0)
	{
	    result = 1;
	    goto out;
	}
    }
    if (ferror (fp))
	error (0, errno, "cannot read %s", finfo->fullname);
out:
    if (fclose (fp) < 0)
	error (0, errno, "cannot close %s", finfo->fullname);
    if (line != NULL)
	free (line);
    return result;
}

/* Read the entire contents of the file NAME into *BUF.
   If NAME is NULL, read from stdin.  *BUF
   is a pointer returned from malloc (or NULL), pointing to *BUFSIZE
   bytes of space.  The actual size is returned in *LEN.  On error,
   give a fatal error.  The name of the file to use in error messages
   (typically will include a directory if we have changed directory)
   is FULLNAME.  MODE is "r" for text or "rb" for binary.  */

void
get_file (name, fullname, mode, buf, bufsize, len)
    const char *name;
    const char *fullname;
    const char *mode;
    char **buf;
    size_t *bufsize;
    size_t *len;
{
    struct stat s;
    size_t nread;
    char *tobuf;
    FILE *e;
    size_t filesize;

    if (name == NULL)
    {
	e = stdin;
	filesize = 100;	/* force allocation of minimum buffer */
    }
    else
    {
	/* Although it would be cleaner in some ways to just read
	   until end of file, reallocating the buffer, this function
	   does get called on files in the working directory which can
	   be of arbitrary size, so I think we better do all that
	   extra allocation.  */

	if (CVS_STAT (name, &s) < 0)
	    error (1, errno, "can't stat %s", fullname);

	/* Convert from signed to unsigned.  */
	filesize = s.st_size;

	e = open_file (name, mode);
    }

    if (*bufsize < filesize)
    {
	*bufsize = filesize;
	*buf = xrealloc (*buf, *bufsize);
    }

    tobuf = *buf;
    nread = 0;
    while (1)
    {
	size_t got;

	got = fread (tobuf, 1, *bufsize - (tobuf - *buf), e);
	if (ferror (e))
	    error (1, errno, "can't read %s", fullname);
	nread += got;
	tobuf += got;

	if (feof (e))
	    break;

	/* Allocate more space if needed.  */
	if (tobuf == *buf + *bufsize)
	{
	    int c;
	    long off;

	    c = getc (e);
	    if (c == EOF)
		break;
	    off = tobuf - *buf;
	    expand_string (buf, bufsize, *bufsize + 100);
	    tobuf = *buf + off;
	    *tobuf++ = c;
	    ++nread;
	}
    }

    if (e != stdin && fclose (e) < 0)
	error (0, errno, "cannot close %s", fullname);

    *len = nread;

    /* Force *BUF to be large enough to hold a null terminator. */
    if (*buf != NULL)
    {
	if (nread == *bufsize)
	    expand_string (buf, bufsize, *bufsize + 1);
	(*buf)[nread] = '\0';
    }
}


/* Follow a chain of symbolic links to its destination.  FILENAME
   should be a handle to a malloc'd block of memory which contains the
   beginning of the chain.  This routine will replace the contents of
   FILENAME with the destination (a real file).  */

void
resolve_symlink (filename)
     char **filename;
{
    if ((! filename) || (! *filename))
	return;

    while (islink (*filename))
    {
	char *newname;
#ifdef HAVE_READLINK
	/* The clean thing to do is probably to have each filesubr.c
	   implement this (with an error if not supported by the
	   platform, in which case islink would presumably return 0).
	   But that would require editing each filesubr.c and so the
	   expedient hack seems to be looking at HAVE_READLINK.  */
	newname = xreadlink (*filename);
#else
	error (1, 0, "internal error: islink doesn't like readlink");
#endif
	
	if (isabsolute (newname))
	{
	    free (*filename);
	    *filename = newname;
	}
	else
	{
	    char *oldname = last_component (*filename);
	    int dirlen = oldname - *filename;
	    char *fullnewname = xmalloc (dirlen + strlen (newname) + 1);
	    strncpy (fullnewname, *filename, dirlen);
	    strcpy (fullnewname + dirlen, newname);
	    free (newname);
	    free (*filename);
	    *filename = fullnewname;
	}
    }
}
OpenPOWER on IntegriCloud