summaryrefslogtreecommitdiffhomepage
path: root/src/logic/tpax_file_create_memory_snapshot.c
blob: 7c1f90ee72398c3c5af2f42d71ba4024c2aafbdd (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
/**************************************************************/
/*  tpax: a topological pax implementation                    */
/*  Copyright (C) 2020--2021  SysDeer Technologies, LLC       */
/*  Released under GPLv2 and GPLv3; see COPYING.TPAX.         */
/**************************************************************/

#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <grp.h>
#include <pwd.h>
#include <sys/stat.h>

#include <tpax/tpax.h>
#include <tpax/tpax_specs.h>
#include "tpax_driver_impl.h"
#include "tpax_errinfo_impl.h"

#ifndef ssizeof
#define ssizeof(x) (ssize_t)(sizeof(x))
#endif

int tpax_file_create_memory_snapshot(
	const struct tpax_driver_ctx *  dctx,
	int                             fdat,
	const char *                    path,
	const struct stat *             srcst,
	void *                          addr)
{
	int          fd;
	char *       ch;
	char *       cap;
	ssize_t      nread;
	struct stat  dstst;

	/* record errors */
	tpax_driver_set_ectx(
		dctx,0,path);

	/* memory snapshot internal limit */
	if (srcst->st_size >= 0x80000000)
		return TPAX_CUSTOM_ERROR(dctx,TPAX_ERR_REGION_SIZE);

	/* open */
	if ((fd = openat(fdat,path,O_CLOEXEC|O_NOCTTY|O_NOFOLLOW,0)) < 0)
		return TPAX_SYSTEM_ERROR(dctx);

	/* stat compare */
	if ((fstat(fd,&dstst)) < 0) {
		close(fd);
		return TPAX_SYSTEM_ERROR(dctx);

	} else if (tpax_stat_compare(srcst,&dstst)) {
		close(fd);
		return TPAX_CUSTOM_ERROR(dctx,TPAX_ERR_FILE_CHANGED);
	}

	/* read loop */
	ch  = addr;
	cap = &ch[srcst->st_size];

	while (ch < cap) {
		nread = read(fd,ch,cap-ch);

		while ((nread < 0) && (errno == EINTR))
			nread = read(fd,ch,cap-ch);

		if (nread < 0) {
			close(fd);
			return TPAX_SYSTEM_ERROR(dctx);

		} else if (nread == 0) {
			close(fd);
			return TPAX_CUSTOM_ERROR(dctx,TPAX_ERR_FLOW_ERROR);

		} else {
			ch += nread;
		}
	}

	/* stat compare */
	if ((fstat(fd,&dstst)) < 0) {
		close(fd);
		return TPAX_SYSTEM_ERROR(dctx);

	} else if (tpax_stat_compare(srcst,&dstst)) {
		close(fd);
		return TPAX_CUSTOM_ERROR(dctx,TPAX_ERR_FILE_CHANGED);
	}

	/* yay */
	close(fd);

	return 0;
}