Support packets in flight
[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 #include "prox_compat.h"
26
27 static char file_error_string[128] = {0};
28
29 const char *file_get_error(void)
30 {
31         return file_error_string;
32 }
33
34 __attribute__((format(printf, 1 ,2))) static void file_set_error(const char *fmt, ...)
35 {
36         va_list ap;
37
38         va_start(ap, fmt);
39         vsnprintf(file_error_string, sizeof(file_error_string), fmt, ap);
40         va_end(ap);
41 }
42
43 static void resolve_path_cfg_dir(char *file_name, size_t len, const char *path)
44 {
45         if (path[0] != '/')
46                 snprintf(file_name, len, "%s/%s", get_cfg_dir(), path);
47         else
48                 prox_strncpy(file_name, path, len);
49 }
50
51 long file_get_size(const char *path)
52 {
53         char file_name[PATH_MAX];
54         struct stat s;
55
56         resolve_path_cfg_dir(file_name, sizeof(file_name), path);
57
58         if (stat(file_name, &s)) {
59                 file_set_error("Stat failed on '%s': %s", path, strerror(errno));
60                 return -1;
61         }
62
63         if ((s.st_mode & S_IFMT) != S_IFREG) {
64                 snprintf(file_error_string, sizeof(file_error_string), "'%s' is not a file", path);
65                 return -1;
66         }
67
68         return s.st_size;
69 }
70
71 int file_read_content(const char *path, uint8_t *mem, size_t beg, size_t len)
72 {
73         char file_name[PATH_MAX];
74         FILE *f;
75
76         resolve_path_cfg_dir(file_name, sizeof(file_name), path);
77         f = fopen(file_name, "r");
78         if (!f) {
79                 file_set_error("Failed to read '%s': %s", path, strerror(errno));
80                 return -1;
81         }
82
83         fseek(f, beg, SEEK_SET);
84
85         size_t ret = fread(mem, 1, len, f);
86         if ((uint32_t)ret !=  len) {
87                 file_set_error("Failed to read '%s:%zu' for %zu bytes: got %zu\n", file_name, beg, len, ret);
88                 return -1;
89         }
90
91         fclose(f);
92         return 0;
93 }