my_default.cc 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663
  1. /* Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
  2. This program is free software; you can redistribute it and/or modify
  3. it under the terms of the GNU General Public License, version 2.0,
  4. as published by the Free Software Foundation.
  5. This program is also distributed with certain software (including
  6. but not limited to OpenSSL) that is licensed under separate terms,
  7. as designated in a particular file or component or in included license
  8. documentation. The authors of MySQL hereby grant you an additional
  9. permission to link the program and your derivative works with the
  10. separately licensed software that they have included with MySQL.
  11. Without limiting anything contained in the foregoing, this file,
  12. which is part of C Driver for MySQL (Connector/C), is also subject to the
  13. Universal FOSS Exception, version 1.0, a copy of which can be found at
  14. http://oss.oracle.com/licenses/universal-foss-exception.
  15. This program is distributed in the hope that it will be useful,
  16. but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. GNU General Public License, version 2.0, for more details.
  19. You should have received a copy of the GNU General Public License
  20. along with this program; if not, write to the Free Software
  21. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
  22. /**
  23. @file mysys/my_default.cc
  24. Add all options from files named "group".cnf from the default_directories
  25. before the command line arguments.
  26. On Windows defaults will also search in the Windows directory for a file
  27. called 'group'.ini
  28. As long as the program uses the last argument for conflicting
  29. options one only have to add a call to "load_defaults" to enable
  30. use of default values.
  31. pre- and end 'blank space' are removed from options and values. The
  32. following escape sequences are recognized in values: @code \b \t \n \r \\
  33. @endcode
  34. The following arguments are handled automatically; If used, they must be
  35. first argument on the command line!
  36. --no-defaults ; no options are read, except for the ones provided in the
  37. login file.
  38. --defaults-file=full-path-to-default-file ; Only this file will be read.
  39. --defaults-extra-file=full-path-to-default-file ; Read this file before ~/
  40. --defaults-group-suffix ; Also read groups with concat(group, suffix)
  41. --print-defaults ; Print the modified command line and exit
  42. --login-path=login-path-name ; Read options under login-path-name from
  43. the login file.
  44. */
  45. #include "my_config.h"
  46. #include <fcntl.h>
  47. #include <stdio.h>
  48. #include <stdlib.h>
  49. #include <sys/types.h>
  50. #include "m_ctype.h"
  51. #include "m_string.h"
  52. #include "my_aes.h"
  53. #include "my_alloc.h"
  54. #include "my_byteorder.h"
  55. #include "my_compiler.h"
  56. #include "my_dbug.h"
  57. #include "my_default.h"
  58. #include "my_dir.h"
  59. #include "my_getopt.h"
  60. #include "my_inttypes.h"
  61. #include "my_io.h"
  62. #include "my_loglevel.h"
  63. #include "my_macros.h"
  64. #include "my_psi_config.h"
  65. #include "mysql/psi/mysql_file.h"
  66. #include "mysql_version.h" // MYSQL_PERSIST_CONFIG_NAME
  67. #include "mysys/my_default_priv.h"
  68. #include "mysys/mysys_priv.h"
  69. #include "mysys_err.h"
  70. #include "typelib.h"
  71. #ifdef _WIN32
  72. #include <winbase.h>
  73. #endif
  74. #include <map>
  75. #include <string>
  76. #include "prealloced_array.h"
  77. using std::string;
  78. struct my_variable_sources {
  79. string m_config_file_name;
  80. enum_variable_source m_source;
  81. };
  82. /**
  83. Defines mapping between variable names (set as part of config files
  84. or command line) and its config file/source value.
  85. ex: If config file /etc/my.cnf has variables max_connections= 30 and
  86. $datadir/mysqld-auto.cnf has variables max_heap_table_size=887808
  87. then this variable will have following key/value pair.
  88. max_connections -> (/etc/my.cnf , enum_variable_source::GLOBAL)
  89. max_heap_table_size -> ($datadir/mysqld-auto.cnf ,
  90. enum_variable_source::PERSISTED)
  91. */
  92. static std::map<string, my_variable_sources> variables_hash;
  93. /**
  94. Defines mapping between config files names and its corresponding enum values.
  95. ex: File /etc/my.cnf is mapped to enum_variable_source::GLOBAL
  96. ~/.my.cnf is mapped to enum_variable_source::USER
  97. command line options are mapped to enum_variable_source::COMMAND_LINE
  98. */
  99. static std::map<string, enum_variable_source> default_paths;
  100. /**
  101. Holds a reference to the directory where the persisted configuration
  102. file is located.
  103. This usually is the data directory.
  104. This is different from ::mysql_real_data_home mostly because it's passed down
  105. to mysys. And is also filled in a bit differently from ::mysql_real_data_home
  106. by Persisted_variables_cache::init()
  107. */
  108. char datadir_buffer[FN_REFLEN] = {0};
  109. #ifdef HAVE_PSI_INTERFACE
  110. extern PSI_file_key key_file_cnf;
  111. #endif
  112. PSI_memory_key key_memory_defaults;
  113. /**
  114. arguments separator
  115. load_defaults() loads arguments from config file and put them
  116. before the arguments from command line, this separator is used to
  117. separate the arguments loaded from config file and arguments user
  118. provided on command line.
  119. Options with value loaded from config file are always in the form
  120. '--option=value', while for command line options, the value can be
  121. given as the next argument. Thus we used a separator so that
  122. handle_options() can distinguish them.
  123. Note: any other places that does not need to distinguish them
  124. should skip the separator.
  125. The content of arguments separator does not matter, one should only
  126. check the pointer, use "----args-separator----" here to ease debug
  127. if someone misused it.
  128. The args seprator will only be added when
  129. my_getopt_use_args_seprator is set to TRUE before calling
  130. load_defaults();
  131. See BUG#25192
  132. */
  133. static const char *args_separator = "----args-separator----";
  134. inline static void set_args_separator(const char **arg) {
  135. DBUG_ASSERT(my_getopt_use_args_separator);
  136. *arg = args_separator;
  137. }
  138. /*
  139. persisted arguments separator
  140. This argument separator string is used to separate arguments loaded
  141. from persisted config file and command line arguments. This string
  142. is placed after command line options if there are any read only
  143. persisted variables in persisted config file.
  144. */
  145. static const char *persist_args_separator = "----persist-args-separator----";
  146. void set_persist_args_separator(char **arg) {
  147. *arg = const_cast<char *>(persist_args_separator);
  148. }
  149. bool my_getopt_is_ro_persist_args_separator(const char *arg) {
  150. return (arg == persist_args_separator);
  151. }
  152. /*
  153. This flag indicates that the argument separator string
  154. (args_separator) should be added to the list of arguments,
  155. in order to separate arguments received from config file
  156. and command line.
  157. */
  158. bool my_getopt_use_args_separator = false;
  159. bool my_getopt_is_args_separator(const char *arg) {
  160. return (arg == args_separator);
  161. }
  162. const char *my_defaults_file = 0;
  163. const char *my_defaults_group_suffix = 0;
  164. const char *my_defaults_extra_file = 0;
  165. static const char *my_login_path = 0;
  166. static char my_defaults_file_buffer[FN_REFLEN];
  167. static char my_defaults_extra_file_buffer[FN_REFLEN];
  168. static bool defaults_already_read = false;
  169. /* Set to TRUE, if --no-defaults is found. */
  170. bool no_defaults = false;
  171. /* Which directories are searched for options (and in which order) */
  172. #define MAX_DEFAULT_DIRS 6
  173. #define DEFAULT_DIRS_SIZE (MAX_DEFAULT_DIRS + 1) /* Terminate with NULL */
  174. static const char **default_directories = NULL;
  175. #ifdef _WIN32
  176. static const char *f_extensions[] = {".ini", ".cnf", 0};
  177. #else
  178. static const char *f_extensions[] = {".cnf", 0};
  179. #endif
  180. extern "C" {
  181. static int handle_default_option(void *in_ctx, const char *group_name,
  182. const char *option, const char *cnf_file);
  183. }
  184. /*
  185. This structure defines the context that we pass to callback
  186. function 'handle_default_option' used in search_default_file
  187. to process each option. This context is used if search_default_file
  188. was called from load_defaults.
  189. */
  190. typedef Prealloced_array<char *, 100> My_args;
  191. struct handle_option_ctx {
  192. MEM_ROOT *alloc;
  193. My_args *m_args;
  194. TYPELIB *group;
  195. };
  196. static int search_default_file(Process_option_func func, void *func_ctx,
  197. const char *dir, const char *config_file,
  198. bool is_login_file);
  199. static int search_default_file_with_ext(
  200. Process_option_func func, void *func_ctx, const char *dir, const char *ext,
  201. const char *config_file, int recursion_level, bool is_login_file);
  202. static bool mysql_file_getline(char *str, int size, MYSQL_FILE *file,
  203. bool is_login_file);
  204. /**
  205. Create the list of default directories.
  206. @verbatim
  207. The directories searched, in order, are:
  208. - Windows: GetSystemWindowsDirectory()
  209. - Windows: GetWindowsDirectory()
  210. - Windows: C:/
  211. - Windows: Directory above where the executable is located
  212. - Unix: /etc/
  213. - Unix: /etc/mysql/
  214. - Unix: --sysconfdir=<path> (compile-time option)
  215. - ALL: getenv("MYSQL_HOME")
  216. - ALL: --defaults-extra-file=<path> (run-time option)
  217. - Unix: ~/
  218. @endverbatim
  219. On all systems, if a directory is already in the list, it will be moved
  220. to the end of the list. This avoids reading defaults files multiple times,
  221. while ensuring the correct precedence.
  222. @param alloc MEM_ROOT where the list of directories is stored
  223. @retval NULL Failure (out of memory, probably)
  224. @retval other Pointer to NULL-terminated array of default directories
  225. */
  226. static const char **init_default_directories(MEM_ROOT *alloc);
  227. static char *remove_end_comment(char *ptr);
  228. /*
  229. Expand a file name so that the current working directory is added if
  230. the name is relative.
  231. RETURNS
  232. 0 All OK
  233. 2 Out of memory or path too long
  234. 3 Not able to get working directory
  235. */
  236. static int fn_expand(const char *filename, char *result_buf) {
  237. char dir[FN_REFLEN];
  238. const int flags = MY_UNPACK_FILENAME | MY_SAFE_PATH | MY_RELATIVE_PATH;
  239. DBUG_ENTER("fn_expand");
  240. DBUG_PRINT("enter", ("filename: %s, result_buf: %p", filename, result_buf));
  241. if (my_getwd(dir, sizeof(dir), MYF(0))) DBUG_RETURN(3);
  242. DBUG_PRINT("debug", ("dir: %s", dir));
  243. if (fn_format(result_buf, filename, dir, "", flags) == NULL) DBUG_RETURN(2);
  244. DBUG_PRINT("return", ("result: %s", result_buf));
  245. DBUG_RETURN(0);
  246. }
  247. /*
  248. Process config files in default directories.
  249. SYNOPSIS
  250. my_search_option_files()
  251. conf_file Basename for configuration file to search for.
  252. If this is a path, then only this file is read.
  253. argc Pointer to argc of original program
  254. argv Pointer to argv of original program
  255. args_used Pointer to variable for storing the number of
  256. arguments used.
  257. func Pointer to the function to process options
  258. func_ctx It's context. Usually it is the structure to
  259. store additional options.
  260. default_directories List of default directories.
  261. found_no_defaults TRUE, if --no-defaults is specified.
  262. DESCRIPTION
  263. Process the default options from argc & argv
  264. Read through each found config file looks and calls 'func' to process
  265. each option. This function also reads options from login file.
  266. NOTES
  267. --defaults-group-suffix is only processed if we are called from
  268. load_defaults().
  269. RETURN
  270. 0 ok
  271. 1 given cinf_file doesn't exist
  272. 2 out of memory
  273. 3 Can't get current working directory
  274. The global variable 'my_defaults_group_suffix' is updated with value for
  275. --defaults_group_suffix
  276. */
  277. int my_search_option_files(const char *conf_file, int *argc, char ***argv,
  278. uint *args_used, Process_option_func func,
  279. void *func_ctx, const char **default_directories,
  280. bool is_login_file, bool found_no_defaults) {
  281. const char **dirs;
  282. char *forced_default_file, *forced_extra_defaults;
  283. int error = 0;
  284. DBUG_ENTER("my_search_option_files");
  285. /* Skip for login file. */
  286. if (!is_login_file) {
  287. /* Check if we want to force the use a specific default file */
  288. *args_used += get_defaults_options(
  289. *argc - *args_used, *argv + *args_used, &forced_default_file,
  290. &forced_extra_defaults, const_cast<char **>(&my_defaults_group_suffix),
  291. const_cast<char **>(&my_login_path), found_no_defaults);
  292. if (!my_defaults_group_suffix)
  293. my_defaults_group_suffix = getenv("MYSQL_GROUP_SUFFIX");
  294. if (forced_extra_defaults && !defaults_already_read) {
  295. int error =
  296. fn_expand(forced_extra_defaults, my_defaults_extra_file_buffer);
  297. if (error) DBUG_RETURN(error);
  298. my_defaults_extra_file = my_defaults_extra_file_buffer;
  299. }
  300. if (forced_default_file && !defaults_already_read) {
  301. int error = fn_expand(forced_default_file, my_defaults_file_buffer);
  302. if (error) DBUG_RETURN(error);
  303. my_defaults_file = my_defaults_file_buffer;
  304. }
  305. defaults_already_read = true;
  306. init_variable_default_paths();
  307. /*
  308. We can only handle 'defaults-group-suffix' if we are called from
  309. load_defaults() as otherwise we can't know the type of 'func_ctx'
  310. */
  311. if (my_defaults_group_suffix && func == handle_default_option) {
  312. /* Handle --defaults-group-suffix= */
  313. uint i;
  314. const char **extra_groups;
  315. const size_t instance_len = strlen(my_defaults_group_suffix);
  316. struct handle_option_ctx *ctx = (struct handle_option_ctx *)func_ctx;
  317. char *ptr;
  318. TYPELIB *group = ctx->group;
  319. if (!(extra_groups = (const char **)ctx->alloc->Alloc(
  320. (2 * group->count + 1) * sizeof(char *))))
  321. DBUG_RETURN(2);
  322. for (i = 0; i < group->count; i++) {
  323. size_t len;
  324. extra_groups[i] = group->type_names[i]; /** copy group */
  325. len = strlen(extra_groups[i]);
  326. if (!(ptr = (char *)ctx->alloc->Alloc((uint)(len + instance_len + 1))))
  327. DBUG_RETURN(2);
  328. extra_groups[i + group->count] = ptr;
  329. /** Construct new group */
  330. memcpy(ptr, extra_groups[i], len);
  331. memcpy(ptr + len, my_defaults_group_suffix, instance_len + 1);
  332. }
  333. group->count *= 2;
  334. group->type_names = extra_groups;
  335. group->type_names[group->count] = 0;
  336. }
  337. } else if (my_login_path && func == handle_default_option) {
  338. /* Handle --login_path= */
  339. uint i;
  340. size_t len;
  341. const char **extra_groups;
  342. size_t instance_len = 0;
  343. struct handle_option_ctx *ctx = (struct handle_option_ctx *)func_ctx;
  344. char *ptr;
  345. TYPELIB *group = ctx->group;
  346. if (!(extra_groups = (const char **)ctx->alloc->Alloc((group->count + 3) *
  347. sizeof(char *))))
  348. DBUG_RETURN(2);
  349. for (i = 0; i < group->count; i++) {
  350. extra_groups[i] = group->type_names[i]; /** copy group */
  351. }
  352. extra_groups[i] = my_login_path;
  353. if (my_defaults_group_suffix && func == handle_default_option) {
  354. instance_len = strlen(my_defaults_group_suffix);
  355. len = strlen(extra_groups[i]);
  356. if (!(ptr = (char *)ctx->alloc->Alloc((uint)(len + instance_len + 1))))
  357. DBUG_RETURN(2);
  358. extra_groups[i + 1] = ptr;
  359. /** Construct new group */
  360. memcpy(ptr, extra_groups[i], len);
  361. memcpy(ptr + len, my_defaults_group_suffix, instance_len + 1);
  362. group->count += 1;
  363. }
  364. group->count += 1;
  365. group->type_names = extra_groups;
  366. group->type_names[group->count] = 0;
  367. }
  368. // If conf_file is an absolute path, we only read it
  369. if (dirname_length(conf_file)) {
  370. if ((error = search_default_file(func, func_ctx, NullS, conf_file,
  371. is_login_file)) < 0)
  372. goto err;
  373. }
  374. // If my defaults file is set (from a previous run), we read it
  375. else if (my_defaults_file) {
  376. if ((error = search_default_file_with_ext(
  377. func, func_ctx, "", "", my_defaults_file, 0, is_login_file)) < 0)
  378. goto err;
  379. if (error > 0) {
  380. my_message_local(ERROR_LEVEL, EE_FAILED_TO_OPEN_DEFAULTS_FILE,
  381. my_defaults_file);
  382. goto err;
  383. }
  384. } else if (!found_no_defaults) {
  385. for (dirs = default_directories; *dirs; dirs++) {
  386. if (**dirs) {
  387. if (search_default_file(func, func_ctx, *dirs, conf_file,
  388. is_login_file) < 0)
  389. goto err;
  390. } else if (my_defaults_extra_file) {
  391. if ((error = search_default_file_with_ext(func, func_ctx, "", "",
  392. my_defaults_extra_file, 0,
  393. is_login_file)) < 0)
  394. goto err; /* Fatal error */
  395. if (error > 0) {
  396. my_message_local(ERROR_LEVEL, EE_FAILED_TO_OPEN_DEFAULTS_FILE,
  397. my_defaults_extra_file);
  398. goto err;
  399. }
  400. }
  401. }
  402. }
  403. DBUG_RETURN(0);
  404. err:
  405. my_message_local(ERROR_LEVEL, EE_FAILED_TO_HANDLE_DEFAULTS_FILE);
  406. DBUG_RETURN(1);
  407. }
  408. /*
  409. The option handler for load_defaults.
  410. SYNOPSIS
  411. handle_deault_option()
  412. in_ctx Handler context. In this case it is a
  413. handle_option_ctx structure.
  414. group_name The name of the group the option belongs to.
  415. option The very option to be processed. It is already
  416. prepared to be used in argv (has -- prefix). If it
  417. is NULL, we are handling a new group (section).
  418. cnf_file Config file name with absolute file path.
  419. DESCRIPTION
  420. This handler checks whether a group is one of the listed and adds an option
  421. to the array if yes. Some other handler can record, for instance, all
  422. groups and their options, not knowing in advance the names and amount of
  423. groups.
  424. RETURN
  425. 0 - ok
  426. 1 - error occurred
  427. */
  428. static int handle_default_option(void *in_ctx, const char *group_name,
  429. const char *option, const char *cnf_file) {
  430. char *tmp;
  431. struct handle_option_ctx *ctx = (struct handle_option_ctx *)in_ctx;
  432. if (!option) return 0;
  433. if (find_type(group_name, ctx->group, FIND_TYPE_NO_PREFIX)) {
  434. if (!(tmp = (char *)ctx->alloc->Alloc(strlen(option) + 1))) return 1;
  435. if (ctx->m_args->push_back(tmp)) return 1;
  436. my_stpcpy(tmp, option);
  437. update_variable_source(option, cnf_file);
  438. }
  439. return 0;
  440. }
  441. /*
  442. Gets options from the command line, however if --no-defaults
  443. option is used, --defaults-file & --defaults-extra-file options
  444. would be ignored.
  445. SYNOPSIS
  446. get_defaults_options()
  447. argc Pointer to argc of original program
  448. argv Pointer to argv of original program
  449. defaults --defaults-file option
  450. extra_defaults --defaults-extra-file option
  451. group_suffix --defaults-group-suffix option
  452. login_path --login-path option
  453. RETURN
  454. # Number of arguments used from *argv
  455. defaults and extra_defaults will be set to option of the appropriate
  456. items of argv array, or to NULL if there are no such options
  457. */
  458. int get_defaults_options(int argc, char **argv, char **defaults,
  459. char **extra_defaults, char **group_suffix,
  460. char **login_path, bool found_no_defaults) {
  461. int org_argc = argc, prev_argc = 0, default_option_count = 0;
  462. *defaults = *extra_defaults = *group_suffix = *login_path = 0;
  463. while (argc >= 2 && argc != prev_argc) {
  464. /* Skip program name or previously handled argument */
  465. argv++;
  466. prev_argc = argc; /* To check if we found */
  467. /* --no-defaults is always the first option. */
  468. if (is_prefix(*argv, "--no-defaults") && !default_option_count) {
  469. argc--;
  470. default_option_count++;
  471. continue;
  472. }
  473. if (!*defaults && is_prefix(*argv, "--defaults-file=") &&
  474. !found_no_defaults) {
  475. *defaults = *argv + sizeof("--defaults-file=") - 1;
  476. argc--;
  477. default_option_count++;
  478. continue;
  479. }
  480. if (!*extra_defaults && is_prefix(*argv, "--defaults-extra-file=") &&
  481. !found_no_defaults) {
  482. *extra_defaults = *argv + sizeof("--defaults-extra-file=") - 1;
  483. argc--;
  484. default_option_count++;
  485. continue;
  486. }
  487. if (!*group_suffix && is_prefix(*argv, "--defaults-group-suffix=")) {
  488. *group_suffix = *argv + sizeof("--defaults-group-suffix=") - 1;
  489. argc--;
  490. default_option_count++;
  491. continue;
  492. }
  493. if (!*login_path && is_prefix(*argv, "--login-path=")) {
  494. *login_path = *argv + sizeof("--login-path=") - 1;
  495. argc--;
  496. default_option_count++;
  497. continue;
  498. }
  499. }
  500. return org_argc - argc;
  501. }
  502. /*
  503. Wrapper around my_load_defaults() for interface compatibility.
  504. SYNOPSIS
  505. load_defaults()
  506. conf_file Basename for configuration file to search for.
  507. If this is a path, then only this file is read.
  508. groups Which [group] entrys to read.
  509. Points to an null terminated array of pointers
  510. argc Pointer to argc of original program
  511. argv Pointer to argv of original program
  512. alloc MEM_ROOT to allocate new argv on
  513. NOTES
  514. This function is NOT thread-safe as it uses a global pointer internally.
  515. See also notes for my_load_defaults().
  516. RETURN
  517. 0 ok
  518. 1 The given conf_file didn't exists
  519. */
  520. int load_defaults(const char *conf_file, const char **groups, int *argc,
  521. char ***argv, MEM_ROOT *alloc) {
  522. return my_load_defaults(conf_file, groups, argc, argv, alloc,
  523. &default_directories);
  524. }
  525. /** A global to turn off or on reading the mylogin file. On by default */
  526. bool my_defaults_read_login_file = true;
  527. /*
  528. Read options from configurations files
  529. SYNOPSIS
  530. my_load_defaults()
  531. conf_file Basename for configuration file to search for.
  532. If this is a path, then only this file is read.
  533. groups Which [group] entrys to read.
  534. Points to an null terminated array of pointers
  535. argc Pointer to argc of original program
  536. argv Pointer to argv of original program
  537. alloc MEM_ROOT to allocate new argv on
  538. default_directories Pointer to a location where a pointer to the
  539. list of default directories will be stored
  540. IMPLEMENTATION
  541. Read options from configuration files and put them BEFORE the arguments
  542. that are already in argc and argv. This way the calling program can
  543. easily command line options override options in configuration files
  544. NOTES
  545. In case of fatal error, the function will print a warning and do
  546. exit(1)
  547. argv will be replaced with a set of filtered arguments, allocated on
  548. the MEM_ROOT given in as "alloc". You must free this MEM_ROOT yourself.
  549. RETURN
  550. - If successful, 0 is returned. If 'default_directories' is not NULL,
  551. a pointer to the array of default directory paths is stored to a location
  552. it points to. That stored value must be passed to my_search_option_files()
  553. later.
  554. - 1 is returned if the given conf_file didn't exist. In this case, the
  555. value pointed to by default_directories is undefined.
  556. */
  557. int my_load_defaults(const char *conf_file, const char **groups, int *argc,
  558. char ***argv, MEM_ROOT *alloc,
  559. const char ***default_directories) {
  560. My_args my_args(key_memory_defaults);
  561. TYPELIB group;
  562. bool found_print_defaults = 0;
  563. uint args_used = 0;
  564. int error = 0;
  565. const char **ptr;
  566. const char **res;
  567. struct handle_option_ctx ctx;
  568. const char **dirs;
  569. char my_login_file[FN_REFLEN];
  570. bool found_no_defaults = false;
  571. uint args_sep = my_getopt_use_args_separator ? 1 : 0;
  572. DBUG_ENTER("load_defaults");
  573. if ((dirs = init_default_directories(alloc)) == NULL) goto err;
  574. /*
  575. Check if the user doesn't want any default option processing
  576. --no-defaults is always the first option
  577. */
  578. if (*argc >= 2 && !strcmp(argv[0][1], "--no-defaults"))
  579. no_defaults = found_no_defaults = true;
  580. group.count = 0;
  581. group.name = "defaults";
  582. group.type_names = groups;
  583. for (; *groups; groups++) group.count++;
  584. ctx.alloc = alloc;
  585. ctx.m_args = &my_args;
  586. ctx.group = &group;
  587. if ((error = my_search_option_files(conf_file, argc, argv, &args_used,
  588. handle_default_option, (void *)&ctx, dirs,
  589. false, found_no_defaults))) {
  590. DBUG_RETURN(error);
  591. }
  592. if (my_defaults_read_login_file) {
  593. /* Read options from login group. */
  594. if (my_default_get_login_file(my_login_file, sizeof(my_login_file)) &&
  595. (error = my_search_option_files(my_login_file, argc, argv, &args_used,
  596. handle_default_option, (void *)&ctx,
  597. dirs, true, found_no_defaults))) {
  598. free_root(alloc, MYF(0));
  599. DBUG_RETURN(error);
  600. }
  601. }
  602. /*
  603. Here error contains <> 0 only if we have a fully specified conf_file
  604. or a forced default file
  605. */
  606. if (!(ptr = (const char **)alloc->Alloc(
  607. (my_args.size() + *argc + 1 + args_sep) * sizeof(char *))))
  608. goto err;
  609. res = ptr;
  610. /* copy name + found arguments + command line arguments to new array */
  611. res[0] = argv[0][0]; /* Name MUST be set */
  612. if (!my_args.empty())
  613. memcpy((res + 1), &my_args[0], my_args.size() * sizeof(char *));
  614. /* Skip --defaults-xxx options */
  615. (*argc) -= args_used;
  616. (*argv) += args_used;
  617. /*
  618. Check if we wan't to see the new argument list
  619. This options must always be the last of the default options
  620. */
  621. if (*argc >= 2 && !strcmp(argv[0][1], "--print-defaults")) {
  622. found_print_defaults = 1;
  623. --*argc;
  624. ++*argv; /* skip argument */
  625. }
  626. if (my_getopt_use_args_separator) {
  627. /* set arguments separator for arguments from config file and
  628. command line */
  629. set_args_separator(&res[my_args.size() + 1]);
  630. }
  631. if (*argc)
  632. memcpy((uchar *)(res + 1 + my_args.size() + args_sep),
  633. (char *)((*argv) + 1), (*argc - 1) * sizeof(char *));
  634. res[my_args.size() + *argc + args_sep] = 0; /* last null */
  635. (*argc) += my_args.size() + args_sep;
  636. *argv = const_cast<char **>(res);
  637. if (default_directories) *default_directories = dirs;
  638. if (found_no_defaults) DBUG_RETURN(0);
  639. if (found_print_defaults) {
  640. int i;
  641. printf("%s would have been started with the following arguments:\n",
  642. **argv);
  643. for (i = 1; i < *argc; i++)
  644. if (!my_getopt_is_args_separator(
  645. (*argv)[i])) /* skip arguments separator */
  646. {
  647. if (strncmp((*argv)[i], "--password", 10) == 0)
  648. printf("%s ", "--password=*****");
  649. else
  650. printf("%s ", (*argv)[i]);
  651. }
  652. puts("");
  653. exit(0);
  654. }
  655. DBUG_RETURN(0);
  656. err:
  657. my_message_local(ERROR_LEVEL, EE_FAILED_TO_HANDLE_DEFAULTS_FILE);
  658. exit(1);
  659. return 0; /* Keep compiler happy */
  660. }
  661. static int search_default_file(Process_option_func opt_handler,
  662. void *handler_ctx, const char *dir,
  663. const char *config_file, bool is_login_file) {
  664. const char **ext;
  665. const char *empty_list[] = {"", 0};
  666. bool have_ext = fn_ext(config_file)[0] != 0;
  667. const char **exts_to_use = have_ext ? empty_list : f_extensions;
  668. for (ext = exts_to_use; *ext; ext++) {
  669. int error;
  670. if ((error =
  671. search_default_file_with_ext(opt_handler, handler_ctx, dir, *ext,
  672. config_file, 0, is_login_file)) < 0)
  673. return error;
  674. }
  675. return 0;
  676. }
  677. /*
  678. Skip over keyword and get argument after keyword
  679. SYNOPSIS
  680. get_argument()
  681. keyword Include directive keyword
  682. kwlen Length of keyword
  683. ptr Pointer to the keword in the line under process
  684. line line number
  685. RETURN
  686. 0 error
  687. # Returns pointer to the argument after the keyword.
  688. */
  689. static char *get_argument(const char *keyword, size_t kwlen, char *ptr,
  690. char *name, uint line) {
  691. char *end;
  692. /* Skip over "include / includedir keyword" and following whitespace */
  693. for (ptr += kwlen - 1; my_isspace(&my_charset_latin1, ptr[0]); ptr++) {
  694. }
  695. /*
  696. Trim trailing whitespace from directory name
  697. The -1 below is for the newline added by fgets()
  698. Note that my_isspace() is true for \r and \n
  699. */
  700. for (end = ptr + strlen(ptr) - 1; my_isspace(&my_charset_latin1, *(end - 1));
  701. end--) {
  702. }
  703. end[0] = 0; /* Cut off end space */
  704. /* Print error msg if there is nothing after !include* directive */
  705. if (end <= ptr) {
  706. my_message_local(ERROR_LEVEL, EE_WRONG_DIRECTIVE_IN_CONFIG_FILE, keyword,
  707. name, line);
  708. return 0;
  709. }
  710. return ptr;
  711. }
  712. /*
  713. Open a configuration file (if exists) and read given options from it
  714. SYNOPSIS
  715. search_default_file_with_ext()
  716. opt_handler Option handler function. It is used to process
  717. every separate option.
  718. handler_ctx Pointer to the structure to store actual
  719. parameters of the function.
  720. dir directory to read
  721. ext Extension for configuration file
  722. config_file Name of configuration file
  723. group groups to read
  724. recursion_level the level of recursion, got while processing
  725. "!include" or "!includedir"
  726. is_login_file TRUE, when login file is being processed.
  727. RETURN
  728. 0 Success
  729. -1 Fatal error, abort
  730. 1 File not found (Warning)
  731. */
  732. static int search_default_file_with_ext(Process_option_func opt_handler,
  733. void *handler_ctx, const char *dir,
  734. const char *ext,
  735. const char *config_file,
  736. int recursion_level,
  737. bool is_login_file) {
  738. char name[FN_REFLEN + 10], buff[4096], curr_gr[4096], *ptr, *end;
  739. const char **tmp_ext;
  740. char *value, option[4096 + 2], tmp[FN_REFLEN];
  741. static const char includedir_keyword[] = "includedir";
  742. static const char include_keyword[] = "include";
  743. const int max_recursion_level = 10;
  744. MYSQL_FILE *fp;
  745. uint line = 0;
  746. bool found_group = 0;
  747. uint i, rc;
  748. MY_DIR *search_dir;
  749. FILEINFO *search_file;
  750. if ((dir ? strlen(dir) : 0) + strlen(config_file) >= FN_REFLEN - 3)
  751. return 0; /* Ignore wrong paths */
  752. if (dir) {
  753. end = convert_dirname(name, dir, NullS);
  754. if (dir[0] == FN_HOMELIB) /* Add . to filenames in home */
  755. *end++ = '.';
  756. strxmov(end, config_file, ext, NullS);
  757. } else {
  758. my_stpcpy(name, config_file);
  759. }
  760. fn_format(name, name, "", "", MY_UNPACK_FILENAME);
  761. if ((rc = check_file_permissions(name, is_login_file)) < 2) return (int)rc;
  762. if (is_login_file) {
  763. if (!(fp = mysql_file_fopen(key_file_cnf, name, O_RDONLY | MY_FOPEN_BINARY,
  764. MYF(0))))
  765. return 1; /* Ignore wrong files. */
  766. } else {
  767. if (!(fp = mysql_file_fopen(key_file_cnf, name, O_RDONLY, MYF(0))))
  768. return 1; /* Ignore wrong files */
  769. }
  770. while (mysql_file_getline(buff, sizeof(buff) - 1, fp, is_login_file)) {
  771. line++;
  772. /* Ignore comment and empty lines */
  773. for (ptr = buff; my_isspace(&my_charset_latin1, *ptr); ptr++) {
  774. }
  775. if (*ptr == '#' || *ptr == ';' || !*ptr) continue;
  776. /* Configuration File Directives */
  777. if (*ptr == '!') {
  778. if (recursion_level >= max_recursion_level) {
  779. for (end = ptr + strlen(ptr) - 1;
  780. my_isspace(&my_charset_latin1, *(end - 1)); end--) {
  781. }
  782. end[0] = 0;
  783. my_message_local(WARNING_LEVEL,
  784. EE_SKIPPING_DIRECTIVE_DUE_TO_MAX_INCLUDE_RECURSION,
  785. ptr, name, line);
  786. continue;
  787. }
  788. /* skip over `!' and following whitespace */
  789. for (++ptr; my_isspace(&my_charset_latin1, ptr[0]); ptr++) {
  790. }
  791. if ((!strncmp(ptr, includedir_keyword, sizeof(includedir_keyword) - 1)) &&
  792. my_isspace(&my_charset_latin1, ptr[sizeof(includedir_keyword) - 1])) {
  793. if (!(ptr = get_argument(includedir_keyword, sizeof(includedir_keyword),
  794. ptr, name, line)))
  795. goto err;
  796. if (!(search_dir = my_dir(ptr, MYF(MY_WME)))) goto err;
  797. for (i = 0; i < search_dir->number_off_files; i++) {
  798. search_file = search_dir->dir_entry + i;
  799. ext = fn_ext(search_file->name);
  800. /* check extension */
  801. for (tmp_ext = f_extensions; *tmp_ext; tmp_ext++) {
  802. if (!strcmp(ext, *tmp_ext)) break;
  803. }
  804. if (*tmp_ext) {
  805. fn_format(tmp, search_file->name, ptr, "",
  806. MY_UNPACK_FILENAME | MY_SAFE_PATH);
  807. /* add the include file to the paths list with the class of the
  808. * including file */
  809. std::map<string, enum_variable_source>::iterator it =
  810. default_paths.find(name);
  811. /*
  812. The current file should always be a part of the paths.
  813. But that applies only for the server.
  814. For direct load_defaults() use all bets are off.
  815. Hence keeping it as a dynamic condition.
  816. */
  817. if (it != default_paths.end()) default_paths[tmp] = it->second;
  818. search_default_file_with_ext(opt_handler, handler_ctx, NULL, NULL,
  819. tmp, recursion_level + 1,
  820. is_login_file);
  821. }
  822. }
  823. my_dirend(search_dir);
  824. } else if ((!strncmp(ptr, include_keyword,
  825. sizeof(include_keyword) - 1)) &&
  826. my_isspace(&my_charset_latin1,
  827. ptr[sizeof(include_keyword) - 1])) {
  828. if (!(ptr = get_argument(include_keyword, sizeof(include_keyword), ptr,
  829. name, line)))
  830. goto err;
  831. /* add the include file to the paths list with the class of the
  832. * including file */
  833. std::map<string, enum_variable_source>::iterator it =
  834. default_paths.find(name);
  835. /*
  836. The current file should always be a part of the paths.
  837. But that applies only for the server.
  838. For direct load_defaults() use all bets are off.
  839. Hence keeping it as a dynamic condition.
  840. */
  841. if (it != default_paths.end() &&
  842. fn_format(tmp, ptr, "", "", MY_UNPACK_FILENAME | MY_SAFE_PATH))
  843. default_paths[tmp] = it->second;
  844. search_default_file_with_ext(opt_handler, handler_ctx, NULL, NULL, ptr,
  845. recursion_level + 1, is_login_file);
  846. }
  847. continue;
  848. }
  849. if (*ptr == '[') /* Group name */
  850. {
  851. found_group = 1;
  852. if (!(end = strchr(++ptr, ']'))) {
  853. my_message_local(ERROR_LEVEL,
  854. EE_INCORRECT_GRP_DEFINITION_IN_CONFIG_FILE, name,
  855. line);
  856. goto err;
  857. }
  858. /* Remove end space */
  859. for (; my_isspace(&my_charset_latin1, end[-1]); end--) {
  860. }
  861. end[0] = 0;
  862. strmake(curr_gr, ptr,
  863. MY_MIN((size_t)(end - ptr) + 1, sizeof(curr_gr) - 1));
  864. /* signal that a new group is found */
  865. opt_handler(handler_ctx, curr_gr, NULL, NULL);
  866. continue;
  867. }
  868. if (!found_group) {
  869. my_message_local(ERROR_LEVEL, EE_OPTION_WITHOUT_GRP_IN_CONFIG_FILE, name,
  870. line);
  871. goto err;
  872. }
  873. end = remove_end_comment(ptr);
  874. if ((value = strchr(ptr, '='))) end = value; /* Option without argument */
  875. for (; my_isspace(&my_charset_latin1, end[-1]); end--) {
  876. }
  877. if (!value) {
  878. strmake(my_stpcpy(option, "--"), ptr, (size_t)(end - ptr));
  879. if (opt_handler(handler_ctx, curr_gr, option, name)) goto err;
  880. } else {
  881. /* Remove pre- and end space */
  882. char *value_end;
  883. for (value++; my_isspace(&my_charset_latin1, *value); value++) {
  884. }
  885. value_end = strend(value);
  886. /*
  887. We don't have to test for value_end >= value as we know there is
  888. an '=' before
  889. */
  890. for (; my_isspace(&my_charset_latin1, value_end[-1]); value_end--) {
  891. }
  892. if (value_end < value) /* Empty string */
  893. value_end = value;
  894. /* remove quotes around argument */
  895. if ((*value == '\"' || *value == '\'') && /* First char is quote */
  896. (value + 1 < value_end) && /* String is longer than 1 */
  897. *value == value_end[-1]) /* First char is equal to last char */
  898. {
  899. value++;
  900. value_end--;
  901. }
  902. ptr = my_stpnmov(my_stpcpy(option, "--"), ptr, (size_t)(end - ptr));
  903. *ptr++ = '=';
  904. for (; value != value_end; value++) {
  905. if (*value == '\\' && value != value_end - 1) {
  906. switch (*++value) {
  907. case 'n':
  908. *ptr++ = '\n';
  909. break;
  910. case 't':
  911. *ptr++ = '\t';
  912. break;
  913. case 'r':
  914. *ptr++ = '\r';
  915. break;
  916. case 'b':
  917. *ptr++ = '\b';
  918. break;
  919. case 's':
  920. *ptr++ = ' '; /* space */
  921. break;
  922. case '\"':
  923. *ptr++ = '\"';
  924. break;
  925. case '\'':
  926. *ptr++ = '\'';
  927. break;
  928. case '\\':
  929. *ptr++ = '\\';
  930. break;
  931. default: /* Unknown; Keep '\' */
  932. *ptr++ = '\\';
  933. *ptr++ = *value;
  934. break;
  935. }
  936. } else
  937. *ptr++ = *value;
  938. }
  939. *ptr = 0;
  940. if (opt_handler(handler_ctx, curr_gr, option, name)) goto err;
  941. }
  942. }
  943. mysql_file_fclose(fp, MYF(0));
  944. return (0);
  945. err:
  946. mysql_file_fclose(fp, MYF(0));
  947. return -1; /* Fatal error */
  948. }
  949. static char *remove_end_comment(char *ptr) {
  950. char quote = 0; /* we are inside quote marks */
  951. char escape = 0; /* symbol is protected by escape chagacter */
  952. for (; *ptr; ptr++) {
  953. if ((*ptr == '\'' || *ptr == '\"') && !escape) {
  954. if (!quote)
  955. quote = *ptr;
  956. else if (quote == *ptr)
  957. quote = 0;
  958. }
  959. /* We are not inside a string */
  960. if (!quote && *ptr == '#') {
  961. *ptr = 0;
  962. return ptr;
  963. }
  964. escape = (quote && *ptr == '\\' && !escape);
  965. }
  966. return ptr;
  967. }
  968. /**
  969. Read one line from the specified file. In case
  970. of scrambled login file, the line read is first
  971. decrypted and then returned.
  972. @param [out] str Buffer to store the read text.
  973. @param [in] size At max, size-1 bytes to be read.
  974. @param [in] file Source file.
  975. @param [in] is_login_file TRUE, when login file is being processed.
  976. @return 1 Success
  977. 0 Error
  978. */
  979. static bool mysql_file_getline(char *str, int size, MYSQL_FILE *file,
  980. bool is_login_file) {
  981. uchar cipher[4096], len_buf[MAX_CIPHER_STORE_LEN];
  982. static unsigned char my_key[LOGIN_KEY_LEN];
  983. int length = 0, cipher_len = 0;
  984. if (is_login_file) {
  985. if (mysql_file_ftell(file) == 0) {
  986. /* Move past unused bytes. */
  987. mysql_file_fseek(file, 4, SEEK_SET);
  988. if (mysql_file_fread(file, my_key, LOGIN_KEY_LEN, MYF(MY_WME)) !=
  989. LOGIN_KEY_LEN)
  990. return 0;
  991. }
  992. if (mysql_file_fread(file, len_buf, MAX_CIPHER_STORE_LEN, MYF(MY_WME)) ==
  993. MAX_CIPHER_STORE_LEN) {
  994. cipher_len = sint4korr(len_buf);
  995. if (cipher_len > size) return 0;
  996. } else
  997. return 0;
  998. mysql_file_fread(file, cipher, cipher_len, MYF(MY_WME));
  999. if ((length = my_aes_decrypt(cipher, cipher_len, (unsigned char *)str,
  1000. my_key, LOGIN_KEY_LEN, my_aes_128_ecb, NULL)) <
  1001. 0) {
  1002. /* Attempt to decrypt failed. */
  1003. return 0;
  1004. }
  1005. str[length] = 0;
  1006. return 1;
  1007. } else {
  1008. if (mysql_file_fgets(str, size, file))
  1009. return 1;
  1010. else
  1011. return 0;
  1012. }
  1013. }
  1014. void my_print_default_files(const char *conf_file) {
  1015. const char *empty_list[] = {"", 0};
  1016. bool have_ext = fn_ext(conf_file)[0] != 0;
  1017. const char **exts_to_use = have_ext ? empty_list : f_extensions;
  1018. char name[FN_REFLEN];
  1019. const char **ext;
  1020. puts(
  1021. "\nDefault options are read from the following files in the given "
  1022. "order:");
  1023. if (dirname_length(conf_file))
  1024. fputs(conf_file, stdout);
  1025. else {
  1026. const char **dirs;
  1027. MEM_ROOT alloc;
  1028. init_alloc_root(key_memory_defaults, &alloc, 512, 0);
  1029. if ((dirs = init_default_directories(&alloc)) == NULL) {
  1030. fputs("Internal error initializing default directories list", stdout);
  1031. } else {
  1032. for (; *dirs; dirs++) {
  1033. for (ext = exts_to_use; *ext; ext++) {
  1034. const char *pos;
  1035. char *end;
  1036. if (**dirs)
  1037. pos = *dirs;
  1038. else if (my_defaults_extra_file)
  1039. pos = my_defaults_extra_file;
  1040. else
  1041. continue;
  1042. end = convert_dirname(name, pos, NullS);
  1043. if (name[0] == FN_HOMELIB) /* Add . to filenames in home */
  1044. *end++ = '.';
  1045. if (my_defaults_extra_file == pos)
  1046. end[(strlen(end) - 1)] = ' ';
  1047. else
  1048. strxmov(end, conf_file, *ext, " ", NullS);
  1049. fputs(name, stdout);
  1050. }
  1051. }
  1052. }
  1053. free_root(&alloc, MYF(0));
  1054. }
  1055. puts("");
  1056. }
  1057. void print_defaults(const char *conf_file, const char **groups) {
  1058. const char **groups_save = groups;
  1059. my_print_default_files(conf_file);
  1060. fputs("The following groups are read:", stdout);
  1061. for (; *groups; groups++) {
  1062. fputc(' ', stdout);
  1063. fputs(*groups, stdout);
  1064. }
  1065. if (my_defaults_group_suffix) {
  1066. groups = groups_save;
  1067. for (; *groups; groups++) {
  1068. fputc(' ', stdout);
  1069. fputs(*groups, stdout);
  1070. fputs(my_defaults_group_suffix, stdout);
  1071. }
  1072. }
  1073. puts(
  1074. "\nThe following options may be given as the first argument:\n\
  1075. --print-defaults Print the program argument list and exit.\n\
  1076. --no-defaults Don't read default options from any option file,\n\
  1077. except for login file.\n\
  1078. --defaults-file=# Only read default options from the given file #.\n\
  1079. --defaults-extra-file=# Read this file after the global files are read.\n\
  1080. --defaults-group-suffix=#\n\
  1081. Also read groups with concat(group, suffix)\n\
  1082. --login-path=# Read this path from the login file.");
  1083. }
  1084. /**
  1085. Initialize all the mappings between default config file paths/
  1086. command line options/persistent config file path/login file path
  1087. and corresponding enum_variable_source values.
  1088. */
  1089. void init_variable_default_paths() {
  1090. char datadir[FN_REFLEN] = {0};
  1091. string extradir =
  1092. (my_defaults_extra_file ? my_defaults_extra_file : string());
  1093. string explicitdir = (my_defaults_file ? my_defaults_file : string());
  1094. string defsyscondir;
  1095. #if defined(DEFAULT_SYSCONFDIR)
  1096. defsyscondir = DEFAULT_SYSCONFDIR;
  1097. #endif
  1098. #ifdef _WIN32
  1099. char buffer[FN_REFLEN];
  1100. /* windows supports ini/cnf extension for some config files */
  1101. if (GetWindowsDirectory(buffer, sizeof(buffer))) {
  1102. default_paths[string(buffer) + "\\my.ini"] = enum_variable_source::GLOBAL;
  1103. default_paths[string(buffer) + "\\my.cnf"] = enum_variable_source::GLOBAL;
  1104. }
  1105. default_paths["C:\\my.ini"] = enum_variable_source::GLOBAL;
  1106. default_paths["C:\\my.cnf"] = enum_variable_source::GLOBAL;
  1107. if (GetModuleFileName(NULL, buffer, (DWORD)sizeof(buffer))) {
  1108. char *end = strend(buffer), *last = NULL;
  1109. for (; end > buffer; end--) {
  1110. if (*end == FN_LIBCHAR) {
  1111. if (last) {
  1112. end[1] = 0;
  1113. break;
  1114. }
  1115. last = end;
  1116. }
  1117. }
  1118. default_paths[string(buffer) + "\\.mylogin.cnf"] =
  1119. enum_variable_source::LOGIN;
  1120. }
  1121. #else
  1122. char *env = getenv("MYSQL_HOME");
  1123. std::string mysql_home(env == nullptr ? "" : env);
  1124. if (!mysql_home.empty()) {
  1125. if (mysql_home.back() != '/') {
  1126. mysql_home.push_back('/');
  1127. }
  1128. default_paths[mysql_home + "my.cnf"] = enum_variable_source::SERVER;
  1129. }
  1130. char buffer[FN_REFLEN] = "~/";
  1131. unpack_filename(buffer, buffer);
  1132. default_paths["/etc/my.cnf"] = enum_variable_source::GLOBAL;
  1133. default_paths["/etc/mysql/my.cnf"] = enum_variable_source::GLOBAL;
  1134. default_paths[string(buffer) + ".my.cnf"] = enum_variable_source::MYSQL_USER;
  1135. default_paths[string(buffer) + ".mylogin.cnf"] = enum_variable_source::LOGIN;
  1136. #if defined(DEFAULT_SYSCONFDIR)
  1137. default_paths[defsyscondir + "/my.cnf"] = enum_variable_source::GLOBAL;
  1138. #endif
  1139. #endif
  1140. if (datadir_buffer[0])
  1141. default_paths[string(datadir_buffer) + MYSQL_PERSIST_CONFIG_NAME + ".cnf"] =
  1142. enum_variable_source::PERSISTED;
  1143. else {
  1144. convert_dirname(datadir, MYSQL_DATADIR, NullS);
  1145. default_paths[string(datadir) + MYSQL_PERSIST_CONFIG_NAME + ".cnf"] =
  1146. enum_variable_source::PERSISTED;
  1147. }
  1148. if (extradir.length()) default_paths[extradir] = enum_variable_source::EXTRA;
  1149. if (explicitdir.length())
  1150. default_paths[explicitdir] = enum_variable_source::EXPLICIT;
  1151. default_paths[""] = enum_variable_source::COMMAND_LINE;
  1152. }
  1153. /**
  1154. Track all options loaded from config files and command line options
  1155. along with the path from where options are loaded. For command line
  1156. options path is empty string.
  1157. Ex:
  1158. /etc/my.cnf has max_connections
  1159. /$datadir/mysqld.auto.cnf has max_user_connections
  1160. ./mysqld --server-id=47
  1161. with this setup, variables_hash has 3 entires of the above options
  1162. along with path of config files and its enum value which is as below:
  1163. max_connections -> (/etc/my.cnf , enum_variable_source::GLOBAL)
  1164. max_user_connections -> ($datadir/mysqld.auto.cnf ,
  1165. enum_variable_source::PERSISTED)
  1166. server-id -> ("" , enum_variable_source::COMMAND_LINE)
  1167. @param [in] opt_name Pointer to option name. opt_name must be in
  1168. the form off --XXXXXX
  1169. @param [in] value Pointer to config file path
  1170. */
  1171. void update_variable_source(const char *opt_name, const char *value) {
  1172. string var_name = string(opt_name);
  1173. string path = (value ? value : string(""));
  1174. string prefix[] = {"loose_", "disable_", "enable_", "maximum_", "skip_"};
  1175. uint prefix_count = sizeof(prefix) / sizeof(prefix[0]);
  1176. /* opt_name must be of form --XXXXX which means min length must be 3 */
  1177. if (var_name.length() < 3) return;
  1178. std::size_t pos = var_name.find("=");
  1179. /* strip the value part if present */
  1180. if (pos != string::npos) var_name = var_name.substr(0, pos);
  1181. /* remove -- */
  1182. var_name = var_name.substr(2);
  1183. /* replace all '-' to '_' */
  1184. while ((pos = var_name.find("-")) != string::npos)
  1185. var_name.replace(pos, 1, "_");
  1186. /*
  1187. check if variable is prefixed with 'loose', 'skip', 'disable',
  1188. 'enable', 'maximum'
  1189. */
  1190. for (uint id = 0; id < prefix_count; id++) {
  1191. if (!var_name.compare(0, prefix[id].size(), prefix[id])) {
  1192. /* check if variables are prefixed with skip_ */
  1193. if (id == 4) {
  1194. bool skip_variable = false;
  1195. string skip_variables[] = {"skip_name_resolve", "skip_networking",
  1196. "skip_show_database",
  1197. "skip_external_locking"};
  1198. for (uint skip_index = 0;
  1199. skip_index < sizeof(skip_variables) / sizeof(skip_variables[0]);
  1200. ++skip_index) {
  1201. if (var_name == skip_variables[skip_index]) {
  1202. /*
  1203. Do not trim the skip_ prefix for variables which
  1204. start with skip
  1205. */
  1206. skip_variable = true;
  1207. break;
  1208. }
  1209. }
  1210. if (skip_variable == false)
  1211. var_name = var_name.substr(prefix[4].size());
  1212. } else
  1213. var_name = var_name.substr(prefix[id].size());
  1214. }
  1215. }
  1216. std::map<string, enum_variable_source>::iterator it =
  1217. default_paths.find(path);
  1218. if (it != default_paths.end()) {
  1219. my_variable_sources source;
  1220. std::pair<std::map<string, my_variable_sources>::iterator, bool> ret;
  1221. source.m_config_file_name = path;
  1222. source.m_source = it->second;
  1223. ret = variables_hash.insert(
  1224. std::pair<string, my_variable_sources>(var_name, source));
  1225. /*
  1226. If value exists replace it with new path. ex: if there exists
  1227. same variables in my.cnf and mysqld-auto.cnf and specified in
  1228. command line options, then final entry into this hash will be
  1229. option name as key and mysqld-auto.cnf file path + PERSISTED
  1230. as value.
  1231. */
  1232. if (ret.second == false) variables_hash[var_name] = source;
  1233. }
  1234. }
  1235. /**
  1236. This function will set value for my_option::arg_source by doing a
  1237. lookup into variables_hash based on opt_name as key. If key is present
  1238. corresponding value (config file, enum value) will be set in value.
  1239. @param [in] opt_name Pointer to option name.
  1240. @param [out] value Pointer to struct holding config file path
  1241. and variable source
  1242. */
  1243. void set_variable_source(const char *opt_name, void *value) {
  1244. string src_name = opt_name;
  1245. std::size_t pos;
  1246. /* replace all '-' to '_' */
  1247. while ((pos = src_name.find("-")) != string::npos)
  1248. src_name.replace(pos, 1, "_");
  1249. std::map<string, my_variable_sources>::iterator it =
  1250. variables_hash.find(src_name);
  1251. if (it != variables_hash.end()) {
  1252. if ((get_opt_arg_source *)value) {
  1253. memcpy(((get_opt_arg_source *)value)->m_path_name,
  1254. it->second.m_config_file_name.c_str(),
  1255. it->second.m_config_file_name.length());
  1256. ((get_opt_arg_source *)value)->m_source = it->second.m_source;
  1257. }
  1258. }
  1259. }
  1260. static int add_directory(MEM_ROOT *alloc, const char *dir, const char **dirs) {
  1261. char buf[FN_REFLEN];
  1262. size_t len;
  1263. char *p;
  1264. bool err MY_ATTRIBUTE((unused));
  1265. len = normalize_dirname(buf, dir);
  1266. if (!(p = strmake_root(alloc, buf, len))) return 1; /* Failure */
  1267. /* Should never fail if DEFAULT_DIRS_SIZE is correct size */
  1268. err = array_append_string_unique(p, dirs, DEFAULT_DIRS_SIZE);
  1269. DBUG_ASSERT(err == false);
  1270. return 0;
  1271. }
  1272. #ifdef _WIN32
  1273. /*
  1274. This wrapper for GetSystemWindowsDirectory() will dynamically bind to the
  1275. function if it is available, emulate it on NT4 Terminal Server by stripping
  1276. the \SYSTEM32 from the end of the results of GetSystemDirectory(), or just
  1277. return GetSystemDirectory().
  1278. */
  1279. typedef UINT(WINAPI *GET_SYSTEM_WINDOWS_DIRECTORY)(LPSTR, UINT);
  1280. static size_t my_get_system_windows_directory(char *buffer, size_t size) {
  1281. size_t count;
  1282. GET_SYSTEM_WINDOWS_DIRECTORY
  1283. func_ptr = (GET_SYSTEM_WINDOWS_DIRECTORY)GetProcAddress(
  1284. GetModuleHandle("kernel32.dll"), "GetSystemWindowsDirectoryA");
  1285. if (func_ptr) return func_ptr(buffer, (uint)size);
  1286. /*
  1287. Windows NT 4.0 Terminal Server Edition:
  1288. To retrieve the shared Windows directory, call GetSystemDirectory and
  1289. trim the "System32" element from the end of the returned path.
  1290. */
  1291. count = GetSystemDirectory(buffer, (uint)size);
  1292. if (count > 8 && stricmp(buffer + (count - 8), "\\System32") == 0) {
  1293. count -= 8;
  1294. buffer[count] = '\0';
  1295. }
  1296. return count;
  1297. }
  1298. static const char *my_get_module_parent(char *buf, size_t size) {
  1299. char *last = NULL;
  1300. char *end;
  1301. if (!GetModuleFileName(NULL, buf, (DWORD)size)) return NULL;
  1302. end = strend(buf);
  1303. /*
  1304. Look for the second-to-last \ in the filename, but hang on
  1305. to a pointer after the last \ in case we're in the root of
  1306. a drive.
  1307. */
  1308. for (; end > buf; end--) {
  1309. if (*end == FN_LIBCHAR) {
  1310. if (last) {
  1311. /* Keep the last '\' as this works both with D:\ and a directory */
  1312. end[1] = 0;
  1313. break;
  1314. }
  1315. last = end;
  1316. }
  1317. }
  1318. return buf;
  1319. }
  1320. #endif /* _WIN32 */
  1321. static const char **init_default_directories(MEM_ROOT *alloc) {
  1322. const char **dirs;
  1323. char *env;
  1324. int errors = 0;
  1325. dirs = (const char **)alloc->Alloc(DEFAULT_DIRS_SIZE * sizeof(char *));
  1326. if (dirs == NULL) return NULL;
  1327. memset(dirs, 0, DEFAULT_DIRS_SIZE * sizeof(char *));
  1328. #ifdef _WIN32
  1329. {
  1330. char fname_buffer[FN_REFLEN];
  1331. if (my_get_system_windows_directory(fname_buffer, sizeof(fname_buffer)))
  1332. errors += add_directory(alloc, fname_buffer, dirs);
  1333. if (GetWindowsDirectory(fname_buffer, sizeof(fname_buffer)))
  1334. errors += add_directory(alloc, fname_buffer, dirs);
  1335. errors += add_directory(alloc, "C:/", dirs);
  1336. if (my_get_module_parent(fname_buffer, sizeof(fname_buffer)) != NULL)
  1337. errors += add_directory(alloc, fname_buffer, dirs);
  1338. }
  1339. #else
  1340. errors += add_directory(alloc, "/etc/", dirs);
  1341. errors += add_directory(alloc, "/etc/mysql/", dirs);
  1342. #if defined(DEFAULT_SYSCONFDIR)
  1343. if (DEFAULT_SYSCONFDIR[0])
  1344. errors += add_directory(alloc, DEFAULT_SYSCONFDIR, dirs);
  1345. #endif /* DEFAULT_SYSCONFDIR */
  1346. #endif
  1347. if ((env = getenv("MYSQL_HOME"))) errors += add_directory(alloc, env, dirs);
  1348. /* Placeholder for --defaults-extra-file=<path> */
  1349. errors += add_directory(alloc, "", dirs);
  1350. #if !defined(_WIN32)
  1351. errors += add_directory(alloc, "~/", dirs);
  1352. #endif
  1353. return (errors > 0 ? NULL : dirs);
  1354. }
  1355. /**
  1356. Place the login file name in the specified buffer.
  1357. @param [out] file_name Buffer to hold login file name
  1358. @param [in] file_name_size Length of the buffer
  1359. @return 1 - Success
  1360. 0 - Failure
  1361. */
  1362. int my_default_get_login_file(char *file_name, size_t file_name_size) {
  1363. size_t rc;
  1364. if (getenv("MYSQL_TEST_LOGIN_FILE"))
  1365. rc = snprintf(file_name, file_name_size, "%s",
  1366. getenv("MYSQL_TEST_LOGIN_FILE"));
  1367. #ifdef _WIN32
  1368. else if (getenv("APPDATA"))
  1369. rc = snprintf(file_name, file_name_size, "%s\\MySQL\\.mylogin.cnf",
  1370. getenv("APPDATA"));
  1371. #else
  1372. else if (getenv("HOME"))
  1373. rc = snprintf(file_name, file_name_size, "%s/.mylogin.cnf", getenv("HOME"));
  1374. #endif
  1375. else {
  1376. memset(file_name, 0, file_name_size);
  1377. return 0;
  1378. }
  1379. /* Anything <= 0 will be treated as error. */
  1380. if (rc <= 0) return 0;
  1381. return 1;
  1382. }
  1383. /**
  1384. Check file permissions of the option file.
  1385. @param [in] file_name Name of the option file.
  1386. @param [in] is_login_file TRUE, when login file is being processed.
  1387. @return 0 - Non-allowable file permissions.
  1388. 1 - Failed to stat.
  1389. 2 - Success.
  1390. */
  1391. int check_file_permissions(const char *file_name, bool is_login_file) {
  1392. #if !defined(_WIN32)
  1393. MY_STAT stat_info;
  1394. if (!my_stat(file_name, &stat_info, MYF(0))) return 1;
  1395. /*
  1396. Ignore .mylogin.cnf file if not exclusively readable/writable
  1397. by current user.
  1398. */
  1399. if (is_login_file && (stat_info.st_mode & (S_IXUSR | S_IRWXG | S_IRWXO)) &&
  1400. (stat_info.st_mode & S_IFMT) == S_IFREG) {
  1401. my_message_local(WARNING_LEVEL, EE_CONFIG_FILE_PERMISSION_ERROR, file_name);
  1402. return 0;
  1403. }
  1404. /*
  1405. Ignore world-writable regular files.
  1406. This is mainly done to protect us to not read a file created by
  1407. the mysqld server, but the check is still valid in most context.
  1408. */
  1409. else if ((stat_info.st_mode & S_IWOTH) &&
  1410. (stat_info.st_mode & S_IFMT) == S_IFREG)
  1411. {
  1412. my_message_local(WARNING_LEVEL, EE_IGNORE_WORLD_WRITABLE_CONFIG_FILE,
  1413. file_name);
  1414. return 0;
  1415. }
  1416. #endif
  1417. return 2; /* Success */
  1418. }