1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
6 #include "extract-word.h"
10 #include "string-table.h"
11 #include "string-util.h"
13 int open_file_parse(const char *v
, OpenFile
**ret
) {
14 _cleanup_free_
char *options
= NULL
;
15 _cleanup_(open_file_freep
) OpenFile
*of
= NULL
;
21 of
= new0(OpenFile
, 1);
25 r
= extract_many_words(&v
, ":", EXTRACT_DONT_COALESCE_SEPARATORS
|EXTRACT_CUNESCAPE
, &of
->path
, &of
->fdname
, &options
);
31 /* Enforce that at most 3 colon-separated words are present */
35 for (const char *p
= options
;;) {
37 _cleanup_free_
char *word
= NULL
;
39 r
= extract_first_word(&p
, &word
, ",", 0);
45 flag
= open_file_flags_from_string(word
);
49 if ((flag
& of
->flags
) != 0)
55 if (isempty(of
->fdname
)) {
56 of
->fdname
= mfree(of
->fdname
);
57 r
= path_extract_filename(of
->path
, &of
->fdname
);
62 r
= open_file_validate(of
);
71 int open_file_validate(const OpenFile
*of
) {
74 if (!path_is_valid(of
->path
) || !path_is_absolute(of
->path
))
77 if (!fdname_is_valid(of
->fdname
))
80 if ((FLAGS_SET(of
->flags
, OPENFILE_READ_ONLY
) + FLAGS_SET(of
->flags
, OPENFILE_APPEND
) +
81 FLAGS_SET(of
->flags
, OPENFILE_TRUNCATE
)) > 1)
84 if ((of
->flags
& ~_OPENFILE_MASK_PUBLIC
) != 0)
90 int open_file_to_string(const OpenFile
*of
, char **ret
) {
91 _cleanup_free_
char *options
= NULL
, *fname
= NULL
, *s
= NULL
;
92 bool has_fdname
= false;
98 s
= xescape(of
->path
, ":");
102 r
= path_extract_filename(of
->path
, &fname
);
106 has_fdname
= !streq(fname
, of
->fdname
);
108 if (!strextend(&s
, ":", of
->fdname
))
111 for (OpenFileFlag flag
= OPENFILE_READ_ONLY
; flag
< _OPENFILE_MAX
; flag
<<= 1)
112 if (FLAGS_SET(of
->flags
, flag
) && !strextend_with_separator(&options
, ",", open_file_flags_to_string(flag
)))
116 if (!(has_fdname
? strextend(&s
, ":", options
) : strextend(&s
, "::", options
)))
124 OpenFile
* open_file_free(OpenFile
*of
) {
134 static const char * const open_file_flags_table
[_OPENFILE_MAX
] = {
135 [OPENFILE_READ_ONLY
] = "read-only",
136 [OPENFILE_APPEND
] = "append",
137 [OPENFILE_TRUNCATE
] = "truncate",
138 [OPENFILE_GRACEFUL
] = "graceful",
141 DEFINE_STRING_TABLE_LOOKUP(open_file_flags
, OpenFileFlag
);