xref: /curl/src/tool_main.c (revision fb711b50)
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 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  * SPDX-License-Identifier: curl
22  *
23  ***************************************************************************/
24 #include "tool_setup.h"
25 
26 #include <sys/stat.h>
27 
28 #ifdef _WIN32
29 #include <tchar.h>
30 #endif
31 
32 #include <signal.h>
33 
34 #ifdef HAVE_FCNTL_H
35 #include <fcntl.h>
36 #endif
37 
38 #include "curlx.h"
39 
40 #include "tool_cfgable.h"
41 #include "tool_doswin.h"
42 #include "tool_msgs.h"
43 #include "tool_operate.h"
44 #include "tool_vms.h"
45 #include "tool_main.h"
46 #include "tool_libinfo.h"
47 #include "tool_stderr.h"
48 
49 /*
50  * This is low-level hard-hacking memory leak tracking and similar. Using
51  * the library level code from this client-side is ugly, but we do this
52  * anyway for convenience.
53  */
54 #include "memdebug.h" /* keep this as LAST include */
55 
56 #ifdef __VMS
57 /*
58  * vms_show is a global variable, used in main() as parameter for
59  * function vms_special_exit() to allow proper curl tool exiting.
60  * Its value may be set in other tool_*.c source files thanks to
61  * forward declaration present in tool_vms.h
62  */
63 int vms_show = 0;
64 #endif
65 
66 #ifdef __MINGW32__
67 /*
68  * There seems to be no way to escape "*" in command-line arguments with MinGW
69  * when command-line argument globbing is enabled under the MSYS shell, so turn
70  * it off.
71  */
72 extern int _CRT_glob;
73 int _CRT_glob = 0;
74 #endif /* __MINGW32__ */
75 
76 /* if we build a static library for unit tests, there is no main() function */
77 #ifndef UNITTESTS
78 
79 #if defined(HAVE_PIPE) && defined(HAVE_FCNTL)
80 /*
81  * Ensure that file descriptors 0, 1 and 2 (stdin, stdout, stderr) are
82  * open before starting to run. Otherwise, the first three network
83  * sockets opened by curl could be used for input sources, downloaded data
84  * or error logs as they will effectively be stdin, stdout and/or stderr.
85  *
86  * fcntl's F_GETFD instruction returns -1 if the file descriptor is closed,
87  * otherwise it returns "the file descriptor flags (which typically can only
88  * be FD_CLOEXEC, which is not set here).
89  */
main_checkfds(void)90 static int main_checkfds(void)
91 {
92   int fd[2];
93   while((fcntl(STDIN_FILENO, F_GETFD) == -1) ||
94         (fcntl(STDOUT_FILENO, F_GETFD) == -1) ||
95         (fcntl(STDERR_FILENO, F_GETFD) == -1))
96     if(pipe(fd))
97       return 1;
98   return 0;
99 }
100 #else
101 #define main_checkfds() 0
102 #endif
103 
104 #ifdef CURLDEBUG
memory_tracking_init(void)105 static void memory_tracking_init(void)
106 {
107   char *env;
108   /* if CURL_MEMDEBUG is set, this starts memory tracking message logging */
109   env = curl_getenv("CURL_MEMDEBUG");
110   if(env) {
111     /* use the value as filename */
112     char fname[CURL_MT_LOGFNAME_BUFSIZE];
113     if(strlen(env) >= CURL_MT_LOGFNAME_BUFSIZE)
114       env[CURL_MT_LOGFNAME_BUFSIZE-1] = '\0';
115     strcpy(fname, env);
116     curl_free(env);
117     curl_dbg_memdebug(fname);
118     /* this weird stuff here is to make curl_free() get called before
119        curl_dbg_memdebug() as otherwise memory tracking will log a free()
120        without an alloc! */
121   }
122   /* if CURL_MEMLIMIT is set, this enables fail-on-alloc-number-N feature */
123   env = curl_getenv("CURL_MEMLIMIT");
124   if(env) {
125     char *endptr;
126     long num = strtol(env, &endptr, 10);
127     if((endptr != env) && (endptr == env + strlen(env)) && (num > 0))
128       curl_dbg_memlimit(num);
129     curl_free(env);
130   }
131 }
132 #else
133 #  define memory_tracking_init() Curl_nop_stmt
134 #endif
135 
136 /*
137  * This is the main global constructor for the app. Call this before
138  * _any_ libcurl usage. If this fails, *NO* libcurl functions may be
139  * used, or havoc may be the result.
140  */
main_init(struct GlobalConfig * config)141 static CURLcode main_init(struct GlobalConfig *config)
142 {
143   CURLcode result = CURLE_OK;
144 
145 #if defined(__DJGPP__) || defined(__GO32__)
146   /* stop stat() wasting time */
147   _djstat_flags |= _STAT_INODE | _STAT_EXEC_MAGIC | _STAT_DIRSIZE;
148 #endif
149 
150   /* Initialise the global config */
151   config->showerror = FALSE;          /* show errors when silent */
152   config->styled_output = TRUE;       /* enable detection */
153   config->parallel_max = PARALLEL_DEFAULT;
154 
155   /* Allocate the initial operate config */
156   config->first = config->last = malloc(sizeof(struct OperationConfig));
157   if(config->first) {
158     /* Perform the libcurl initialization */
159     result = curl_global_init(CURL_GLOBAL_DEFAULT);
160     if(!result) {
161       /* Get information about libcurl */
162       result = get_libcurl_info();
163 
164       if(!result) {
165         /* Initialise the config */
166         config_init(config->first);
167         config->first->global = config;
168       }
169       else {
170         errorf(config, "error retrieving curl library information");
171         free(config->first);
172       }
173     }
174     else {
175       errorf(config, "error initializing curl library");
176       free(config->first);
177     }
178   }
179   else {
180     errorf(config, "error initializing curl");
181     result = CURLE_FAILED_INIT;
182   }
183 
184   return result;
185 }
186 
free_globalconfig(struct GlobalConfig * config)187 static void free_globalconfig(struct GlobalConfig *config)
188 {
189   Curl_safefree(config->trace_dump);
190 
191   if(config->trace_fopened && config->trace_stream)
192     fclose(config->trace_stream);
193   config->trace_stream = NULL;
194 
195   Curl_safefree(config->libcurl);
196 }
197 
198 /*
199  * This is the main global destructor for the app. Call this after
200  * _all_ libcurl usage is done.
201  */
main_free(struct GlobalConfig * config)202 static void main_free(struct GlobalConfig *config)
203 {
204   /* Cleanup the easy handle */
205   /* Main cleanup */
206   curl_global_cleanup();
207   free_globalconfig(config);
208 
209   /* Free the config structures */
210   config_free(config->last);
211   config->first = NULL;
212   config->last = NULL;
213 }
214 
215 /*
216 ** curl tool main function.
217 */
218 #ifdef _UNICODE
219 #if defined(__GNUC__) || defined(__clang__)
220 /* GCC does not know about wmain() */
221 #pragma GCC diagnostic push
222 #pragma GCC diagnostic ignored "-Wmissing-prototypes"
223 #pragma GCC diagnostic ignored "-Wmissing-declarations"
224 #endif
wmain(int argc,wchar_t * argv[])225 int wmain(int argc, wchar_t *argv[])
226 #else
227 int main(int argc, char *argv[])
228 #endif
229 {
230   CURLcode result = CURLE_OK;
231   struct GlobalConfig global;
232   memset(&global, 0, sizeof(global));
233 
234   tool_init_stderr();
235 
236 #ifdef _WIN32
237   /* Undocumented diagnostic option to list the full paths of all loaded
238      modules. This is purposely pre-init. */
239   if(argc == 2 && !_tcscmp(argv[1], _T("--dump-module-paths"))) {
240     struct curl_slist *item, *head = GetLoadedModulePaths();
241     for(item = head; item; item = item->next)
242       printf("%s\n", item->data);
243     curl_slist_free_all(head);
244     return head ? 0 : 1;
245   }
246   /* win32_init must be called before other init routines. */
247   result = win32_init();
248   if(result) {
249     errorf(&global, "(%d) Windows-specific init failed", result);
250     return (int)result;
251   }
252 #endif
253 
254   if(main_checkfds()) {
255     errorf(&global, "out of file descriptors");
256     return CURLE_FAILED_INIT;
257   }
258 
259 #if defined(HAVE_SIGNAL) && defined(SIGPIPE)
260   (void)signal(SIGPIPE, SIG_IGN);
261 #endif
262 
263   /* Initialize memory tracking */
264   memory_tracking_init();
265 
266   /* Initialize the curl library - do not call any libcurl functions before
267      this point */
268   result = main_init(&global);
269   if(!result) {
270     /* Start our curl operation */
271     result = operate(&global, argc, argv);
272 
273     /* Perform the main cleanup */
274     main_free(&global);
275   }
276 
277 #ifdef _WIN32
278   /* Flush buffers of all streams opened in write or update mode */
279   fflush(NULL);
280 #endif
281 
282 #ifdef __VMS
283   vms_special_exit(result, vms_show);
284 #else
285   return (int)result;
286 #endif
287 }
288 
289 #ifdef _UNICODE
290 #if defined(__GNUC__) || defined(__clang__)
291 #pragma GCC diagnostic pop
292 #endif
293 #endif
294 
295 #endif /* ndef UNITTESTS */
296