1#!@PERL_PATH@
2# -*- cperl -*-
3#
4# Copyright (c) 2007, 2017, Oracle and/or its affiliates. All rights reserved.
5#
6# This program is free software; you can redistribute it and/or modify
7# it under the terms of the GNU General Public License, version 2.0,
8# as published by the Free Software Foundation.
9#
10# This program is also distributed with certain software (including
11# but not limited to OpenSSL) that is licensed under separate terms,
12# as designated in a particular file or component or in included license
13# documentation.  The authors of MySQL hereby grant you an additional
14# permission to link the program and your derivative works with the
15# separately licensed software that they have included with MySQL.
16#
17# This program is distributed in the hope that it will be useful,
18# but WITHOUT ANY WARRANTY; without even the implied warranty of
19# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20# GNU General Public License, version 2.0, for more details.
21#
22# You should have received a copy of the GNU General Public License
23# along with this program; if not, write to the Free Software
24# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
25
26##############################################################################
27#
28#  This scripts creates the MySQL Server system tables.
29#
30#  This script try to match the shell script version as close as possible,
31#  but in addition being compatible with ActiveState Perl on Windows.
32#
33#  All unrecognized arguments to this script are passed to mysqld.
34#
35#  NOTE: This script in 5.0 doesn't really match the shell script
36#        version 100%, it is more close to the 5.1 version.
37#
38#  NOTE: This script was deliberately written to be as close to the shell
39#        script as possible, to make the maintenance of both in parallel
40#        easier.
41#
42##############################################################################
43
44use strict;
45use warnings;
46
47#############################################################################
48#
49# Check if all needed modules are available, exit if something is missing.
50#############################################################################
51#
52
53BEGIN {
54  my @req_mods = ('Fcntl', 'File::Basename', 'File::Copy', 'Getopt::Long',
55                  'Sys::Hostname', 'Data::Dumper');
56  my @missing_mods;
57  my $req;
58  foreach $req (@req_mods) {
59    eval 'require ' . $req;
60    if ($@) {
61      push(@missing_mods, $req);
62    } else {
63      $req->import();
64    }
65  }
66  # this avoids the confusing "BEGIN failed--compilation aborted" message
67  local $SIG{__DIE__} = sub {warn @_; exit 1};
68
69  if (@missing_mods) {
70    my $msg = "FATAL ERROR: please install the following Perl modules " .
71              "before executing $0:\n" . join("\n",@missing_mods)."\n";
72    die $msg;
73  }
74}
75
76Getopt::Long::Configure("pass_through");
77
78my @args;                       # Argument list filled in
79my $basedir;
80
81##############################################################################
82#
83#  Usage information
84#
85##############################################################################
86
87sub usage
88{
89  print <<EOF1;
90Usage: $0 [OPTIONS]
91  --basedir=path       The path to the MySQL installation directory.
92  --builddir=path      If using --srcdir with out-of-directory builds, you
93                       will need to set this to the location of the build
94                       directory where built files reside.
95  --cross-bootstrap    For internal use.  Used when building the MySQL system
96                       tables on a different host than the target.
97  --datadir=path       The path to the MySQL data directory.
98                       If missing, the directory will be created, but its
99                       parent directory must already exist and be writable.
100  --defaults-extra-file=name
101                       Read this file after the global files are read.
102  --defaults-file=name Only read default options from the given file name.
103  --force              Causes mysql_install_db to run even if DNS does not
104                       work.  In that case, grant table entries that
105                       normally use hostnames will use IP addresses.
106  --help               Display this help and exit.                     
107  --ldata=path         The path to the MySQL data directory. Same as --datadir.
108  --no-defaults        Don't read default options from any option file.
109  --keep-my-cnf        Don't try to create my.cnf based on template. 
110                       Useful for systems with working, updated my.cnf.
111                       Deprecated, will be removed in future version.
112EOF1
113  if ( $^O !~ m/^(MSWin32|cygwin)$/ ) {
114    print <<EOF2;
115  --random-passwords   Create and set a random password for all root accounts
116                       and set the "password expired" flag,
117                       also remove the anonymous accounts.
118EOF2
119  }
120  print <<EOF3;
121  --rpm                For internal use.  This option is used by RPM files
122                       during the MySQL installation process.
123  --skip-name-resolve  Use IP addresses rather than hostnames when creating
124                       grant table entries.  This option can be useful if
125                       your DNS does not work.
126  --srcdir=path        The path to the MySQL source directory.  This option
127                       uses the compiled binaries and support files within the
128                       source tree, useful for if you don't want to install
129                       MySQL yet and just want to create the system tables.
130EOF3
131  if ( $^O !~ m/^(MSWin32|cygwin)$/ ) {
132    print <<EOF4;
133  --user=user_name     The login username to use for running mysqld.  Files
134                       and directories created by mysqld will be owned by this
135                       user.  You must be root to use this option.  By default
136                       mysqld runs using your current login name and files and
137                       directories that it creates will be owned by you.
138EOF4
139  }
140  print <<EOF5;
141Any other options are passed to the mysqld program.
142
143EOF5
144  exit 1;
145}
146
147##############################################################################
148#
149#  Parse an argument list
150#
151#  We only need to pass arguments through to the server if we don't
152#  handle them here.  So, we collect unrecognized options (passed on
153#  the command line) into the args variable.
154#
155##############################################################################
156
157sub parse_arguments
158{
159  my $opt = shift;
160
161  my @saved_ARGV = @ARGV;
162  @ARGV = @_;                           # Set ARGV so GetOptions works
163
164  my $pick_args;
165  if (@ARGV and $ARGV[0] eq 'PICK-ARGS-FROM-ARGV')
166  {
167    $pick_args = 1;
168    shift @ARGV;
169  }
170
171  GetOptions(
172             $opt,
173             "force",
174             "basedir=s",
175             "builddir=s",      # FIXME not documented
176             "srcdir=s",
177             "ldata|datadir=s",
178
179             # Note that the user will be passed to mysqld so that it runs
180             # as 'user' (crucial e.g. if log-bin=/some_other_path/
181             # where a chown of datadir won't help)
182             "user=s",
183
184             "skip-name-resolve",
185             "verbose",
186             "keep-my-cnf",
187             "rpm",
188             "help",
189             "random-passwords",
190
191             # These options will also be pased to mysqld.
192             "defaults-file=s",
193             "defaults-extra-file=s",
194             "no-defaults",
195
196             # Used when building the MySQL system tables on a different host than
197             # the target. The platform-independent files that are created in
198             # --datadir on the host can be copied to the target system.
199             #
200             # The most common use for this feature is in the Windows installer
201             # which will take the files from datadir and include them as part of
202             # the install package.  See top-level 'dist-hook' make target.
203             #
204             # --windows is a deprecated alias
205             "cross-bootstrap|windows",
206  ) or usage();
207
208  usage() if $opt->{help};
209
210  if ( $opt->{'no-defaults'} && ( $opt->{'defaults-extra-file'} ||
211				  $opt->{'defaults-file'} ) )
212  {
213    error($opt,
214	  "Cannot use both --no-defaults and --defaults-[extra-]file");
215  }
216
217  @args =  @ARGV if $pick_args;
218
219  @ARGV = @saved_ARGV;                  # Set back ARGV
220}
221
222##############################################################################
223#
224#  Try to find a specific file within --basedir which can either be a binary
225#  release or installed source directory and return the path.
226#
227##############################################################################
228
229sub find_in_basedir
230{
231  my $opt   = shift;
232  my $mode  = shift;            # "dir" or "file"
233  my $files = shift;
234
235  foreach my $file ( @{ref($files) ? $files : [$files]} )
236  {
237    foreach my $dir ( @_ )
238    {
239      foreach my $part ( "$file","$file.exe","release/$file.exe",
240                         "debug/$file.exe","relwithdebinfo/$file.exe" )
241      {
242        my $path = "$basedir/$dir/$part";
243        if ( -f $path )
244        {
245          return $mode eq "dir" ? dirname($path) : $path;
246        }
247      }
248    }
249  }
250}
251
252##############################################################################
253#
254#  Just a function to write out an error report
255#
256##############################################################################
257
258sub cannot_find_file
259{
260  my $file = shift;
261
262  print "FATAL ERROR: Could not find $file\n";
263  print "\n";
264  print "If you compiled from source, you need to run 'make install' to\n";
265  print "copy the software into the correct location ready for operation.\n";
266  print "\n";
267  print "If you are using a binary release, you must either be at the top\n";
268  print "level of the extracted archive, or pass the --basedir option\n";
269  print "pointing to that location.\n";
270  print "\n";
271
272  exit 1;
273}
274
275##############################################################################
276#
277#  Form a command line that can handle spaces in paths and arguments
278#
279##############################################################################
280
281# FIXME this backslash escaping needed if using '"..."' ?
282# This regexp makes sure that any special chars are quoted,
283# so the arg gets passed exactly to the server.
284# XXX: This is broken; true fix requires using eval and proper
285# quoting of every single arg ($opt->{basedir}, $opt->{ldata}, etc.)
286#  join(" ", map {s/([^\w\_\.\-])/\\$1/g}
287
288sub quote_options {
289  my @cmd;
290  foreach my $opt ( @_ )
291  {
292    next unless $opt;           # If undefined or empty, just skip
293    push(@cmd, "\"$opt\"");     # Quote argument
294  }
295  return join(" ", @cmd);
296}
297
298##############################################################################
299#
300#  Simple escape mechanism (\-escape any ' and \), suitable for two contexts:
301#  - single-quoted SQL strings
302#  - single-quoted option values on the right hand side of = in my.cnf
303#
304##############################################################################
305
306# (Function and comment copied from 'mysql_secure_installation')
307
308# These two contexts don't handle escapes identically.  SQL strings allow
309# quoting any character (\C => C, for any C), but my.cnf parsing allows
310# quoting only \, ' or ".  For example, password='a\b' quotes a 3-character
311# string in my.cnf, but a 2-character string in SQL.
312#
313# This simple escape works correctly in both places.
314
315# FIXME: What about double quote in password? Not handled here - not needed?
316
317sub basic_single_escape {
318  my ($str) = @_;
319  # Inside a character class, \ is not special; this escapes both \ and '
320  $str =~ s/([\'])/\\$1/g;
321  return $str;
322}
323
324##############################################################################
325#
326#  Handle the files with confidential contents
327#
328##############################################################################
329
330my $secret_file;   # full path name of the confidential file
331my $escaped_password;      # the password, with special characters escaped
332
333sub ensure_secret_file {
334  $secret_file = $ENV{HOME} . "/.mysql_secret";
335
336  # Create safe files to avoid leaking info to other users
337  # Loop may be extended if we need more ...
338  foreach my $file ( $secret_file ) {
339    next if -f $file;                   # Already exists
340    local *FILE;
341    sysopen(FILE, $file, O_CREAT, 0600)
342      or die "ERROR: can't create $file: $!";
343    close FILE;
344  }
345}
346
347##############################################################################
348#
349#  Append an arbitrary number of lines to an existing file
350#
351##############################################################################
352
353sub append_file {
354  my $file = shift;
355  -f $file or die "ERROR: file is missing \"$file\": $!";
356  open(FILE, ">>$file") or die "ERROR: can't append to file \"$file\": $!";
357  foreach my $line ( @_ ) {
358    print FILE $line, "\n";             # Add EOL char
359  }
360  close FILE;
361}
362
363##############################################################################
364#
365#  Inform the user about the generated random password
366#
367##############################################################################
368
369sub tell_root_password {
370  my $now = localtime(); # scalar context = printable string
371
372  # Now, we need to tell the user the new root password.
373  # We use "append_file" to protect the user in case they are doing multiple
374  # installations intermixed with backups and restores.
375  # While this would be really bad practice, it still might happen.
376  # As long as this file is not destroyed, the time stamps may rescue them.
377  # Having the comment and the password on the same line makes it easier
378  # to automatically extract the password (automated testing!), and the final
379  # empty line is for better redability.
380  append_file($secret_file,
381             "# The random password set for the root user at $now (local time): " .
382                 $escaped_password,
383             "");
384  print "A random root password has been set. You will find it in '$secret_file'.\n";
385}
386
387##############################################################################
388#
389#  Generate a random password
390#
391##############################################################################
392
393sub generate_random_password {
394  # On Linux, Solaris, Max OS X and FreeBSD we have a random device available.
395  my $randfile = "/dev/urandom";
396  open(FD, $randfile) || return "";
397  my $password = "";
398  my $pass_len = 16;
399  my $c;
400  while (length($password) < $pass_len) {
401    $c = getc(FD);
402    if ($c =~ /\w/) {
403      $password .= $c;
404    }
405  }
406  close(FD);
407  return $password;
408}
409
410
411##############################################################################
412#
413#  Ok, let's go.  We first need to parse arguments which are required by
414#  my_print_defaults so that we can execute it first, then later re-parse
415#  the command line to add any extra bits that we need.
416#
417##############################################################################
418
419my $opt = {};
420parse_arguments($opt, 'PICK-ARGS-FROM-ARGV', @ARGV);
421
422# ----------------------------------------------------------------------
423# Actual basedir, not to be confused with --basedir option
424# ----------------------------------------------------------------------
425
426if ( $opt->{srcdir} ) {
427  $basedir= $opt->{builddir};
428} else {
429  $basedir= $opt->{basedir};
430}
431$basedir= "@prefix@" if ! $basedir;		# Default
432
433# ----------------------------------------------------------------------
434# We can now find my_print_defaults.  This script supports:
435#
436#   --srcdir=path pointing to compiled source tree
437#   --basedir=path pointing to installed binary location
438#
439# or default to compiled-in locations.
440# ----------------------------------------------------------------------
441
442my $print_defaults;
443my $keep_my_cnf = 0;
444
445if ( $opt->{srcdir} and $opt->{basedir} )
446{
447  error($opt,"Specify either --basedir or --srcdir, not both");
448}
449if ( $opt->{'keep-my-cnf'} )
450{
451  $keep_my_cnf = 1;
452}
453if ( $opt->{srcdir} )
454{
455  $opt->{builddir} = $opt->{srcdir} unless $opt->{builddir};
456  $print_defaults = "$opt->{builddir}/extra/my_print_defaults";
457}
458else
459{
460  $print_defaults = find_in_basedir($opt,"file","my_print_defaults","bin","extra");
461}
462if ( ! $print_defaults )
463{
464  $print_defaults='@bindir@/my_print_defaults';
465}
466
467-x $print_defaults or -f "$print_defaults.exe"
468  or cannot_find_file($print_defaults);
469
470my $config_file;
471my $copy_cfg_file;
472
473# ----------------------------------------------------------------------
474# This will be the default config file (unless creation is unwanted)
475# ----------------------------------------------------------------------
476
477my $cnfext = ( $^O =~ m/^(MSWin32|cygwin)$/ ) ? "ini" : "cnf";
478
479$config_file= "$basedir/my.$cnfext";
480
481my $cfg_template= find_in_basedir($opt,"file","my-default.$cnfext",
482				  ".", "share","share/mysql","support-files");
483# Distros might move files
484if ((! -r $cfg_template) && (-r "@pkgdatadir@/my-default.cnf")) {
485  $cfg_template = "@pkgdatadir@/my-default.cnf";
486}
487
488-e $cfg_template or cannot_find_file("my-default.$cnfext");
489
490$copy_cfg_file= $config_file;
491my $failed_write_cfg= 0;
492if (-e $copy_cfg_file)
493{
494  $copy_cfg_file =~ s/my.$cnfext/my-new.$cnfext/;
495  # Too early to print warning here, the user may not notice
496}
497
498if ( ! $keep_my_cnf ) {
499  open (TEMPL, $cfg_template) or error($opt, "Could not open config template $cfg_template");
500  if (open (CFG, "> $copy_cfg_file")) {
501    while (<TEMPL>) {
502      # Remove lines beginning with # *** which are template comments
503      print CFG $_ unless /^# \*\*\*/;
504    }
505    close CFG;
506  } else {
507    warning($opt,"Could not write to config file $copy_cfg_file: $!");
508    $failed_write_cfg= 1;
509  }
510  close TEMPL;
511}
512
513# ----------------------------------------------------------------------
514# Now we can get arguments from the groups [mysqld] and [mysql_install_db]
515# in the my.cfg file, then re-run to merge with command line arguments.
516# ----------------------------------------------------------------------
517
518my $cmd;
519my @default_options;
520if ( $opt->{'defaults-file'} )
521{
522  $cmd = quote_options($print_defaults,
523                       "--defaults-file=$opt->{'defaults-file'}",
524                       "mysqld", "mysql_install_db");
525}
526else
527{
528  $cmd = quote_options($print_defaults, "mysqld", "mysql_install_db");
529}
530
531open(PIPE, "$cmd |") or error($opt,"can't run $cmd: $!");
532while ( <PIPE> )
533{
534  chomp;
535  next unless /\S/;
536  push(@default_options, $_);
537}
538close PIPE;
539$opt = {};                              # Reset the arguments FIXME ?
540parse_arguments($opt, @default_options);
541parse_arguments($opt, 'PICK-ARGS-FROM-ARGV', @ARGV);
542
543# ----------------------------------------------------------------------
544# Create a random password for root, if requested and implemented
545# ----------------------------------------------------------------------
546
547if ( $opt->{'random-passwords'} ) {
548  # Add other non-working OS like this: $^O =~ m/^(solaris|linux|freebsd|darwin)$/
549  # and maintain "usage()".
550  # Issue 1: random password creation
551  # Issue 2: confidential file
552  if ( $^O =~ m/^(MSWin32|cygwin)$/ ) {
553    print "Random password not yet implemented for $^O - option will be ignored\n";
554    delete $opt->{'random-passwords'};
555  } else {
556    ensure_secret_file();
557    my $password = generate_random_password();
558    if ( $password ) {
559      # "true" means "string is non-empty"
560      $escaped_password = basic_single_escape($password);
561    } else {
562      # Whatever the reason (missing "/dev/urandom"), an empty password is bad
563      print "Could not generate a random password - not setting one\n";
564      delete $opt->{'random-passwords'};
565    }
566  }
567}
568
569# ----------------------------------------------------------------------
570# Configure paths to support files
571# ----------------------------------------------------------------------
572
573# FIXME $extra_bindir is not used
574my ($bindir,$extra_bindir,$mysqld,$pkgdatadir,$mysqld_opt,$scriptdir);
575
576if ( $opt->{srcdir} )
577{
578  $bindir         = "$basedir/client";
579  $extra_bindir   = "$basedir/extra";
580  $mysqld         = "$basedir/sql/mysqld";
581  $mysqld_opt     = "--language=$opt->{srcdir}/sql/share/english";
582  $pkgdatadir     = "$opt->{srcdir}/scripts";
583  $scriptdir      = "$opt->{srcdir}/scripts";
584}
585elsif ( $opt->{basedir} )
586{
587  $bindir         = "$opt->{basedir}/bin";
588  $extra_bindir   = $bindir;
589  $mysqld         = find_in_basedir($opt,"file",["mysqld-nt","mysqld"],
590                                    "libexec","sbin","bin") ||  # ,"sql"
591                    find_in_basedir($opt,"file","mysqld-nt",
592                                  "bin");  # ,"sql"
593  $pkgdatadir     = find_in_basedir($opt,"dir","fill_help_tables.sql",
594                                    "share","share/mysql");  # ,"scripts"
595  $scriptdir      = "$opt->{basedir}/scripts";
596}
597else
598{
599  $bindir         = '@bindir@';
600  $extra_bindir   = $bindir;
601  $mysqld         = '@libexecdir@/mysqld';
602  $pkgdatadir     = '@pkgdatadir@';
603  $scriptdir      = '@scriptdir@';
604}
605
606unless ( $opt->{ldata} )
607{
608  $opt->{ldata} = '@localstatedir@';
609}
610
611if ( $opt->{srcdir} )
612{
613  $pkgdatadir = "$opt->{srcdir}/scripts";
614}
615
616# ----------------------------------------------------------------------
617# Set up paths to SQL scripts required for bootstrap
618# ----------------------------------------------------------------------
619
620my $fill_help_tables     = "$pkgdatadir/fill_help_tables.sql";
621my $create_system_tables = "$pkgdatadir/mysql_system_tables.sql";
622my $fill_system_tables   = "$pkgdatadir/mysql_system_tables_data.sql";
623my $security_commands    = "$pkgdatadir/mysql_security_commands.sql";
624
625foreach my $f ( $fill_help_tables, $create_system_tables, $fill_system_tables, $security_commands )
626{
627  -f $f or cannot_find_file($f);
628}
629
630-x $mysqld or -f "$mysqld.exe" or cannot_find_file($mysqld);
631# Try to determine the hostname
632my $hostname = hostname();
633
634# ----------------------------------------------------------------------
635# Check if hostname is valid
636# ----------------------------------------------------------------------
637
638my $resolved;
639if ( !$opt->{'cross-bootstrap'} and !$opt->{rpm} and !$opt->{force} )
640{
641  my $resolveip = "$extra_bindir/resolveip";
642
643  $resolved = `$resolveip $hostname 2>&1`;
644  if ( $? != 0 )
645  {
646    $resolved=`$resolveip localhost 2>&1`;
647    if ( $? != 0 )
648    {
649      error($opt,
650            "Neither host '$hostname' nor 'localhost' could be looked up with",
651            "$resolveip",
652            "Please configure the 'hostname' command to return a correct",
653            "hostname.",
654            "If you want to solve this at a later stage, restart this script",
655            "with the --force option");
656    }
657    warning($opt,
658            "The host '$hostname' could not be looked up with $resolveip.",
659            "This probably means that your libc libraries are not 100 % compatible",
660            "with this binary MySQL version. The MySQL daemon, mysqld, should work",
661            "normally with the exception that host name resolving will not work.",
662            "This means that you should use IP addresses instead of hostnames",
663            "when specifying MySQL privileges !");
664  }
665}
666
667# FIXME what does this really mean....
668if ( $opt->{'skip-name-resolve'} and $resolved and $resolved =~ /\s/ )
669{
670  $hostname = (split(' ', $resolved))[5];
671}
672
673# ----------------------------------------------------------------------
674# Create database directories mysql & test
675# ----------------------------------------------------------------------
676
677# FIXME The shell variant uses "mkdir -p":
678#  - because it is silent if the target exists, or
679#  - because it will cerate the path?
680# Path creation is demanded by testers in bug# 14731457, but that might be risky
681# in case of typos as this is run by root.
682# For now, give an error message:
683my $parent = dirname ( $opt->{ldata} );
684if ( ! -d $parent ) {
685  error($opt,
686        "The parent directory for the data directory '$opt->{ldata}' does not exist.",
687        "If that path was really intended, please create that directory path and then",
688        "restart this script.",
689        "If some other path was intended, please use the correct path when restarting this script.");
690}
691
692my $opt_user= $opt->{user};
693my @pwnam;
694if ($opt_user)
695{
696  if ( $^O =~ m/^(MSWin32|cygwin)$/ )
697  {
698    warning($opt, "The --user option is not supported on Windows, ignoring");
699    $opt_user= undef;
700  }
701  else
702  {
703    @pwnam= getpwnam($opt_user);
704  }
705}
706
707foreach my $dir ( $opt->{ldata}, "$opt->{ldata}/mysql", "$opt->{ldata}/test" )
708{
709  mkdir($dir, 0700) unless -d $dir;
710  if ($opt_user and -w "/")
711  {
712    chown($pwnam[2], $pwnam[3], $dir)
713      or error($opt, "Could not chown directory $dir");
714  }
715}
716
717push(@args, "--user=$opt->{user}") if $opt->{user};
718
719# ----------------------------------------------------------------------
720# Configure mysqld command line
721# ----------------------------------------------------------------------
722
723# FIXME use --init-file instead of --bootstrap ?!
724
725my $defaults_option = "";
726if ( $opt->{'no-defaults'} )
727{
728  $defaults_option= "--no-defaults";
729}
730elsif ( $opt->{'defaults-file'} )
731{
732  $defaults_option= "--defaults-file=$opt->{'defaults-file'}";
733}
734
735my $defaults_extra= "--defaults-extra-file=$opt->{'defaults-extra-file'}"
736  if $opt->{'defaults-extra-file'};
737
738my $mysqld_bootstrap = $ENV{MYSQLD_BOOTSTRAP} || $mysqld;
739my $mysqld_install_cmd_line = quote_options($mysqld_bootstrap,
740                                            $defaults_option,
741					    $defaults_extra,
742                                            $mysqld_opt,
743                                            "--bootstrap",
744                                            "--basedir=$basedir",
745                                            "--datadir=$opt->{ldata}",
746                                            "--log-warnings=0",
747                                            "--loose-skip-ndbcluster",
748                                            "--max_allowed_packet=8M",
749                                            "--default-storage-engine=MyISAM",
750                                            "--net_buffer_length=16K",
751                                            @args,
752                                          );
753
754# ----------------------------------------------------------------------
755# Create the system and help tables by passing them to "mysqld --bootstrap"
756# ----------------------------------------------------------------------
757
758report_verbose_wait($opt,"Installing MySQL system tables...");
759
760open(SQL, $create_system_tables)
761  or error($opt,"can't open $create_system_tables for reading: $!");
762open(SQL2, $fill_system_tables)
763  or error($opt,"can't open $fill_system_tables for reading: $!");
764# FIXME  > /dev/null ?
765if ( open(PIPE, "| $mysqld_install_cmd_line") )
766{
767  print PIPE "use mysql;\n";
768  while ( <SQL> )
769  {
770    # When doing a "cross bootstrap" install, no reference to the current
771    # host should be added to the system tables.  So we filter out any
772    # lines which contain the current host name.
773    next if $opt->{'cross-bootstrap'} and /\@current_hostname/;
774
775    print PIPE $_;
776  }
777  while ( <SQL2> )
778  {
779    # When doing a "cross bootstrap" install, no reference to the current
780    # host should be added to the system tables.  So we filter out any
781    # lines which contain the current host name.
782    next if $opt->{'cross-bootstrap'} and /\@current_hostname/;
783
784    print PIPE $_;
785  }
786
787  if ( $opt->{'random-passwords'} )
788  {
789    open(SQL3, $security_commands)
790      or error($opt,"can't open $security_commands for reading: $!");
791    while ( <SQL3> )
792    {
793      # using the implicit variable $_ !
794      s/ABC123xyz/$escaped_password/e ;  # Replace placeholder by random password
795    print PIPE $_;
796  }
797    close SQL3;
798    tell_root_password();
799  }
800
801  close PIPE;
802  close SQL;
803  close SQL2;
804
805  report_verbose($opt,"OK");
806
807  # ----------------------------------------------------------------------
808  # Pipe fill_help_tables.sql to "mysqld --bootstrap"
809  # ----------------------------------------------------------------------
810
811  report_verbose_wait($opt,"Filling help tables...");
812  open(SQL, $fill_help_tables)
813    or error($opt,"can't open $fill_help_tables for reading: $!");
814  # FIXME  > /dev/null ?
815  if ( open(PIPE, "| $mysqld_install_cmd_line") )
816  {
817    print PIPE "use mysql;\n";
818    while ( <SQL> )
819    {
820      print PIPE $_;
821    }
822    close PIPE;
823    close SQL;
824
825    report_verbose($opt,"OK");
826  }
827  else
828  {
829    warning($opt,"HELP FILES ARE NOT COMPLETELY INSTALLED!",
830                 "The \"HELP\" command might not work properly");
831  }
832
833  report_verbose($opt,"To start mysqld at boot time you have to copy",
834                      "support-files/mysql.server to the right place " .
835                      "for your system");
836
837  if ( !$opt->{'cross-bootstrap'} )
838  {
839    # This is not a true installation on a running system.  The end user must
840    # set a password after installing the data files on the real host system.
841    # At this point, there is no end user, so it does not make sense to print
842    # this reminder.
843    if ( $opt->{'random-passwords'} ) {
844      report($opt,
845             "A RANDOM PASSWORD HAS BEEN SET FOR THE MySQL root USER !",
846             "You will find that password in '$secret_file'.",
847             "",
848             "You must change that password on your first connect,",
849             "no other statement but 'SET PASSWORD' will be accepted.",
850             "See the manual for the semantics of the 'password expired' flag.",
851             "",
852             "Also, the account for the anonymous user has been removed.",
853             "",
854             "In addition, you can run:",
855             "",
856             "  $bindir/mysql_secure_installation",
857             "",
858             "which will also give you the option of removing the test database.",
859             "This is strongly recommended for production servers.",
860             "",
861             "See the manual for more instructions.");
862    } else {
863    report($opt,
864           "PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !",
865           "To do so, start the server, then issue the following commands:",
866           "",
867           "  $bindir/mysqladmin -u root password 'new-password'",
868           "  $bindir/mysqladmin -u root -h $hostname password 'new-password'",
869           "",
870           "Alternatively you can run:",
871           "",
872           "  $bindir/mysql_secure_installation",
873           "",
874           "which will also give you the option of removing the test",
875           "databases and anonymous user created by default.  This is",
876           "strongly recommended for production servers.",
877           "",
878           "See the manual for more instructions.");
879    }
880
881    if ( !$opt->{rpm} )
882    {
883      report($opt,
884             "You can start the MySQL daemon with:",
885             "",
886             "  cd " . '@prefix@' . " ; $bindir/mysqld_safe &",
887             "",
888             "You can test the MySQL daemon with mysql-test-run.pl",
889             "",
890             "  cd mysql-test ; perl mysql-test-run.pl");
891    }
892    report($opt,
893           "Please report any problems at http://bugs.mysql.com/",
894           "",
895           "The latest information about MySQL is available on the web at",
896           "",
897           "  http://www.mysql.com",
898           "",
899           "Support MySQL by buying support/licenses at http://shop.mysql.com");
900
901    if ($keep_my_cnf)
902    {
903      report($opt,
904	     "Note: new default config file not created.",
905	     "Please make sure your config file is current");
906    }
907    elsif ($copy_cfg_file eq $config_file and !$failed_write_cfg)
908    {
909      report($opt,
910	     "New default config file was created as $config_file and",
911	     "will be used by default by the server when you start it.",
912	     "You may edit this file to change server settings");
913    }
914    elsif ($failed_write_cfg)
915    {
916      warning($opt,
917	      "Could not copy config file template $cfg_template to",
918	      "$copy_cfg_file, may not have access rights to do so.",
919	      "You may want to copy the file manually, or create your own,",
920              "it will then be used by default by the server when you start it.");
921    }
922    else
923    {
924      warning($opt,
925	      "Found existing config file $config_file on the system.",
926	      "Because this file might be in use, it was not replaced,",
927	      "but was used in bootstrap (unless you used --defaults-file)",
928	      "and when you later start the server.",
929	      "The new default config file was created as $copy_cfg_file,",
930	      "please compare it with your file and take the changes you need.");
931    }
932    foreach my $cfg ( "/etc/my.$cnfext", "/etc/mysql/my.$cnfext" )
933    {
934      check_sys_cfg_file ($opt, $cfg);
935    }
936  }
937  exit 0
938}
939else
940{
941  error($opt,
942        "Installation of system tables failed!",
943         "",
944        "Examine the logs in $opt->{ldata} for more information.",
945        "You can try to start the mysqld daemon with:",
946        "$mysqld --skip-grant-tables &",
947        "and use the command line tool",
948        "$bindir/mysql to connect to the mysql",
949        "database and look at the grant tables:",
950        "",
951        "shell> $bindir/mysql -u root mysql",
952        "mysql> show tables",
953        "",
954        "Try 'mysqld --help' if you have problems with paths. Using --log",
955        "gives you a log in $opt->{ldata} that may be helpful.",
956        "",
957        "The latest information about MySQL is available on the web at",
958        "http://www.mysql.com",
959        "Please consult the MySQL manual section: 'Problems running mysql_install_db',",
960        "and the manual section that describes problems on your OS.",
961        "Another information source is the MySQL email archive.",
962        "",
963        "Please check all of the above before submitting a bug report",
964        "at http://bugs.mysql.com/")
965}
966
967##############################################################################
968#
969#  Misc
970#
971##############################################################################
972
973sub check_sys_cfg_file
974{
975  my $opt= shift;
976  my $fname= shift;
977
978  if ( -e $fname )
979  {
980    warning($opt,
981	    "Default config file $fname exists on the system",
982	    "This file will be read by default by the MySQL server",
983	    "If you do not want to use this, either remove it, or use the",
984	    "--defaults-file argument to mysqld_safe when starting the server");
985  }
986}
987
988sub report_verbose
989{
990  my $opt  = shift;
991  my $text = shift;
992
993  report_verbose_wait($opt, $text, @_);
994  print "\n\n";
995}
996
997sub report_verbose_wait
998{
999  my $opt  = shift;
1000  my $text = shift;
1001
1002  if ( $opt->{verbose} or (!$opt->{rpm} and !$opt->{'cross-bootstrap'}) )
1003  {
1004    print "$text";
1005    map {print "\n$_"} @_;
1006  }
1007}
1008
1009sub report
1010{
1011  my $opt  = shift;
1012  my $text = shift;
1013
1014  print "$text\n";
1015  map {print "$_\n"} @_;
1016  print "\n";
1017}
1018
1019sub error
1020{
1021  my $opt  = shift;
1022  my $text = shift;
1023
1024  print "FATAL ERROR: $text\n";
1025  map {print "$_\n"} @_;
1026  exit 1;
1027}
1028
1029sub warning
1030{
1031  my $opt  = shift;
1032  my $text = shift;
1033
1034  print "WARNING: $text\n";
1035  map {print "$_\n"} @_;
1036  print "\n";
1037}
1038
1039# Include dummy lines with patterns that generalized pkgadd script expects
1040
1041my $_pkgadd_fodder= "
1042basedir=foo
1043datadir=bar
1044";
1045