1 /* wordsplit - a word splitter
2    Copyright (C) 2009-2018 Sergey Poznyakoff
3 
4    This program is free software; you can redistribute it and/or modify it
5    under the terms of the GNU General Public License as published by the
6    Free Software Foundation; either version 3 of the License, or (at your
7    option) any later version.
8 
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13 
14    You should have received a copy of the GNU General Public License along
15    with this program. If not, see <http://www.gnu.org/licenses/>. */
16 
17 #ifndef __WORDSPLIT_H
18 #define __WORDSPLIT_H
19 
20 #include <stddef.h>
21 
22 typedef struct wordsplit wordsplit_t;
23 
24 /* Structure used to direct the splitting.  Members marked with [Input]
25    can be defined before calling wordsplit(), those marked with [Output]
26    provide return values when the function returns.  If neither mark is
27    used, the member is internal and must not be used by the caller.
28 
29    In the comments below, the identifiers in parentheses indicate bits that
30    must be set (or unset, if starting with !) in ws_flags (if starting with
31    WRDSF_) or ws_options (if starting with WRDSO_) to initialize or use the
32    given member.
33 
34    If not redefined explicitly, most of them are set to some reasonable
35    default value upon entry to wordsplit(). */
36 struct wordsplit
37 {
38   size_t ws_wordc;          /* [Output] Number of words in ws_wordv. */
39   char **ws_wordv;          /* [Output] Array of parsed out words. */
40   size_t ws_offs;           /* [Input] (WRDSF_DOOFFS) Number of initial
41 			       elements in ws_wordv to fill with NULLs. */
42   size_t ws_wordn;          /* Number of elements ws_wordv can accomodate. */
43   int ws_flags;             /* [Input] Flags passed to wordsplit. */
44   int ws_options;           /* [Input] (WRDSF_OPTIONS)
45 			       Additional options. */
46   size_t ws_maxwords;       /* [Input] (WRDSO_MAXWORDS) Return at most that
47 			       many words */
48   size_t ws_wordi;          /* [Output] (WRDSF_INCREMENTAL) Total number of
49 			       words returned so far */
50 
51   const char *ws_delim;     /* [Input] (WRDSF_DELIM) Word delimiters. */
52   const char *ws_comment;   /* [Input] (WRDSF_COMMENT) Comment characters. */
53   const char *ws_escape[2]; /* [Input] (WRDSF_ESCAPE) Characters to be escaped
54 			       with backslash. */
55   void (*ws_alloc_die) (wordsplit_t *wsp);
56                             /* [Input] (WRDSF_ALLOC_DIE) Function called when
57 			       out of memory.  Must not return. */
58   void (*ws_error) (const char *, ...)
59                    __attribute__ ((__format__ (__printf__, 1, 2)));
60                             /* [Input] (WRDSF_ERROR) Function used for error
61 			       reporting */
62   void (*ws_debug) (const char *, ...)
63                    __attribute__ ((__format__ (__printf__, 1, 2)));
64                             /* [Input] (WRDSF_DEBUG) Function used for debug
65 			       output. */
66   const char **ws_env;      /* [Input] (WRDSF_ENV, !WRDSF_NOVAR) Array of
67 			       environment variables. */
68 
69   char **ws_envbuf;
70   size_t ws_envidx;
71   size_t ws_envsiz;
72 
73   int (*ws_getvar) (char **ret, const char *var, size_t len, void *clos);
74                             /* [Input] (WRDSF_GETVAR, !WRDSF_NOVAR) Looks up
75 			       the name VAR (LEN bytes long) in the table of
76 			       variables and if found returns in memory
77 			       location pointed to by RET the value of that
78 			       variable.  Returns WRDSE_OK (0) on success,
79 			       and an error code (see WRDSE_* defines below)
80 			       on error.  User-specific errors can be returned
81 			       by storing the error diagnostic string in RET
82 			       and returning WRDSE_USERERR.
83                                Whatever is stored in RET, it must be allocated
84 			       using malloc(3). */
85   void *ws_closure;         /* [Input] (WRDSF_CLOSURE) Passed as the CLOS
86 			       argument to ws_getvar and ws_command. */
87   int (*ws_command) (char **ret, const char *cmd, size_t len, char **argv,
88                      void *clos);
89 	                    /* [Input] (!WRDSF_NOCMD) Returns in the memory
90 			       location pointed to by RET the expansion of
91 			       the command CMD (LEN bytes long).  On input,
92 			       ARGV contains CMD split out to words.
93 
94 			       See ws_getvar for a discussion of possible
95 			       return values. */
96 
97   const char *ws_input;     /* Input string (the S argument to wordsplit. */
98   size_t ws_len;            /* Length of ws_input. */
99   size_t ws_endp;           /* Points past the last processed byte in
100 			       ws_input. */
101   int ws_errno;             /* [Output] Error code, if an error occurred. */
102   char *ws_usererr;         /* Points to textual description of
103 			       the error, if ws_errno is WRDSE_USERERR.  Must
104 			       be allocated with malloc(3). */
105   struct wordsplit_node *ws_head, *ws_tail;
106                             /* Doubly-linked list of parsed out nodes. */
107   int ws_lvl;               /* Invocation nesting level. */
108 };
109 
110 /* Initial size for ws_env, if allocated automatically */
111 #define WORDSPLIT_ENV_INIT 16
112 
113 /* Wordsplit flags. */
114 /* Append the words found to the array resulting from a previous
115    call. */
116 #define WRDSF_APPEND            0x00000001
117 /* Insert ws_offs initial NULLs in the array ws_wordv.
118    (These are not counted in the returned ws_wordc.) */
119 #define WRDSF_DOOFFS            0x00000002
120 /* Don't do command substitution. */
121 #define WRDSF_NOCMD             0x00000004
122 /* The parameter p resulted from a previous call to
123    wordsplit(), and wordsplit_free() was not called. Reuse the
124    allocated storage. */
125 #define WRDSF_REUSE             0x00000008
126 /* Print errors */
127 #define WRDSF_SHOWERR           0x00000010
128 /* Consider it an error if an undefined variable is expanded. */
129 #define WRDSF_UNDEF             0x00000020
130 /* Don't do variable expansion. */
131 #define WRDSF_NOVAR             0x00000040
132 /* Abort on ENOMEM error */
133 #define WRDSF_ENOMEMABRT        0x00000080
134 /* Trim off any leading and trailind whitespace */
135 #define WRDSF_WS                0x00000100
136 /* Handle single quotes */
137 #define WRDSF_SQUOTE            0x00000200
138 /* Handle double quotes */
139 #define WRDSF_DQUOTE            0x00000400
140 /* Handle single and double quotes */
141 #define WRDSF_QUOTE             (WRDSF_SQUOTE|WRDSF_DQUOTE)
142 /* Replace each input sequence of repeated delimiters with a single
143    delimiter */
144 #define WRDSF_SQUEEZE_DELIMS    0x00000800
145 /* Return delimiters */
146 #define WRDSF_RETURN_DELIMS     0x00001000
147 /* Treat sed expressions as words */
148 #define WRDSF_SED_EXPR          0x00002000
149 /* ws_delim field is initialized */
150 #define WRDSF_DELIM             0x00004000
151 /* ws_comment field is initialized */
152 #define WRDSF_COMMENT           0x00008000
153 /* ws_alloc_die field is initialized */
154 #define WRDSF_ALLOC_DIE         0x00010000
155 /* ws_error field is initialized */
156 #define WRDSF_ERROR             0x00020000
157 /* ws_debug field is initialized */
158 #define WRDSF_DEBUG             0x00040000
159 /* ws_env field is initialized */
160 #define WRDSF_ENV               0x00080000
161 /* ws_getvar field is initialized */
162 #define WRDSF_GETVAR            0x00100000
163 /* enable debugging */
164 #define WRDSF_SHOWDBG           0x00200000
165 /* Don't split input into words.  Useful for side effects. */
166 #define WRDSF_NOSPLIT           0x00400000
167 /* Keep undefined variables in place, instead of expanding them to
168    empty strings. */
169 #define WRDSF_KEEPUNDEF         0x00800000
170 /* Warn about undefined variables */
171 #define WRDSF_WARNUNDEF         0x01000000
172 /* Handle C escapes */
173 #define WRDSF_CESCAPES          0x02000000
174 /* ws_closure is set */
175 #define WRDSF_CLOSURE           0x04000000
176 /* ws_env is a Key/Value environment, i.e. the value of a variable is
177    stored in the element that follows its name. */
178 #define WRDSF_ENV_KV            0x08000000
179 /* ws_escape is set */
180 #define WRDSF_ESCAPE            0x10000000
181 /* Incremental mode */
182 #define WRDSF_INCREMENTAL       0x20000000
183 /* Perform pathname and tilde expansion */
184 #define WRDSF_PATHEXPAND        0x40000000
185 /* ws_options is initialized */
186 #define WRDSF_OPTIONS           0x80000000
187 
188 #define WRDSF_DEFFLAGS	       \
189   (WRDSF_NOVAR | WRDSF_NOCMD | \
190    WRDSF_QUOTE | WRDSF_SQUEEZE_DELIMS | WRDSF_CESCAPES)
191 
192 /* Remove the word that produces empty string after path expansion */
193 #define WRDSO_NULLGLOB        0x00000001
194 /* Print error message if path expansion produces empty string */
195 #define WRDSO_FAILGLOB        0x00000002
196 /* Allow a leading period to be matched by metacharacters. */
197 #define WRDSO_DOTGLOB         0x00000004
198 #if 0 /* Unused value */
199 #define WRDSO_ARGV            0x00000008
200 /* Keep backslash in unrecognized escape sequences in words */
201 #endif
202 #define WRDSO_BSKEEP_WORD     0x00000010
203 /* Handle octal escapes in words */
204 #define WRDSO_OESC_WORD       0x00000020
205 /* Handle hex escapes in words */
206 #define WRDSO_XESC_WORD       0x00000040
207 
208 /* ws_maxwords field is initialized */
209 #define WRDSO_MAXWORDS        0x00000080
210 
211 /* Keep backslash in unrecognized escape sequences in quoted strings */
212 #define WRDSO_BSKEEP_QUOTE    0x00000100
213 /* Handle octal escapes in quoted strings */
214 #define WRDSO_OESC_QUOTE      0x00000200
215 /* Handle hex escapes in quoted strings */
216 #define WRDSO_XESC_QUOTE      0x00000400
217 
218 #define WRDSO_BSKEEP          WRDSO_BSKEEP_WORD
219 #define WRDSO_OESC            WRDSO_OESC_WORD
220 #define WRDSO_XESC            WRDSO_XESC_WORD
221 
222 /* Indices into ws_escape */
223 #define WRDSX_WORD  0
224 #define WRDSX_QUOTE 1
225 
226 /* Set escape option F in WS for words (Q==0) or quoted strings (Q==1) */
227 #define WRDSO_ESC_SET(ws,q,f) ((ws)->ws_options |= ((f) << 4*(q)))
228 /* Test WS for escape option F for words (Q==0) or quoted strings (Q==1) */
229 #define WRDSO_ESC_TEST(ws,q,f) ((ws)->ws_options & ((f) << 4*(q)))
230 
231 #define WRDSE_OK         0
232 #define WRDSE_EOF        WRDSE_OK
233 #define WRDSE_QUOTE      1
234 #define WRDSE_NOSPACE    2
235 #define WRDSE_USAGE      3
236 #define WRDSE_CBRACE     4
237 #define WRDSE_UNDEF      5
238 #define WRDSE_NOINPUT    6
239 #define WRDSE_PAREN      7
240 #define WRDSE_GLOBERR    8
241 #define WRDSE_USERERR    9
242 
243 int wordsplit (const char *s, wordsplit_t *ws, int flags);
244 int wordsplit_len (const char *s, size_t len, wordsplit_t *ws, int flags);
245 void wordsplit_free (wordsplit_t *ws);
246 void wordsplit_free_words (wordsplit_t *ws);
247 void wordsplit_free_envbuf (wordsplit_t *ws);
248 int wordsplit_get_words (wordsplit_t *ws, size_t *wordc, char ***wordv);
249 
250 static inline void wordsplit_getwords (wordsplit_t *ws, size_t *wordc, char ***wordv)
251   __attribute__ ((deprecated));
252 
253 static inline void
wordsplit_getwords(wordsplit_t * ws,size_t * wordc,char *** wordv)254 wordsplit_getwords (wordsplit_t *ws, size_t *wordc, char ***wordv)
255 {
256   wordsplit_get_words (ws, wordc, wordv);
257 }
258 
259 int wordsplit_append (wordsplit_t *wsp, int argc, char **argv);
260 
261 int wordsplit_c_unquote_char (int c);
262 int wordsplit_c_quote_char (int c);
263 size_t wordsplit_c_quoted_length (const char *str, int quote_hex, int *quote);
264 void wordsplit_c_quote_copy (char *dst, const char *src, int quote_hex);
265 
266 void wordsplit_perror (wordsplit_t *ws);
267 const char *wordsplit_strerror (wordsplit_t *ws);
268 
269 void wordsplit_clearerr (wordsplit_t *ws);
270 
271 #endif
272