Adding PROX(Packet pROcessing eXecution engine) VNF to sampleVNF
[samplevnf.git] / VNFs / DPPD-PROX / file_utils.c
1 /*
2 // Copyright (c) 2010-2017 Intel Corporation
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //     http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 */
16
17 #include <stdio.h>
18 #include <limits.h>
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <unistd.h>
22
23 #include "prox_args.h"
24 #include "file_utils.h"
25
26 static char file_error_string[128] = {0};
27
28 const char *file_get_error(void)
29 {
30         return file_error_string;
31 }
32
33 __attribute__((format(printf, 1 ,2))) static void file_set_error(const char *fmt, ...)
34 {
35         va_list ap;
36
37         va_start(ap, fmt);
38         vsnprintf(file_error_string, sizeof(file_error_string), fmt, ap);
39         va_end(ap);
40 }
41
42 static void resolve_path_cfg_dir(char *file_name, size_t len, const char *path)
43 {
44         if (path[0] != '/')
45                 snprintf(file_name, len, "%s/%s", get_cfg_dir(), path);
46         else
47                 strncpy(file_name, path, len);
48 }
49
50 long file_get_size(const char *path)
51 {
52         char file_name[PATH_MAX];
53         struct stat s;
54
55         resolve_path_cfg_dir(file_name, sizeof(file_name), path);
56
57         if (stat(file_name, &s)) {
58                 file_set_error("Stat failed on '%s': %s", path, strerror(errno));
59                 return -1;
60         }
61
62         if ((s.st_mode & S_IFMT) != S_IFREG) {
63                 snprintf(file_error_string, sizeof(file_error_string), "'%s' is not a file", path);
64                 return -1;
65         }
66
67         return s.st_size;
68 }
69
70 int file_read_content(const char *path, uint8_t *mem, size_t beg, size_t len)
71 {
72         char file_name[PATH_MAX];
73         FILE *f;
74
75         resolve_path_cfg_dir(file_name, sizeof(file_name), path);
76         f = fopen(file_name, "r");
77         if (!f) {
78                 file_set_error("Failed to read '%s': %s", path, strerror(errno));
79                 return -1;
80         }
81
82         fseek(f, beg, SEEK_SET);
83
84         size_t ret = fread(mem, 1, len, f);
85         if ((uint32_t)ret !=  len) {
86                 file_set_error("Failed to read '%s:%zu' for %zu bytes: got %zu\n", file_name, beg, len, ret);
87                 return -1;
88         }
89
90         fclose(f);
91         return 0;
92 }