mysqlaccess
上传用户:dzyhzl
上传日期:2019-04-29
资源大小:56270k
文件大小:112k
源码类别:

模拟服务器

开发平台:

C/C++

  1. #!/usr/bin/perl
  2. # ****************************
  3. package MySQLaccess;
  4. #use strict;
  5. use POSIX qw(tmpnam);
  6. use Fcntl;
  7. BEGIN {
  8. # ****************************
  9. # static information...
  10. $VERSION     = "2.06, 20 Dec 2000";
  11. $0           =~ m%/([^/]+)$%o;
  12. $script      = $1;
  13.         $script      = 'MySQLAccess' unless $script;
  14. $script_conf = "$script.conf";
  15. $script_log  = $ENV{'HOME'}."/$script.log";
  16. # ****************************
  17. # information on MySQL
  18. $MYSQL     = '/usr/local/mysql/bin/mysql';    # path to mysql executable
  19. $SERVER    = '3.21';
  20. $MYSQL_OPT = ' --batch --unbuffered';
  21. $ACCESS_DB = 'mysql';  # name of DB with grant-tables
  22. $ACCESS_H  = 'host';  # 
  23. $ACCESS_U  = 'user';          # 
  24. $ACCESS_D  = 'db';               #
  25. # Add/Edit privileges
  26. $ACCESS_H_TMP = 'host_tmp';      
  27. $ACCESS_U_TMP = 'user_tmp';      
  28. $ACCESS_D_TMP = 'db_tmp';        
  29. $ACCESS_H_BCK = 'host_backup';   
  30. $ACCESS_U_BCK = 'user_backup';   
  31. $ACCESS_D_BCK = 'db_backup';     
  32.         $DIFF      = '/usr/bin/diff'; 
  33.         $TMP_PATH  = '/tmp';             #path to writable tmp-directory
  34.         $MYSQLDUMP = '/usr/local/mysql/bin/mysqldump';
  35.                                          #path to mysqldump executable
  36.         $MYSQLADMIN= 'http://foobar.com/MySQLadmin';
  37.                                          #URL of CGI for manipulating
  38.                                          #the temporary grant-tables
  39. }
  40. END {
  41. unlink $MYSQL_CNF if defined $MYSQL_CNF and not $DEBUG;
  42. }
  43. $INFO = <<"_INFO";
  44. --------------------------------------------------------------------------
  45.    mysqlaccess (Version $VERSION)
  46.    ~~~~~~~~~~~
  47.    Copyright (C) 1997,1998 Yves.Carlier@rug.ac.be
  48.                            University of Ghent (RUG), Belgium
  49.                            Administratieve Informatieverwerking (AIV)
  50.    report the access-privileges for a USER from a HOST to a DB
  51.    Many thanks go to <monty@mysql.com> and <psmith@BayNetworks.COM>
  52.    for their suggestions, debugging and patches. 
  53.    use `$script -?' to get more information on available options.
  54.    From version 2.0x, $script can also be used through a WEB-browser
  55.    if it is ran as a CGI-script.  (See the release-notes)
  56. --------------------------------------------------------------------------
  57. _INFO
  58. $OPTIONS = <<_OPTIONS;
  59. Usage: $script [host [user [db]]] OPTIONS
  60.   -?, --help           display this helpscreen and exit
  61.   -v, --version        print information on the program `$script'
  62.   -u, --user=#         username for logging in to the db
  63.   -p, --password=#     validate password for user
  64.   -h, --host=#         name or IP-number of the host
  65.   -d, --db=#           name of the database
  66.   -U, --superuser=#    connect as superuser
  67.   -P, --spassword=#    password for superuser
  68.   -H, --rhost=#        remote MySQL-server to connect to
  69.       --old_server     connect to old MySQL-server (before v3.21) which 
  70.                        does not yet know how to handle full where clauses.
  71.   -b, --brief          single-line tabular report
  72.   -t, --table          report in table-format
  73.   --relnotes           print release-notes
  74.   --plan               print suggestions/ideas for future releases
  75.   --howto              some examples of how to run `$script'
  76.   --debug=N            enter debuglevel N (0..3)
  77.   --copy               reload temporary grant-tables from original ones
  78.   --preview            show differences in privileges after making
  79.                        changes in (temporary) grant-tables
  80.   --commit             copy grant-rules from temporary tables to grant-tables
  81.                        (!don't forget to do an mysqladmin reload)
  82.   --rollback           undo the last changes to the grant-tables.
  83.   Note:
  84.     + At least the user and the db must be given (even with wildcards)
  85.     + If no host is given, `localhost' is assumed
  86.     + Wilcards (*,?,%,_) are allowed for host, user and db, but be sure 
  87.       to escape them from your shell!! (ie type \* or '*')
  88. _OPTIONS
  89. $RELEASE = <<'_RELEASE';
  90.  
  91. Release Notes:
  92. -------------
  93.   0.1-beta1: internal
  94.   - first trial.
  95.  
  96.   0.1-beta2: (1997-02-27)
  97.   - complete rewrite of the granting-rules, based on the documentation
  98.     found in de FAQ.
  99.   - IP-number and name for a host are equiv.
  100.  
  101.   0.1-beta3: (1997-03-10)
  102.   - more information
  103.   - 'localhost' and the name/ip of the local machine are now equiv.
  104.   0.1-beta4: (1997-03-11)
  105.   - inform the user if he has not enough priv. to read the mysql db
  106.   1.0-beta1: (1997-03-12)
  107.   suggestions by Monty:
  108.   - connect as superuser with superpassword.
  109.   - mysqlaccess could also notice if all tables are empty. This means
  110.     that all user have full access!
  111.   - It would be nice if one could optionally start mysqlaccess without
  112.     any options just the arguments 'user db' or 'host user db', where
  113.     host is 'localhost' if one uses only two arguments.
  114.   1.0-beta2: (1997-03-14)
  115.   - bugfix: translation to reg.expr of _ and %.
  116.   - bugfix: error in matching regular expression and string given
  117.             by user which resulted in
  118.             'test_123' being matched with 'test'
  119.   1.0-beta3: (1997-03-14)
  120.   - bugfix: the user-field should not be treated as a sql-regexpr,
  121.             but as a plain string.
  122.   - bugfix: the host-table should not be used if the host isn't empty in db
  123.                                           or  if the host isn't emty in user
  124.             (Monty)
  125.  
  126.   1.0-beta4: (1997-03-14)
  127.   - bugfix: in an expression "$i = $j or $k", the '=' binds tighter than the or
  128.             which results in problems...
  129.             (by Monty)
  130.   - running mysqlaccess with "perl -w" gives less warnings...   ;-)
  131.   1.0-beta5: (1997-04-04)
  132.   - bugfix: The table sorting was only being applied to the "user" table; all
  133.             the tables need to be sorted.  Rewrote the sort algorithm, and
  134.             the table walk algorithm (no temp file anymore), and various
  135.             other cleanups.  I believe the access calculation is 100% correct.
  136.             (by Paul D. Smith <psmith@baynetworks.com>)
  137.   - Allow the debug level to be set on the cmd line with --debug=N.
  138.             (by Paul D. Smith <psmith@baynetworks.com>)
  139.   - More -w cleanups; should be totally -w-clean.
  140.             (by Paul D. Smith <psmith@baynetworks.com>)
  141.  
  142.   1.1-beta1: (1997-04-xx) 
  143.   1.1-beta2: (1997-04-11)
  144.   - new options:
  145.              --all_users : report access-rights for all possible users
  146.              --all_dbs   : report access-rights for all possible dbs
  147.              --all_hosts : report access-rights for all possible hosts
  148.              --brief     : as brief as possible, don't mention notes,warnings and rules
  149.              --password  : validate password for user 
  150.   - layout: long messages are wrapped on the report.
  151.   - functionality:
  152.             more descriptive notes and warnings
  153.             wildcards (*,?) are allowed in the user,host and db options
  154.             setting xxxx=* is equiv to using option --all_xxxx
  155.             note: make sure you escape your wildcards, so they don't get
  156.                   interpreted by the shell.  use * or '*'
  157.   - bugfix: Fieldnames which should be skipped on the output can now have
  158.             a first capital letter.
  159.   - bugfix: any option with a '.' (eg ip-number) was interpreted as
  160.             a wildcard-expression.
  161.   - bugfix: When no entry was found in the db-table, the default accessrights are
  162.             N, instead of the faulty Y in a previous version.
  163.  
  164.   1.1-beta-3  : (1997-04-xx)
  165.   1.1-beta-4  : (1997-04-xx)
  166.   1.1-beta-5  : (1997-04-xx)
  167.   1.1         : (1997-04-28)
  168.   - new options:
  169.             --rhost     : name of mysql-server to connect to
  170.             --plan      : print suggestions/ideas for future releases
  171.             --relnotes  : display release-notes
  172.             --howto     : display examples on how to use mysqlaccess
  173.             --brief     : single-line tabular output
  174.   - functionality/bugfix:
  175.     *      removed options --all_users,--all_dbs,--all_hosts, which 
  176.            were redundant with the wildcard-expressions for the corresponding
  177.            options. They made the processing of the commandline too painful 
  178.            and confusing ;-)
  179.            (suggested by psmith)
  180.     *      redefined the option --brief, which now gives a single-line 
  181.            tabular output
  182.     *      Now we check if the right version of the mysql-client is used,
  183.            since we might use an option not yet implemented in an
  184.            older version (--unbuffered, since 3.0.18)
  185.            Also the error-messages the mysql-client reports are 
  186.            better interpreted ;-)  
  187.     *      Wildcards can now be given following the SQL-expression 
  188.            (%,_) and the Regular-expression (*,?) syntax.
  189.   - speed: we now open a bidirectional pipe to the mysql-client, and keep 
  190.            it open throughout the whole run. Queries are written to,
  191.            and the answers read from the pipe.
  192.            (suggested by monty)
  193.   - bugfixes:
  194.     *      the Rules were not properly reset over iterations 
  195.     *      when in different tables the field-names were not identical, 
  196.            eg. Select_priv and select_priv, they were considered as 
  197.            definitions of 2 different access-rights.
  198.     *      the IP-number of a host with a name containing wildcards should
  199.            not be searched for in Name2IP and IP2Name.
  200.     *      various other small things, pointed out by <monty> and <psmith>
  201.   1.2         : (1997-05-13)
  202.   - bugfix:
  203.     * Fixed bug in acl with anonymous user:  Now if one gets accepted by the
  204.       user table as a empty user name, the user name is set to '' when 
  205.       checking against the 'db' and 'host' tables. (Bug fixed in MySQL3.20.19)
  206.   1.2-1       : (1997-xx-xx)
  207.   - bugfix:
  208.     * hashes should  be initialized with () instead of {} <psmith>
  209.     * "my" variable $name masks earlier declaration in same scope,
  210.       using perl 5.004 <????>
  211.   1.2-2       : (1997-06-10)
  212.     
  213.   2.0p1-3     : (1997-10-xx)
  214.   - new
  215.     * packages
  216.     * log-file for debug-output : /tmp/mysqlaccess.log
  217.     * default values are read from a configuration file $script.conf
  218.       first this file is looked for in the current directory; if not
  219.       found it is looked for in /etc/
  220.       Note that when default-values are given, these can't get overriden
  221.       by empty (blanc) values!
  222.     * CGI-BIN version with HTML and forms interface.  Simply place the
  223.       script in an ScriptAliased directory, make the configuration file
  224.       available in the that directory or in /etc, and point your browser
  225.       to the right URL. 
  226.     * copy the grant-rules to temporary tables, where you are safe to
  227.       play with them.
  228.     * preview changes in privileges after changing grant-rules,
  229.       before taking them into production
  230.     * copy the new grant-rules from the temporary tables back to the
  231.       grant-tables.
  232.     * Undo all changes made in the grant-tables (1-level undo).
  233.   -new options:
  234.     * --table   : as opposite of the --brief option.
  235.     * --copy    : (re)load temporary grant-tables from original ones.
  236.     * --preview : preview changes in privileges after changing
  237.                   some or more entries in the grant-tables.
  238.     * --commit  : copy grant-rules from temporary tables to grant-tables
  239.                   (!don't forget to do an mysqladmin reload)
  240.     * --rollback: undo the last changes to the grant-tables.
  241.   - bugfix:
  242.     * if the table db is empty, mysqlaccess freezed 
  243.       (by X Zhu <X.Zhu@Bradford.ac.uk>)
  244.   2.0         : (1997-10-09)
  245.   - fixed some "-w" warnings.
  246.   - complain when certain programs and paths can't be found.
  247.   2.01        : (1997-12-12)
  248.   - bugfix:
  249.     * rules for db-table where not calculated and reported correctly.
  250.   2.02        : (1998-01-xx)
  251.   - bugfix:
  252.     * Privileges of the user-table were not AND-ed properly with the
  253.       other privileges. (reported by monty)
  254.   - new option:
  255.     * --old_server: mysqlaccess will now use a full where clause when
  256.                     retrieving information from the MySQL-server.  If
  257.                     you are connecting to an old server (before v3.21)
  258.                     use the option --old_server.
  259.   2.03         : (1998-02-27)
  260.   - bugfix:
  261.     * in Host::MatchTemplate: incorrect match if host-field was left empty.
  262.   2.04-alpha1  : (2000-02-11)
  263.   Closes vulnerability due to former implementation requiring passwords
  264.   to be passed on the command line.
  265.   - functionality
  266.     Option values for --password -p -spassword -P  may now be omitted from
  267.     command line, in which case the values will be prompted for.
  268.       (fix supplied by Steve Harvey <sgh@vex.net>)
  269.    2.05: (2000-02-17)   Monty
  270.    Moved the log file from /tmp to ~
  271.    2.06:  Don't print '+++USING FULL WHERE CLAUSE+++'
  272. _RELEASE
  273. $TODO = <<_TODO;
  274.  Plans:
  275.  -----
  276.   -a full where clause is use now.  How can we handle older servers?
  277.   -add some more functionality for DNS.
  278.   -select the warnings more carefuly.
  279.   >>  I think that the warnings should either be enhanced to _really_
  280.   >>  understand and report real problems accurately, or restricted to
  281.   >>  only printing things that it knows with 100% certainty. <psmith)
  282.   >>  Why do I have both '%' and 'any_other_host' in there?  Isn't that
  283.   >>  the same thing?  I think it's because I have an actual host '%' in
  284.   >>  one of my tables.  Probably the script should catch that and not
  285.   >>  duplicate output. <psmith>
  286. _TODO
  287. # From the FAQ: the Grant-algorithm
  288. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  289. # The host table is mainly to maintain a list of "secure" servers.
  290. # At TCX hosts contain a list of all machines on local network. These are granted
  291. # all privileges.
  292. # Technically the user grant is calculated by:
  293. #
  294. #    1.First sort all entries by host by putting host without wildcards first,
  295. #      after this host with wildcards and entries with host = ".
  296. #      Under each host sort user by the same criterias.
  297. #    2.Get grant for user from the "db" table.
  298. #    3.If hostname is "empty" for the found entry, AND the privileges with
  299. #      the privileges for the host in "host" table.
  300. #      (Remove all which is not "Y" in both)
  301. #    4.OR (add) the privileges for the user from the "user" table.
  302. #     (add all privileges which is "Y" in "user")
  303. #
  304. #    When matching, use the first found match.
  305. #
  306. # -----------------------------------------------------------------------------------
  307. $HOWTO = <<_HOWTO;
  308. Examples of how to call $script:
  309. ~~~~~~~~
  310. 1)Calling $script with 2 arguments:
  311.   $ $script root mysql
  312.      ->report rights of user root logged on at the local host in db mysql
  313.   Access-rights
  314.   for USER 'root', from HOST 'localhost', to DB 'mysql'
  315.           +-----------------+---+ +-----------------+---+
  316.           | select_priv     | Y | | drop_priv       | Y |
  317.           | insert_priv     | Y | | reload_priv     | Y |
  318.           | update_priv     | Y | | shutdown_priv   | Y |
  319.           | delete_priv     | Y | | process_priv    | Y |
  320.           | create_priv     | Y | | file_priv       | Y |
  321.           +-----------------+---+ +-----------------+---+
  322.   BEWARE:  Everybody can access your DB as user 'root'
  323.         :  WITHOUT supplying a password.  Be very careful about it!!
  324.   The following rules are used:
  325.    db    : 'No matching rule'
  326.    host  : 'Not processed: host-field is not empty in db-table.'
  327.    user  : 'localhost','root','','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y'
  328. 2)Calling $script with 3 arguments:
  329.   $ $script foo.bar nobody Foo 
  330.      ->report rights of user root logged in at machine foobar to db Foo
  331.   Access-rights
  332.   for USER 'nobody', from HOST 'foo.bar', to DB 'Foo'
  333.           +-----------------+---+ +-----------------+---+
  334.           | select_priv     | Y | | drop_priv       | N |
  335.           | insert_priv     | Y | | reload_priv     | N |
  336.           | update_priv     | Y | | shutdown_priv   | N |
  337.           | delete_priv     | Y | | process_priv    | N |
  338.           | create_priv     | N | | file_priv       | N |
  339.           +-----------------+---+ +-----------------+---+
  340.   BEWARE:  Everybody can access your DB as user 'nobody'
  341.         :  WITHOUT supplying a password.  Be very careful about it!!
  342.   The following rules are used:
  343.    db    : 'foo.bar','Foo','nobody','Y','Y','Y','N','N','N'
  344.    host  : 'Not processed: host-field is not empty in db-table.'
  345.    user  : 'foo.bar','nobody','','N','N','N','Y','N','N','N','N','N','N'
  346. 3)Using wildcards:
  347.   $ $script  \* nobody Foo --brief
  348.      ->report access-rights of user nobody from all machines to db Foo,
  349.        and use a matrix-report.
  350.   Sel  Ins  Upd  Del  Crea Drop Reld Shut Proc File Host,User,DB        
  351.   ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- --------------------
  352.    Y    Y    Y    Y    N    N    N    N    N    N   localhost,nobody,Foo
  353.    N    N    N    N    N    N    N    N    N    N   %,nobody,Foo  
  354.    N    N    N    N    N    N    N    N    N    N   any_other_host,nobody,Foo
  355. _HOWTO
  356. # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
  357. #                       START OF THE PROGRAM                            #
  358. # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
  359. use Getopt::Long;
  360. use Sys::Hostname;
  361. use IPC::Open3;
  362. #use CGI; #moved to use of CGI by monty
  363. # ****************************
  364. # debugging flag
  365. # can be set to 0,1,2,3
  366. # a higher value gives more info
  367. # ! this can also be set on the command-line
  368. $DEBUG   = 0;
  369. # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>8
  370. #  Normaly nothing should be changed beneeth this line
  371. # ****************************
  372. # no caching on STDOUT
  373. $|=1;
  374. $MYSQL_CNF = POSIX::tmpnam();
  375. %MYSQL_CNF = (client    => { },
  376.                       mysql     => { },
  377.                       mysqldump => { },
  378. );
  379. $NEW_USER = 'ANY_NEW_USER';
  380. $NEW_DB   = 'ANY_NEW_DB'  ;
  381. # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
  382. #  mysqlaccess:                                              #
  383. #  ~~~~~~~~~~~                                               #
  384. #  Lets get to it,                                           #
  385. #  and start the program by processing the parameters        #
  386. # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
  387. ($CMD,$CGI) = GetMode();
  388. # ****************************
  389. # the copyright message should
  390. # always be printed (once)
  391. MySQLaccess::Report::Print_Header();
  392. # *****************************
  393. # Read configuration-file
  394.   MySQLaccess::Debug::Print(1, "Reading configuration file...");
  395.   if (-f "./$script_conf") {
  396.      require "./$script_conf";
  397.   }
  398.   elsif (-f "/etc/$script_conf") {
  399.      require "/etc/$script_conf";
  400.   }
  401. # ****************************
  402. # Read in all parameters
  403. if ($MySQLaccess::CMD) { #command-line version
  404. # ----------------------------
  405. # Get options from commandline
  406. $Getopt::Long::ignorecase=0; #case sensitive options
  407. if ( grep(/-?/,@ARGV) ) { MySQLaccess::Report::Print_Usage(); exit 0; }
  408. GetOptions("help"          => $Param{'help'}
  409.           ,"host|h=s"      => $Param{'host'}
  410.           ,"user|u=s"      => $Param{'user'}
  411.           ,"password|p:s"  => $Param{'password'}
  412.           ,"db|d=s"        => $Param{'db'}
  413.           ,"superuser|U=s" => $Param{'superuser'}
  414.           ,"spassword|P:s" => $Param{'spassword'}
  415.           ,"rhost|H=s"     => $Param{'rhost'}
  416.                   ,"old_server"    => $Param{'old_server'}
  417.           ,"debug=i"       => $Param{'DEBUG'}
  418.           ,"brief|b"       => $Param{'brief'}
  419.           ,"table|t"       => $Param{'table'}
  420.           ,"relnotes"      => $Param{'relnotes'}
  421.           ,"plan"          => $Param{'plan'}
  422.           ,"howto"         => $Param{'howto'}
  423.           ,"version|v"     => $Param{'version'}
  424.                   ,"preview"       => $Param{'preview'}
  425.                   ,"copy"          => $Param{'copy'}
  426.                   ,"commit"        => $Param{'commit'}
  427.                   ,'rollback'      => $Param{'rollback'}
  428.   );
  429.         # -----------------------------
  430.         # set DEBUG
  431.         $DEBUG = $Param{'DEBUG'} if ($Param{'DEBUG'}>=$DEBUG);
  432. # -----------------------------
  433. # check for things which aren't
  434. # declared as options:
  435. # 2 arguments: (user,db) -> ('localhost','user','db')
  436. if ($#ARGV == 1) {
  437.    MySQLaccess::Debug::Print(2,"$script called with 2 arguments:");
  438.    $Param{'host'} = $Param{'host'} || 'localhost'; 
  439.    $Param{'user'} = $ARGV[0] || $Param{'user'};
  440.            $Param{'db'}   = $ARGV[1] || $Param{'db'}; 
  441. }
  442. # 3 arguments: (host,user,db)
  443. if ($#ARGV == 2) {
  444.    MySQLaccess::Debug::Print(2,"$script called with 3 arguments:");
  445.    $Param{'host'} = $ARGV[0] || $Param{'host'};
  446.    $Param{'user'} = $ARGV[1] || $Param{'user'};
  447.    $Param{'db'}   = $ARGV[2] || $Param{'db'};
  448. }
  449. # -------------------------------------
  450. # prompt for user password if requested
  451. if ( defined($Param{'password'}) && length($Param{'password'}) == 0 ) {
  452.            $Param{'password'} = PromptPass(
  453.                         "Password for MySQL user $Param{'user'}: ");
  454. }
  455. }
  456. if ($MySQLaccess::CGI) { #CGI-version
  457. use CGI;
  458.   $Q = new CGI;
  459. $Param{'help'} = $Q->param('help') ;
  460. $Param{'host'} = $Q->param('host') || $Q->param('h') || $Param{'host'};
  461. $Param{'user'} = $Q->param('user') || $Q->param('u') || $Param{'user'};
  462. $Param{'db'}   = $Q->param('db')   || $Q->param('d') || $Param{'db'};
  463. $Param{'password'}  = $Q->param('password')  || $Q->param('p') || $Param{'password'};
  464. $Param{'superuser'} = $Q->param('superuser') || $Q->param('U') || $Param{'superuser'};
  465. $Param{'spassword'} = $Q->param('spassword') || $Q->param('P') || $Param{'spassword'};
  466. $Param{'rhost'}     = $Q->param('rhost')     || $Q->param('H') || $Param{'rhost'};
  467. $Param{'old_server'}= $Q->param('old_server')|| $Param{'old_server'};
  468. $Param{'debug'}     = $Q->param('debug')     || $Param{'debug'};
  469. $Param{'brief'}     = $Q->param('brief')     || $Param{'brief'}; 
  470. $Param{'table'}     = $Q->param('table')     || $Param{'table'}; 
  471. $Param{'relnotes'}  = $Q->param('relnotes');
  472. $Param{'plan'}      = $Q->param('plan');
  473. $Param{'howto'}     = $Q->param('howto'); 
  474. $Param{'version'}   = $Q->param('version') ? $Q->param('version') : $Q->param('v');
  475. $Param{'edit'}      = $Q->param('edit'); 
  476. $Param{'preview'}   = $Q->param('preview'); 
  477. $Param{'copy'}      = $Q->param('copy'); 
  478. $Param{'commit'}    = $Q->param('commit'); 
  479. $Param{'rollback'}  = $Q->param('rollback'); 
  480.         # -----------------------------
  481.         # set DEBUG
  482.         $DEBUG = $Q->param('debug') if ($Q->param('debug')>=$DEBUG);
  483. }
  484. # ----------------------
  485. # brief and table-format 
  486. # exclude each-other
  487. # table-format is prefered
  488. if (defined($Param{'table'})) { undef($Param{'brief'}); }
  489. if (defined($Param{'preview'}) or
  490.     defined($Param{'copy'}) or
  491.     defined($Param{'commit'}) or
  492.     defined($Param{'rollback'}) ) { $Param{'edit'}='on'; }
  493. # ----------------------
  494. # if no host is given
  495. # assume we mean 'localhost'
  496. if (!defined($Param{'host'}))      { $Param{'host'}='localhost'; }
  497. # ----------------------
  498. # perform some checks
  499. # -> eliminate 'broken pipe' error
  500. push(@MySQLaccess::Grant::Error,'not_found_mysql')     if !(-x $MYSQL);
  501. push(@MySQLaccess::Grant::Error,'not_found_diff')      if !(-x $DIFF);
  502. push(@MySQLaccess::Grant::Error,'not_found_mysqldump') if !(-x $MYSQLDUMP);
  503. push(@MySQLaccess::Grant::Error,'not_found_tmp')       if !(-d $TMP_PATH);
  504. push(@MySQLaccess::Grant::Error,'write_err_tmp')       if !(-w $TMP_PATH);
  505. if (@MySQLaccess::Grant::Error) {
  506.    MySQLaccess::Report::Print_Error_Messages() ;
  507.    exit 0;
  508. }
  509. #-----------------------
  510. # get info/help if necc.
  511. $print_usage=1;
  512. if ( defined($Param{'version'}) ) {
  513.    MySQLaccess::Report::Print_Version();
  514.    $print_usage=0;
  515.    MySQLaccess::Report::Print_Footer();
  516.    MySQLaccess::DB::CloseConnection();
  517.    exit 0;
  518. #   exit 0;
  519. }
  520. if ( defined($Param{'relnotes'}) ) {
  521.    MySQLaccess::Report::Print_Relnotes();
  522.    $print_usage=0;
  523.    MySQLaccess::Report::Print_Footer();
  524.    MySQLaccess::DB::CloseConnection();
  525.    exit 0;
  526. #   exit 0;
  527. }
  528. if ( defined($Param{'plan'}) ) {
  529.    MySQLaccess::Report::Print_Plans();
  530.    $print_usage=0;
  531.    MySQLaccess::Report::Print_Footer();
  532.    MySQLaccess::DB::CloseConnection();
  533.    exit 0;
  534. #   exit 0;
  535. }
  536. if ( defined($Param{'howto'}) ) {
  537.    MySQLaccess::Report::Print_HowTo();
  538.    $print_usage=0;
  539.    MySQLaccess::Report::Print_Footer();
  540.    MySQLaccess::DB::CloseConnection();
  541.    exit 0;
  542. #   exit 0;
  543. }
  544. # -----------------------------
  545. # generate a help-screen in CMD-mode
  546. # or a blanc form in CGI-mode 
  547. if ( defined($Param{'help'}) 
  548.      or !defined($Param{'user'}) 
  549.      or !defined($Param{'host'})
  550.      or !defined($Param{'db'}) 
  551.    ) {
  552.    push(@MySQLaccess::Grant::Error,'user_required') unless defined($Param{'user'});
  553.    push(@MySQLaccess::Grant::Error,'db_required') unless defined($Param{'db'});
  554.    push(@MySQLaccess::Grant::Error,'host_required') unless defined($Param{'host'});
  555.    MySQLaccess::Report::Print_Usage() if $print_usage;
  556.    exit 0;
  557. }
  558. # ----------------------------
  559. # get hostname and local-ip
  560. # for localhost
  561. $localhost = MySQLaccess::Host::LocalHost();
  562. $local_ip  = MySQLaccess::Host::Name2IP($localhost);
  563. $MySQLaccess::Host::localhost = MySQLaccess::Host::LocalHost();
  564. $MySQLaccess::Host::local_ip  = MySQLaccess::Host::Name2IP($localhost);
  565. MySQLaccess::Debug::Print(3, "localhost name=$localhost, ip=$local_ip");
  566. #-----------------------------------
  567. # version of MySQL-server to connect
  568. # to determine use of full where clause
  569. $MySQLaccess::Host::SERVER = $Param{'old_server'} ? '3.20' : $SERVER;
  570. #---------------------------------
  571. # create the config file for mysql and mysqldump
  572. # to avoid passing authentication info on the command line
  573. #
  574. MergeConfigFiles();
  575. die "Unsafe config file found: $unsafeConfign"  if $unsafeConfig;
  576. if (defined($Param{'superuser'})) {
  577.    $MYSQL_CNF{'mysql'}{'user'} = $Param{'superuser'};
  578.    $MYSQL_CNF{'mysqldump'}{'user'} = $Param{'superuser'};
  579. }
  580. if (defined($Param{'spassword'})) {
  581.    if ( $CMD && length($Param{'spassword'}) == 0 ) {
  582.       $Param{'spassword'} =
  583.            PromptPass("Password for MySQL superuser $Param{'superuser'}: ");
  584.    }
  585.    if ( length($Param{'spassword'}) > 0 ) {
  586.       $MYSQL_CNF{'mysql'}{'password'} = $Param{'spassword'};
  587.       $MYSQL_CNF{'mysqldump'}{'password'} = $Param{'spassword'};
  588.    }
  589. }
  590. WriteTempConfigFile();
  591. #---------------------------------
  592. # Inform user if he has not enough
  593. # privileges to read the access-db
  594. if ( $nerror=MySQLaccess::DB::OpenConnection() ) {
  595.     MySQLaccess::Report::Print_Error_Access($nerror);
  596.     exit 0;
  597. }
  598. # -----------------------
  599. # Read MySQL ACL-files
  600. if ($nerror=MySQLaccess::Grant::ReadTables()) {
  601.     MySQLaccess::Report::Print_Error_Access($nerror);
  602.     exit 0;
  603. };
  604. if ($Param{'edit'} and $nerror=MySQLaccess::Grant::ReadTables('tmp')) {
  605.     MySQLaccess::Report::Print_Error_Access($nerror);
  606.     exit 0;
  607. }
  608. #---------------------------------
  609. # reload temporay grant-tables 
  610. # with data from original ones
  611. if ( defined($Param{'copy'}) ) {
  612.    $nerror=MySQLaccess::DB::LoadTmpTables();
  613.    if ($nerror) {
  614.       MySQLaccess::Report::Print_Error_Access($nerror);
  615.       exit 0;
  616.    }
  617.    my $msg = "The grant-rules are copied from the grant-tables ton"
  618.            . "the temporary tables.";
  619.    MySQLaccess::Report::Print_Message([$msg]);
  620. #   MySQLaccess::Report::Print_Footer();
  621. #   MySQLaccess::DB::CloseConnection();
  622. #   exit 0;
  623. }
  624. #---------------------------------
  625. # preview result of changes in the 
  626. # grant-tables
  627. if ( defined($Param{'preview'}) ) {
  628.    $aref=MySQLaccess::Grant::Diff_Privileges();
  629.    MySQLaccess::Report::Print_Diff_ACL($aref);
  630. #   MySQLaccess::Report::Print_Footer();
  631. #   MySQLaccess::DB::CloseConnection();
  632. #   exit 0;
  633. }
  634. #---------------------------------
  635. # reload grant-tables 
  636. # with data from temporary tables
  637. if ( defined($Param{'commit'}) ) {
  638.    if ($nerror = MySQLaccess::DB::CommitGrantTables()) {
  639.       MySQLaccess::Report::Print_Error_Access($nerror);
  640.       exit 0;
  641.    }
  642.    my $msg = "The grant-rules have been copied from the temporary tablesn"
  643.            . "to the grant-tables.";
  644.    my $msg1= "Don't forget to do an 'mysqladmin reload' before thesen"
  645.            . "changes take effect.";
  646.    my $msg2= "A backup-version of your original grant-rules are saved in then"
  647.            . "backup-tables, so you can always perform a 1-level rollback.";
  648.    MySQLaccess::Report::Print_Message([$msg,$msg1,$msg2]);
  649. #   MySQLaccess::Report::Print_Footer();
  650. #   MySQLaccess::DB::CloseConnection();
  651. #   exit 0;
  652. }
  653. #---------------------------------
  654. # restore previous grant-rules
  655. # with data from backup tables
  656. if ( defined($Param{'rollback'}) ) {
  657.    if ($nerror = MySQLaccess::DB::RollbackGrantTables()) {
  658.       MySQLaccess::Report::Print_Error_Access($nerror);
  659.       exit 0;
  660.    }
  661.    my $msg = "The old grant-rules have been copied back from the backup tablesn"
  662.            . "to the grant-tables.";
  663.    my $msg1= "Don't forget to do an 'mysqladmin reload' before thesen"
  664.            . "changes take effect.";
  665.    MySQLaccess::Report::Print_Message([$msg,$msg1]);
  666. #   MySQLaccess::Report::Print_Footer();
  667. #   MySQLaccess::DB::CloseConnection();
  668. #   exit 0;
  669. }
  670. #----------------------------------
  671. # show edit-taskbar
  672. if ( defined($Param{'edit'})) {
  673.    if ($MySQLaccess::CGI ) {
  674.    MySQLaccess::Report::Print_Edit();
  675.    $print_usage=0;
  676.    MySQLaccess::Report::Print_Footer();
  677.    MySQLaccess::DB::CloseConnection();
  678.    exit 0;
  679.    }
  680.    else {
  681.    MySQLaccess::Report::Print_Edit();
  682.    $print_usage=0;
  683.    MySQLaccess::Report::Print_Footer();
  684.    MySQLaccess::DB::CloseConnection();
  685.    exit 0;
  686.    }
  687. }
  688. # -----------------------------
  689. # Build list of users,dbs,hosts
  690. # to process...
  691. @all_dbs   = @{MySQLaccess::DB::Get_All_dbs($Param{'db'})};
  692. @all_users = @{MySQLaccess::DB::Get_All_users($Param{'user'})};
  693. @all_hosts = @{MySQLaccess::DB::Get_All_hosts($Param{'host'})};
  694. #if EDIT-mode
  695. #@all_dbs_tmp   = @{MySQLaccess::DB::Get_All_dbs($Param{'db'},'tmp')};
  696. #@all_users_tmp = @{MySQLaccess::DB::Get_All_users($Param{'user'},'tmp')};
  697. #@all_hosts_tmp = @{MySQLaccess::DB::Get_All_hosts($Param{'host'},'tmp')};
  698. # -----------------------------
  699. # Report access-rights for each
  700. # tuple (host,user,db)
  701. #$headers=0;
  702. my %Access = ();
  703. foreach $host (@all_hosts) {
  704.   foreach $user (@all_users) {
  705.     foreach $db (@all_dbs) {
  706.       MySQLaccess::Grant::Initialize();
  707.       %Access = MySQLaccess::Grant::Get_Access_Rights($host,$user,$db);
  708.       MySQLaccess::Report::Print_Access_rights($host,$user,$db,%Access);
  709.     }
  710.   }
  711. }
  712. # -----------------------------
  713. # End script
  714. MySQLaccess::Report::Print_Footer();
  715. MySQLaccess::DB::CloseConnection();
  716. exit 0;
  717. #############################################################
  718. #  FUNCTIONS  #
  719. ###############
  720. sub GetMode {
  721.    my $cmd=0;
  722.    my $cgi=0;
  723.    if (defined($ENV{'HTTP_HOST'})) { $cmd=0; $cgi=1; }
  724.    else                            { $cmd=1; $cgi=0; } 
  725.    return ($cmd,$cgi);
  726. }
  727. # ================================
  728. # sub PromptPass
  729. #  prompt tty for a password
  730. # ================================
  731. sub PromptPass {
  732.     my ($prompt) = @_;
  733.     my $password;
  734.     $ENV{PATH} = "/bin:/usr/bin";
  735.     $ENV{IFS} = " tn";
  736.     $ENV{SHELL} = "/bin/sh";
  737.     system "stty -echo";
  738.     print $prompt;
  739.     chomp($password = <STDIN>);
  740.     print "n";
  741.     system "stty echo";
  742.     $password;
  743. }
  744. # =================================
  745. # sub CheckUnsafeFile
  746. #  tell if a config file containing a password is unsafe
  747. # =================================
  748. sub CheckUnsafeFile {
  749.     my ($fname) = @_;
  750.     my ($dev, $ino, $mode, $nlink,
  751.         $uid, $gid, $rdev, $size,
  752.         $atime, $mtime, $ctime, $blksize, $blocks) = stat($fname);
  753.     if ( $uid != $< ) {   # unsafe if owned by other than current user
  754.         return 1;
  755.     }
  756.     if ( $mode & 066 ) {  # unsafe if accessible by other
  757.         return 1;
  758.     }
  759.     $fname =~ s#/[^/]+$##;
  760.     if ( (length $fname) > 0 ) {
  761.         return CheckUnsafeDir($fname);
  762.     }
  763.     return 0;
  764. }
  765. # =================================
  766. # sub CheckUnsafeDir
  767. #  tell if a directory is unsafe
  768. # =================================
  769. sub CheckUnsafeDir {
  770.     my ($fname) = @_;
  771.     my ($dev, $ino, $mode, $nlink,
  772.         $uid, $gid, $rdev, $size,
  773.         $atime, $mtime, $ctime, $blksize, $blocks) = stat($fname);
  774.     # not owned by me or root
  775.     if ( ($uid != $<) && ($uid != 0) ) {
  776.         return 1;
  777.     }
  778.     if ( $mode & 022 ) {  # unsafe if writable by other
  779.         return 1  unless $mode & 01000;  # but sticky bit ok
  780.     }
  781.     $fname =~ s#/[^/]+$##;
  782.     if ( (length $fname) > 0 ) {
  783.         return CheckUnsafeDir($fname);
  784.     }
  785.     return 0;
  786. }
  787. # =================================
  788. # sub MergeConfigFile
  789. #  merge data from .cnf file
  790. # =================================
  791. sub MergeConfigFile {
  792.     my ($fname) = @_;
  793.     my ($group, $item, $value);
  794.     if ( open CNF, $fname ) {
  795.          while (<CNF>) {
  796.              s/^s+//;
  797.              next if /^[#;]/;
  798.              if ( /[s*(w+)s*]/ ) {
  799.                  $group = $1;
  800.                  $group =~ tr/A-Z/a-z/;
  801.                  if ( !exists $MYSQL_CNF{$group} ) {
  802.                      undef $group;
  803.                  }
  804.              } elsif ( defined $group ) {
  805.                  ($item, $value) = /((?:w|-)+)s*=s*(S+)/;
  806.                  # don't unquote backslashes as we just write it back out
  807.                  if ( defined $item ) {
  808.                      if ( $item =~ /^password$/ ) {
  809.                          if ( CheckUnsafeFile($fname) ) {
  810.                              $unsafeConfig = $fname;
  811.                          }
  812.                      }
  813.                      if ( $group eq 'client' ) {
  814.                          $MYSQL_CNF{'mysql'}{$item} = $value;
  815.                          $MYSQL_CNF{'mysqldump'}{$item} = $value;
  816.                      } else {
  817.                          $MYSQL_CNF{$group}{$item} = $value;
  818.                      }
  819.                  }
  820.              }
  821.          }
  822.          close(CNF);
  823.     }
  824. }
  825. # =================================
  826. # sub MergeConfigFiles
  827. #  merge options from config files
  828. #  NOTE: really should do two separate merges for each
  829. #    client to exactly duplicate order of resulting argument lists
  830. # =================================
  831. sub MergeConfigFiles {
  832.     my ($name,$pass,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) = getpwuid $<;
  833.     MergeConfigFile("/etc/my.cnf");
  834.     MergeConfigFile("$dir/.my.cnf");
  835. }
  836. # =================================
  837. # sub WriteTempConfigFile
  838. #  write 
  839. # =================================
  840. sub WriteTempConfigFile {
  841.    sysopen CNFFILE, $MYSQL_CNF, O_RDWR|O_CREAT|O_EXCL, 0700
  842.       or die "sysopen $MYSQL_CNF: $!";
  843.    
  844.    # groups may be in any order, generic groups such as [client] assumed
  845.    # here to be empty
  846.    foreach $group (keys %MYSQL_CNF) {
  847.       print CNFFILE "[$group]n";
  848.       foreach $item (keys %{$MYSQL_CNF{$group}}) {
  849.          if ( defined $MYSQL_CNF{$group}{$item} ) {
  850.             print CNFFILE "$item=$MYSQL_CNF{$group}{$item}n";
  851.          } else {
  852.             print CNFFILE "$itemn";
  853.          }
  854.       }
  855.       print CNFFILE "n";
  856.    }
  857.    close(CNFFILE);
  858. }
  859. ######################################################################
  860. package MySQLaccess::DB;
  861. ###########
  862. BEGIN {
  863.     $DEBUG     = 2;
  864.     $DEBUG     = $MySQLaccess::DEBUG unless ($DEBUG);
  865.     # Error-messages from the MySQL client
  866.     %ACCESS_ERR= ('Access_denied'       => 'Access denied' 
  867.                  ,'Dbaccess_denied'     => 'Access to database denied'
  868.                  ,'Unrecognized_option' => 'unrecognized option' 
  869.                  ,'Unknown_table'       => "Can't find file:"
  870.                  ,'unknown_error'       => '^ERROR:'
  871.                  );
  872. }
  873. # ######################################
  874. #  Connecting to the MYSQL DB
  875. # ======================================
  876. # sub OpenConnection
  877. #  Open an connection to the mysql-db
  878. #  questions to MYSQL_Q
  879. #  answers from MYSQL_A
  880. # ======================================
  881. sub OpenConnection {
  882.     my $pid;
  883.     MySQLaccess::Debug::Print(2,"OpenConnection:");
  884.     # check path to mysql-client executable
  885.     if (! -f $MySQLaccess::MYSQL) {
  886.        if ($MySQLaccess::CMD) { die "Could not find MySQL-client '$MySQLaccess::MYSQL'"; }
  887.        if ($MySQLaccess::CGI) { 
  888.           print "<center>n<font color=Red>n";
  889.           print "ERROR: Could not find MySQL-client '$MySQLaccess::MYSQL'";
  890.           print "</center>n</font>n";
  891.           exit 0;
  892.        }
  893.     }
  894.     # path to mysql executable
  895.     my $connect = "$MySQLaccess::MYSQL --defaults-file=$MySQLaccess::MYSQL_CNF";
  896.     $connect .= " $MySQLaccess::MYSQL_OPT";
  897.     # superuser, spassword transmitted via defaults-file
  898.     if (defined($MySQLaccess::Param{'rhost'}))     { $connect .= " --host=$MySQLaccess::Param{'rhost'}"; }
  899.     # other options??
  900.     # grant-database
  901.     $connect .= " $MySQLaccess::ACCESS_DB";
  902.     # open connection (not using /bin/sh -c)
  903.     MySQLaccess::Debug::Print(2,"Connecting to: $connect");
  904.     $pid=IPC::Open3::open3(*MYSQL_Q,*MYSQL_A,"",split /s+/,$connect);
  905.     MySQLaccess::Debug::Print(2,"PID of open pipe: $pid");
  906.     
  907.     # check connection 
  908.     print MYSQL_Q "select 'ok';n";
  909.     $answer = <MYSQL_A>; #answer from mysql
  910.     MySQLaccess::Debug::Print(2,"Answer: $answern");
  911.     foreach $nerror (sort(keys(%ACCESS_ERR))) {
  912.       MySQLaccess::Debug::Print(3,"check answer for error $ACCESS_ERR{$nerror}");
  913.       if (grep(/$ACCESS_ERR{$nerror}/i,$answer)) { 
  914.          MySQLaccess::Debug::Print(2,"Answer contain error [$nerror]");
  915.          return $nerror; 
  916.       }
  917.     }
  918. if (0) {
  919.     # check server-version 
  920.     print MYSQL_Q "select 'ok';n";
  921.     $answer = <MYSQL_A>; #answer from mysql
  922.     MySQLaccess::Debug::Print(2,"Answer: $answern");
  923.     foreach $nerror (sort(keys(%ACCESS_ERR))) {
  924.       MySQLaccess::Debug::Print(3,"check answer for error $ACCESS_ERR{$nerror}");
  925.       if (grep(/$ACCESS_ERR{$nerror}/i,$answer)) { 
  926.          MySQLaccess::Debug::Print(2,"Answer contain error [$nerror]");
  927.          return $nerror; 
  928.       }
  929.     }
  930. }
  931.     my $skip=<MYSQL_A>; 
  932.     return 0; 
  933. }
  934. # ======================================
  935. # sub CloseConnection
  936. #  Close the connection to the mysql-db
  937. # ======================================
  938. sub CloseConnection {
  939.     close MYSQL_Q;
  940.     close MYSQL_A;
  941. }
  942. # ===========================================================
  943. # sub CreateTable($table)
  944. #  Create temporary/backup table
  945. # ===========================================================
  946. sub CreateTable {
  947.     my $pid;
  948.     my ($table,$force) = @_;
  949.     my %tables = ( $MySQLaccess::ACCESS_U_TMP => $MySQLaccess::ACCESS_U,
  950.                    $MySQLaccess::ACCESS_H_TMP => $MySQLaccess::ACCESS_H,
  951.                    $MySQLaccess::ACCESS_D_TMP => $MySQLaccess::ACCESS_D,
  952.                    $MySQLaccess::ACCESS_U_BCK => $MySQLaccess::ACCESS_U,
  953.                    $MySQLaccess::ACCESS_H_BCK => $MySQLaccess::ACCESS_H,
  954.                    $MySQLaccess::ACCESS_D_BCK => $MySQLaccess::ACCESS_D,
  955.                    $MySQLaccess::ACCESS_U => $MySQLaccess::ACCESS_U_BCK,
  956.                    $MySQLaccess::ACCESS_H => $MySQLaccess::ACCESS_H_BCK,
  957.                    $MySQLaccess::ACCESS_D => $MySQLaccess::ACCESS_D_BCK,
  958.                  ); 
  959.     my $tbl;
  960.     my $query="";
  961.     my $delim;
  962.     my $skip;
  963.     my $create;
  964.     my @known_tables=();
  965. #    print STDERR "CreateTable($table)n";
  966.     MySQLaccess::Debug::Print(1,"CreateTable($table):");
  967.     ## error-handling
  968.     return 'Unknown_table' unless defined($tables{$table});
  969.     ## build list of known/existing tables;
  970.     ## if 'force' existing table is dropped first
  971.     if (defined($force) and $force) {
  972.        @known_tables = Show_Tables();
  973.        if (grep(/^$table$/,@known_tables)) {
  974.        $query = "DROP TABLE $table;";
  975.        }
  976.     }
  977.     ## path to mysqldump executable
  978.     my $connect = $MySQLaccess::MYSQLDUMP;
  979.     $connect .= " --defaults-file=$MySQLaccess::MYSQL_CNF --no-data";
  980.     # superuser, spassword transmitted via defaults-file
  981.     if (defined($MySQLaccess::Param{'rhost'}))     { $connect .= " --host=$MySQLaccess::Param{'rhost'}"; }
  982.     $connect .= " $MySQLaccess::ACCESS_DB";
  983.     $connect .= " $tables{$table}";
  984.     ## get creation-data for original table
  985.     $create = '';
  986.     my $mysqldump = $connect;
  987.     $mysqldump =~ s/ $TABLE / $tbl /;
  988.     # open connection (not using /bin/sh -c)
  989.     MySQLaccess::Debug::Print(2,"Connecting to: $connect");
  990.     $pid=IPC::Open3::open3(*DONTCARE,*CREATE,"",split /s+/,$mysqldump);
  991.     MySQLaccess::Debug::Print(2,"PID of open pipe: $pid");
  992.     #open(CREATE,"$mysqldump");
  993.     @create = <CREATE>;
  994.     $create = "@create";
  995.     foreach $nerror (sort(keys(%ACCESS_ERR))) {
  996.        MySQLaccess::Debug::Print(3,"check answer for error $ACCESS_ERR{$nerror}");
  997.        if (grep(/$ACCESS_ERR{$nerror}/i,$create)) { 
  998.           MySQLaccess::Debug::Print(2,"Answer contain error [$nerror]");
  999.           return $nerror; 
  1000.        }
  1001.     }
  1002.     close(CREATE);
  1003.     close(DONTCARE);
  1004.     ## manipulate result for creation-data for temporary table
  1005.     $create =~ s/CREATE TABLE $tables{$table} (/CREATE TABLE $table (/;
  1006.     ## recreate temporary table
  1007.     $query .= "$createn";
  1008.     $query .= "select 'ok';";
  1009.     ## execute query
  1010.     print MYSQL_Q "$queryn";
  1011. #    print STDERR $query;
  1012.     $answer = <MYSQL_A>; #answer from mysql
  1013. #    print STDERR "A>",$answer;
  1014.     MySQLaccess::Debug::Print(2,"Answer: $answern");
  1015.     foreach $nerror (sort(keys(%ACCESS_ERR))) {
  1016. #       print STDERR "->$nerror?";
  1017.        MySQLaccess::Debug::Print(3,"check answer for error $ACCESS_ERR{$nerror}");
  1018.        if (grep(/$ACCESS_ERR{$nerror}/i,$answer)) { 
  1019. #          print STDERR "Yes!";
  1020.           MySQLaccess::Debug::Print(2,"Answer contain error [$nerror]");
  1021.           return $nerror; 
  1022.        }
  1023.     }
  1024.     $delim = <MYSQL_A>; # read header
  1025.     if ($delim ne "okn") {
  1026.        while (($line=<MYSQL_A>) ne "okn")
  1027.        { MySQLaccess::Debug::Print(3," A> $line"); }
  1028.         $skip = <MYSQL_A>; # skip result 'ok'
  1029.     }
  1030. #    print STDERR "CreateTable donen";
  1031.     return 0;
  1032. }
  1033. # ===========================================================
  1034. # sub CopyTable()
  1035. #  Copy the structure and the data of a table to another table
  1036. # ===========================================================
  1037. sub CopyTable {
  1038.     my ($from,$to,$force) = @_;
  1039.     my @known_tables  = Show_Tables();    
  1040.     my $query = "";
  1041.     my $nerror= 0;
  1042.     my $skip;
  1043. #    print STDERR "CopyTable($from,$to)n";
  1044.     MySQLaccess::Debug::Print(1,"MySQLaccess::DB::CopyTable($from,$to)");
  1045.     ## error-handling
  1046.     if (!grep(/^$from$/,@known_tables)) { return 'Unknown_table'; }
  1047.     ## copy structure 
  1048.     ## if forced
  1049.     if (defined($force) and $force) {
  1050.        return $nerror if ($nerror=CreateTable($to,$force)); 
  1051. #       print STDERR "Structure copiedn";
  1052.     }
  1053.     ## copy data
  1054.     $query .= "DELETE FROM $to;";
  1055.     $query .= "INSERT INTO $to SELECT * FROM $from;";
  1056.     $query .= "SELECT 'ok';n";
  1057.     MySQLaccess::Debug::Print(2,"Query: $query");
  1058.        
  1059.     ## execute query
  1060.     print MYSQL_Q "$queryn";
  1061. #    print STDERR $query;
  1062.     ## check for errors...
  1063.     my $answer = <MYSQL_A>; #answer from mysql
  1064. #    print STDERR $answer;
  1065.     MySQLaccess::Debug::Print(2,"Answer: $answern");
  1066.     foreach $nerror (sort(keys(%ACCESS_ERR))) {
  1067.        MySQLaccess::Debug::Print(3,"check answer for error $ACCESS_ERR{$nerror}");
  1068.        if (grep(/$ACCESS_ERR{$nerror}/i,$answer)) { 
  1069.           MySQLaccess::Debug::Print(2,"Answer contain error [$nerror]");
  1070.           return $nerror; 
  1071.        }
  1072.     }
  1073.     my $delim = <MYSQL_A>; # read header
  1074. #    print STDERR $delim;
  1075.     if ($delim ne "okn") {
  1076.        while (($line=<MYSQL_A>) ne "okn")
  1077.        { MySQLaccess::Debug::Print(3," A> $line"); }
  1078.        $skip = <MYSQL_A>; # skip result 'ok'
  1079.     }
  1080.     return 0;
  1081. }
  1082. # ===========================================================
  1083. # sub LoadTmpTables()
  1084. #  (Re)load temporary tables with entries of ACL-tables
  1085. # ===========================================================
  1086. sub LoadTmpTables {
  1087.     my %tables = ( $MySQLaccess::ACCESS_U => $MySQLaccess::ACCESS_U_TMP,
  1088.                    $MySQLaccess::ACCESS_H => $MySQLaccess::ACCESS_H_TMP,
  1089.                    $MySQLaccess::ACCESS_D => $MySQLaccess::ACCESS_D_TMP,
  1090.                  ); 
  1091.     my $tbl;
  1092.     my $nerror;
  1093.     
  1094. #    print STDERR "LoadTmpTables:n";
  1095.     MySQLaccess::Debug::Print(1,"LoadTmpTables():");
  1096.     foreach $tbl (keys(%tables)) {
  1097. #       print STDERR "$tbl -> $tables{$tbl}n";
  1098.        MySQLaccess::Debug::Print(2,"Loading table $tbl -> $tables{$tbl}.");
  1099.        return $nerror if ($nerror=CopyTable($tbl,$tables{$tbl},'force'));
  1100.     }
  1101.     return 0;
  1102. }
  1103. # ===========================================================
  1104. # sub BackupGrantTables()
  1105. #  Make a backup of the original grant-tables
  1106. # ===========================================================
  1107. sub BackupGrantTables {
  1108.     my %tables = ( $MySQLaccess::ACCESS_U => $MySQLaccess::ACCESS_U_BCK,
  1109.                    $MySQLaccess::ACCESS_H => $MySQLaccess::ACCESS_H_BCK,
  1110.                    $MySQLaccess::ACCESS_D => $MySQLaccess::ACCESS_D_BCK,
  1111.                  ); 
  1112.     my $tbl;
  1113.     my $nerror;
  1114.     
  1115. #    print STDERR "BackupGrantTables:n";
  1116.     MySQLaccess::Debug::Print(1,"BackupGrantTables():");
  1117.     foreach $tbl (keys(%tables)) {
  1118. #       print STDERR "$tbl -> $tables{$tbl}n";
  1119.        MySQLaccess::Debug::Print(2,"Backup table $tbl -> $tables{$tbl}.");
  1120.        return $nerror if ($nerror=CopyTable($tbl,$tables{$tbl},'force'));
  1121.     }
  1122.     return 0;
  1123. }
  1124. # ===========================================================
  1125. # sub RollbackGrantTables()
  1126. #  Rollback the backup of the grant-tables
  1127. # ===========================================================
  1128. sub RollbackGrantTables {
  1129.     my %tables = ( $MySQLaccess::ACCESS_U_BCK => $MySQLaccess::ACCESS_U,
  1130.                    $MySQLaccess::ACCESS_H_BCK => $MySQLaccess::ACCESS_H,
  1131.                    $MySQLaccess::ACCESS_D_BCK => $MySQLaccess::ACCESS_D,
  1132.                  ); 
  1133.     my $tbl;
  1134.     my $nerror;
  1135.     
  1136. #    print STDERR "RollbackGrantTables:n";
  1137.     MySQLaccess::Debug::Print(1,"RollbackGrantTables():");
  1138.     foreach $tbl (keys(%tables)) {
  1139. #       print STDERR "$tbl -> $tables{$tbl}n";
  1140.        MySQLaccess::Debug::Print(2,"Rollback table $tbl -> $tables{$tbl}.");
  1141.        return $nerror if ($nerror=CopyTable($tbl,$tables{$tbl},'force'));
  1142.     }
  1143.     return 0;
  1144. }
  1145. # ===========================================================
  1146. # sub CommitGrantTables()
  1147. #  Copy grant-rules from temporary tables to the ACL-tables
  1148. # ===========================================================
  1149. sub CommitGrantTables {
  1150.     my %tables = ( $MySQLaccess::ACCESS_U => $MySQLaccess::ACCESS_U_TMP,
  1151.                    $MySQLaccess::ACCESS_H => $MySQLaccess::ACCESS_H_TMP,
  1152.                    $MySQLaccess::ACCESS_D => $MySQLaccess::ACCESS_D_TMP,
  1153.                  ); 
  1154.     my $tbl;
  1155.     my $query;
  1156.     my $delim;
  1157.     my $skip;
  1158.     my $create;
  1159.     print STDERR "CommitGrantTables()n";
  1160.     MySQLaccess::Debug::Print(1,"CommitGrantTables():");
  1161.     
  1162.     ## Make backup of original grant-tables
  1163.     MySQLaccess::Debug::Print(2,"Making backup of original grant-tables...");
  1164.     BackupGrantTables();
  1165.     ## Copy data from temporay tables to grant-tables
  1166.     foreach $tbl (keys(%tables)) {
  1167.        print STDERR "$tbl -> $tables{$tbl}n";
  1168.        MySQLaccess::Debug::Print(2,"Loading data $tables{$tbl} -> $tbl.");
  1169.        return $nerror if ($nerror=CopyTable($tables{$tbl},$tbl));
  1170.     }
  1171.     return 0;
  1172. }
  1173. # ===========================================================
  1174. # sub Show_Fields($table): 
  1175. #  return (a reference to) a hash which holds the names
  1176. #  of all relevant grant-fields, with their index in the record,
  1177. #  and (a reference to) an array which holds the fieldnames.
  1178. # ===========================================================
  1179. sub Show_Fields {
  1180.     my ($table) = @_;
  1181.     my %skip = ('host' => [0,1]
  1182.                ,'user' => [0,1,2]
  1183.                ,'db'   => [0,1,2]
  1184.                );
  1185.     my %Struct = ();
  1186.     my @Struct = ();
  1187.     my $query = "show fields from $table;select 'ok';n";
  1188.     my $i=0;
  1189.     my $line;
  1190. #print STDERR $query;
  1191.     MySQLaccess::Debug::Print(1,"Show_Fields($table):");
  1192.     MySQLaccess::Debug::Print(2,"SQL: $query");
  1193.     print MYSQL_Q "$query";
  1194.     my $skip = <MYSQL_A>;  #skip header
  1195.     while (($line=<MYSQL_A>) ne "okn")
  1196.     {
  1197. #print STDERR ">",$line;
  1198. chop($line);
  1199. MySQLaccess::Debug::Print(2," $table>: $line");
  1200. my ($field,$type,$null,$key,$default,$extra) = split(' ',$line);
  1201.         $field = ucfirst($field); 
  1202. MySQLaccess::Debug::Print(3, " <split: $field - $type - $null - $key - $default - $extra");
  1203. if (! grep(/$i/,@{$skip{$table}}) ){
  1204.    $Struct{$field} = $i; #hash
  1205.    push(@Struct,$field); #array
  1206.    MySQLaccess::Debug::Print(3," ==> added column[$i]: $field ($Struct{$field})");
  1207.         else {
  1208.            MySQLaccess::Debug::Print(3," ==> skipped column[$i], value=[$field]");
  1209.         }
  1210. $i++;
  1211.     }
  1212.     $skip=<MYSQL_A>;  # Get ok row (found already ok header)
  1213.     MySQLaccess::Debug::Print(2, "Array:");
  1214.     foreach $field (@Struct) { MySQLaccess::Debug::Print(2,"+ $field"); }
  1215.     MySQLaccess::Debug::Print(2,"Hash:");
  1216.     foreach $field (keys(%Struct)) { MySQLaccess::Debug::Print(2,"+ $field -> $Struct{$field}"); }
  1217.     return  (%Struct,@Struct); 
  1218. }
  1219. # ===========================================================
  1220. # sub Show_Tables(): 
  1221. #  return (a reference to) an array which holds all 
  1222. #  known tables.
  1223. # ===========================================================
  1224. sub Show_Tables {
  1225.     my @Tables = ();
  1226.     my $query = "show tables;select 'ok';n";
  1227.     my $i=0;
  1228.     my $line;
  1229.     MySQLaccess::Debug::Print(1,"Show_Tables():");
  1230.     MySQLaccess::Debug::Print(2,"SQL: $query");
  1231.     print MYSQL_Q "$query";
  1232.     my $skip = <MYSQL_A>;  #skip header
  1233.     while (($line=<MYSQL_A>) ne "okn")
  1234.     {
  1235. chop($line);
  1236. push(@Tables,$line); #array
  1237. MySQLaccess::Debug::Print(3," ==> added table: $line");
  1238.     }
  1239.     $skip=<MYSQL_A>;  # Get ok row (found already ok header)
  1240.     MySQLaccess::Debug::Print(2, "Array:");
  1241.     foreach $tbl (@Tables) { MySQLaccess::Debug::Print(2,"+ $tbl"); }
  1242.     return @Tables; 
  1243. }
  1244. # ======================================
  1245. # sub Validate_Password($passwd,$host,$user,$encpw)
  1246. #  Validate the given password 
  1247. #  for user '$user' 
  1248. #  connecting from host '$host'
  1249. # ======================================
  1250. sub Validate_Password {
  1251.     my ($password,$host,$user,$encpw) = @_;
  1252.     my $valid=0;
  1253.     MySQLaccess::Debug::Print(1,"Validate_Password($password,$host,$user,$encpw)");
  1254.     my $sql = "select host,user,password from user having "
  1255.              ."host='$host' and user='$user' and password='$encpw' "
  1256.              ."and password=PASSWORD('$password');n";
  1257.     $sql .= "select 'ok';n";
  1258.     MySQLaccess::Debug::Print(2,"SQL = $sql");
  1259.     print MYSQL_Q "$sql";
  1260.     
  1261.     # if password is valid, at least 1 row returns before we read 'ok'
  1262.     while ( ($line=<MYSQL_A>) ne "okn") {
  1263.       MySQLaccess::Debug::Print(2," A> $line");
  1264.       $valid = defined($line); 
  1265.     }
  1266.     my $skip = <MYSQL_A>; # read 'ok'
  1267.     return $valid;
  1268. }
  1269. # ==========================================================
  1270. # sub Sort_fields: (rewritten by psmith)
  1271. #  Build the query for an ordered list of entries
  1272. # ==========================================================
  1273. sub Sort_fields {
  1274.   my ($start, $end, $sofar, $this, @rest) = (@_);
  1275.   my @where = ("((FIELD not like '\%') AND (FIELD <> ''))",
  1276.                "((FIELD like '%\%%') OR (FIELD like '%\_%'))",
  1277.                "(FIELD = '')");
  1278.   my $res = '';
  1279.   $this or return ("$start $sofar $end");
  1280.   $sofar .= ' AND ' if $sofar;
  1281.   foreach $w (@where) {
  1282.     my $f = $w;
  1283.     $f =~ s/FIELD/$this/g;
  1284.     $res .= Sort_fields($start, $end, "$sofar$f", @rest);
  1285.   }
  1286.   return ($res);
  1287. }
  1288. # ===========================================================
  1289. # sub Sort_table: (rewritten by psmith)
  1290. #  return all entries in the given table,
  1291. #  in an ordered fashion
  1292. # ===========================================================
  1293. sub Sort_table {
  1294.     my ($tbl, @order) = @_;
  1295.     my @res=();
  1296.     # as long as there's no full where clause (Distrib 3.20)...
  1297.     # use having :-(
  1298.     # NOTE: this clause WILL NOT work on 3.21, because of the
  1299.     # order of 'ORDER BY' and 'HAVING'
  1300.     my $start = "SELECT *,UCASE(host) as ucase_host FROM $tbl ";
  1301.     $start   .= 'ORDER BY ' . join(',', @order) ." HAVING ";
  1302.     my $end   = ";n";
  1303.     # server version 3.21 has a full where clause :-)
  1304.     if ($MySQLaccess::Host::SERVER >= '3.21') {
  1305.     # print "+++USING FULL WHERE CLAUSE+++n";
  1306.        $start = "SELECT *,UCASE(host) as ucase_host FROM $tbl WHERE ";
  1307.        $end = ' ORDER BY ' . join(',', @order) . ";n";
  1308.     }
  1309.     MySQLaccess::Debug::Print(1,"Sort_table():");
  1310.     MySQLaccess::Debug::Print(2,"Sorting table $tbl by `@order'");
  1311.     my $tmp;
  1312.     foreach $tmp (@order)
  1313.     {
  1314.       $tmp="UCASE(host)" if ($tmp eq "ucase_host");
  1315.     }
  1316.     my $query  = Sort_fields($start, $end, '', @order);
  1317.     $query    .= "select 'ok';n";
  1318.     MySQLaccess::Debug::Print(2,"Query: $query");
  1319.     print MYSQL_Q "$queryn";
  1320.     my $delim = <MYSQL_A>; # read header
  1321.     MySQLaccess::Debug::Print(3," A> $delim");
  1322.     if ($delim ne "okn") {
  1323.        if ($delim =~ /^ERROR/) {
  1324.        push(@MySQLaccess::Grant::Error,'use_old_server');
  1325.        MySQLaccess::Report::Print_Error_Messages() ;
  1326.        exit 1;
  1327.        }
  1328.        while (($line=<MYSQL_A>) ne "okn")
  1329.        {
  1330.            MySQLaccess::Debug::Print(3," A> $line");
  1331.            push(@res,$line);
  1332.        }
  1333.     }
  1334.     my $skip = <MYSQL_A>; # skip result 'ok'
  1335.     # remove columnheaders from output
  1336.     @res = grep(!/^Q$delimE$/, @res);
  1337.     # remove trailing n from each returned record
  1338.     chomp(@res); 
  1339.     # each record has 1 field to much : ucase_host
  1340.     @res = grep { /(.*)t.*$/; $_ = $1; } @res;
  1341.     MySQLaccess::Debug::Print(2,"Result of sorted table $tbl:");
  1342.     foreach $line (@res) { MySQLaccess::Debug::Print(2," >>$line"); }
  1343.     return @res;
  1344. }
  1345. # ===========================================================
  1346. # sub Get_All_db(template): 
  1347. #  return all db the grant-tables are working on,
  1348. #  which conform to the template
  1349. # ===========================================================
  1350. sub Get_All_dbs {
  1351.    my ($template,$tmp) = @_;
  1352.    my @db=();
  1353.    my $aref;
  1354.    # working with  temporary tables or production tables
  1355.    if (defined($tmp) and $tmp) {
  1356.       $aref = @MySQLaccess::Grant::sorted_db_tmp_table ;
  1357.    }
  1358.    else {
  1359.       $aref = @MySQLaccess::Grant::sorted_db_table;
  1360.    }
  1361.    MySQLaccess::Debug::Print(1," template=[$template]");
  1362.    # get all db for which access-rights can be calculated,
  1363.    # which conform to the template.
  1364.    # !! these db's don't have to exist yet, so it's not
  1365.    #    enough to look which db already exist on the system
  1366.    $reg_expr = $template;
  1367.    if ($template =~ /[*?]/) {
  1368.       $reg_expr =~ tr/*?/%_/;
  1369.       #$reg_expr = MySQLaccess::Wildcards::Wild2Reg($template);
  1370.    }
  1371.    $reg_expr = MySQLaccess::Wildcards::SQL2Reg("$reg_expr");
  1372.    if ( ! ($template =~ /[*?%_]/) ) {
  1373.       push(@db,$template);
  1374.       return @db;
  1375.    }
  1376.    MySQLaccess::Debug::Print(2,"#Reading db-table...");
  1377.    foreach $record (@{$aref}) { #MySQLaccess::Grant::sorted_db_table) {
  1378.     my @record=split(/t/,$record);
  1379.     my $db = $record[1];
  1380.     MySQLaccess::Debug::Print(2,"> $db ");
  1381.     if ( (!grep(/$db/i,@db)) and ($db =~/$reg_expr/i) ) {
  1382.        push(@db,$db);
  1383.        MySQLaccess::Debug::Print(2,"added");
  1384.     } 
  1385.     else {
  1386.        MySQLaccess::Debug::Print(2,"skipped");
  1387.     }
  1388.    }
  1389.    # if no rule is found for a certain db in the db-table,
  1390.    # the rights of the user are used, so we should inform
  1391.    # the user for
  1392.    if (!grep(/^%$/,@db)) { push(@db,"$MySQLaccess::NEW_DB"); }
  1393.    return @db;
  1394. }
  1395. # ===========================================================
  1396. # sub Get_All_users(template): 
  1397. #  return all users the grant-tables are working on,
  1398. #  which conform to the template
  1399. # ===========================================================
  1400. sub Get_All_users {
  1401.    ($template,$tmp) = @_; # nog verder uitwerken!!!
  1402.    my @user=();
  1403.    my $aref;
  1404.    # working with  temporary tables or production tables
  1405.    if (defined($tmp) and $tmp) {
  1406.       $aref = @MySQLaccess::Grant::sorted_user_tmp_table ;
  1407.    }
  1408.    else {
  1409.       $aref = @MySQLaccess::Grant::sorted_user_table;
  1410.    }
  1411.    MySQLaccess::Debug::Print(1,"Debug Get_All_users:");
  1412.    # get all db for which access-rights can be calculated.
  1413.    # !! these db's don't have to exist yet, so it's not
  1414.    #    enough to look which db already exist on the system
  1415.    $reg_expr = $template;
  1416.    if ($template =~ /[*?]/) {
  1417.       $reg_expr =~ tr/*?/%_/;
  1418.       #$reg_expr = MySQLaccess::Wildcards::Wild2Reg($template);
  1419.    }
  1420.    $reg_expr = MySQLaccess::Wildcards::SQL2Reg("$reg_expr");
  1421.    if ( ! ($template =~ /[*?%_]/) ) {
  1422.       push(@user,$template);
  1423.       return @user;
  1424.    }
  1425.    MySQLaccess::Debug::Print(2,"#Reading user-table...");
  1426.    foreach $record (@{$aref}) { #MySQLaccess::Grant::sorted_user_table) {
  1427.     my @record=split(/t/,$record);
  1428.     my $user = $record[1];
  1429.     MySQLaccess::Debug::Print(2,"> $user ");
  1430.     if ( (!grep(/$user/,@user)) and ($user=~/$reg_expr/)) {
  1431.        push(@user,$user);
  1432.        MySQLaccess::Debug::Print(2, "added");
  1433.     } 
  1434.     else {
  1435.        MySQLaccess::Debug::Print(2, "skipped");
  1436.     }
  1437.    }
  1438.    # Any user means also:
  1439.    # - the 'empty' user, ie without supplying a username
  1440.    # - any user still to be defined/created
  1441.    #push(@user,'');               #without_suplying_a_username
  1442.    push(@user,"$MySQLaccess::NEW_USER");
  1443.    #push(@Warnings,'minimum_priv');
  1444.    return @user;
  1445. }
  1446. # ===========================================================
  1447. # sub Get_All_hosts(template): 
  1448. #  return all hosts the grant-tables are working on,
  1449. #  which conform to the template
  1450. # ===========================================================
  1451. sub Get_All_hosts {
  1452.    my ($template,$tmp) = @_;
  1453.    my @host=();
  1454.    my $aref;
  1455.    my $aref1;
  1456.    # working with  temporary tables or production tables
  1457.    if (defined($tmp) and $tmp) {
  1458.       $aref = @MySQLaccess::Grant::sorted_host_tmp_table ;
  1459.       $aref1= @MySQLaccess::Grant::sorted_db_tmp_table ;
  1460.    }
  1461.    else {
  1462.       $aref = @MySQLaccess::Grant::sorted_host_table;
  1463.       $aref1= @MySQLaccess::Grant::sorted_db_table ;
  1464.    }
  1465.    MySQLaccess::Debug::Print(1, "Debug Get_All_hosts:");
  1466.    # get all db for which access-rights can be calculated.
  1467.    # !! these db's don't have to exist yet, so it's not
  1468.    #    enough to look which db already exist on the system
  1469.    $reg_expr = $template;
  1470.    if ($template =~ /[*?]/) {
  1471.       $reg_expr =~ tr/*?/%_/;
  1472.       #$reg_expr = MySQLaccess::Wildcards::Wild2Reg($template);
  1473.    }
  1474.    $reg_expr = MySQLaccess::Wildcards::SQL2Reg("$reg_expr");
  1475.    if ( ! ($template =~ /[*?%_]/) ) {
  1476.       push(@host,$template);
  1477.       return @host;
  1478.    }
  1479.    MySQLaccess::Debug::Print(1, "#Reading db-table...");
  1480.    foreach $record (@{$aref1}) { #MySQLaccess::Grant::sorted_db_table) {
  1481.     my @record=split(/t/,$record);
  1482.     my $host = $record[0];
  1483.     MySQLaccess::Debug::Print(2, "> $host ");
  1484.     if (! grep(/$host/i,@host)) {
  1485.        push(@host,$host);
  1486.        MySQLaccess::Debug::Print(2, "added");
  1487.     } 
  1488.     else {
  1489.        MySQLaccess::Debug::Print(2, "skipped");
  1490.     }
  1491.    }
  1492.    MySQLaccess::Debug::Print(1, "#Reading host-table...");
  1493.    foreach $record (@{$aref}) {
  1494.     my @record=split(/t/,$record);
  1495.     my $host = $record[0];
  1496.     MySQLaccess::Debug::Print(2, "> $host ");
  1497.     if ( (!grep(/$host/,@host)) and ($host=~/$reg_expr/)) {
  1498.        push(@host,$host);
  1499.        MySQLaccess::Debug::Print(2, "added");
  1500.     } 
  1501.     else {
  1502.        MySQLaccess::Debug::Print(2, "skipped");
  1503.     }
  1504.    }
  1505.    # DOUBT:
  1506.    #print "#Reading user-table...n" if ($DEBUG>1);
  1507.    #foreach $record (@MySQLaccess::Grant::sorted_user_table) {
  1508.    # my @record=split(/t/,$record);
  1509.    # my $host = $record[0];
  1510.    # print "> $host " if ($DEBUG>2);
  1511.    # if ( (!grep(/$host/,@host)) and ($host=~/$reg_expr/)) {
  1512.    #    push(@host,$host);
  1513.    #    print "addedn" if ($DEBUG>2);
  1514.    # } 
  1515.    # else {
  1516.    #    print "skippedn" if ($DEBUG>2);
  1517.    # }
  1518.    #}
  1519.    # Any host also means:
  1520.    # - any host still to be defined/created
  1521.    #push(@host,"any_other_host");
  1522.    @host = sort(@host);
  1523.    return @host;
  1524. }
  1525. ##########################################################################
  1526. package MySQLaccess::Grant;
  1527. ##############
  1528. BEGIN {
  1529.     $DEBUG     = 0;
  1530.     $DEBUG     = $MySQLaccess::DEBUG unless ($DEBUG);
  1531. }
  1532. # ===========================================================
  1533. # sub Diff_Privileges()
  1534. #  Calculate diff between temporary and original grant-tables
  1535. # ===========================================================
  1536. sub Diff_Privileges {
  1537.    my @before=();
  1538.    my @after =();
  1539.    my @diffs =();
  1540.    # -----------------------------
  1541.    # Build list of users,dbs,hosts
  1542.    # to process...
  1543.    my @all_dbs   = @{MySQLaccess::DB::Get_All_dbs('*')};
  1544.    my @all_users = @{MySQLaccess::DB::Get_All_users('*')};
  1545.    my @all_hosts = @{MySQLaccess::DB::Get_All_hosts('*')};
  1546.    #if EDIT-mode
  1547.    my @all_dbs_tmp   = @{MySQLaccess::DB::Get_All_dbs('*','tmp')};
  1548.    my @all_users_tmp = @{MySQLaccess::DB::Get_All_users('*','tmp')};
  1549.    my @all_hosts_tmp = @{MySQLaccess::DB::Get_All_hosts('*','tmp')};
  1550.    my %Access;
  1551.    # ------------------------------------
  1552.    # Build list of priv. for grant-tables
  1553.    foreach $host (@all_hosts) {
  1554.      foreach $user (@all_users) {
  1555.        foreach $db (@all_dbs) {
  1556.          MySQLaccess::Grant::Initialize();
  1557.          %Access = MySQLaccess::Grant::Get_Access_Rights($host,$user,$db);
  1558.          push(@before,MySQLaccess::Report::Raw_Report($host,$user,$db,%Access));
  1559.        }
  1560.      }
  1561.    }
  1562.    # ----------------------------------
  1563.    # Build list of priv. for tmp-tables
  1564.    foreach $host (@all_hosts_tmp) {
  1565.      foreach $user (@all_users_tmp) {
  1566.        foreach $db (@all_dbs_tmp) {
  1567.          MySQLaccess::Grant::Initialize('tmp');
  1568.          %Access = MySQLaccess::Grant::Get_Access_Rights($host,$user,$db,'tmp');
  1569.          push(@after,MySQLaccess::Report::Raw_Report($host,$user,$db,%Access));
  1570.        }
  1571.      }
  1572.    }
  1573.    # ----------------------------------
  1574.    # Write results to temp-file to make
  1575.    # DIFF
  1576.    @before = sort(@before);
  1577.    @after  = sort(@after);
  1578.    $before = "$MySQLaccess::TMP_PATH/$MySQLaccess::script.before.$$";
  1579.    $after  = "$MySQLaccess::TMP_PATH/$MySQLaccess::script.after.$$";
  1580.    #$after = "/tmp/t0";
  1581.    open(BEFORE,"> $before") ||
  1582.     push(@MySQLaccess::Report::Errors,"Can't open temporary file $before for writing");
  1583.    open(AFTER,"> $after") ||
  1584.     push(@MySQLaccess::Report::Errors,"Can't open temporary file $after for writing");
  1585.    print BEFORE join("n",@before);
  1586.    print AFTER  join("n",@after);
  1587.    close(BEFORE);
  1588.    close(AFTER);
  1589.    # ----------------------------------
  1590.    # compute difference
  1591.    my $cmd="$MySQLaccess::DIFF $before $after |";
  1592.    open(DIFF,"$cmd");
  1593.    @diffs = <DIFF>;
  1594.    @diffs = grep(/[<>]/,@diffs);
  1595.    chomp(@diffs);
  1596.    close(DIFF);
  1597.    # ----------------------------------
  1598.    # cleanup temp. files
  1599.    unlink(BEFORE);
  1600.    unlink(AFTER);
  1601.    return @diffs;
  1602. }
  1603. # ===========================================================
  1604. # sub Initialize()
  1605. #
  1606. # ===========================================================
  1607. sub Initialize {
  1608.     %MySQLaccess::Grant::Access       = %{Default_Access_Rights()};
  1609.     @MySQLaccess::Grant::Errors       = ();
  1610.     @MySQLaccess::Grant::Warnings     = ();
  1611.     @MySQLaccess::Grant::Notes        = ();
  1612.     # -----
  1613.     # rules
  1614.     $MySQLaccess::Grant::Rules{'user'} = 'no_rule_found';
  1615.     $MySQLaccess::Grant::Rules{'db'}   = 'no_rule_found';
  1616.     $MySQLaccess::Grant::Rules{'host'} = 'no_equiv_host';
  1617.     $MySQLaccess::Grant::full_access   = 1;
  1618.     $MySQLaccess::Grant::process_host_table = 0;
  1619.     return 1;
  1620. }
  1621. # ===========================================================
  1622. # sub ReadTables()
  1623. #  
  1624. # ===========================================================
  1625. sub ReadTables {
  1626.     my ($tmp) = @_;
  1627.     my ($HOST,$DB,$USER);
  1628.     my @tables;
  1629.     # build list of available tables
  1630.     @tables = MySQLaccess::DB::Show_Tables();
  1631.     # reading production grant-tables or temporary tables?
  1632.     $tmp = (defined($tmp) and $tmp) ? 1 : 0;
  1633.     if ($tmp) { #reading temporary tables
  1634.        $HOST=$MySQLaccess::ACCESS_H_TMP;
  1635.        $DB  =$MySQLaccess::ACCESS_D_TMP;
  1636.        $USER=$MySQLaccess::ACCESS_U_TMP;
  1637.        # ----------------------------
  1638.        # do tables exist?
  1639.        if (!grep(/$HOST/,@tables)) { MySQLaccess::DB::CreateTable($HOST); }
  1640.        if (!grep(/$USER/,@tables)) { MySQLaccess::DB::CreateTable($USER); }
  1641.        if (!grep(/$DB/,@tables))   { MySQLaccess::DB::CreateTable($DB); }
  1642.        MySQLaccess::Debug::Print(1,"Finding fields in tmp-ACL files:");
  1643.        # -----------------------------
  1644.        # Get record-layout 
  1645.        my ($h1,$h2) = MySQLaccess::DB::Show_Fields($HOST);
  1646.        my ($d1,$d2) = MySQLaccess::DB::Show_Fields($DB);
  1647.        my ($u1,$u2) = MySQLaccess::DB::Show_Fields($USER);
  1648.        %MySQLaccess::Grant::H_tmp = %{$h1}; @MySQLaccess::Grant::H_tmp = @{$h2};
  1649.        %MySQLaccess::Grant::D_tmp = %{$d1}; @MySQLaccess::Grant::D_tmp = @{$d2};
  1650.        %MySQLaccess::Grant::U_tmp = %{$u1}; @MySQLaccess::Grant::U_tmp = @{$u2};
  1651. #       @MySQLaccess::Grant::Privileges_tmp=@{Make_Privlist()};
  1652. #
  1653.        MySQLaccess::Debug::Print(1, "Reading sorted temp-tables:");
  1654.        @MySQLaccess::Grant::sorted_db_tmp_table  = MySQLaccess::DB::Sort_table($DB, 'ucase_host', 'user', 'db');
  1655.        @MySQLaccess::Grant::sorted_host_tmp_table= MySQLaccess::DB::Sort_table($HOST, 'ucase_host', 'db');
  1656.        @MySQLaccess::Grant::sorted_user_tmp_table= defined($MySQLaccess::Param{'password'}) ?
  1657.                            MySQLaccess::DB::Sort_table($USER, 'ucase_host', 'user', 'password'):
  1658.                            MySQLaccess::DB::Sort_table($USER, 'ucase_host', 'user');
  1659.     }
  1660.     else {      #reading production grant-tables
  1661.        $HOST=$MySQLaccess::ACCESS_H;
  1662.        $DB  =$MySQLaccess::ACCESS_D;
  1663.        $USER=$MySQLaccess::ACCESS_U;
  1664.        MySQLaccess::Debug::Print(1,"Finding fields in ACL files:");
  1665.        # -----------------------------
  1666.        # Get record-layout 
  1667.        my ($h1,$h2) = MySQLaccess::DB::Show_Fields($HOST);
  1668.        my ($d1,$d2) = MySQLaccess::DB::Show_Fields($DB);
  1669.        my ($u1,$u2) = MySQLaccess::DB::Show_Fields($USER);
  1670.        %MySQLaccess::Grant::H = %{$h1}; @MySQLaccess::Grant::H = @{$h2};
  1671.        %MySQLaccess::Grant::D = %{$d1}; @MySQLaccess::Grant::D = @{$d2};
  1672.        %MySQLaccess::Grant::U = %{$u1}; @MySQLaccess::Grant::U = @{$u2};
  1673.        @MySQLaccess::Grant::Privileges=@{Make_Privlist()};
  1674.        MySQLaccess::Debug::Print(1, "Reading sorted tables:");
  1675.        @MySQLaccess::Grant::sorted_db_table  = MySQLaccess::DB::Sort_table($DB, 'ucase_host', 'user', 'db');
  1676.        @MySQLaccess::Grant::sorted_host_table= MySQLaccess::DB::Sort_table($HOST, 'ucase_host', 'db');
  1677.        @MySQLaccess::Grant::sorted_user_table= defined($MySQLaccess::Param{'password'}) ?
  1678.                            MySQLaccess::DB::Sort_table($USER, 'ucase_host', 'user', 'password'):
  1679.                            MySQLaccess::DB::Sort_table($USER, 'ucase_host', 'user');
  1680.     }
  1681.     return 0;
  1682. }
  1683. # ===========================================================
  1684. # sub Get_Access_Rights(host,user,db)
  1685. #  report the access_rights for the tuple ($host,$user,$db).
  1686. # ===========================================================
  1687. sub Get_Access_Rights {
  1688.   local ($host,$user,$db,$tmp) = @_;
  1689.    my $aref_user;
  1690.    my $aref_host;
  1691.    my $aref_db;
  1692.    # working with  temporary tables or production tables
  1693.    if (defined($tmp) and $tmp) {
  1694.       $aref_user = @MySQLaccess::Grant::sorted_user_tmp_table;
  1695.       $aref_host = @MySQLaccess::Grant::sorted_host_tmp_table;
  1696.       $aref_db   = @MySQLaccess::Grant::sorted_db_tmp_table;   
  1697.    }
  1698.    else {
  1699.       $aref_user = @MySQLaccess::Grant::sorted_user_table;
  1700.       $aref_host = @MySQLaccess::Grant::sorted_host_table;
  1701.       $aref_db   = @MySQLaccess::Grant::sorted_db_table; 
  1702.    }
  1703.   my ($refrecord,$refgrant);
  1704.   my ($_host_,$_user_,$encpw_);
  1705.   my %_Access_;
  1706.   MySQLaccess::Debug::Print(1, "for ($host,$user,$db):");  
  1707.   # ******************************************************************************
  1708.   # Create default access-rights
  1709.   #   default access-rights are no access at all!!
  1710.   # ******************************************************************************
  1711.   # get hostname for IP-address
  1712.   # get IP-address for hostname
  1713.   local $host_name = MySQLaccess::Host::IP2Name($host);
  1714.   local $host_ip   = MySQLaccess::Host::Name2IP($host);
  1715.   MySQLaccess::Debug::Print(3,"host=$host, hostname=$host_name, host-ip =$host_ip");
  1716.   MySQLaccess::Debug::Print(3,"user=$user");
  1717.   MySQLaccess::Debug::Print(3,"db  =$db");
  1718.   # ***********************************************************************
  1719.   # retrieve information on USER
  1720.   #  check all records in mysql::user for matches with the tuple (host,user)
  1721.   # ***********************************************************************
  1722.   #    4.OR (add) the privileges for the user from the "user" table.
  1723.   #     (add all privileges which is "Y" in "user")
  1724.   ($refrecord,$refgrant)    = Get_grant_from_user($host,$user,$aref_user);
  1725.   ($_host_,$_user_,$encpw_) = @{$refrecord};
  1726.   %_access_                 = %{$refgrant};
  1727.   foreach $field (keys(%U)) { ##only priv. set in user-table
  1728.     $MySQLaccess::Grant::Access{$field} = ($MySQLaccess::Grant::Access{$field} or $_access_{$field});
  1729.   }
  1730.   if ($_user_ eq $MySQLaccess::NEW_USER) { 
  1731.      push(@Warnings,'minimum_priv');
  1732.   }
  1733.   if ($_user_ ne $user) {
  1734.      $user=$_user_;
  1735.      push(@Warnings,'anonymous_access');
  1736.   }
  1737.   # *******************************************************
  1738.   #  Validate password if this has been asked to do
  1739.   # *******************************************************
  1740.   if (defined($password)) {
  1741.      $valid = Validate_Password($password,$_host_,$_user_,$_encpw_,$aref_user);
  1742.      if (!$valid) { push(@Errors,'invalid_password'); }
  1743.      else         { push(@Notes,'valid_password'); }
  1744.   }
  1745.   # ******************************************************************************
  1746.   # retrieve information on DB
  1747.   #  check all records in mysql::db for matches with the triple (host,db,user)
  1748.   #  first match is used.
  1749.   # ******************************************************************************
  1750.   #    2.Get grant for user from the "db" table.
  1751.   ($refrecord,$refgrant)=Get_grant_from_db($host,$db,$user,$aref_db); #set process_host_table
  1752.   ($_host_,$_user_,$encpw_) = @{$refrecord};
  1753.   %_access_                 = %{$refgrant};
  1754.   foreach $field (keys(%D)) { ##only priv. set in db-table
  1755.     $MySQLaccess::Grant::Access{$field} = ($MySQLaccess::Grant::Access{$field} or $_access_{$field});
  1756.   }
  1757.   # ***********************************************************************
  1758.   # retrieve information on HOST
  1759.   #  check all records in mysql::host for matches with the tuple (host,db)
  1760.   #
  1761.   #  ' The host table is mainly to maintain a list of "secure" servers. '
  1762.   # ***********************************************************************
  1763.   #    3.If hostname is "empty" for the found entry, AND the privileges with
  1764.   #      the privileges for the host in "host" table.
  1765.   #      (Remove all which is not "Y" in both)
  1766.   if ($MySQLaccess::Grant::process_host_table) {
  1767.      ($refrecord,$refgrant)=Get_grant_from_host($host,$db,$aref_host);
  1768.      ($_host_,$_user_,$encpw_) = @{$refrecord};
  1769.      %_access_                 = %{$refgrant};
  1770.      foreach $field (keys(%H)) {  ##only priv. set in host-table 
  1771.        $MySQLaccess::Grant::Access{$field} = ($MySQLaccess::Grant::Access{$field} and $_access_{$field});
  1772.      } 
  1773.   }
  1774.   MySQLaccess::Debug::Print(1,"done for ($host,$user,$db)");
  1775.   return %MySQLaccess::Grant::Access;
  1776. }
  1777. # ####################################
  1778. # FINDING THE RIGHT GRANT-RULE
  1779. # ==========================================================
  1780. # sub Get_grant_from_user:
  1781. # ==========================================================
  1782. sub Get_grant_from_user {
  1783.   my ($host,$user,$aref) = @_;
  1784.   MySQLaccess::Debug::Print(1, "");
  1785.   MySQLaccess::Debug::Print(1, "(host=$host,user=$user)");
  1786.   my %Access_user = %{Default_Access_Rights()}; 
  1787.   my $rule_found=0;
  1788.   my @record = ();
  1789.   my $record;
  1790.   foreach $record (@{$aref}) {
  1791.     $MySQLaccess::Grant::full_access=0;
  1792.     MySQLaccess::Debug::Print(3, "Record= $record");
  1793.     @record=split(/t/,$record);
  1794.     # check host and db
  1795.     # with possible wildcards in field
  1796.     # replace mysql-wildcards by reg-wildcards
  1797.     my $host_tpl = MySQLaccess::Wildcards::SQL2Reg($record[0]);
  1798.     my $user_tpl = $record[1]; #user field isn't pattern-matched!!
  1799.     my $passwd   = $record[2];
  1800.     MySQLaccess::Debug::Print(3, "=>host_tpl : read=$record[0] -> converted=$host_tpl");
  1801.     MySQLaccess::Debug::Print(3, "=>user_tpl : read=$record[1] -> $user_tpl");
  1802.     MySQLaccess::Debug::Print(3, "=>password : read=$record[2] -> $passwd");
  1803.     if ( MySQLaccess::Host::MatchTemplate($host,$host_tpl) and
  1804.          MySQLaccess::Wildcards::MatchTemplate($user_tpl,$user)
  1805.        ) 
  1806.     {
  1807.   MySQLaccess::Debug::Print(2, "FOUND!!");
  1808.         if ($passwd eq '') { push(@Warnings,'insecure_user');  }
  1809.         else               { push(@Notes,'password_required'); }
  1810.         foreach $field (keys(%U)) {
  1811.           $Access_user{$field} = $MySQLaccess::Report::Answer{$record[$U{$field}]};
  1812.         }
  1813.         #print "n" if $DEBUG;
  1814.         $MySQLaccess::Grant::Rules{'user'} = $record;
  1815.         $rule_found=1;
  1816.         last;
  1817.     }
  1818.   }
  1819.   # -------------------------------
  1820.   #  setting privileges to user-priv
  1821.   MySQLaccess::Debug::Print(2, "Rights after parsing user-table..:");
  1822.   if (! $rule_found ) {
  1823.      @record=();
  1824.      MySQLaccess::Debug::Print(2, "NO record found in the user-table!!");
  1825.   }
  1826.   else {
  1827.      MySQLaccess::Debug::Print(2, "Selected record=@record");
  1828.      MySQLaccess::Debug::Print(2, "<=?=> $record");
  1829.   }
  1830.  
  1831.   MySQLaccess::Debug::Print(1, "returning @record");
  1832.   return (@record,%Access_user); #matching record in user-table
  1833. }
  1834. # ==========================================================
  1835. # sub Get_grant_from_db:
  1836. # ==========================================================
  1837. sub Get_grant_from_db {
  1838.   my ($host,$db,$user,$aref) = @_;
  1839.   MySQLaccess::Debug::Print(1, "(host=$host,user=$user,db=$db)");
  1840.   my %Access_db    = %{Default_Access_Rights()};
  1841.   my $rule_found=0;
  1842.   foreach $record (@{$aref}) {
  1843.     $full_access=0;
  1844.     MySQLaccess::Debug::Print(2, "Read db: $record");
  1845.     @record=split(/t/,$record);
  1846.     # check host and db
  1847.     # with possible wildcards in field
  1848.     # replace mysql-wildcards by reg-wildcards
  1849.     my $host_tpl = MySQLaccess::Wildcards::SQL2Reg($record[0]);
  1850.     my $db_tpl   = MySQLaccess::Wildcards::SQL2Reg($record[1]);
  1851.     my $user_tpl = $record[2]; #user field isn't pattern matched!!
  1852.     MySQLaccess::Debug::Print(3, "=>host_tpl : read=$record[0] -> converted=$host_tpl");
  1853.     MySQLaccess::Debug::Print(3, "=>db_tpl   : read=$record[1] -> $db_tpl");
  1854.     MySQLaccess::Debug::Print(3, "=>user_tpl : read=$record[2] -> $user_tpl");
  1855.     if ( ( MySQLaccess::Host::Is_localhost($host_tpl)
  1856.            or  MySQLaccess::Wildcards::MatchTemplate($host_tpl,$host_name)
  1857.            or  MySQLaccess::Wildcards::MatchTemplate($host_tpl,$host_ip) )
  1858.          and ( MySQLaccess::Wildcards::MatchTemplate($db_tpl,$db) )
  1859.          and ( MySQLaccess::Wildcards::MatchTemplate($user_tpl,$user) ) ) {
  1860.  
  1861.       $MySQLaccess::Grant::process_host_table = ($record[0] eq '');
  1862.       if ($user_tpl eq '') { push(@Warnings,'public_database'); }
  1863.       foreach $field (keys(%D)) {
  1864.         $Access_db{$field} = $MySQLaccess::Report::Answer{$record[$D{$field}]};
  1865.       }
  1866.       $rule_found=1;
  1867.       $MySQLaccess::Grant::Rules{'db'} = $record;
  1868.       last;
  1869.     }
  1870.   }
  1871.   # -------------------------------
  1872.   #  setting privileges to db-priv
  1873.   MySQLaccess::Debug::Print(2, "Rights after parsing db-table..:");
  1874.   if (! $rule_found ) {
  1875.     MySQLaccess::Debug::Print(2, "NO rule found in db-table => no access granted!!");
  1876.   }
  1877.   return (@record,%Access_db);
  1878. }
  1879. # ==========================================================
  1880. # sub Get_grant_from_host:
  1881. # ==========================================================
  1882. sub Get_grant_from_host {
  1883.   my ($host,$db,$aref) = @_;
  1884.   MySQLaccess::Debug::Print(1, "Get_grant_from_host()");
  1885.   my %Access_host = %{Default_Access_Rights()};
  1886.   # the host-table doesn't have to be processed if the host-field
  1887.   # in the db-table isn't empty
  1888.   if (!$MySQLaccess::Grant::process_host_table) {
  1889.     MySQLaccess::Debug::Print(2, ">> Host-table doesn't have to be processed!!");
  1890.     $MySQLaccess::Grant::Rules{'host'} = 'no_equiv_host';
  1891.     return ([],%Access_host);
  1892.   }
  1893.   my $rule_found=0;
  1894.   my @record = ();
  1895.   foreach $record (@{$aref}) {
  1896.     $full_access=0;
  1897.     MySQLaccess::Debug::Print(2, "host: $record");
  1898.     @record=split(/t/,$record);
  1899.     # check host and db
  1900.     # with possible wildcards in field
  1901.     # replace mysql-wildcards by reg-wildcards
  1902.     my $host_tpl = MySQLaccess::Wildcards::SQL2Reg($record[0]);
  1903.     my $db_tpl   = MySQLaccess::Wildcards::SQL2Reg($record[1]);
  1904.     MySQLaccess::Debug::Print(3, "=>host_tpl : $record[0] -> $host_tpl");
  1905.     MySQLaccess::Debug::Print(3, "=>db_tpl   : $record[1] -> $db_tpl");
  1906.     if ( ( MySQLaccess::Host::Is_localhost($host_tpl)
  1907.            or MySQLaccess::Wildcards::MatchTemplate($host_tpl,$host_name)
  1908.            or MySQLaccess::Wildcards::MatchTemplate($host_tpl,$host_ip) )
  1909.          and ( MySQLaccess::Wildcards::MatchTemplate($db_tpl,$db) ) ) {
  1910.       $MySQLaccess::Grant::Rules{'host'} = $record;
  1911.       $rule_found=1;
  1912.       foreach $field (keys(%H)) {
  1913.         $Access_host{$field} = $MySQLaccess::Report::Answer{$record[$H{$field}]};
  1914.       }
  1915.       last;
  1916.     }
  1917.   }
  1918.   # -------------------------------
  1919.   #  setting privileges to host-priv
  1920.   MySQLaccess::Debug::Print(2, "Rights after parsing host-table..:");
  1921.   if (! $rule_found ) {
  1922.      @record=();
  1923.      MySQLaccess::Debug::Print(2, "NO restrictions found in the host-table!!");
  1924.   }
  1925.   # --------------------------------
  1926.   # debugging access-rights in db 
  1927.   return (@record,%Access_host); #matching record in host-table
  1928. }
  1929. # ===========================================================
  1930. # sub Default_Access_Rights():
  1931. #  return (a reference to) a hash which holds all default
  1932. #  priviliges currently defined in the grant-tables.
  1933. # ===========================================================
  1934. sub Default_Access_Rights {
  1935.     my %right = ();
  1936.     MySQLaccess::Debug::Print(2, "Debug Default_Access_Rights():");
  1937.     # add entry for all fields in the HOST-table
  1938.     foreach $field (keys(%MySQLaccess::Grant::H)) {
  1939. $right{$field}='0' unless (defined($right{$field}));
  1940.     }
  1941.     # add entry for all fields in the DB-table
  1942.     foreach $field (keys(%MySQLaccess::Grant::D)) {
  1943. $right{$field}='0' unless (defined($right{$field}));
  1944.     }
  1945.     # add entry for all fields in the USER-table
  1946.     foreach $field (keys(%MySQLaccess::Grant::U)) {
  1947. $right{$field}='0' unless (defined($right{$field}));
  1948.     }
  1949.     # --------------
  1950.     # debugging info
  1951.     foreach $field (keys(%right)) { MySQLaccess::Debug::Print(3, sprintf("> %15s : %1s",$field,$right{$field})); }
  1952.     return %right;
  1953. }
  1954. # ======================================
  1955. # sub Make_Privlist
  1956. #  Make an ordered list of the privileges
  1957. #  that should be reported
  1958. # ======================================
  1959. sub Make_Privlist {
  1960.     # layout:
  1961.     #'select_priv',     'create_priv',
  1962.     #'insert_priv',     'drop_priv',
  1963.     #'update_priv',     'reload_priv',
  1964.     #'delete_priv',     'process_priv',
  1965.     #'file_priv',       'shutdown_priv');
  1966.     my $right;
  1967.     my @privlist=();
  1968.     foreach $right (@U) {
  1969. if (! grep(/$right/,@privlist)) { push(@privlist,$right); }
  1970.     };
  1971.     foreach $right (@D) {
  1972. if (! grep(/$right/,@privlist)) { push(@privlist,$right); }
  1973.     };
  1974.     foreach $right (@H) {
  1975. if (! grep(/$right/,@privlist)) { push(@privlist,$right); }
  1976.     };
  1977. #       print "Privileges:n";
  1978. #       foreach $field (@privlist) { print " > $fieldn"; }
  1979.     return @privlist;
  1980. }
  1981. ########################################################################
  1982. package MySQLaccess::Report;
  1983. use Exporter ();
  1984. @EXPORT = qw(&Print_Header());
  1985. BEGIN {
  1986.     $FORM = $ENV{'SCRIPT_NAME'};
  1987.     $DEBUG     = 0;
  1988.     $DEBUG     = $MySQLaccess::DEBUG unless ($DEBUG);
  1989.     # translation-table for poss. answers
  1990.     %Answer =  ('Y' =>  1 , 'N' =>  0
  1991.                , 1  => 'Y',  0  => 'N'
  1992.                ,'?' => '?', ''  => '?'
  1993.                );
  1994.     $headers   = 0;
  1995.     $separator = 0;
  1996. # ****************************
  1997. # Notes and warnings
  1998. %MESSAGES = ( 
  1999.   'insecure_user' 
  2000.    => "Everybody can access your DB as user `$user' from host `$host'n"
  2001.      ."WITHOUT supplying a password.n"
  2002.      ."Be very careful about it!!"
  2003.  ,'password_required' 
  2004.    => "A password is required for user `$user' :-("
  2005.  ,'invalid_password'
  2006.    => "The password '$password' for user `$user' is invalid :-P"
  2007.  , 'valid_password'
  2008.    => "You supplied the right password for user `$user' :-)"
  2009.  ,'public_database' 
  2010.    => "Any user with the appropriate permissions has access to your DB!n"
  2011.      ."Check your users!"
  2012.  ,'full_access' 
  2013.    => "All grant-tables are empty, which gives full access to ALL users !!"
  2014.  ,'no_rule_found'
  2015.    => "No matching rule"
  2016.  ,'no_equiv_host' 
  2017.    => "Not processed: host-field is not empty in db-table."
  2018.  ,'least_priv'
  2019.    => "If the final priveliges of the user are more then you gave the user,n"
  2020.      ."check the priveliges in the db-table `$db'."
  2021.  ,'minimum_priv'
  2022.    => "The privileges for any new user are AT LEASTn"
  2023.      ."the ones shown in the table above,n"
  2024.      ."since these are the privileges of the db `$db'.n"
  2025.  ,'not_found_mysql'
  2026.    => "The MySQL client program <$MySQLaccess::MYSQL> could not be found.n"
  2027.      ."+ Check your path, orn"
  2028.      ."+ edit the source of this script to point $MYSQL to the mysql client.n"
  2029.  ,'not_found_mysqldump'
  2030.    => "The MySQL dump program <$MySQLaccess::MYSQLDUMP> could not be found.n"
  2031.      ."+ Check your path, orn"
  2032.      ."+ edit the source of this script to point $MYSQLDUMP to the mysqldump program.n"
  2033.  ,'not_found_diff'
  2034.    => "The diff program <$MySQLaccess::DIFF> could not be found.n"
  2035.      ."+ Check your path, orn"
  2036.      ."+ edit the source of this script to point $DIFF to the diff program.n"
  2037.  ,'not_found_tmp'
  2038.    => "The temporary directory <$MySQLaccess::TMP_PATH> could not be found.n"
  2039.      ."+ create this directory (writeable!), orn"
  2040.      ."+ edit the source of this script to point $TMP_PATH to the right directory.n"
  2041.  ,'write_err_tmp'
  2042.    => "The temporary directory <$MySQLaccess::TMP_PATH> is not writable.n"
  2043.      ."+ make this directory writeable!, orn"
  2044.      ."+ edit the source of this script to point $TMP_PATH to another directory.n"
  2045.  ,'Unrecognized_option'
  2046.    => "Sorry,n"
  2047.      ."You are using an old version of the mysql-program,n"
  2048.      ."which does not yet implement a neccessary option.n"
  2049.      ."n"
  2050.      ."You need at least Version 6.2 of the mysql-client,n"
  2051.      ."which was build in MySQL v3.0.18, to use this versionn"
  2052.      ."of `$MySQLaccess::script'."
  2053.  ,'Access_denied'
  2054.    => "Sorry,n"
  2055.      ."An error occured when trying to connect to the databasen"
  2056.      ."with the grant-tables:n"
  2057.      ."* Maybe YOU do not have READ-access to this database?n"
  2058.      ."* If you used the -U option, you may have supplied an invalid username?n"
  2059.      ."  for the superuser?n"
  2060.      ."* If you used the -U option, it may be possible you have to supplyn"
  2061.      ."  a superuser-password to, with the -P option?n"
  2062.      ."* If you used the -P option, you may have supplied an invalid password?n"
  2063.  ,'Dbaccess_denied'
  2064.    => "Sorry,n"
  2065.      ."An error occured when trying to connect to the databasen"
  2066.      ."with the grant-tables. (dbaccess denied)n"
  2067.  ,'Unknown_tmp_table'
  2068.    => "Sorry,n"
  2069.      ."An error occured when trying to work with the temporary tables in the databasen"
  2070.      ."with the grant-tables. (One of the temporary tables does not exist)n"
  2071.  ,'Unknown_table'
  2072.    => "Sorry,n"
  2073.      ."An error occured when trying to work with some tables in the databasen"
  2074.      ."with the grant-tables. (table does not exist)n"
  2075.  ,'use_old_server'
  2076.    => "Sorry,n"
  2077.      ."An error occured when executing an SQL statement.n"
  2078.      ."You might consider altering the use of the parameter `--old_server' when n"
  2079.      ."calling `$MySQLaccess::script'."
  2080.  ,'unknown_error'
  2081.    => "Sorry,n"
  2082.      ."An error occured when trying to connect to the databasen"
  2083.      ."with the grant-tables. (unknown error)n"
  2084.  ,'anonymous_access'
  2085.    => "Accessing the db as an anonymous user.n"
  2086.      ."Your username has no relevancen"
  2087.  ,'user_required'
  2088.    => "You have to supply a userid."
  2089.  ,'db_required'
  2090.    => "You have to supply the name of a database."
  2091.  ,'host_required'
  2092.    => "You have to supply the name of a host."
  2093.  );
  2094. # =====================================
  2095. # sub Print_Header:
  2096. #  print header info
  2097. # =====================================
  2098. sub Print_Header {
  2099.     if ($MySQLaccess::CMD) { #command-line mode
  2100.     print "$MySQLaccess::script Version $MySQLaccess::VERSIONn"
  2101.          ."By RUG-AIV, by Yves Carlier (Yves.Carlier@rug.ac.be)n"
  2102.          ."Changes by Steve Harvey (sgh@vex.net)n"
  2103.          ."This software comes with ABSOLUTELY NO WARRANTY.n";
  2104.     }
  2105.     if ($MySQLaccess::CGI) { #CGI-BIN mode
  2106.     print "content-type: text/htmlnn" 
  2107.        . "<HTML>n"
  2108.          ."<HEAD>n"
  2109.          ."<TITLE>MySQLaccess</TITLE>n"
  2110.          ."</HEAD>n"
  2111.          ."<BODY>n"
  2112.          ."<H1>$MySQLaccess::script Version $MySQLaccess::VERSION</H1>n" 
  2113.          ."<CENTER>n<ADDRESS>n"
  2114.          ."By RUG-AIV, by Yves Carlier (<a href=mailto:Yves.Carlier@rug.ac.be>Yves.Carlier@rug.ac.be</a>)<BR>n"
  2115.          ."Changes by Steve Harvey (<a href=mailto:sgh@vex.net>sgh@vex.net</a>)<BR>n"
  2116.          ."This software comes with ABSOLUTELY NO WARRANTY.<BR>n"
  2117.          ."</ADDRESS>n</CENTER>n"
  2118.          ."<HR>n";
  2119.     Print_Taskbar();
  2120.     print "<HR>n";
  2121.     }
  2122.     return 1;
  2123. }
  2124. # =====================================
  2125. # sub Print_Footer:
  2126. #  print footer info
  2127. # =====================================
  2128. sub Print_Footer {
  2129.     if ($MySQLaccess::CMD) { #command-line mode
  2130.     print "n"
  2131.          ."BUGs can be reported by email to Yves.Carlier@rug.ac.ben";
  2132.     }
  2133.     if ($MySQLaccess::CGI) { #CGI-BIN mode
  2134.     if ($MySQLaccess::Param{'brief'}) {
  2135.     print "</table>n";  #close table in brief-output
  2136.     }
  2137.     print "<HR>n"
  2138.          ."<ADDRESS>n"
  2139.          ."BUGs can be reported by email to <a href=mailto:Yves.Carlier@rug.ac.be>Yves.Carlier@rug.ac.be</a><BR>n"
  2140. #         ."Don't forget to mention the version $VERSION!<BR>n"
  2141.          ."</ADDRESS>n"
  2142.          ."</BODY>n"
  2143.          ."</HTML>n";
  2144.     }
  2145.     return 1;
  2146. }
  2147. # =====================================
  2148. # sub Print_Taskbar:
  2149. #  print taskbar on STDOUT
  2150. # =====================================
  2151. sub Print_Taskbar {
  2152.     print "<CENTER>n"
  2153.          ."[<a href=$FORM?relnotes=on>Release&nbsp;Notes</a>] n"
  2154.          ."[<a href=$FORM?version=on>Version</a>] n"
  2155.          ."[<a href=$FORM?plan=on>Future&nbsp;Plans</a>] n"
  2156.          ."[<a href=$FORM?howto=on>Examples</a>] n"
  2157.          ."[<a href=$FORM?help=on>New check</a>] n"
  2158.          ."[<a href=$FORM?edit=on>Change/edit ACL</a>] n"
  2159.          ."</CENTER>n";
  2160.     return 1;
  2161. }
  2162. # =====================================
  2163. # sub Print_Form:
  2164. #  print CGI-form
  2165. # =====================================
  2166. sub Print_Form {
  2167. print <<EOForm;
  2168. <center>
  2169. <!-- Quering -->
  2170. <FORM method=POST action=$FORM>
  2171. <table border width="100%" >
  2172. <tr>
  2173.   <th>MySQL server</th>
  2174.   <th>User information</th>
  2175.   <th>Reports</th>
  2176.   </tr>
  2177. <tr>
  2178.   <td valign=top>
  2179.   <table>
  2180.   <tr>
  2181.     <td halign=right><b>Host</b><br><font size=-2>(Host on which MySQL-server resides.)</font></td>
  2182.     <td valign=top><INPUT name=rhost type=text size=15 maxlength=15 value="$MySQLaccess::Param{'rhost'}"></td>
  2183.     </tr>
  2184.   <tr>
  2185.     <td halign=right><b>Superuser</b><br><font size=-2>(User which has <font color="Red">read-access</font> to grant-tables.)</font></td>
  2186.     <td valign=top><INPUT name=superuser type=text size=15 maxlength=15 value="$MySQLaccess::Param{'superuser'}"></td>
  2187.     </tr>
  2188.   <tr>
  2189.     <td halign=right><b>Password</b><br><font size=-2>(of Superuser.)</font></td>
  2190.     <td valign=top><INPUT name=spassword type=password size=15 maxlength=15 value="$MySQLaccess::Param{'spassword'}"></td>
  2191.     </tr>
  2192.   </table>
  2193.   </td>
  2194.   <td valign=top>
  2195.   <table>
  2196.   <tr>
  2197.     <td halign=right><b><font color=Red>User</font></b><br><font size=-2>(Userid used to connect to MySQL-database.)</font></td>
  2198.     <td halign=top><INPUT name=user type=text size=15 maxlength=15 value="$MySQLaccess::Param{'user'}"></td>
  2199.     </tr>
  2200.   <tr>
  2201.     <td halign=right><b>Password</b><br><font size=-2>(Password user has to give to get access to MySQL-database.)</font></td>
  2202.     <td valign=top><INPUT name=password type=password size=15 maxlength=15 value="$MySQLaccess::Param{'password'}"></td>
  2203.     </tr>
  2204.   <tr>
  2205.     <td halign=right><b><font color=Red>Database</font></b><br><font size=-2>(Name of MySQL-database user tries to connect to.</font><br><font size=-2>Wildcards <font color="Green">(*,?,%,_)</font> are allowed.)</font></td>
  2206.     <td valign=top><INPUT name=db type=text size=15 maxlength=15 value="$MySQLaccess::Param{'db'}"></td>
  2207.     </tr>
  2208.   <tr>
  2209.     <td halign=right><b>Host</b><br><font size=-2>(Host from where the user is trying to connect to MySQL-database.</font><br><font size=-2>Wildcards <font color="Green">(*,?,%,_)</font> are allowed.)</font></td>
  2210.     <td valign=top><INPUT name=host type=text size=15 maxlength=15 value="$MySQLaccess::Param{'host'}"></td>
  2211.     </tr>
  2212.   </table>
  2213.   </td>
  2214.   <td valign=center>
  2215.   <table cellspacing=5 cellpadding=2 cols=1 height="100%">
  2216.   <tr align=center>
  2217.     <td halign=right><INPUT type=submit name=brief value="Brief"><br>
  2218.                      <INPUT type=submit name=table value="Tabular"></td>
  2219.     </tr>
  2220.   <tr align=center>
  2221.     <td></td>
  2222.     </tr>
  2223.   <tr align=center>
  2224.     <td halign=right><INPUT type=reset value="Clear"></td>
  2225.     </tr>
  2226.   </table>
  2227.   </td>
  2228.   </tr>
  2229. </table>
  2230. </form>
  2231. </BODY>
  2232. </HTML>
  2233. EOForm
  2234.     return 1;
  2235. }
  2236. # =====================================
  2237. # sub Print_Usage:
  2238. #  print some information on STDOUT
  2239. # =====================================
  2240. sub Print_Usage {
  2241.     Print_Error_Messages();
  2242.     if ($MySQLaccess::CMD) { #command-line mode
  2243.         Print_Options();
  2244.     }
  2245.     if ($MySQLaccess::CGI) { #CGI-BIN mode
  2246.         Print_Form();
  2247.     }    
  2248.     return 1;
  2249. }
  2250. # ======================================
  2251. # sub Print_Version:
  2252. # ======================================
  2253. sub Print_Version {
  2254.     if ($MySQLaccess::CMD) {
  2255.        print $MySQLaccess::INFO;
  2256.     }
  2257.     if ($MySQLaccess::CGI) { 
  2258.        print "<PRE>n"; 
  2259.        print $MySQLaccess::INFO;
  2260.        print "</PRE>n"; 
  2261.     }
  2262.     return 1;
  2263. }
  2264. # ======================================
  2265. # sub Print_Relnotes:
  2266. # ======================================
  2267. sub Print_Relnotes {
  2268.     if ($MySQLaccess::CMD) {
  2269.        print $MySQLaccess::RELEASE;
  2270.     }
  2271.     if ($MySQLaccess::CGI) { 
  2272.        print "<PRE>n";
  2273.        print $MySQLaccess::RELEASE;
  2274.        print "</PRE>n"; 
  2275.     }
  2276.     return 1;
  2277. }
  2278. # ======================================
  2279. # sub Print_Plans:
  2280. # ======================================
  2281. sub Print_Plans {
  2282.     if ($MySQLaccess::CMD) {
  2283.        print $MySQLaccess::TODO;
  2284.     }
  2285.     if ($MySQLaccess::CGI) { 
  2286.        print "<PRE>n";
  2287.        print $MySQLaccess::TODO;
  2288.        print "</PRE>n"; 
  2289.     }
  2290.     return 1;
  2291. }
  2292. # ======================================
  2293. # sub Print_HowTo:
  2294. # ======================================
  2295. sub Print_HowTo {
  2296.     if ($MySQLaccess::CMD) {
  2297.        print $MySQLaccess::HOWTO;
  2298.     }
  2299.     if ($MySQLaccess::CGI) { 
  2300.        print "<PRE>n"; 
  2301.        print $MySQLaccess::HOWTO;
  2302.        print "</PRE>n"; 
  2303.     }
  2304.     return 1;
  2305. }
  2306. # ======================================
  2307. # sub Print_Options:
  2308. # ======================================
  2309. sub Print_Options {
  2310.     if ($MySQLaccess::CGI) { print "<PRE>n"; }
  2311.     print $MySQLaccess::OPTIONS;
  2312.     if ($MySQLaccess::CGI) { print "</PRE>n"; }
  2313.     return 1;
  2314. }
  2315. # ======================================
  2316. # sub Print_Error_Access:
  2317. # ======================================
  2318. sub Print_Error_Access {
  2319.     my ($error) = @_;
  2320.     print "n";
  2321.     if ($MySQLaccess::CGI) { print "<font color=Red>n<PRE>n"; }
  2322.     print $MESSAGES{$error};
  2323.     if ($MySQLaccess::CGI) { print "</PRE>n</font>n"; }
  2324.     print "n";
  2325.     return 1;
  2326. }
  2327. # ======================================
  2328. # sub Print_Error_Messages:
  2329. # ======================================
  2330. sub Print_Error_Messages {
  2331. #    my ($error) = @_;
  2332.     print "n";
  2333.     if ($MySQLaccess::CGI) { print "<font color=Red>n<center>n"; }
  2334.     foreach $error (@MySQLaccess::Grant::Error) {
  2335.        print $MESSAGES{$error};
  2336.        print $MySQLaccess::CGI ? "<br>n" : "n";
  2337.     }
  2338.     if ($MySQLaccess::CGI) { print "</center>n</font>n"; }
  2339.     print "n";
  2340.     return 1;
  2341. }
  2342. # ======================================
  2343. # sub Print_Message:
  2344. # ======================================
  2345. sub Print_Message {
  2346.     my ($aref) = @_;
  2347.     my @messages = @{$aref};
  2348.     print "n";
  2349.     if ($MySQLaccess::CGI) { print "<font color=DarkGreen>n<center>n"; }
  2350.     foreach $msg (@messages) {
  2351.        print $msg;
  2352.        print $MySQLaccess::CGI ? "<br>n" : "n";
  2353.     }
  2354.     if ($MySQLaccess::CGI) { print "</center>n</font>n"; }
  2355.     print "n";
  2356.     return 1;
  2357. }
  2358. # ======================================
  2359. # sub Print_Edit:
  2360. # ======================================
  2361. sub Print_Edit {
  2362.     print "n";
  2363.     if (!$MySQLaccess::CGI) { 
  2364.        print "Note: Editing the temporary tables is NOT supported in CMD-line mode!n";
  2365.        return 0;
  2366.     }
  2367.     print "<CENTER>n"
  2368.          ."<form action=$FORM method=GET>n"
  2369.          ."<table width=90% border>n"
  2370.          ."<tr>n"
  2371.          ." <td><input type=checkbox name=copy value=on> Copy grant-rules to temporary tables<br></td>n"
  2372.          ." <td rowspan=5 align=center valign=center><input type=submit value=Go></td>n"
  2373.          ."</tr>n"
  2374.          ."<tr>n"
  2375.          ." <td> Edit temporary tables with external application:<br>"
  2376.          ." <a href="$MySQLaccess::MYSQLADMIN">$MySQLaccess::MYSQLADMIN</a></td>n"
  2377.          ."</tr>n"
  2378.          ."<tr>n"
  2379.          ." <td><input type=checkbox name=preview value=on> Preview changes made in temporary tables</td>n"
  2380.          ."</tr>n"
  2381.          ."<tr>n"
  2382.          ." <td><input type=checkbox name=commit value=on> Make changes permanent</td>n"
  2383.          ."</tr>n"
  2384.          ."<tr>n"
  2385.          ." <td><input type=checkbox name=rollback value=on> Restore previous grand-rules</td>n"
  2386.          ."</tr>n"
  2387.          ."<tr>n"
  2388.          ." <td colspan=2 align=center><font size=-2 color=Red>You need write,delete and drop-privileges to perform the above actions</font></td>n"
  2389.          ."</tr>n"
  2390.          ."</table>n"
  2391.          ."</form>n"
  2392.          ."</CENTER>n";
  2393.     return 1;
  2394. }
  2395. # ======================================
  2396. # sub Print_Access_rights:
  2397. #  print the access-rights on STDOUT
  2398. # ======================================
  2399. sub Print_Access_rights {
  2400.     my ($host,$user,$db,$refhash) = @_;
  2401.     if (defined($MySQLaccess::Param{'brief'})) { 
  2402. #       if ($MySQLaccess::CGI) { print "<PRE>n"; }
  2403.        Matrix_Report($host,$user,$db,$refhash);  
  2404. #       if ($MySQLaccess::CGI) { print "</PRE>n"; }
  2405.     }
  2406.     else { 
  2407.        Tabular_Report($host,$user,$db,$refhash); 
  2408.        $MySQLaccess::Report::separator = $MySQLaccess::CGI ? "<hr>" : "-"x80;
  2409.     }
  2410.     return 1;
  2411. }
  2412. # ======================================
  2413. # sub Print_Diff_ACL:
  2414. #  print the diff. in the grants before and after
  2415. # ======================================
  2416. sub Print_Diff_ACL {
  2417.     my ($aref) = @_;
  2418.     my @diffs = @{$aref};
  2419.     my %block = ( '<' => 'Before',
  2420.                   '>' => 'After',
  2421.                 );
  2422.     my %color = ( '<' => 'Green',
  2423.                   '>' => 'Red',
  2424.                 ); 
  2425.     my $curblock = '';
  2426.     # -----------------------------
  2427.     # create column-headers
  2428.     foreach $field (@MySQLaccess::Grant::Privileges) {
  2429.       push(@headers,substr($field,0,4));
  2430.     }
  2431.     if ($MySQLaccess::CMD) {
  2432.     print "n";
  2433.     print "Differences in access-rights BEFORE and AFTER changes in grant-tablesn";
  2434. #    print "---------------------------------------------------------------------n";
  2435.       my $line1="";
  2436.       my $line2="";
  2437.       $line1 .= sprintf("| %-30s|",'Host,User,DB');
  2438.       $line2 .= sprintf("+-%-30s+",'-' x 30);
  2439.       foreach $header (@headers) {
  2440.         $line1 .= sprintf("%-4s|",$header);
  2441.         $line2 .= sprintf("%s+",'----');
  2442.       }
  2443.       print "$line2n";
  2444.       print "$line1n";
  2445.       print "$line2n";
  2446.       $format = "format STDOUT = n"
  2447.               . "^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< " . " @|||" x 10 ."n"
  2448.               . '$host_user_db,@priv' . "n"
  2449.               . ".n";
  2450. #print $format;
  2451.       eval $format;
  2452.     }
  2453.     if ($MySQLaccess::CGI) {
  2454.     print "<table border width=100%>n";
  2455.     print "<tr>n";
  2456.     print "<th colspan=11>";
  2457.     print "Differences in access-rights <font color=$color{'<'}>BEFORE</font> "
  2458.          ."and <font color=$color{'>'}>AFTER</font> changes to grant-tables</font>n";
  2459.     print "</th>";
  2460.     print "</tr>n";
  2461.     print "<tr>n";    
  2462.     $line1 .= sprintf("<th>%-20s</th>",'Host, User, DB');
  2463.     foreach $header (@headers) {
  2464.       $line1 .= sprintf("<th>%-4s</th>",$header);
  2465.     }
  2466.     print "$line1</tr>n";
  2467.     }
  2468.     foreach $line (@diffs) {
  2469.         $type = substr($line,0,1);
  2470.         $line = substr($line,1);
  2471.         ($host,$user,$db,@priv) = split(/,/,$line);
  2472.         if ($MySQLaccess::CMD) {
  2473.            if ($type ne $curblock) {
  2474.               $curblock = $type;
  2475.               print $block{$curblock},":n";
  2476.            }
  2477.            #print "$linen";
  2478.            write;
  2479.         }
  2480.         if ($MySQLaccess::CGI) {
  2481.            if ($type ne $curblock) {
  2482.               $curblock = $type;
  2483.               print "<tr><td><b>$block{$curblock}<b></td></tr>n";
  2484.            }
  2485.            $line1="<td><font color=$color{$type}>$host, $user, $db</font></td>";
  2486.            foreach $field (@priv) {
  2487.               $line1 .= sprintf("<td align=center><font color=$color{$type}>%-4s</font></td>",$field);
  2488.            }
  2489.            print "<tr>$line1</tr>n";
  2490.         }
  2491.     }
  2492.     print      "n";
  2493.     if ($MySQLaccess::CMD) {
  2494.     print "---------------------------------------------------------------------n";
  2495.     }
  2496.     if ($MySQLaccess::CGI) {
  2497.     print      "</table><br>";
  2498.     }
  2499.     return 1;
  2500. }
  2501. # ======================================
  2502. # sub Tabular_Report
  2503. #  Tabular report,
  2504. #  suitable for 1 triple (host,db,user)
  2505. # ======================================
  2506. sub Tabular_Report {
  2507.     my ($host,$user,$db,$a) = @_;
  2508.     my $column=2;
  2509.     # -----------------------------
  2510.     # separator
  2511.     if ($MySQLaccess::Report::separator) { print "$MySQLaccess::Report::separatorn"; }
  2512.     
  2513.     # -----------------------------
  2514.     # print table of access-rights
  2515.     my $rows = int(@MySQLaccess::Grant::Privileges/2);  #round up
  2516.     my @table=();
  2517.     $j=0;
  2518.     for $i (0 .. $rows-1) {
  2519.       $table[$j]=$MySQLaccess::Grant::Privileges[$i];
  2520.       $j = $j+2;
  2521.     }
  2522.     $j=1;
  2523.     for $i ($rows .. $#MySQLaccess::Grant::Privileges) {
  2524.       $table[$j]=$MySQLaccess::Grant::Privileges[$i];
  2525.       $j = $j+2;
  2526.     }
  2527.     if ($MySQLaccess::CMD) {
  2528.     print "n";
  2529.     print "Access-rightsn";
  2530.     print "for USER '$user', from HOST '$host', to DB '$db'n";
  2531.     }
  2532.     if ($MySQLaccess::CGI) {
  2533.     print "<table border width=100%>n";
  2534.     print "<tr>n";
  2535.     }
  2536.     if ($MySQLaccess::CGI) {
  2537.     print "<th colspan=5>";
  2538.     print "<font color=Red>Access-rights</font>n";
  2539.     print "for USER '<font color=Green>$user</font>', from HOST '<font color=Green>$host</font>', to DB '<font color=Green>$db</font>'n";
  2540.     print "</th>";
  2541.     print "</tr>n";
  2542.     print "<tr>n";
  2543.     }
  2544.     if ($MySQLaccess::CMD) {
  2545.     print      "t+-----------------+---+t+-----------------+---+";
  2546.     }
  2547.     foreach $field (@table) {
  2548.         if ($MySQLaccess::CMD) {
  2549.           if ($column==2) { print "nt"; $column=1;}
  2550.           else            { print "t";   $column=2;}
  2551.           printf "| %-15s | %s |",$field,$Answer{$a->{$field}}; 
  2552.         }
  2553.         if ($MySQLaccess::CGI) {
  2554.           if ($column==2) { print "</tr>n<tr>n"; $column=1;}
  2555.           else            { print "<td width=10%></td>";   $column=2;}
  2556.           printf " <td width=35%><b>%-15s</b></td><td width=10%>%s</td>n",$field,$Answer{$a->{$field}}; 
  2557.         }
  2558.     }
  2559.     print      "n";
  2560.     if ($MySQLaccess::CMD) {
  2561.     print      "t+-----------------+---+t+-----------------+---+n";
  2562.     }
  2563.     if ($MySQLaccess::CGI) {
  2564.     print      "</tr>n</table><br>";
  2565.     }
  2566.     # ---------------
  2567.     # print notes:
  2568.     foreach $note (@MySQLaccess::Grant::Notes) {
  2569.       my $message = $MESSAGES{$note};
  2570.       $message =~ s/$user/$user/g; 
  2571.       $message =~ s/$db/$db/g;
  2572.       $message =~ s/$host/$host/g;
  2573.       $message =~ s/$password/$password/g;
  2574.       $PREFIX='NOTE';
  2575.       if ($MySQLaccess::CMD) {
  2576.       my @lines = split(/n/,$message);
  2577.       foreach $line (@lines) { 
  2578.         print "$PREFIX:t $linen"; 
  2579.         $PREFIX='    ';
  2580.       }
  2581.       }
  2582.       if ($MySQLaccess::CGI) {
  2583.       print "<b>$PREFIX:</b> $message<br>n";
  2584.       }
  2585.     } 
  2586.     # ---------------
  2587.     # print warnings:
  2588.     foreach $warning (@MySQLaccess::Grant::Warnings) {
  2589.       my $message = $MESSAGES{$warning};
  2590.       $message =~ s/$user/$user/g;
  2591.       $message =~ s/$db/$db/g;
  2592.       $message =~ s/$host/$host/g;
  2593.       $message =~ s/$password/$password/g;
  2594.       $PREFIX='BEWARE';
  2595.       if ($MySQLaccess::CMD) {
  2596.       my @lines = split(/n/,$message);
  2597.       foreach $line (@lines) { 
  2598.         print "$PREFIX:t $linen"; 
  2599.         $PREFIX='      ';
  2600.       }
  2601.       }
  2602.       if ($MySQLaccess::CGI) {
  2603.       print "<b>$PREFIX:</b> $message<br>n";
  2604.       }
  2605.     }
  2606.     # ---------------
  2607.     # print errors:
  2608.     foreach $error (@MySQLaccess::Grant::Errors) {
  2609.       my $message = $MESSAGES{$error};
  2610.       $message =~ s/$user/$user/g;
  2611.       $message =~ s/$db/$db/g;
  2612.       $message =~ s/$host/$host/g;
  2613.       $message =~ s/$password/$password/g;
  2614.       $PREFIX='ERROR';
  2615.       if ($MySQLaccess::CMD) {
  2616.       my @lines = split(/n/,$message);
  2617.       foreach $line (@lines) { 
  2618.         print "$PREFIX:t $linen"; 
  2619.         $PREFIX='    ';
  2620.       }
  2621.       }
  2622.       if ($MySQLaccess::CGI) {
  2623.       print "<b>$PREFIX:</b> $message<br>n";
  2624.       }
  2625.     }
  2626.     # ---------------
  2627.     # inform if there are no rules ==> full access for everyone.
  2628.     if ($MySQLaccess::Grant::full_access) { print "$MESSAGES{'full_access'}n"; }
  2629.     # ---------------
  2630.     # print the rules used
  2631.     print "n";
  2632.     if ($MySQLaccess::CMD) {
  2633.     print "The following rules are used:n";
  2634.     foreach $field (sort(keys(%MySQLaccess::Grant::Rules))) {
  2635.       my $rule = (defined($MESSAGES{$MySQLaccess::Grant::Rules{$field}}) ? $MESSAGES{$MySQLaccess::Grant::Rules{$field}} : $MySQLaccess::Grant::Rules{$field});
  2636.       $rule =~ s/t/','/g;
  2637.       printf " %-5s : '%s'n",$field,$rule;
  2638.     }
  2639.     }
  2640.     if ($MySQLaccess::CGI) {
  2641.     print "<br>n";
  2642.     print "<table border width=100%>n";
  2643.     print "<tr><th colspan=2>The following rules are used:</th></tr>n";
  2644.     foreach $field (sort(keys(%MySQLaccess::Grant::Rules))) {
  2645.       my $rule = (defined($MESSAGES{$MySQLaccess::Grant::Rules{$field}}) ? $MESSAGES{$MySQLaccess::Grant::Rules{$field}} : $MySQLaccess::Grant::Rules{$field});
  2646.       $rule =~ s/t/','/g;
  2647.       printf "<tr><th>%-5s</th><td>'%s'</td></tr>n",$field,$rule;
  2648.     }
  2649.     print "</table>n";
  2650.     }
  2651.  
  2652.     return 1;
  2653. }
  2654. # ======================================
  2655. # sub Matrix_Report:
  2656. #  single-line output foreach triple,
  2657. #  no notes,warnings,...
  2658. # ======================================
  2659. sub Matrix_Report {
  2660.     my ($host,$user,$db,$a) = @_;
  2661.     my @headers = ();
  2662.     
  2663.     if (! $headers) {
  2664.        # -----------------------------
  2665.        # create column-headers
  2666.        foreach $field (@MySQLaccess::Grant::Privileges) {
  2667.          push(@headers,substr($field,0,4));
  2668.        }
  2669.     
  2670.        # -----------------------------
  2671.        # print column-headers
  2672.        print "n";
  2673.        if ($MySQLaccess::CMD) {
  2674.          my $line1="";
  2675.          my $line2="";
  2676.          foreach $header (@headers) {
  2677.            $line1 .= sprintf("%-4s ",$header);
  2678.            $line2 .= sprintf("%s ",'----');
  2679.          }
  2680.          $line1 .= sprintf("| %-20s",'Host,User,DB');
  2681.          $line2 .= sprintf("+ %-20s",'-' x 20);
  2682.          print "$line1n";
  2683.          print "$line2n";
  2684.        }
  2685.        if ($MySQLaccess::CGI) {
  2686.          print "<table width=100% border>n";
  2687.          my $line1="<tr>";
  2688.          foreach $header (@headers) {
  2689.            $line1 .= sprintf("<th>%-4s</th>",$header);
  2690.          }
  2691.          $line1 .= sprintf("<th>%-20s</th>",'Host, User, DB');
  2692.          print "$line1</tr>n";
  2693.        }
  2694.        # ----------------------------
  2695.        # column-headers should only be 
  2696.        # printed once.
  2697.        $MySQLaccess::Report::headers=1;
  2698.     }
  2699.     # ------------------------
  2700.     # print access-information
  2701.     if ($MySQLaccess::CMD) {
  2702.       foreach $field (@MySQLaccess::Grant::Privileges) {
  2703.      printf " %-2s  ",$Answer{$a->{$field}}; 
  2704.       }
  2705.       printf "| %-20s",join(',',$host,$user,$db);
  2706.       print "n";
  2707.     }
  2708.     if ($MySQLaccess::CGI) {
  2709.       print "<tr>";
  2710.       foreach $field (@MySQLaccess::Grant::Privileges) {
  2711.      printf "<td align=center>%-2s</td>",$Answer{$a->{$field}}; 
  2712.       }
  2713.       printf "<td><b>%-20s</b></td>",join(', ',$host,$user,$db);
  2714.       print "</tr>n";
  2715.     }
  2716.     return 1;
  2717. }
  2718. # ======================================
  2719. # sub Raw_Report:
  2720. #  single-line output foreach triple,
  2721. #  no notes,warnings,...
  2722. # ======================================
  2723. sub Raw_Report {
  2724.     my ($host,$user,$db,$a) = @_;
  2725.     my @headers = ();
  2726.     my $string = "";
  2727.     
  2728.     # ------------------------
  2729.     # print access-information
  2730.     $string = "$host,$user,$db,";
  2731.     foreach $field (@MySQLaccess::Grant::Privileges) {
  2732.   $string .= $Answer{$a->{$field}} . ","; 
  2733.     }
  2734.     return $string;
  2735. }
  2736. #######################################################################
  2737. package MySQLaccess::Wildcards;
  2738. BEGIN {
  2739.     $DEBUG     = 0;
  2740.     $DEBUG     = $MySQLaccess::DEBUG unless ($DEBUG);
  2741. }
  2742. # ############################################
  2743. # SQL, WILDCARDS and REGULAR EXPRESSIONS 
  2744. # ============================================
  2745. # translage SQL-expressions to Reg-expressions
  2746. # ============================================
  2747. sub SQL2Reg {
  2748.     my ($expr) = @_;
  2749.     my $expr_o = $expr;
  2750.     $expr  =~ s/./\./g;
  2751.     $expr  =~ s/\%/02/g;
  2752.     $expr  =~ s/%/.*/g;
  2753.     $expr  =~ s/02/%/g;
  2754.     $expr  =~ s/\_/02/g;
  2755.     $expr  =~ s/_/.+/g;
  2756.     $expr  =~ s/02/_/g;
  2757.     MySQLaccess::Debug::Print(2,"$expr_o --> $expr");
  2758.     return $expr;
  2759. }
  2760. # translage WILDcards to Reg-expressions
  2761. # ============================================
  2762. sub Wild2Reg {
  2763.     my ($expr) = @_;
  2764.     my $expr_o = $expr;
  2765.     $expr  =~ s/./\./g;
  2766.     $expr  =~ s/\*/02/g;
  2767.     $expr  =~ s/*/.*/g;
  2768.     $expr  =~ s/02/*/g;
  2769.     $expr  =~ s/\?/02/g;
  2770.     $expr  =~ s/?/.+/g;
  2771.     $expr  =~ s/02/?/g;
  2772.     MySQLaccess::Debug::Print(2,"$expr_o --> $expr");
  2773.     return $expr;
  2774. }
  2775. # =============================================
  2776. # match a given string with a template
  2777. # =============================================
  2778. sub MatchTemplate {
  2779.     my ($tpl,$string) = @_;
  2780.     my $match=0;
  2781.     if ($string=~ /^$tpl$/ or $tpl eq '') { $match=1; }
  2782.     else                                  { $match=0;}
  2783.     MySQLaccess::Debug::Print(2,"($tpl,$string) --> $match");
  2784.     return $match;
  2785. }
  2786. #######################################################################
  2787. package MySQLaccess::Host;
  2788. BEGIN {
  2789.     $localhost = undef;
  2790.     $DEBUG     = 2;
  2791.     $DEBUG     = $MySQLaccess::DEBUG unless ($DEBUG);
  2792. }
  2793. # ======================================
  2794. # sub IP2Name
  2795. #  return the Name with the corr. IP-nmbr
  2796. #  (no aliases yet!!)
  2797. # ======================================
  2798. sub IP2Name {
  2799.     my ($ip) = @_;
  2800.     my $ip_o = $ip;
  2801.     if ($ip !~ /([0-9]+).([0-9]+).([0-9]+).([0-9]+)/o) {
  2802.        MySQLaccess::Debug::Print(3,"'$ip' is not an ip-number, returning IP=$ip");
  2803.        return $ip;
  2804.     }
  2805.     MySQLaccess::Debug::Print(4,"IP=$ip split up => $1.$2.$3.$4");
  2806.     $ip = pack "C4",$1,$2,$3,$4;
  2807.     MySQLaccess::Debug::Print(4,"IP packed -> >>$ip<<n");
  2808.     my ($name,$aliases,$addrtype,$length,@addrs) = gethostbyaddr($ip, AF_INET);
  2809.     MySQLaccess::Debug::Print(3,"IP=$ip_o => hostname=$name");
  2810.     MySQLaccess::Debug::Print(4,"aliases=$aliases");
  2811.     MySQLaccess::Debug::Print(4,"addrtype=$addrtype - length=$length");
  2812.     return ($name || $ip);
  2813.     #return ($name || undef);
  2814. }
  2815. # ======================================
  2816. # sub Name2IP
  2817. #  return the IP-number of the host
  2818. # ======================================
  2819. sub Name2IP {
  2820.     my ($name) = @_;
  2821.     if ($name =~ /[%_]/) { 
  2822.        MySQLaccess::Debug::Print(3,"'$name' contains SQL-wildcards, returning name=$name");
  2823.        return $name; 
  2824.     }
  2825.     my ($_name,$aliases,$addrtype,$length,@addrs) = gethostbyname($name);
  2826.     my ($a,$b,$c,$d) = unpack('C4',$addrs[0]);
  2827.     my $ip = "$a.$b.$c.$d";
  2828.     MySQLaccess::Debug::Print(3,"hostname=$name => IP=$ip");
  2829.     MySQLaccess::Debug::Print(4,"aliases=$aliases");
  2830.     MySQLaccess::Debug::Print(4,"addrtype=$addrtype - length=$length");
  2831.     #if ($ip ne "") { return "$ip"; }
  2832.     #else           { return undef; }
  2833.     return ($ip || $name);
  2834. }
  2835. # ========================================
  2836. # sub LocalHost
  2837. #  some special action has to be taken for
  2838. #  the localhost
  2839. # ========================================
  2840. sub LocalHost {
  2841.     if (!defined($MySQLaccess::Host::localhost)) {
  2842.        $MySQLaccess::Host::localhost = Sys::Hostname::hostname();
  2843.        MySQLaccess::Debug::Print(3,"Setting package variable $localhost=$MySQLaccess::Host::localhost");
  2844.     }
  2845.     my $host = $localhost;
  2846.     MySQLaccess::Debug::Print(3,"localhost = $host");
  2847.     return $host;
  2848. }
  2849. # ========================================
  2850. # check if the given hostname (or ip)
  2851. # corresponds with the localhost
  2852. # ========================================
  2853. sub Is_localhost {
  2854.     my ($host_tpl) = @_;
  2855.     my $isit = 0;
  2856.     if (($MySQLaccess::host_name eq $localhost) or ($MySQLaccess::host_ip eq $local_ip)) {
  2857. MySQLaccess::Debug::Print(2,"Checking for localhost");
  2858.       MySQLaccess::Debug::Print(3,"because ($MySQLaccess::host_name EQ $localhost) AND ($MySQLaccess::host_ip EQ $local_ip)");
  2859.       $isit = ( 'localhost' =~ /$host_tpl/ ) ? 1 : 0;
  2860.       MySQLaccess::Debug::Print(3," 'localhost' =?= $host_tpl  -> $isit");
  2861.       return $isit;
  2862.     }
  2863.     else {
  2864.       MySQLaccess::Debug::Print(4,"Not checking for localhost");
  2865.       MySQLaccess::Debug::Print(4,"because ($MySQLaccess::host_name != $localhost) AND ($MySQLaccess::host_ip != $local_ip)");
  2866.       return 0;
  2867.     }
  2868. }
  2869. # =========================================
  2870. # check if host (IP or name) can be matched
  2871. # on the template.
  2872. # =========================================
  2873. sub MatchTemplate {
  2874.     my ($host,$tpl) = @_;
  2875.     my $match = 0;
  2876.    
  2877.     MySQLaccess::Debug::Print(1, "($host) =?= ($tpl)");
  2878.     my $host_name = IP2Name($host);
  2879.     my $host_ip   = Name2IP($host);
  2880.     MySQLaccess::Debug::Print(2, "name=$host_name ; ip=$host_ip");
  2881.     $match = (MySQLaccess::Wildcards::MatchTemplate($tpl,$host_name) or
  2882.              MySQLaccess::Wildcards::MatchTemplate($tpl,$host_ip));
  2883.     MySQLaccess::Debug::Print(2, "($host_name,$host_ip) =?= ($tpl): $ncount");
  2884.     return $match;
  2885. }
  2886. ########################################################################
  2887. package MySQLaccess::Debug;
  2888. BEGIN {
  2889.    my $dbg_file = "$MySQLaccess::script_log";
  2890.    open(DEBUG,"> $dbg_file") or warn "Could not open outputfile $dbg_file for debugging-infon";
  2891.    select DEBUG;
  2892.    $| = 1;
  2893.    select STDOUT;
  2894. }
  2895. # =========================================
  2896. # Print debugging information on STDERR
  2897. # =========================================
  2898. sub Print {
  2899.     my ($level,$mesg) = @_;
  2900.     my ($pack,$file,$line,$subname,$hasargs,$wantarray) = caller(1);
  2901.     my ($PACK)  = split('::',$subname); 
  2902.     my $DEBUG = ${$PACK."::DEBUG"} ? ${$PACK."::DEBUG"} : $MySQLaccess::DEBUG ;
  2903.     my ($sec,$min,$hour) = localtime();
  2904.     print DEBUG "[$hour:$min:$sec $subname] $mesgn" if ($DEBUG>=$level);
  2905. }