1 // This file is part of BOINC.
2 // http://boinc.berkeley.edu
3 // Copyright (C) 2017 University of California
4 //
5 // BOINC is free software; you can redistribute it and/or modify it
6 // under the terms of the GNU Lesser General Public License
7 // as published by the Free Software Foundation,
8 // either version 3 of the License, or (at your option) any later version.
9 //
10 // BOINC is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 // See the GNU Lesser General Public License for more details.
14 //
15 // You should have received a copy of the GNU Lesser General Public License
16 // along with BOINC. If not, see <http://www.gnu.org/licenses/>.
17
18 // command-line version of the BOINC client
19
20 // This file contains no GUI-related code.
21
22 #include "cpp.h"
23
24 #ifdef WIN32
25 #include "boinc_win.h"
26 #include "sysmon_win.h"
27 #include "win_util.h"
28 #ifdef _MSC_VER
29 #define snprintf _snprintf
30 #endif
31
32 #else
33 #include "config.h"
34 #if HAVE_SYS_SOCKET_H
35 #include <sys/types.h>
36 #include <sys/socket.h>
37 #endif
38 #include <sys/stat.h>
39 #include <syslog.h>
40 #include <cstdlib>
41 #include <unistd.h>
42 #include <csignal>
43
44 #ifdef ANDROID
45 #include "android/log.h"
46 #endif
47
48 #endif
49
50 #ifdef __APPLE__
51 #include <Carbon/Carbon.h>
52 #include "hostinfo.h"
53 #endif
54
55 #include "diagnostics.h"
56 #include "error_numbers.h"
57 #include "str_util.h"
58 #include "str_replace.h"
59 #include "util.h"
60 #include "prefs.h"
61 #include "filesys.h"
62 #include "network.h"
63 #include "idlemon.h"
64
65 #include "client_state.h"
66 #include "file_names.h"
67 #include "log_flags.h"
68 #include "client_msgs.h"
69 #include "http_curl.h"
70 #include "sandbox.h"
71
72 #include "main.h"
73
74 // Log informational messages to system specific places
75 //
log_message_startup(const char * msg)76 void log_message_startup(const char* msg) {
77 char evt_msg[2048];
78 char* time_string = time_to_string(dtime());
79
80 snprintf(evt_msg, sizeof(evt_msg),
81 "%s %s\n",
82 time_string, msg
83 );
84 if (!gstate.executing_as_daemon) {
85 fprintf(stdout, "%s", evt_msg);
86 } else {
87 #ifdef _WIN32
88 LogEventInfoMessage(evt_msg);
89 #elif defined(__EMX__)
90 #elif defined (__APPLE__)
91 #elif defined (ANDROID)
92 __android_log_print(ANDROID_LOG_INFO, "BOINC", evt_msg);
93 #else
94 syslog(LOG_DAEMON|LOG_INFO, "%s", evt_msg);
95 #endif
96 }
97 }
98
99 // Log error messages to system specific places
100 //
log_message_error(const char * msg)101 void log_message_error(const char* msg) {
102 char evt_msg[2048];
103 char* time_string = time_to_string(dtime());
104 #ifdef _WIN32
105 char buf[1024];
106 snprintf(evt_msg, sizeof(evt_msg),
107 "%s %s\n"
108 "GLE: %s\n",
109 time_string, msg,
110 windows_format_error_string(GetLastError(), buf, sizeof(buf))
111 );
112 #else
113 snprintf(evt_msg, sizeof(evt_msg),
114 "%s %s\n",
115 time_string, msg
116 );
117 #endif
118 if (!gstate.executing_as_daemon) {
119 fprintf(stderr, "%s", evt_msg);
120 } else {
121 #ifdef _WIN32
122 LogEventErrorMessage(evt_msg);
123 #elif defined(__EMX__)
124 #elif defined (__APPLE__)
125 #elif defined (ANDROID)
126 __android_log_print(ANDROID_LOG_ERROR, "BOINC", evt_msg);
127 #else
128 syslog(LOG_DAEMON|LOG_ERR, "%s", evt_msg);
129 #endif
130 }
131 }
132
log_message_error(const char * msg,int error_code)133 void log_message_error(const char* msg, int error_code) {
134 char evt_msg[2048];
135 char* time_string = time_to_string(dtime());
136 snprintf(evt_msg, sizeof(evt_msg),
137 "%s %s\n"
138 "Error Code: %d\n",
139 time_string, msg, error_code
140 );
141 if (!gstate.executing_as_daemon) {
142 fprintf(stderr, "%s", evt_msg);
143 } else {
144 #ifdef _WIN32
145 LogEventErrorMessage(evt_msg);
146 #elif defined(__EMX__)
147 #elif defined (__APPLE__)
148 #elif defined (ANDROID)
149 __android_log_print(ANDROID_LOG_ERROR, "BOINC", evt_msg);
150 #else
151 syslog(LOG_DAEMON|LOG_ERR, "%s", evt_msg);
152 #endif
153 }
154 }
155
156 #ifndef _WIN32
signal_handler(int signum)157 static void signal_handler(int signum) {
158 msg_printf(NULL, MSG_INFO, "Received signal %d", signum);
159 switch(signum) {
160 case SIGHUP:
161 case SIGINT:
162 case SIGQUIT:
163 case SIGTERM:
164 #ifdef SIGPWR
165 case SIGPWR:
166 #endif
167 gstate.requested_exit = true;
168 #ifdef __EMX__
169 // close socket
170 shutdown(gstate.gui_rpcs.lsock, 2);
171 #endif
172 break;
173 default:
174 msg_printf(NULL, MSG_INTERNAL_ERROR, "Signal not handled");
175 }
176 }
177 #endif
178
init_core_client(int argc,char ** argv)179 static void init_core_client(int argc, char** argv) {
180 setbuf(stdout, 0);
181 setbuf(stderr, 0);
182
183 cc_config.defaults();
184 gstate.parse_cmdline(argc, argv);
185 gstate.now = dtime();
186
187 #ifdef _WIN32
188 if (!cc_config.allow_multiple_clients) {
189 chdir_to_data_dir();
190 }
191 #endif
192
193 #ifndef _WIN32
194 if (g_use_sandbox)
195 // Set file creation mask to be writable by both user and group and
196 // world-executable but neither world-readable nor world-writable
197 // Our umask will be inherited by all our child processes
198 //
199 umask (6);
200 #endif
201
202 // Initialize the BOINC Diagnostics Framework
203 int flags =
204 #ifdef _DEBUG
205 BOINC_DIAG_MEMORYLEAKCHECKENABLED |
206 #endif
207 BOINC_DIAG_DUMPCALLSTACKENABLED |
208 BOINC_DIAG_HEAPCHECKENABLED |
209 BOINC_DIAG_TRACETOSTDOUT;
210
211 if (gstate.redirect_io || gstate.executing_as_daemon || gstate.detach_console) {
212 flags |=
213 BOINC_DIAG_REDIRECTSTDERR |
214 BOINC_DIAG_REDIRECTSTDOUT;
215 }
216
217 diagnostics_init(flags, "stdoutdae", "stderrdae");
218
219 #ifdef _WIN32
220 // Specify which allocation will cause a debugger to break. Use a previous
221 // memory leak detection report which looks like this:
222 // {650} normal block at 0x000000000070A6F0, 24 bytes long.
223 // Data: < N P p > 80 1E 4E 00 00 00 00 00 50 AE 70 00 00 00 00 00
224 //_CrtSetBreakAlloc(650);
225 //_CrtSetBreakAlloc(651);
226 //_CrtSetBreakAlloc(652);
227 //_CrtSetBreakAlloc(653);
228 //_CrtSetBreakAlloc(654);
229 #endif
230
231 read_config_file(true);
232
233 // Win32 - detach from console if requested
234 #ifdef _WIN32
235 if (gstate.detach_console) {
236 FreeConsole();
237 }
238 #endif
239
240 // Unix: install signal handlers
241 #ifndef _WIN32
242 // Handle quit signals gracefully
243 boinc_set_signal_handler(SIGHUP, (handler_t)signal_handler);
244 boinc_set_signal_handler(SIGINT, (handler_t)signal_handler);
245 boinc_set_signal_handler(SIGQUIT, (handler_t)signal_handler);
246 boinc_set_signal_handler(SIGTERM, (handler_t)signal_handler);
247 #ifdef SIGPWR
248 boinc_set_signal_handler(SIGPWR, (handler_t)signal_handler);
249 #endif
250 #endif
251 }
252
253 // Some dual-GPU laptops (e.g., Macbook Pro) don't power down
254 // the more powerful GPU until all applications which used them exit.
255 // To save battery life, the client launches a second instance
256 // of the client as a child process to detect and get info
257 // about the GPUs.
258 // The child process writes the info to a temp file which our main
259 // client then reads.
260 //
do_gpu_detection(int argc,char ** argv)261 static void do_gpu_detection(int argc, char** argv) {
262 vector<string> warnings;
263
264 boinc_install_signal_handlers();
265 gstate.parse_cmdline(argc, argv);
266 gstate.now = dtime();
267
268 int flags =
269 BOINC_DIAG_DUMPCALLSTACKENABLED |
270 BOINC_DIAG_HEAPCHECKENABLED |
271 BOINC_DIAG_TRACETOSTDOUT |
272 BOINC_DIAG_REDIRECTSTDERR |
273 BOINC_DIAG_REDIRECTSTDOUT;
274
275 diagnostics_init(flags, "stdoutgpudetect", "stderrgpudetect");
276
277 read_config_file(true);
278
279 coprocs.detect_gpus(warnings);
280 coprocs.write_coproc_info_file(warnings);
281 warnings.clear();
282 }
283
initialize()284 static int initialize() {
285 int retval;
286
287 if (!cc_config.allow_multiple_clients) {
288 retval = wait_client_mutex(".", 10);
289 if (retval) {
290 log_message_error("Another instance of BOINC is running.");
291 return ERR_EXEC;
292 }
293 }
294
295
296 // Initialize WinSock
297 #if defined(_WIN32) && defined(USE_WINSOCK)
298 if (WinsockInitialize() != 0) {
299 log_message_error("Failed to initialize the Windows Sockets interface.");
300 return ERR_IO;
301 }
302 #endif
303
304 curl_init();
305
306 #ifdef _WIN32
307 if(!startup_idle_monitor()) {
308 log_message_error(
309 "Failed to initialize the BOINC idle monitor interface."
310 "BOINC will not be able to determine if the user is idle or not...\n"
311 );
312 }
313 #endif
314
315 return 0;
316 }
317
finalize()318 static int finalize() {
319 static bool finalized = false;
320 if (finalized) return 0;
321 finalized = true;
322 gstate.quit_activities();
323
324 #ifdef _WIN32
325 shutdown_idle_monitor();
326
327 #ifdef USE_WINSOCK
328 if (WinsockCleanup()) {
329 log_message_error("WinSockCleanup() failed");
330 return ERR_IO;
331 }
332 #endif
333
334 cleanup_system_monitor();
335
336 #endif
337
338 curl_cleanup();
339
340 #ifdef _DEBUG
341 gstate.free_mem();
342 #endif
343
344 diagnostics_finish();
345 gstate.cleanup_completed = true;
346 return 0;
347 }
348
boinc_main_loop()349 int boinc_main_loop() {
350 int retval;
351
352 retval = initialize();
353 if (retval) return retval;
354
355 #ifdef __APPLE__
356 // If we run too soon during system boot we can cause a kernel panic
357 if (gstate.executing_as_daemon) {
358 if (get_system_uptime() < 120) { // If system has been up for less than 2 minutes
359 boinc_sleep(30.);
360 }
361 }
362 #endif
363
364 retval = gstate.init();
365 if (retval) {
366 log_message_error("gstate.init() failed", retval);
367 return retval;
368 }
369
370 log_message_startup("Initialization completed");
371
372 while (1) {
373 if (!gstate.poll_slow_events()) {
374 gstate.do_io_or_sleep(POLL_INTERVAL);
375 }
376 fflush(stderr);
377 fflush(stdout);
378
379 if (gstate.time_to_exit()) {
380 msg_printf(NULL, MSG_INFO, "Time to exit");
381 break;
382 }
383 if (gstate.requested_exit) {
384 if (cc_config.abort_jobs_on_exit) {
385 if (!gstate.in_abort_sequence) {
386 msg_printf(NULL, MSG_INFO,
387 "Exit requested; starting abort sequence"
388 );
389 gstate.start_abort_sequence();
390 }
391 } else {
392 msg_printf(NULL, MSG_INFO, "Exiting");
393 break;
394 }
395 }
396 if (gstate.in_abort_sequence) {
397 if (gstate.abort_sequence_done()) {
398 msg_printf(NULL, MSG_INFO, "Abort sequence done; exiting");
399 break;
400 }
401 }
402 }
403
404 return finalize();
405 }
406
main(int argc,char ** argv)407 int main(int argc, char** argv) {
408 int retval = 0;
409
410 coprocs.set_path_to_client(argv[0]); // Used to launch a child process for --detect_gpus
411
412 for (int index = 1; index < argc; index++) {
413 if (strcmp(argv[index], "-daemon") == 0 || strcmp(argv[index], "--daemon") == 0) {
414 gstate.executing_as_daemon = true;
415 log_message_startup("BOINC is initializing...");
416 #if !defined(_WIN32) && !defined(__EMX__) && !defined(__APPLE__)
417 // from <unistd.h>:
418 // Detach from the controlling terminal and run in the background
419 // as system daemon.
420 // Don't change working directory to root ("/"), but redirect
421 // standard input, standard output and standard error to /dev/null.
422 //
423 retval = daemon(1, 0);
424 break;
425 #endif
426 }
427
428 if (!strcmp(argv[index], "--detect_gpus")) {
429 do_gpu_detection(argc, argv);
430 return 0;
431 }
432
433 if (!strcmp(argv[index], "--run_test_app")) {
434 read_config_file(true);
435 run_test_app();
436 }
437
438 #ifdef _WIN32
439 // This bit of silliness is required to properly detach when run from within a command
440 // prompt under Win32. The root cause of the problem is that CMD.EXE does not return
441 // control to the user until the spawned program exits, detaching from the console is
442 // not enough. So we need to do the following. If the -detach flag is given, trap it
443 // prior to the main setup in init_core_client. Reinvoke the program, changing the
444 // -detach into -detach_phase_two, and then exit. At this point, cmd.exe thinks all is
445 // well, and returns control to the user. Meanwhile the second invocation will grok the
446 // -detach_phase_two flag, and detach itself from the console, finally getting us to
447 // where we want to be.
448
449 // FIXME FIXME. Duplicate instances of -detach may cause this to be
450 // executed unnecessarily. At worst, I think it leads to a few extra
451 // processes being created and destroyed.
452 if (strcmp(argv[index], "-detach") == 0 || strcmp(argv[index], "--detach") == 0 ||
453 strcmp(argv[index], "-detach_console") == 0 || strcmp(argv[index], "--detach_console") == 0
454 ) {
455 int i, len;
456 char *commandLine;
457 STARTUPINFO si;
458 PROCESS_INFORMATION pi;
459
460 argv[index] = "-detach_phase_two";
461
462 // start with space for two '"'s
463 len = 2;
464 for (i = 0; i < argc; i++) {
465 len += (int)strlen(argv[i]) + 1;
466 }
467 if ((commandLine = (char *) malloc(len)) == NULL) {
468 // Drop back ten and punt. Can't do the detach thing, so we just carry on.
469 // At least the program will start.
470 break;
471 }
472 commandLine[0] = '"';
473 // OK, we can safely use strcpy and strcat, since we know that we allocated enough
474 strlcpy(&commandLine[1], argv[0], len);
475 strlcat(commandLine, "\"", len);
476 for (i = 1; i < argc; i++) {
477 strlcat(commandLine, " ", len);
478 strlcat(commandLine, argv[i], len);
479 }
480
481 memset(&si, 0, sizeof(si));
482 si.cb = sizeof(si);
483
484 // If process creation succeeds, we exit, if it fails punt and continue
485 // as usual. We won't detach properly, but the program will run.
486 if (CreateProcess(NULL, commandLine, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi)) {
487 exit(0);
488 }
489 break;
490 }
491 #endif
492
493 }
494
495 init_core_client(argc, argv);
496
497 #ifdef _WIN32
498
499 retval = initialize_system_monitor(argc, argv);
500 if (retval) return retval;
501
502 if ( (argc > 1) && (strcmp(argv[1], "-daemon") == 0 || strcmp(argv[1], "--daemon") == 0) ) {
503 retval = initialize_service_dispatcher(argc, argv);
504 } else {
505 retval = boinc_main_loop();
506 }
507
508 #else
509
510 #ifdef SANDBOX
511 // Make sure owners, groups and permissions are correct
512 // for the current setting of g_use_sandbox
513 //
514 // NOTE: GDB and LLDB can't attach to applications which are running as
515 // a different user or group.
516 // Normally, the Mac Development (Debug) builds do not define SANDBOX, so
517 // check_security() is never called. However, it is possible to use GDB
518 // or LLDB on sandbox-specific code, as long as the code is run as the
519 // current user (i.e., not as boinc_master or boinc_project), and the
520 // current user is a member of both groups boinc_master and boinc_project.
521 // However, this has not been thoroughly tested. Please see the comments
522 // in SetupSecurity.cpp and check_security.cpp for more details.
523 int securityErr = check_security(g_use_sandbox, false, NULL, 0);
524 if (securityErr) {
525 #if (defined(__APPLE__) && defined (_DEBUG))
526 printf(
527 "To debug with sandbox security enabled, the current user\n"
528 "must be a member of both groups boinc_master and boinc_project."
529 );
530 #else // ! (defined(__APPLE__) && defined (_DEBUG))
531 printf(
532 "File ownership or permissions are set in a way that\n"
533 "does not allow sandboxed execution of BOINC applications.\n"
534 "To use BOINC anyway, use the -insecure command line option.\n"
535 "To change ownership/permission, reinstall BOINC"
536 #ifdef __APPLE__
537 " or run\n the shell script Mac_SA_Secure.sh"
538 #else
539 " or run\n the shell script secure.sh"
540 #endif
541 ". (Error code %d)\n", securityErr
542 );
543 #endif // ! (defined(__APPLE__) && defined (_DEBUG))
544 return ERR_USER_PERMISSION;
545 }
546 #endif // SANDBOX
547
548 retval = boinc_main_loop();
549
550 #endif
551 return retval;
552 }
553
554