1 /* radare2 - LGPL - Copyright 2009-2020 - pancake */
2 
3 #include <r_core.h>
4 
5 static const char *fortunes[] = {
6 	"tips", "fun",
7 };
8 
getFortuneFile(RCore * core,const char * type)9 static char *getFortuneFile(RCore *core, const char *type) {
10 	return r_str_newf (R_JOIN_3_PATHS ("%s", R2_FORTUNES, "fortunes.%s"),
11 		r_sys_prefix (NULL), type);
12 }
13 
r_core_fortune_list_types(void)14 R_API void r_core_fortune_list_types(void) {
15 	size_t i;
16 	for (i = 0; i < R_ARRAY_SIZE (fortunes); i++) {
17 		r_cons_printf ("%s\n", fortunes[i]);
18 	}
19 }
20 
r_core_fortune_list(RCore * core)21 R_API void r_core_fortune_list(RCore *core) {
22 	// TODO: use file.fortunes // can be dangerous in sandbox mode
23 	const char *types = (char *)r_config_get (core->config, "cfg.fortunes.type");
24 	size_t i, j;
25 	for (i = 0; i < R_ARRAY_SIZE (fortunes); i++) {
26 		if (strstr (types, fortunes[i])) {
27 			char *file = getFortuneFile (core, fortunes[i]);
28 			char *str = r_file_slurp (file, NULL);
29 			if (!str) {
30 				free (file);
31 				continue;
32 			}
33 			for (j = 0; str[j]; j++) {
34 				if (str[j] == '\n') {
35 					if (i < j) {
36 						str[j] = '\0';
37 						r_cons_printf ("%s\n", str + i);
38 					}
39 					i = j + 1;
40 				}
41 			}
42 			free (str);
43 			free (file);
44 		}
45 	}
46 }
47 
getrandomline(RCore * core)48 static char *getrandomline(RCore *core) {
49 	size_t i;
50 	const char *types = (char *)r_config_get (core->config, "cfg.fortunes.type");
51 	char *line = NULL, *templine;
52 	for (i = 0; i < R_ARRAY_SIZE (fortunes); i++) {
53 		if (strstr (types, fortunes[i])) {
54 			int lines = 0;
55 			char *file = getFortuneFile(core, fortunes[i]);
56 			templine = r_file_slurp_random_line_count (file, &lines);
57 			if (templine && *templine) {
58 				free (line);
59 				line = templine;
60 			}
61 			free (file);
62 		}
63 	}
64 	return line;
65 }
66 
r_core_fortune_print_random(RCore * core)67 R_API void r_core_fortune_print_random(RCore *core) {
68 	// TODO: use file.fortunes // can be dangerous in sandbox mode
69 	char *line = getrandomline (core);
70 	if (!line) {
71 		line = getrandomline (core);
72 	}
73 	if (line) {
74 		if (r_config_get_i (core->config, "cfg.fortunes.clippy")) {
75 			r_core_clippy (core, line);
76 		} else {
77 			r_cons_printf (" -- %s\n", line);
78 		}
79 		if (r_config_get_i (core->config, "cfg.fortunes.tts")) {
80 			r_sys_tts (line, true);
81 		}
82 		free (line);
83 	}
84 }
85