1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at https://curl.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  ***************************************************************************/
22 #include "tool_setup.h"
23 
24 #define ENABLE_CURLX_PRINTF
25 /* use our own printf() functions */
26 #include "curlx.h"
27 
28 #include "tool_cfgable.h"
29 #include "tool_getparam.h"
30 #include "tool_helpers.h"
31 #include "tool_homedir.h"
32 #include "tool_msgs.h"
33 #include "tool_parsecfg.h"
34 #include "dynbuf.h"
35 
36 #include "memdebug.h" /* keep this as LAST include */
37 
38 /* only acknowledge colon or equals as separators if the option was not
39    specified with an initial dash! */
40 #define ISSEP(x,dash) (!dash && (((x) == '=') || ((x) == ':')))
41 
42 static const char *unslashquote(const char *line, char *param);
43 
44 #define MAX_CONFIG_LINE_LENGTH (100*1024)
45 static bool my_get_line(FILE *fp, struct curlx_dynbuf *, bool *error);
46 
47 #ifdef WIN32
execpath(const char * filename)48 static FILE *execpath(const char *filename)
49 {
50   char filebuffer[512];
51   /* Get the filename of our executable. GetModuleFileName is already declared
52    * via inclusions done in setup header file.  We assume that we are using
53    * the ASCII version here.
54    */
55   unsigned long len = GetModuleFileNameA(0, filebuffer, sizeof(filebuffer));
56   if(len > 0 && len < sizeof(filebuffer)) {
57     /* We got a valid filename - get the directory part */
58     char *lastdirchar = strrchr(filebuffer, '\\');
59     if(lastdirchar) {
60       size_t remaining;
61       *lastdirchar = 0;
62       /* If we have enough space, build the RC filename */
63       remaining = sizeof(filebuffer) - strlen(filebuffer);
64       if(strlen(filename) < remaining - 1) {
65         msnprintf(lastdirchar, remaining, "%s%s", DIR_CHAR, filename);
66         return fopen(filebuffer, FOPEN_READTEXT);
67       }
68     }
69   }
70 
71   return NULL;
72 }
73 #endif
74 
75 
76 /* return 0 on everything-is-fine, and non-zero otherwise */
parseconfig(const char * filename,struct GlobalConfig * global)77 int parseconfig(const char *filename, struct GlobalConfig *global)
78 {
79   FILE *file = NULL;
80   bool usedarg = FALSE;
81   int rc = 0;
82   struct OperationConfig *operation = global->last;
83   char *pathalloc = NULL;
84 
85   if(!filename || !*filename) {
86     /* NULL or no file name attempts to load .curlrc from the homedir! */
87 
88     char *home = homedir(".curlrc");
89 #ifndef WIN32
90     if(home) {
91       pathalloc = curl_maprintf("%s%s.curlrc", home, DIR_CHAR);
92       if(!pathalloc) {
93         free(home);
94         return 1; /* out of memory */
95       }
96       filename = pathalloc;
97     }
98 #else /* Windows */
99     if(home) {
100       int i = 0;
101       char prefix = '.';
102       do {
103         /* if it was allocated in a previous attempt */
104         curl_free(pathalloc);
105         /* check for .curlrc then _curlrc in the home dir */
106         pathalloc = curl_maprintf("%s%s%ccurlrc", home, DIR_CHAR, prefix);
107         if(!pathalloc) {
108           free(home);
109           return 1; /* out of memory */
110         }
111 
112         /* Check if the file exists - if not, try _curlrc */
113         file = fopen(pathalloc, FOPEN_READTEXT);
114         if(file) {
115           filename = pathalloc;
116           break;
117         }
118         prefix = '_';
119       } while(++i < 2);
120     }
121     if(!filename) {
122       /* check for .curlrc then _curlrc in the dir of the executable */
123       file = execpath(".curlrc");
124       if(!file)
125         file = execpath("_curlrc");
126     }
127 #endif
128 
129     Curl_safefree(home); /* we've used it, now free it */
130   }
131 
132   if(!file && filename) { /* no need to fopen() again */
133     if(strcmp(filename, "-"))
134       file = fopen(filename, FOPEN_READTEXT);
135     else
136       file = stdin;
137   }
138 
139   if(file) {
140     char *line;
141     char *option;
142     char *param;
143     int lineno = 0;
144     bool dashed_option;
145     struct curlx_dynbuf buf;
146     bool fileerror;
147     curlx_dyn_init(&buf, MAX_CONFIG_LINE_LENGTH);
148 
149     while(my_get_line(file, &buf, &fileerror)) {
150       int res;
151       bool alloced_param = FALSE;
152       lineno++;
153       line = curlx_dyn_ptr(&buf);
154       if(!line) {
155         rc = 1; /* out of memory */
156         break;
157       }
158 
159       /* line with # in the first non-blank column is a comment! */
160       while(*line && ISSPACE(*line))
161         line++;
162 
163       switch(*line) {
164       case '#':
165       case '/':
166       case '\r':
167       case '\n':
168       case '*':
169       case '\0':
170         curlx_dyn_reset(&buf);
171         continue;
172       }
173 
174       /* the option keywords starts here */
175       option = line;
176 
177       /* the option starts with a dash? */
178       dashed_option = option[0]=='-'?TRUE:FALSE;
179 
180       while(*line && !ISSPACE(*line) && !ISSEP(*line, dashed_option))
181         line++;
182       /* ... and has ended here */
183 
184       if(*line)
185         *line++ = '\0'; /* null-terminate, we have a local copy of the data */
186 
187 #ifdef DEBUG_CONFIG
188       fprintf(stderr, "GOT: %s\n", option);
189 #endif
190 
191       /* pass spaces and separator(s) */
192       while(*line && (ISSPACE(*line) || ISSEP(*line, dashed_option)))
193         line++;
194 
195       /* the parameter starts here (unless quoted) */
196       if(*line == '\"') {
197         /* quoted parameter, do the quote dance */
198         line++;
199         param = malloc(strlen(line) + 1); /* parameter */
200         if(!param) {
201           /* out of memory */
202           rc = 1;
203           break;
204         }
205         alloced_param = TRUE;
206         (void)unslashquote(line, param);
207       }
208       else {
209         param = line; /* parameter starts here */
210         while(*line && !ISSPACE(*line))
211           line++;
212 
213         if(*line) {
214           *line = '\0'; /* null-terminate */
215 
216           /* to detect mistakes better, see if there's data following */
217           line++;
218           /* pass all spaces */
219           while(*line && ISSPACE(*line))
220             line++;
221 
222           switch(*line) {
223           case '\0':
224           case '\r':
225           case '\n':
226           case '#': /* comment */
227             break;
228           default:
229             warnf(operation->global, "%s:%d: warning: '%s' uses unquoted "
230                   "whitespace in the line that may cause side-effects!\n",
231                   filename, lineno, option);
232           }
233         }
234         if(!*param)
235           /* do this so getparameter can check for required parameters.
236              Otherwise it always thinks there's a parameter. */
237           param = NULL;
238       }
239 
240 #ifdef DEBUG_CONFIG
241       fprintf(stderr, "PARAM: \"%s\"\n",(param ? param : "(null)"));
242 #endif
243       res = getparameter(option, param, &usedarg, global, operation);
244       operation = global->last;
245 
246       if(!res && param && *param && !usedarg)
247         /* we passed in a parameter that wasn't used! */
248         res = PARAM_GOT_EXTRA_PARAMETER;
249 
250       if(res == PARAM_NEXT_OPERATION) {
251         if(operation->url_list && operation->url_list->url) {
252           /* Allocate the next config */
253           operation->next = malloc(sizeof(struct OperationConfig));
254           if(operation->next) {
255             /* Initialise the newly created config */
256             config_init(operation->next);
257 
258             /* Set the global config pointer */
259             operation->next->global = global;
260 
261             /* Update the last operation pointer */
262             global->last = operation->next;
263 
264             /* Move onto the new config */
265             operation->next->prev = operation;
266             operation = operation->next;
267           }
268           else
269             res = PARAM_NO_MEM;
270         }
271       }
272 
273       if(res != PARAM_OK && res != PARAM_NEXT_OPERATION) {
274         /* the help request isn't really an error */
275         if(!strcmp(filename, "-")) {
276           filename = "<stdin>";
277         }
278         if(res != PARAM_HELP_REQUESTED &&
279            res != PARAM_MANUAL_REQUESTED &&
280            res != PARAM_VERSION_INFO_REQUESTED &&
281            res != PARAM_ENGINES_REQUESTED) {
282           const char *reason = param2text(res);
283           warnf(operation->global, "%s:%d: warning: '%s' %s\n",
284                 filename, lineno, option, reason);
285         }
286       }
287 
288       if(alloced_param)
289         Curl_safefree(param);
290 
291       curlx_dyn_reset(&buf);
292     }
293     curlx_dyn_free(&buf);
294     if(file != stdin)
295       fclose(file);
296     if(fileerror)
297       rc = 1;
298   }
299   else
300     rc = 1; /* couldn't open the file */
301 
302   curl_free(pathalloc);
303   return rc;
304 }
305 
306 /*
307  * Copies the string from line to the buffer at param, unquoting
308  * backslash-quoted characters and NUL-terminating the output string.
309  * Stops at the first non-backslash-quoted double quote character or the
310  * end of the input string. param must be at least as long as the input
311  * string.  Returns the pointer after the last handled input character.
312  */
unslashquote(const char * line,char * param)313 static const char *unslashquote(const char *line, char *param)
314 {
315   while(*line && (*line != '\"')) {
316     if(*line == '\\') {
317       char out;
318       line++;
319 
320       /* default is to output the letter after the backslash */
321       switch(out = *line) {
322       case '\0':
323         continue; /* this'll break out of the loop */
324       case 't':
325         out = '\t';
326         break;
327       case 'n':
328         out = '\n';
329         break;
330       case 'r':
331         out = '\r';
332         break;
333       case 'v':
334         out = '\v';
335         break;
336       }
337       *param++ = out;
338       line++;
339     }
340     else
341       *param++ = *line++;
342   }
343   *param = '\0'; /* always null-terminate */
344   return line;
345 }
346 
347 /*
348  * Reads a line from the given file, ensuring is NUL terminated.
349  */
my_get_line(FILE * fp,struct curlx_dynbuf * db,bool * error)350 static bool my_get_line(FILE *fp, struct curlx_dynbuf *db,
351                         bool *error)
352 {
353   char buf[4096];
354   *error = FALSE;
355   do {
356     /* fgets() returns s on success, and NULL on error or when end of file
357        occurs while no characters have been read. */
358     if(!fgets(buf, sizeof(buf), fp))
359       /* only if there's data in the line, return TRUE */
360       return curlx_dyn_len(db) ? TRUE : FALSE;
361     if(curlx_dyn_add(db, buf)) {
362       *error = TRUE; /* error */
363       return FALSE; /* stop reading */
364     }
365   } while(!strchr(buf, '\n'));
366 
367   return TRUE; /* continue */
368 }
369