xref: /original-bsd/usr.bin/uucp/libuu/gename.c (revision 57124d5e)
1 #ifndef lint
2 static char sccsid[] = "@(#)gename.c	5.6 (Berkeley) 10/09/85";
3 #endif
4 
5 #include "uucp.h"
6 
7 #define SEQLEN 4
8 #define SLOCKTIME 10L
9 #define SLOCKTRIES 5
10 /*
11  * the alphabet can be anything, but if it's not in ascii order,
12  * sequence ordering is not preserved
13  */
14 static char alphabet[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
15 
16 #ifdef BSD4_2
17 #include <sys/file.h>
18 #endif BSD4_2
19 
20 /*LINTLIBRARY*/
21 
22 /*
23  *	generate file name
24  */
25 gename(pre, sys, grade, file)
26 char pre, *sys, grade, *file;
27 {
28 	register int i, fd;
29 	static char snum[5];
30 	static char *lastchar = NULL;
31 
32 	if (lastchar == NULL || (snum[SEQLEN-1] = *(lastchar++)) == '\0') {
33 #ifndef BSD4_2
34 		for (i = 0; i < SLOCKTRIES; i++) {
35 			if (!ulockf(SEQLOCK, SLOCKTIME))
36 				break;
37 			sleep(5);
38 		}
39 
40 		if (i >= SLOCKTRIES) {
41 			logent(SEQLOCK, "CAN NOT LOCK");
42 			goto getrandseq;
43 		}
44 #endif !BSD4_2
45 
46 		if ((fd = open(SEQFILE, 2)) >= 0) {
47 			register char *p;
48 #ifdef BSD4_2
49 			flock(fd, LOCK_EX);
50 #endif !BSD4_2
51 			read(fd, snum, SEQLEN);
52 			/* increment the penultimate character */
53 			for (i = SEQLEN - 2; i >= 0; --i) {
54 				if ((p = index(alphabet, snum[i])) == NULL)
55 					goto getrandseq;
56 				if (++p < &alphabet[sizeof alphabet - 1]) {
57 					snum[i] = *p;
58 					break;
59 				} else		/* carry */
60 					snum[i] = alphabet[0];	/* continue */
61 			}
62 			snum[SEQLEN-1] = alphabet[0];
63 		} else {
64 			extern int errno;
65 			fd = creat(SEQFILE, 0666);
66 getrandseq:		srand((int)time((time_t *)0));
67 			assert(SEQFILE, "is missing or trashed\n", errno);
68 			for (i = 0; i < SEQLEN; i++)
69 				snum[i] = alphabet[rand() % (sizeof alphabet - 1)];
70 			snum[SEQLEN-1] = alphabet[0];
71 		}
72 
73 		if (fd >= 0) {
74 			lseek(fd, 0L, 0);
75 			write(fd, snum, SEQLEN);
76 			close(fd);
77 		}
78 #ifndef BSD4_2
79 		rmlock(SEQLOCK);
80 #endif !BSD4_2
81 		lastchar = alphabet + 1;
82 	}
83 	sprintf(file,"%c.%.*s%c%.*s", pre, SYSNSIZE, sys, grade, SEQLEN, snum);
84 	DEBUG(4, "file - %s\n", file);
85 }
86