summaryrefslogtreecommitdiffstats
path: root/common/bbs/fhdr_stamp.c
blob: 05c9bccf2fa349dc19e56942bd7b32fe22343168 (plain) (blame)
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
/* $Id$ */
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "cmsys.h"  // for time4_t
#include "cmbbs.h"

#if __GNUC__
#define GCC_WEAK __attribute__ ((weak))
#define GCC_INLINE __attribute__ ((always_inline))
#else
#define GCC_WEAK
#define GCC_INLINE
#endif

static inline int fhdr_stamp(char *fpath, fileheader_t *fh, int type) GCC_INLINE;
int stampfile(char *fpath, fileheader_t *fh) GCC_WEAK;
int stampdir(char *fpath, fileheader_t *fh) GCC_WEAK;
int stamplink(char *fpath, fileheader_t * fh) GCC_WEAK;

#define STAMP_FILE  0
#define STAMP_DIR   1
#define STAMP_LINK  2

static inline int
fhdr_stamp(char *fpath, fileheader_t *fh, int type)
{
    char       *ip = fpath;
    time4_t     dtime = time(0);
    struct tm   ptime;
    int         res = 0;

    if (access(fpath, X_OK | R_OK | W_OK))
    mkdir(fpath, 0755);

    while (*(++ip));
    *ip++ = '/';

    switch (type) {
    case STAMP_FILE:
        do {
        sprintf(ip, "M.%d.A.%3.3X", (int)(++dtime), (unsigned int)(random() & 0xFFF));
        } while ((res = open(fpath, O_CREAT | O_EXCL | O_WRONLY, 0644)) == -1 && errno == EEXIST);
        break;
    case STAMP_DIR:
        do {
        sprintf(ip, "D%X", (int)++dtime & 07777);
        } while ((res = mkdir(fpath, 0755)) == -1 && errno == EEXIST);
        break;
    case STAMP_LINK:
        do {
        sprintf(ip, "S%X", (int)++dtime);
        } while ((res = symlink("temp", fpath)) == -1 && errno == EEXIST);
        break;
    default:
        // unknown
        return -1;
        break;
    }

    if (res == -1)
    return -1;
    close(res);

    memset(fh, 0, sizeof(fileheader_t));
    strlcpy(fh->filename, ip, sizeof(fh->filename));
    localtime4_r(&dtime, &ptime);
    snprintf(fh->date, sizeof(fh->date), "%2d/%02d", ptime.tm_mon + 1, ptime.tm_mday);

    return 0;
}

int
stampfile(char *fpath, fileheader_t *fh)
{
    return fhdr_stamp(fpath, fh, STAMP_FILE);
}

int
stampdir(char *fpath, fileheader_t *fh)
{
    return fhdr_stamp(fpath, fh, STAMP_DIR);
}

int
stamplink(char *fpath, fileheader_t * fh)
{
    return fhdr_stamp(fpath, fh, STAMP_LINK);
}