xref: /original-bsd/usr.bin/uucp/libuu/gename.c (revision e74403ba)
1 #ifndef lint
2 static char sccsid[] = "@(#)gename.c	5.2 (Berkeley) 07/19/83";
3 #endif
4 
5 #include "uucp.h"
6 #include <sys/types.h>
7 
8 #define SEQLEN 4
9 
10 /*******
11  *	gename(pre, sys, grade, file)	generate file name
12  *	char grade, *sys, pre, *file;
13  *
14  *	return codes:  none
15  */
16 
17 gename(pre, sys, grade, file)
18 char pre, *sys, grade, *file;
19 {
20 	static char sqnum[5];
21 
22 	getseq(sqnum);
23 	sprintf(file, "%c.%.7s%c%.*s", pre, sys, grade, SEQLEN, sqnum);
24 	DEBUG(4, "file - %s\n", file);
25 	return;
26 }
27 
28 
29 #define SLOCKTIME 10L
30 #define SLOCKTRIES 5
31 
32 /*******
33  *	getseq(snum)	get next sequence number
34  *	char *snum;
35  *
36  *	return codes:  none
37  */
38 
39 static
40 getseq(snum)
41 register char *snum;
42 {
43 	/*
44 	 * the alphabet can be anything, but if it's not in ascii order,
45 	 * sequence ordering is not preserved
46 	 */
47 	char	*alphabet =
48 	    "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
49 	register int i, fd;
50 	static char *lastchar;
51 
52 	if (lastchar == NULL || (snum[SEQLEN-1] = *(lastchar++)) == '\0') {
53 		for (i = 0; i < SLOCKTRIES; i++) {
54 			if (!ulockf(SEQLOCK, (time_t)SLOCKTIME))
55 				break;
56 			sleep(5);
57 		}
58 
59 		ASSERT(i < SLOCKTRIES, "CAN NOT GET", "SEQLOCK", 0);
60 
61 		if ((fd = open(SEQFILE, 2)) >= 0) {
62 			int alphalen;
63 			register char	*p;
64 			char *index();
65 
66 			alphalen = strlen(alphabet);
67 			read(fd, snum, SEQLEN);
68 			/* increment the penultimate character */
69 			for (i = SEQLEN - 2; i >= 0; --i) {
70 				if ((p = index(alphabet, snum[i])) == NULL) {
71 					/* drastic but effective */
72 					snum[i] = alphabet[alphalen - 1];
73 					DEBUG(6, "bad seqf: %s\n", snum);
74 				}
75 				if (++p < &alphabet[alphalen]) {
76 					snum[i] = *p;
77 					break;
78 				} else		/* carry */
79 					snum[i] = alphabet[0];	/* continue */
80 			}
81 			snum[SEQLEN-1] = alphabet[0];
82 		} else {
83 			if ((fd = creat(SEQFILE, 0666)) < 0)
84 				return(FAIL);
85 			for (i = 0; i < SEQLEN; i++)
86 				snum[i] = alphabet[0];
87 		}
88 
89 		lseek(fd, 0L, 0);
90 		write(fd, snum, SEQLEN);
91 		close(fd);
92 		rmlock(SEQLOCK);
93 		lastchar = alphabet + 1;
94 	}
95 	return(0);
96 }
97