sql_acl.cc 167 KB
Newer Older
1
/* Copyright (C) 2000-2003 MySQL AB
unknown's avatar
unknown committed
2

unknown's avatar
unknown committed
3 4 5 6
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
unknown's avatar
unknown committed
7

unknown's avatar
unknown committed
8 9 10 11
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
unknown's avatar
unknown committed
12

unknown's avatar
unknown committed
13 14 15 16 17 18 19
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */


/*
  The privileges are saved in the following tables:
20 21
  mysql/user	 ; super user who are allowed to do almost anything
  mysql/host	 ; host privileges. This is used if host is empty in mysql/db.
unknown's avatar
unknown committed
22 23 24 25 26 27 28 29
  mysql/db	 ; database privileges / user

  data in tables is sorted according to how many not-wild-cards there is
  in the relevant fields. Empty strings comes last.
*/

#include "mysql_priv.h"
#include "hash_filo.h"
30 31 32
#ifdef HAVE_REPLICATION
#include "sql_repl.h" //for tables_ok()
#endif
unknown's avatar
unknown committed
33 34
#include <m_ctype.h>
#include <stdarg.h>
35 36
#include "sp_head.h"
#include "sp.h"
unknown's avatar
unknown committed
37

unknown's avatar
unknown committed
38
#ifndef NO_EMBEDDED_ACCESS_CHECKS
39

unknown's avatar
unknown committed
40 41 42
class acl_entry :public hash_filo_element
{
public:
unknown's avatar
unknown committed
43
  ulong access;
unknown's avatar
unknown committed
44 45 46 47
  uint16 length;
  char key[1];					// Key will be stored here
};

unknown's avatar
unknown committed
48

unknown's avatar
unknown committed
49 50 51 52 53 54 55
static byte* acl_entry_get_key(acl_entry *entry,uint *length,
			       my_bool not_used __attribute__((unused)))
{
  *length=(uint) entry->length;
  return (byte*) entry->key;
}

unknown's avatar
unknown committed
56
#define IP_ADDR_STRLEN (3+1+3+1+3+1+3)
57
#define ACL_KEY_LENGTH (IP_ADDR_STRLEN+1+NAME_LEN+1+USERNAME_LENGTH+1)
unknown's avatar
unknown committed
58 59 60 61 62

static DYNAMIC_ARRAY acl_hosts,acl_users,acl_dbs;
static MEM_ROOT mem, memex;
static bool initialized=0;
static bool allow_all_hosts=1;
63
static HASH acl_check_hosts, column_priv_hash, proc_priv_hash, func_priv_hash;
unknown's avatar
unknown committed
64 65
static DYNAMIC_ARRAY acl_wild_hosts;
static hash_filo *acl_cache;
66
static uint grant_version=0; /* Version of priv tables. incremented by acl_load */
unknown's avatar
unknown committed
67
static ulong get_access(TABLE *form,uint fieldnr, uint *next_field=0);
unknown's avatar
unknown committed
68 69 70
static int acl_compare(ACL_ACCESS *a,ACL_ACCESS *b);
static ulong get_sort(uint count,...);
static void init_check_host(void);
71 72
static ACL_USER *find_acl_user(const char *host, const char *user,
                               my_bool exact);
73 74
static bool update_user_table(THD *thd, TABLE *table,
                              const char *host, const char *user,
75
			      const char *new_password, uint new_password_len);
unknown's avatar
unknown committed
76
static void update_hostname(acl_host_and_ip *host, const char *hostname);
77
static bool compare_hostname(const acl_host_and_ip *host,const char *hostname,
unknown's avatar
unknown committed
78
			     const char *ip);
79 80
static my_bool acl_load(THD *thd, TABLE_LIST *tables);
static my_bool grant_load(TABLE_LIST *tables);
unknown's avatar
unknown committed
81

82 83 84 85 86 87 88 89 90 91 92 93 94 95
/*
  Convert scrambled password to binary form, according to scramble type, 
  Binary form is stored in user.salt.
*/

static
void
set_user_salt(ACL_USER *acl_user, const char *password, uint password_len)
{
  if (password_len == SCRAMBLED_PASSWORD_CHAR_LENGTH)
  {
    get_salt_from_password(acl_user->salt, password);
    acl_user->salt_len= SCRAMBLE_LENGTH;
  }
96
  else if (password_len == SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
97 98
  {
    get_salt_from_password_323((ulong *) acl_user->salt, password);
99
    acl_user->salt_len= SCRAMBLE_LENGTH_323;
100 101 102 103 104
  }
  else
    acl_user->salt_len= 0;
}

105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
/*
  This after_update function is used when user.password is less than
  SCRAMBLE_LENGTH bytes.
*/

static void restrict_update_of_old_passwords_var(THD *thd,
                                                 enum_var_type var_type)
{
  if (var_type == OPT_GLOBAL)
  {
    pthread_mutex_lock(&LOCK_global_system_variables);
    global_system_variables.old_passwords= 1;
    pthread_mutex_unlock(&LOCK_global_system_variables);
  }
  else
    thd->variables.old_passwords= 1;
}

123

124
/*
125 126
  Initialize structures responsible for user/db-level privilege checking and
  load privilege information for them from tables in the 'mysql' database.
127 128 129

  SYNOPSIS
    acl_init()
130 131 132 133 134 135
      dont_read_acl_tables  TRUE if we want to skip loading data from
                            privilege tables and disable privilege checking.

  NOTES
    This function is mostly responsible for preparatory steps, main work
    on initialization and grants loading is done in acl_reload().
136 137 138 139 140 141

  RETURN VALUES
    0	ok
    1	Could not initialize grant's
*/

142
my_bool acl_init(bool dont_read_acl_tables)
unknown's avatar
unknown committed
143
{
unknown's avatar
unknown committed
144
  THD  *thd;
145
  my_bool return_val;
unknown's avatar
unknown committed
146 147
  DBUG_ENTER("acl_init");

148 149 150
  acl_cache= new hash_filo(ACL_CACHE_SIZE, 0, 0,
                           (hash_get_key) acl_entry_get_key,
                           (hash_free_key) free, system_charset_info);
unknown's avatar
unknown committed
151
  if (dont_read_acl_tables)
152
  {
unknown's avatar
unknown committed
153
    DBUG_RETURN(0); /* purecov: tested */
unknown's avatar
unknown committed
154 155
  }

156 157 158
  /*
    To be able to run this from boot, we allocate a temporary THD
  */
unknown's avatar
unknown committed
159 160
  if (!(thd=new THD))
    DBUG_RETURN(1); /* purecov: inspected */
161
  thd->store_globals();
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
  /*
    It is safe to call acl_reload() since acl_* arrays and hashes which
    will be freed there are global static objects and thus are initialized
    by zeros at startup.
  */
  return_val= acl_reload(thd);
  delete thd;
  /* Remember that we don't have a THD */
  my_pthread_setspecific_ptr(THR_THD,  0);
  DBUG_RETURN(return_val);
}


/*
  Initialize structures responsible for user/db-level privilege checking
  and load information about grants from open privilege tables.

  SYNOPSIS
    acl_load()
      thd     Current thread
      tables  List containing open "mysql.host", "mysql.user" and
              "mysql.db" tables.

  RETURN VALUES
    FALSE  Success
    TRUE   Error
*/

static my_bool acl_load(THD *thd, TABLE_LIST *tables)
{
  TABLE *table;
  READ_RECORD read_record_info;
  my_bool return_val= 1;
  bool check_no_resolve= specialflag & SPECIAL_NO_RESOLVE;
  char tmp_name[NAME_LEN+1];
  DBUG_ENTER("acl_load");

199 200
  grant_version++; /* Privileges updated */
  mysql_proc_table_exists= 1;			// Assume mysql.proc exists
201

unknown's avatar
unknown committed
202 203
  acl_cache->clear(1);				// Clear locked hostname cache

204
  init_sql_alloc(&mem, ACL_ALLOC_BLOCK_SIZE, 0);
unknown's avatar
unknown committed
205
  init_read_record(&read_record_info,thd,table= tables[0].table,NULL,1,0);
206
  VOID(my_init_dynamic_array(&acl_hosts,sizeof(ACL_HOST),20,50));
unknown's avatar
unknown committed
207 208 209
  while (!(read_record_info.read_record(&read_record_info)))
  {
    ACL_HOST host;
210 211
    update_hostname(&host.host,get_field(&mem, table->field[0]));
    host.db=	 get_field(&mem, table->field[1]);
212
    if (lower_case_table_names && host.db)
213 214
    {
      /*
215 216
        convert db to lower case and give a warning if the db wasn't
        already in lower case
217
      */
218 219
      (void) strmov(tmp_name, host.db);
      my_casedn_str(files_charset_info, host.db);
220 221 222
      if (strcmp(host.db, tmp_name) != 0)
        sql_print_warning("'host' entry '%s|%s' had database in mixed "
                          "case that has been forced to lowercase because "
223 224
                          "lower_case_table_names is set. It will not be "
                          "possible to remove this privilege using REVOKE.",
225 226
                          host.host.hostname, host.db);
    }
unknown's avatar
unknown committed
227 228
    host.access= get_access(table,2);
    host.access= fix_rights_for_db(host.access);
229
    host.sort=	 get_sort(2,host.host.hostname,host.db);
unknown's avatar
SCRUM  
unknown committed
230 231
    if (check_no_resolve && hostname_requires_resolving(host.host.hostname))
    {
unknown's avatar
unknown committed
232
      sql_print_warning("'host' entry '%s|%s' "
unknown's avatar
SCRUM  
unknown committed
233
		      "ignored in --skip-name-resolve mode.",
234
		      host.host.hostname, host.db?host.db:"");
unknown's avatar
SCRUM  
unknown committed
235 236
      continue;
    }
unknown's avatar
unknown committed
237
#ifndef TO_BE_REMOVED
238
    if (table->s->fields == 8)
unknown's avatar
unknown committed
239 240
    {						// Without grant
      if (host.access & CREATE_ACL)
241
	host.access|=REFERENCES_ACL | INDEX_ACL | ALTER_ACL | CREATE_TMP_ACL;
unknown's avatar
unknown committed
242 243 244 245 246 247 248 249 250 251
    }
#endif
    VOID(push_dynamic(&acl_hosts,(gptr) &host));
  }
  qsort((gptr) dynamic_element(&acl_hosts,0,ACL_HOST*),acl_hosts.elements,
	sizeof(ACL_HOST),(qsort_cmp) acl_compare);
  end_read_record(&read_record_info);
  freeze_size(&acl_hosts);

  init_read_record(&read_record_info,thd,table=tables[1].table,NULL,1,0);
252
  VOID(my_init_dynamic_array(&acl_users,sizeof(ACL_USER),50,100));
253
  if (table->field[2]->field_length < SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
unknown's avatar
unknown committed
254
  {
255 256 257
    sql_print_error("Fatal error: mysql.user table is damaged or in "
                    "unsupported 3.20 format.");
    goto end;
unknown's avatar
unknown committed
258 259
  }

260
  DBUG_PRINT("info",("user table fields: %d, password length: %d",
261
		     table->s->fields, table->field[2]->field_length));
262

263 264
  pthread_mutex_lock(&LOCK_global_system_variables);
  if (table->field[2]->field_length < SCRAMBLED_PASSWORD_CHAR_LENGTH)
265
  {
266 267 268 269 270 271 272 273 274 275 276 277 278 279
    if (opt_secure_auth)
    {
      pthread_mutex_unlock(&LOCK_global_system_variables);
      sql_print_error("Fatal error: mysql.user table is in old format, "
                      "but server started with --secure-auth option.");
      goto end;
    }
    sys_old_passwords.after_update= restrict_update_of_old_passwords_var;
    if (global_system_variables.old_passwords)
      pthread_mutex_unlock(&LOCK_global_system_variables);
    else
    {
      global_system_variables.old_passwords= 1;
      pthread_mutex_unlock(&LOCK_global_system_variables);
280 281 282
      sql_print_warning("mysql.user table is not updated to new password format; "
                        "Disabling new password usage until "
                        "mysql_fix_privilege_tables is run");
283 284 285 286
    }
    thd->variables.old_passwords= 1;
  }
  else
287
  {
288 289
    sys_old_passwords.after_update= 0;
    pthread_mutex_unlock(&LOCK_global_system_variables);
290 291
  }

unknown's avatar
unknown committed
292 293 294 295
  allow_all_hosts=0;
  while (!(read_record_info.read_record(&read_record_info)))
  {
    ACL_USER user;
296 297
    update_hostname(&user.host, get_field(&mem, table->field[0]));
    user.user= get_field(&mem, table->field[1]);
unknown's avatar
SCRUM  
unknown committed
298 299
    if (check_no_resolve && hostname_requires_resolving(user.host.hostname))
    {
unknown's avatar
unknown committed
300 301
      sql_print_warning("'user' entry '%s@%s' "
                        "ignored in --skip-name-resolve mode.",
302
		      user.user, user.host.hostname);
unknown's avatar
SCRUM  
unknown committed
303 304 305
      continue;
    }

306 307 308 309
    const char *password= get_field(&mem, table->field[2]);
    uint password_len= password ? strlen(password) : 0;
    set_user_salt(&user, password, password_len);
    if (user.salt_len == 0 && password_len != 0)
unknown's avatar
unknown committed
310
    {
311 312
      switch (password_len) {
      case 45: /* 4.1: to be removed */
unknown's avatar
unknown committed
313 314 315 316 317
        sql_print_warning("Found 4.1 style password for user '%s@%s'. "
                          "Ignoring user. "
                          "You should change password for this user.",
                          user.user ? user.user : "",
                          user.host.hostname ? user.host.hostname : "");
318 319
        break;
      default:
unknown's avatar
unknown committed
320 321 322
        sql_print_warning("Found invalid password for user: '%s@%s'; "
                          "Ignoring user", user.user ? user.user : "",
                           user.host.hostname ? user.host.hostname : "");
323 324
        break;
      }
unknown's avatar
unknown committed
325
    }
326
    else                                        // password is correct
unknown's avatar
unknown committed
327
    {
unknown's avatar
unknown committed
328 329
      uint next_field;
      user.access= get_access(table,3,&next_field) & GLOBAL_ACLS;
330 331 332 333
      /*
        if it is pre 5.0.1 privilege table then map CREATE privilege on
        CREATE VIEW & SHOW VIEW privileges
      */
334
      if (table->s->fields <= 31 && (user.access & CREATE_ACL))
335
        user.access|= (CREATE_VIEW_ACL | SHOW_VIEW_ACL);
336 337 338 339 340

      /*
        if it is pre 5.0.2 privilege table then map CREATE/ALTER privilege on
        CREATE PROCEDURE & ALTER PROCEDURE privileges
      */
341
      if (table->s->fields <= 33 && (user.access & CREATE_ACL))
342
        user.access|= CREATE_PROC_ACL;
343
      if (table->s->fields <= 33 && (user.access & ALTER_ACL))
344 345
        user.access|= ALTER_PROC_ACL;

346 347 348 349 350 351
      /*
        pre 5.0.3 did not have CREATE_USER_ACL
      */
      if (table->s->fields <= 36 && (user.access & GRANT_ACL))
        user.access|= CREATE_USER_ACL;

352 353 354
      user.sort= get_sort(2,user.host.hostname,user.user);
      user.hostname_length= (user.host.hostname ?
                             (uint) strlen(user.host.hostname) : 0);
unknown's avatar
VIEW  
unknown committed
355

356 357
      /* Starting from 4.0.2 we have more fields */
      if (table->s->fields >= 31)
358
      {
unknown's avatar
unknown committed
359
        char *ssl_type=get_field(&mem, table->field[next_field++]);
360 361 362 363 364 365 366 367 368
        if (!ssl_type)
          user.ssl_type=SSL_TYPE_NONE;
        else if (!strcmp(ssl_type, "ANY"))
          user.ssl_type=SSL_TYPE_ANY;
        else if (!strcmp(ssl_type, "X509"))
          user.ssl_type=SSL_TYPE_X509;
        else  /* !strcmp(ssl_type, "SPECIFIED") */
          user.ssl_type=SSL_TYPE_SPECIFIED;

unknown's avatar
unknown committed
369 370 371
        user.ssl_cipher=   get_field(&mem, table->field[next_field++]);
        user.x509_issuer=  get_field(&mem, table->field[next_field++]);
        user.x509_subject= get_field(&mem, table->field[next_field++]);
372

unknown's avatar
unknown committed
373 374 375 376 377
        char *ptr = get_field(&mem, table->field[next_field++]);
        user.user_resource.questions=ptr ? atoi(ptr) : 0;
        ptr = get_field(&mem, table->field[next_field++]);
        user.user_resource.updates=ptr ? atoi(ptr) : 0;
        ptr = get_field(&mem, table->field[next_field++]);
378
        user.user_resource.conn_per_hour= ptr ? atoi(ptr) : 0;
379
        if (user.user_resource.questions || user.user_resource.updates ||
380
            user.user_resource.conn_per_hour)
381
          mqh_used=1;
382

383
        if (table->s->fields >= 36)
384 385 386 387 388 389 390
        {
          /* Starting from 5.0.3 we have max_user_connections field */
          ptr= get_field(&mem, table->field[next_field++]);
          user.user_resource.user_conn= ptr ? atoi(ptr) : 0;
        }
        else
          user.user_resource.user_conn= 0;
391
      }
392 393 394
      else
      {
        user.ssl_type=SSL_TYPE_NONE;
395
        bzero((char *)&(user.user_resource),sizeof(user.user_resource));
unknown's avatar
unknown committed
396
#ifndef TO_BE_REMOVED
397
        if (table->s->fields <= 13)
398 399 400 401 402 403 404 405 406 407
        {						// Without grant
          if (user.access & CREATE_ACL)
            user.access|=REFERENCES_ACL | INDEX_ACL | ALTER_ACL;
        }
        /* Convert old privileges */
        user.access|= LOCK_TABLES_ACL | CREATE_TMP_ACL | SHOW_DB_ACL;
        if (user.access & FILE_ACL)
          user.access|= REPL_CLIENT_ACL | REPL_SLAVE_ACL;
        if (user.access & PROCESS_ACL)
          user.access|= SUPER_ACL | EXECUTE_ACL;
unknown's avatar
unknown committed
408
#endif
409 410 411 412 413
      }
      VOID(push_dynamic(&acl_users,(gptr) &user));
      if (!user.host.hostname || user.host.hostname[0] == wild_many &&
          !user.host.hostname[1])
        allow_all_hosts=1;			// Anyone can connect
unknown's avatar
unknown committed
414
    }
unknown's avatar
unknown committed
415 416 417 418 419
  }
  qsort((gptr) dynamic_element(&acl_users,0,ACL_USER*),acl_users.elements,
	sizeof(ACL_USER),(qsort_cmp) acl_compare);
  end_read_record(&read_record_info);
  freeze_size(&acl_users);
unknown's avatar
unknown committed
420

unknown's avatar
unknown committed
421
  init_read_record(&read_record_info,thd,table=tables[2].table,NULL,1,0);
422
  VOID(my_init_dynamic_array(&acl_dbs,sizeof(ACL_DB),50,100));
unknown's avatar
unknown committed
423 424 425
  while (!(read_record_info.read_record(&read_record_info)))
  {
    ACL_DB db;
426 427
    update_hostname(&db.host,get_field(&mem, table->field[0]));
    db.db=get_field(&mem, table->field[1]);
428 429
    if (!db.db)
    {
unknown's avatar
unknown committed
430
      sql_print_warning("Found an entry in the 'db' table with empty database name; Skipped");
431
      continue;
432
    }
433
    db.user=get_field(&mem, table->field[2]);
unknown's avatar
SCRUM  
unknown committed
434 435
    if (check_no_resolve && hostname_requires_resolving(db.host.hostname))
    {
unknown's avatar
unknown committed
436 437
      sql_print_warning("'db' entry '%s %s@%s' "
		        "ignored in --skip-name-resolve mode.",
438
		        db.db, db.user, db.host.hostname);
unknown's avatar
SCRUM  
unknown committed
439 440
      continue;
    }
unknown's avatar
unknown committed
441 442
    db.access=get_access(table,3);
    db.access=fix_rights_for_db(db.access);
443 444 445
    if (lower_case_table_names)
    {
      /*
446 447
        convert db to lower case and give a warning if the db wasn't
        already in lower case
448 449
      */
      (void)strmov(tmp_name, db.db);
450
      my_casedn_str(files_charset_info, db.db);
451 452 453 454
      if (strcmp(db.db, tmp_name) != 0)
      {
        sql_print_warning("'db' entry '%s %s@%s' had database in mixed "
                          "case that has been forced to lowercase because "
455 456
                          "lower_case_table_names is set. It will not be "
                          "possible to remove this privilege using REVOKE.",
457 458 459
		          db.db, db.user, db.host.hostname, db.host.hostname);
      }
    }
unknown's avatar
unknown committed
460 461
    db.sort=get_sort(3,db.host.hostname,db.db,db.user);
#ifndef TO_BE_REMOVED
462
    if (table->s->fields <=  9)
unknown's avatar
unknown committed
463 464 465 466 467 468 469 470 471 472 473 474 475
    {						// Without grant
      if (db.access & CREATE_ACL)
	db.access|=REFERENCES_ACL | INDEX_ACL | ALTER_ACL;
    }
#endif
    VOID(push_dynamic(&acl_dbs,(gptr) &db));
  }
  qsort((gptr) dynamic_element(&acl_dbs,0,ACL_DB*),acl_dbs.elements,
	sizeof(ACL_DB),(qsort_cmp) acl_compare);
  end_read_record(&read_record_info);
  freeze_size(&acl_dbs);
  init_check_host();

476 477 478 479 480
  initialized=1;
  return_val=0;

end:
  DBUG_RETURN(return_val);
unknown's avatar
unknown committed
481 482 483 484 485
}


void acl_free(bool end)
{
486
  free_root(&mem,MYF(0));
unknown's avatar
unknown committed
487 488 489 490 491 492 493 494 495 496 497 498 499 500
  delete_dynamic(&acl_hosts);
  delete_dynamic(&acl_users);
  delete_dynamic(&acl_dbs);
  delete_dynamic(&acl_wild_hosts);
  hash_free(&acl_check_hosts);
  if (!end)
    acl_cache->clear(1); /* purecov: inspected */
  else
  {
    delete acl_cache;
    acl_cache=0;
  }
}

501 502

/*
503 504
  Forget current user/db-level privileges and read new privileges
  from the privilege tables.
505 506 507

  SYNOPSIS
    acl_reload()
508 509 510 511 512 513 514 515 516 517 518
      thd  Current thread

  NOTE
    All tables of calling thread which were open and locked by LOCK TABLES
    statement will be unlocked and closed.
    This function is also used for initialization of structures responsible
    for user/db-level privilege checking.

  RETURN VALUE
    FALSE  Success
    TRUE   Failure
519
*/
unknown's avatar
unknown committed
520

521
my_bool acl_reload(THD *thd)
unknown's avatar
unknown committed
522
{
523
  TABLE_LIST tables[3];
unknown's avatar
unknown committed
524 525 526
  DYNAMIC_ARRAY old_acl_hosts,old_acl_users,old_acl_dbs;
  MEM_ROOT old_mem;
  bool old_initialized;
527
  my_bool return_val= 1;
unknown's avatar
unknown committed
528 529
  DBUG_ENTER("acl_reload");

530
  if (thd->locked_tables)
unknown's avatar
unknown committed
531
  {					// Can't have locked tables here
532 533 534
    thd->lock=thd->locked_tables;
    thd->locked_tables=0;
    close_thread_tables(thd);
unknown's avatar
unknown committed
535
  }
536 537 538 539 540 541

  /*
    To avoid deadlocks we should obtain table locks before
    obtaining acl_cache->lock mutex.
  */
  bzero((char*) tables, sizeof(tables));
542 543 544 545 546 547
  tables[0].alias= tables[0].table_name= (char*) "host";
  tables[1].alias= tables[1].table_name= (char*) "user";
  tables[2].alias= tables[2].table_name= (char*) "db";
  tables[0].db=tables[1].db=tables[2].db=(char*) "mysql";
  tables[0].next_local= tables[0].next_global= tables+1;
  tables[1].next_local= tables[1].next_global= tables+2;
548 549 550 551 552 553 554 555 556
  tables[0].lock_type=tables[1].lock_type=tables[2].lock_type=TL_READ;

  if (simple_open_n_lock_tables(thd, tables))
  {
    sql_print_error("Fatal error: Can't open and lock privilege tables: %s",
		    thd->net.last_error);
    goto end;
  }

unknown's avatar
unknown committed
557 558 559 560 561 562 563 564 565 566
  if ((old_initialized=initialized))
    VOID(pthread_mutex_lock(&acl_cache->lock));

  old_acl_hosts=acl_hosts;
  old_acl_users=acl_users;
  old_acl_dbs=acl_dbs;
  old_mem=mem;
  delete_dynamic(&acl_wild_hosts);
  hash_free(&acl_check_hosts);

567
  if ((return_val= acl_load(thd, tables)))
unknown's avatar
unknown committed
568
  {					// Error. Revert to old list
569
    DBUG_PRINT("error",("Reverting to old privileges"));
570
    acl_free();				/* purecov: inspected */
unknown's avatar
unknown committed
571 572 573 574 575 576 577 578
    acl_hosts=old_acl_hosts;
    acl_users=old_acl_users;
    acl_dbs=old_acl_dbs;
    mem=old_mem;
    init_check_host();
  }
  else
  {
579
    free_root(&old_mem,MYF(0));
unknown's avatar
unknown committed
580 581 582 583 584 585
    delete_dynamic(&old_acl_hosts);
    delete_dynamic(&old_acl_users);
    delete_dynamic(&old_acl_dbs);
  }
  if (old_initialized)
    VOID(pthread_mutex_unlock(&acl_cache->lock));
586 587 588
end:
  close_thread_tables(thd);
  DBUG_RETURN(return_val);
unknown's avatar
unknown committed
589 590 591
}


unknown's avatar
unknown committed
592 593
/*
  Get all access bits from table after fieldnr
unknown's avatar
unknown committed
594 595

  IMPLEMENTATION
unknown's avatar
unknown committed
596 597
  We know that the access privileges ends when there is no more fields
  or the field is not an enum with two elements.
unknown's avatar
unknown committed
598 599 600 601 602 603 604 605 606 607 608

  SYNOPSIS
    get_access()
    form        an open table to read privileges from.
                The record should be already read in table->record[0]
    fieldnr     number of the first privilege (that is ENUM('N','Y') field
    next_field  on return - number of the field next to the last ENUM
                (unless next_field == 0)

  RETURN VALUE
    privilege mask
unknown's avatar
unknown committed
609
*/
unknown's avatar
unknown committed
610

unknown's avatar
unknown committed
611
static ulong get_access(TABLE *form, uint fieldnr, uint *next_field)
unknown's avatar
unknown committed
612
{
unknown's avatar
unknown committed
613
  ulong access_bits=0,bit;
unknown's avatar
unknown committed
614
  char buff[2];
unknown's avatar
unknown committed
615
  String res(buff,sizeof(buff),&my_charset_latin1);
unknown's avatar
unknown committed
616 617
  Field **pos;

unknown's avatar
unknown committed
618 619 620
  for (pos=form->field+fieldnr, bit=1;
       *pos && (*pos)->real_type() == FIELD_TYPE_ENUM &&
	 ((Field_enum*) (*pos))->typelib->count == 2 ;
unknown's avatar
unknown committed
621
       pos++, fieldnr++, bit<<=1)
unknown's avatar
unknown committed
622
  {
623
    (*pos)->val_str(&res);
unknown's avatar
unknown committed
624
    if (my_toupper(&my_charset_latin1, res[0]) == 'Y')
unknown's avatar
unknown committed
625
      access_bits|= bit;
unknown's avatar
unknown committed
626
  }
unknown's avatar
unknown committed
627 628
  if (next_field)
    *next_field=fieldnr;
unknown's avatar
unknown committed
629 630 631 632 633
  return access_bits;
}


/*
unknown's avatar
unknown committed
634 635 636 637 638
  Return a number which, if sorted 'desc', puts strings in this order:
    no wildcards
    wildcards
    empty string
*/
unknown's avatar
unknown committed
639 640 641 642 643 644 645

static ulong get_sort(uint count,...)
{
  va_list args;
  va_start(args,count);
  ulong sort=0;

646 647 648
  /* Should not use this function with more than 4 arguments for compare. */
  DBUG_ASSERT(count <= 4);

unknown's avatar
unknown committed
649 650
  while (count--)
  {
651 652 653
    char *start, *str= va_arg(args,char*);
    uint chars= 0;
    uint wild_pos= 0;           /* first wildcard position */
unknown's avatar
unknown committed
654

unknown's avatar
unknown committed
655
    if ((start= str))
unknown's avatar
unknown committed
656 657 658 659
    {
      for (; *str ; str++)
      {
	if (*str == wild_many || *str == wild_one || *str == wild_prefix)
660
        {
unknown's avatar
unknown committed
661
          wild_pos= (uint) (str - start) + 1;
662 663
          break;
        }
unknown's avatar
unknown committed
664
        chars= 128;                             // Marker that chars existed
unknown's avatar
unknown committed
665 666
      }
    }
unknown's avatar
unknown committed
667
    sort= (sort << 8) + (wild_pos ? min(wild_pos, 127) : chars);
unknown's avatar
unknown committed
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
  }
  va_end(args);
  return sort;
}


static int acl_compare(ACL_ACCESS *a,ACL_ACCESS *b)
{
  if (a->sort > b->sort)
    return -1;
  if (a->sort < b->sort)
    return 1;
  return 0;
}

683

684
/*
unknown's avatar
unknown committed
685 686
  Seek ACL entry for a user, check password, SSL cypher, and if
  everything is OK, update THD user data and USER_RESOURCES struct.
687

unknown's avatar
unknown committed
688 689 690 691
  IMPLEMENTATION
   This function does not check if the user has any sensible privileges:
   only user's existence and  validity is checked.
   Note, that entire operation is protected by acl_cache_lock.
unknown's avatar
unknown committed
692

693
  SYNOPSIS
694 695 696 697 698 699
    acl_getroot()
    thd         thread handle. If all checks are OK,
                thd->priv_user, thd->master_access are updated.
                thd->host, thd->ip, thd->user are used for checks.
    mqh         user resources; on success mqh is reset, else
                unchanged
700
    passwd      scrambled & crypted password, received from client
701 702 703 704 705 706 707
                (to check): thd->scramble or thd->scramble_323 is
                used to decrypt passwd, so they must contain
                original random string,
    passwd_len  length of passwd, must be one of 0, 8,
                SCRAMBLE_LENGTH_323, SCRAMBLE_LENGTH
    'thd' and 'mqh' are updated on success; other params are IN.
  
unknown's avatar
unknown committed
708
  RETURN VALUE
709 710
    0  success: thd->priv_user, thd->priv_host, thd->master_access, mqh are
       updated
711
    1  user not found or authentication failure
unknown's avatar
unknown committed
712
    2  user found, has long (4.1.1) salt, but passwd is in old (3.23) format.
713
   -1  user found, has short (3.23) salt, but passwd is in new (4.1.1) format.
unknown's avatar
unknown committed
714 715
*/

716 717
int acl_getroot(THD *thd, USER_RESOURCES  *mqh,
                const char *passwd, uint passwd_len)
unknown's avatar
unknown committed
718
{
unknown's avatar
merge  
unknown committed
719 720 721
  ulong user_access= NO_ACCESS;
  int res= 1;
  ACL_USER *acl_user= 0;
722
  DBUG_ENTER("acl_getroot");
unknown's avatar
unknown committed
723 724

  if (!initialized)
725
  {
726 727 728 729 730 731
    /* 
      here if mysqld's been started with --skip-grant-tables option.
    */
    thd->priv_user= (char *) "";                // privileges for
    *thd->priv_host= '\0';                      // the user are unknown
    thd->master_access= ~NO_ACCESS;             // everything is allowed
unknown's avatar
merge  
unknown committed
732
    bzero((char*) mqh, sizeof(*mqh));
733
    DBUG_RETURN(0);
734
  }
735

unknown's avatar
unknown committed
736
  VOID(pthread_mutex_lock(&acl_cache->lock));
unknown's avatar
unknown committed
737

unknown's avatar
unknown committed
738
  /*
739 740 741
    Find acl entry in user database. Note, that find_acl_user is not the same,
    because it doesn't take into account the case when user is not empty,
    but acl_user->user is empty
unknown's avatar
unknown committed
742
  */
unknown's avatar
unknown committed
743

744
  for (uint i=0 ; i < acl_users.elements ; i++)
745
  {
unknown's avatar
unknown committed
746 747
    ACL_USER *acl_user_tmp= dynamic_element(&acl_users,i,ACL_USER*);
    if (!acl_user_tmp->user || !strcmp(thd->user, acl_user_tmp->user))
unknown's avatar
unknown committed
748
    {
unknown's avatar
unknown committed
749
      if (compare_hostname(&acl_user_tmp->host, thd->host, thd->ip))
unknown's avatar
unknown committed
750
      {
751
        /* check password: it should be empty or valid */
unknown's avatar
unknown committed
752
        if (passwd_len == acl_user_tmp->salt_len)
unknown's avatar
unknown committed
753
        {
unknown's avatar
unknown committed
754
          if (acl_user_tmp->salt_len == 0 ||
unknown's avatar
unknown committed
755 756
              (acl_user_tmp->salt_len == SCRAMBLE_LENGTH ?
              check_scramble(passwd, thd->scramble, acl_user_tmp->salt) :
757
              check_scramble_323(passwd, thd->scramble,
unknown's avatar
unknown committed
758
                                 (ulong *) acl_user_tmp->salt)) == 0)
759
          {
unknown's avatar
unknown committed
760
            acl_user= acl_user_tmp;
761 762
            res= 0;
          }
unknown's avatar
unknown committed
763
        }
764
        else if (passwd_len == SCRAMBLE_LENGTH &&
unknown's avatar
unknown committed
765
                 acl_user_tmp->salt_len == SCRAMBLE_LENGTH_323)
766
          res= -1;
unknown's avatar
unknown committed
767
        else if (passwd_len == SCRAMBLE_LENGTH_323 &&
unknown's avatar
unknown committed
768
                 acl_user_tmp->salt_len == SCRAMBLE_LENGTH)
unknown's avatar
unknown committed
769
          res= 2;
770 771
        /* linear search complete: */
        break;
unknown's avatar
unknown committed
772
      }
unknown's avatar
unknown committed
773
    }
774
  }
775 776 777 778
  /*
    This was moved to separate tree because of heavy HAVE_OPENSSL case.
    If acl_user is not null, res is 0.
  */
unknown's avatar
unknown committed
779 780 781

  if (acl_user)
  {
782
    /* OK. User found and password checked continue validation */
783
#ifdef HAVE_OPENSSL
unknown's avatar
unknown committed
784
    Vio *vio=thd->net.vio;
unknown's avatar
unknown committed
785
    SSL *ssl= (SSL*) vio->ssl_arg;
786
#endif
unknown's avatar
merge  
unknown committed
787

788
    /*
unknown's avatar
unknown committed
789
      At this point we know that user is allowed to connect
790 791 792 793 794 795
      from given host by given username/password pair. Now
      we check if SSL is required, if user is using SSL and
      if X509 certificate attributes are OK
    */
    switch (acl_user->ssl_type) {
    case SSL_TYPE_NOT_SPECIFIED:		// Impossible
unknown's avatar
merge  
unknown committed
796 797
    case SSL_TYPE_NONE:				// SSL is not required
      user_access= acl_user->access;
798
      break;
799
#ifdef HAVE_OPENSSL
unknown's avatar
merge  
unknown committed
800
    case SSL_TYPE_ANY:				// Any kind of SSL is ok
801
      if (vio_type(vio) == VIO_TYPE_SSL)
unknown's avatar
merge  
unknown committed
802
	user_access= acl_user->access;
803 804 805 806 807
      break;
    case SSL_TYPE_X509: /* Client should have any valid certificate. */
      /*
	Connections with non-valid certificates are dropped already
	in sslaccept() anyway, so we do not check validity here.
unknown's avatar
merge  
unknown committed
808

unknown's avatar
unknown committed
809 810
	We need to check for absence of SSL because without SSL
	we should reject connection.
811
      */
unknown's avatar
unknown committed
812
      if (vio_type(vio) == VIO_TYPE_SSL &&
unknown's avatar
unknown committed
813 814
	  SSL_get_verify_result(ssl) == X509_V_OK &&
	  SSL_get_peer_certificate(ssl))
unknown's avatar
merge  
unknown committed
815
	user_access= acl_user->access;
816 817 818 819 820 821 822 823
      break;
    case SSL_TYPE_SPECIFIED: /* Client should have specified attrib */
      /*
	We do not check for absence of SSL because without SSL it does
	not pass all checks here anyway.
	If cipher name is specified, we compare it to actual cipher in
	use.
      */
unknown's avatar
unknown committed
824
      X509 *cert;
unknown's avatar
unknown committed
825
      if (vio_type(vio) != VIO_TYPE_SSL ||
unknown's avatar
unknown committed
826
	  SSL_get_verify_result(ssl) != X509_V_OK)
unknown's avatar
unknown committed
827
	break;
828
      if (acl_user->ssl_cipher)
unknown's avatar
unknown committed
829
      {
830
	DBUG_PRINT("info",("comparing ciphers: '%s' and '%s'",
unknown's avatar
unknown committed
831 832
			   acl_user->ssl_cipher,SSL_get_cipher(ssl)));
	if (!strcmp(acl_user->ssl_cipher,SSL_get_cipher(ssl)))
unknown's avatar
merge  
unknown committed
833
	  user_access= acl_user->access;
834 835
	else
	{
unknown's avatar
unknown committed
836
	  if (global_system_variables.log_warnings)
unknown's avatar
unknown committed
837 838 839
	    sql_print_information("X509 ciphers mismatch: should be '%s' but is '%s'",
			      acl_user->ssl_cipher,
			      SSL_get_cipher(ssl));
840 841
	  break;
	}
unknown's avatar
unknown committed
842
      }
843 844
      /* Prepare certificate (if exists) */
      DBUG_PRINT("info",("checkpoint 1"));
unknown's avatar
unknown committed
845 846 847 848 849
      if (!(cert= SSL_get_peer_certificate(ssl)))
      {
	user_access=NO_ACCESS;
	break;
      }
850
      DBUG_PRINT("info",("checkpoint 2"));
851
      /* If X509 issuer is specified, we check it... */
852
      if (acl_user->x509_issuer)
unknown's avatar
unknown committed
853
      {
unknown's avatar
unknown committed
854
        DBUG_PRINT("info",("checkpoint 3"));
855 856 857
	char *ptr = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
	DBUG_PRINT("info",("comparing issuers: '%s' and '%s'",
			   acl_user->x509_issuer, ptr));
unknown's avatar
unknown committed
858
        if (strcmp(acl_user->x509_issuer, ptr))
859
        {
unknown's avatar
unknown committed
860
          if (global_system_variables.log_warnings)
unknown's avatar
unknown committed
861 862
            sql_print_information("X509 issuer mismatch: should be '%s' "
			      "but is '%s'", acl_user->x509_issuer, ptr);
863
          free(ptr);
unknown's avatar
unknown committed
864
          break;
865
        }
unknown's avatar
merge  
unknown committed
866
        user_access= acl_user->access;
unknown's avatar
unknown committed
867
        free(ptr);
unknown's avatar
unknown committed
868
      }
869 870 871 872
      DBUG_PRINT("info",("checkpoint 4"));
      /* X509 subject is specified, we check it .. */
      if (acl_user->x509_subject)
      {
unknown's avatar
unknown committed
873 874 875 876
        char *ptr= X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
        DBUG_PRINT("info",("comparing subjects: '%s' and '%s'",
                           acl_user->x509_subject, ptr));
        if (strcmp(acl_user->x509_subject,ptr))
877
        {
unknown's avatar
unknown committed
878
          if (global_system_variables.log_warnings)
unknown's avatar
unknown committed
879
            sql_print_information("X509 subject mismatch: '%s' vs '%s'",
unknown's avatar
unknown committed
880
                            acl_user->x509_subject, ptr);
881
        }
unknown's avatar
unknown committed
882
        else
unknown's avatar
merge  
unknown committed
883
          user_access= acl_user->access;
unknown's avatar
unknown committed
884
        free(ptr);
885 886
      }
      break;
unknown's avatar
unknown committed
887
#else  /* HAVE_OPENSSL */
unknown's avatar
unknown committed
888
    default:
889
      /*
unknown's avatar
unknown committed
890 891 892
        If we don't have SSL but SSL is required for this user the 
        authentication should fail.
      */
893 894
      break;
#endif /* HAVE_OPENSSL */
unknown's avatar
unknown committed
895
    }
unknown's avatar
merge  
unknown committed
896
    thd->master_access= user_access;
897 898
    thd->priv_user= acl_user->user ? thd->user : (char *) "";
    *mqh= acl_user->user_resource;
899

900 901 902 903 904
    if (acl_user->host.hostname)
      strmake(thd->priv_host, acl_user->host.hostname, MAX_HOSTNAME);
    else
      *thd->priv_host= 0;
  }
unknown's avatar
unknown committed
905
  VOID(pthread_mutex_unlock(&acl_cache->lock));
906
  DBUG_RETURN(res);
unknown's avatar
unknown committed
907 908 909
}


910 911 912
/*
 * This is like acl_getroot() above, but it doesn't check password,
 * and we don't care about the user resources.
913
 * Used to get access rights for SQL SECURITY DEFINER invocation of
914 915 916 917 918
 * stored procedures.
 */
int acl_getroot_no_password(THD *thd)
{
  int res= 1;
919
  uint i;
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
  ACL_USER *acl_user= 0;
  DBUG_ENTER("acl_getroot_no_password");

  if (!initialized)
  {
    /* 
      here if mysqld's been started with --skip-grant-tables option.
    */
    thd->priv_user= (char *) "";                // privileges for
    *thd->priv_host= '\0';                      // the user are unknown
    thd->master_access= ~NO_ACCESS;             // everything is allowed
    DBUG_RETURN(0);
  }

  VOID(pthread_mutex_lock(&acl_cache->lock));

936 937 938
  thd->master_access= 0;
  thd->db_access= 0;

939 940 941 942 943 944
  /*
     Find acl entry in user database.
     This is specially tailored to suit the check we do for CALL of
     a stored procedure; thd->user is set to what is actually a
     priv_user, which can be ''.
  */
945
  for (i=0 ; i < acl_users.elements ; i++)
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
  {
    acl_user= dynamic_element(&acl_users,i,ACL_USER*);
    if ((!acl_user->user && (!thd->user || !thd->user[0])) ||
	(acl_user->user && strcmp(thd->user, acl_user->user) == 0))
    {
      if (compare_hostname(&acl_user->host, thd->host, thd->ip))
      {
	res= 0;
	break;
      }
    }
  }

  if (acl_user)
  {
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
    for (i=0 ; i < acl_dbs.elements ; i++)
    {
      ACL_DB *acl_db= dynamic_element(&acl_dbs, i, ACL_DB*);
      if (!acl_db->user ||
	  (thd->user && thd->user[0] && !strcmp(thd->user, acl_db->user)))
      {
	if (compare_hostname(&acl_db->host, thd->host, thd->ip))
	{
	  if (!acl_db->db || (thd->db && !strcmp(acl_db->db, thd->db)))
	  {
	    thd->db_access= acl_db->access;
	    break;
	  }
	}
      }
    }
977 978 979 980 981 982 983 984 985 986 987 988
    thd->master_access= acl_user->access;
    thd->priv_user= acl_user->user ? thd->user : (char *) "";

    if (acl_user->host.hostname)
      strmake(thd->priv_host, acl_user->host.hostname, MAX_HOSTNAME);
    else
      *thd->priv_host= 0;
  }
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  DBUG_RETURN(res);
}

unknown's avatar
unknown committed
989 990 991 992 993 994 995
static byte* check_get_key(ACL_USER *buff,uint *length,
			   my_bool not_used __attribute__((unused)))
{
  *length=buff->hostname_length;
  return (byte*) buff->host.hostname;
}

996

unknown's avatar
unknown committed
997
static void acl_update_user(const char *user, const char *host,
998
			    const char *password, uint password_len,
999 1000 1001 1002
			    enum SSL_type ssl_type,
			    const char *ssl_cipher,
			    const char *x509_issuer,
			    const char *x509_subject,
unknown's avatar
unknown committed
1003
			    USER_RESOURCES  *mqh,
unknown's avatar
unknown committed
1004
			    ulong privileges)
unknown's avatar
unknown committed
1005 1006 1007 1008 1009 1010 1011 1012 1013
{
  for (uint i=0 ; i < acl_users.elements ; i++)
  {
    ACL_USER *acl_user=dynamic_element(&acl_users,i,ACL_USER*);
    if (!acl_user->user && !user[0] ||
	acl_user->user &&
	!strcmp(user,acl_user->user))
    {
      if (!acl_user->host.hostname && !host[0] ||
unknown's avatar
unknown committed
1014
	  acl_user->host.hostname &&
1015
	  !my_strcasecmp(system_charset_info, host, acl_user->host.hostname))
unknown's avatar
unknown committed
1016 1017
      {
	acl_user->access=privileges;
1018
	if (mqh->specified_limits & USER_RESOURCES::QUERIES_PER_HOUR)
1019
	  acl_user->user_resource.questions=mqh->questions;
1020
	if (mqh->specified_limits & USER_RESOURCES::UPDATES_PER_HOUR)
1021
	  acl_user->user_resource.updates=mqh->updates;
1022 1023 1024 1025
	if (mqh->specified_limits & USER_RESOURCES::CONNECTIONS_PER_HOUR)
	  acl_user->user_resource.conn_per_hour= mqh->conn_per_hour;
	if (mqh->specified_limits & USER_RESOURCES::USER_CONNECTIONS)
	  acl_user->user_resource.user_conn= mqh->user_conn;
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
	if (ssl_type != SSL_TYPE_NOT_SPECIFIED)
	{
	  acl_user->ssl_type= ssl_type;
	  acl_user->ssl_cipher= (ssl_cipher ? strdup_root(&mem,ssl_cipher) :
				 0);
	  acl_user->x509_issuer= (x509_issuer ? strdup_root(&mem,x509_issuer) :
				  0);
	  acl_user->x509_subject= (x509_subject ?
				   strdup_root(&mem,x509_subject) : 0);
	}
unknown's avatar
unknown committed
1036 1037
	if (password)
	  set_user_salt(acl_user, password, password_len);
1038
        /* search complete: */
unknown's avatar
unknown committed
1039 1040 1041 1042 1043 1044 1045 1046
	break;
      }
    }
  }
}


static void acl_insert_user(const char *user, const char *host,
1047
			    const char *password, uint password_len,
1048 1049 1050 1051
			    enum SSL_type ssl_type,
			    const char *ssl_cipher,
			    const char *x509_issuer,
			    const char *x509_subject,
1052
			    USER_RESOURCES *mqh,
unknown's avatar
unknown committed
1053
			    ulong privileges)
unknown's avatar
unknown committed
1054 1055
{
  ACL_USER acl_user;
1056
  acl_user.user=*user ? strdup_root(&mem,user) : 0;
unknown's avatar
unknown committed
1057
  update_hostname(&acl_user.host, *host ? strdup_root(&mem, host): 0);
unknown's avatar
unknown committed
1058
  acl_user.access=privileges;
1059
  acl_user.user_resource = *mqh;
unknown's avatar
unknown committed
1060
  acl_user.sort=get_sort(2,acl_user.host.hostname,acl_user.user);
1061
  acl_user.hostname_length=(uint) strlen(host);
1062 1063 1064 1065 1066
  acl_user.ssl_type= (ssl_type != SSL_TYPE_NOT_SPECIFIED ?
		      ssl_type : SSL_TYPE_NONE);
  acl_user.ssl_cipher=	ssl_cipher   ? strdup_root(&mem,ssl_cipher) : 0;
  acl_user.x509_issuer= x509_issuer  ? strdup_root(&mem,x509_issuer) : 0;
  acl_user.x509_subject=x509_subject ? strdup_root(&mem,x509_subject) : 0;
1067 1068

  set_user_salt(&acl_user, password, password_len);
unknown's avatar
unknown committed
1069 1070 1071 1072

  VOID(push_dynamic(&acl_users,(gptr) &acl_user));
  if (!acl_user.host.hostname || acl_user.host.hostname[0] == wild_many
      && !acl_user.host.hostname[1])
unknown's avatar
unknown committed
1073
    allow_all_hosts=1;		// Anyone can connect /* purecov: tested */
unknown's avatar
unknown committed
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
  qsort((gptr) dynamic_element(&acl_users,0,ACL_USER*),acl_users.elements,
	sizeof(ACL_USER),(qsort_cmp) acl_compare);

  /* We must free acl_check_hosts as its memory is mapped to acl_user */
  delete_dynamic(&acl_wild_hosts);
  hash_free(&acl_check_hosts);
  init_check_host();
}


static void acl_update_db(const char *user, const char *host, const char *db,
unknown's avatar
unknown committed
1085
			  ulong privileges)
unknown's avatar
unknown committed
1086 1087 1088 1089 1090 1091 1092 1093 1094
{
  for (uint i=0 ; i < acl_dbs.elements ; i++)
  {
    ACL_DB *acl_db=dynamic_element(&acl_dbs,i,ACL_DB*);
    if (!acl_db->user && !user[0] ||
	acl_db->user &&
	!strcmp(user,acl_db->user))
    {
      if (!acl_db->host.hostname && !host[0] ||
1095
	  acl_db->host.hostname &&
1096
	  !my_strcasecmp(system_charset_info, host, acl_db->host.hostname))
unknown's avatar
unknown committed
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
      {
	if (!acl_db->db && !db[0] ||
	    acl_db->db && !strcmp(db,acl_db->db))
	{
	  if (privileges)
	    acl_db->access=privileges;
	  else
	    delete_dynamic_element(&acl_dbs,i);
	}
      }
    }
  }
}


1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
/*
  Insert a user/db/host combination into the global acl_cache

  SYNOPSIS
    acl_insert_db()
    user		User name
    host		Host name
    db			Database name
    privileges		Bitmap of privileges

  NOTES
    acl_cache->lock must be locked when calling this
*/

unknown's avatar
unknown committed
1126
static void acl_insert_db(const char *user, const char *host, const char *db,
unknown's avatar
unknown committed
1127
			  ulong privileges)
unknown's avatar
unknown committed
1128 1129
{
  ACL_DB acl_db;
1130
  safe_mutex_assert_owner(&acl_cache->lock);
unknown's avatar
unknown committed
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
  acl_db.user=strdup_root(&mem,user);
  update_hostname(&acl_db.host,strdup_root(&mem,host));
  acl_db.db=strdup_root(&mem,db);
  acl_db.access=privileges;
  acl_db.sort=get_sort(3,acl_db.host.hostname,acl_db.db,acl_db.user);
  VOID(push_dynamic(&acl_dbs,(gptr) &acl_db));
  qsort((gptr) dynamic_element(&acl_dbs,0,ACL_DB*),acl_dbs.elements,
	sizeof(ACL_DB),(qsort_cmp) acl_compare);
}


1142 1143 1144

/*
  Get privilege for a host, user and db combination
1145 1146 1147

  as db_is_pattern changes the semantics of comparison,
  acl_cache is not used if db_is_pattern is set.
1148
*/
unknown's avatar
unknown committed
1149

1150
ulong acl_get(const char *host, const char *ip,
1151
              const char *user, const char *db, my_bool db_is_pattern)
unknown's avatar
unknown committed
1152
{
1153
  ulong host_access= ~(ulong)0, db_access= 0;
unknown's avatar
unknown committed
1154
  uint i,key_length;
unknown's avatar
unknown committed
1155
  char key[ACL_KEY_LENGTH],*tmp_db,*end;
unknown's avatar
unknown committed
1156
  acl_entry *entry;
unknown's avatar
unknown committed
1157
  DBUG_ENTER("acl_get");
unknown's avatar
unknown committed
1158 1159

  VOID(pthread_mutex_lock(&acl_cache->lock));
1160
  end=strmov((tmp_db=strmov(strmov(key, ip ? ip : "")+1,user)+1),db);
unknown's avatar
unknown committed
1161 1162
  if (lower_case_table_names)
  {
1163
    my_casedn_str(files_charset_info, tmp_db);
unknown's avatar
unknown committed
1164 1165
    db=tmp_db;
  }
unknown's avatar
unknown committed
1166
  key_length=(uint) (end-key);
1167
  if (!db_is_pattern && (entry=(acl_entry*) acl_cache->search(key,key_length)))
unknown's avatar
unknown committed
1168 1169 1170
  {
    db_access=entry->access;
    VOID(pthread_mutex_unlock(&acl_cache->lock));
unknown's avatar
unknown committed
1171 1172
    DBUG_PRINT("exit", ("access: 0x%lx", db_access));
    DBUG_RETURN(db_access);
unknown's avatar
unknown committed
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
  }

  /*
    Check if there are some access rights for database and user
  */
  for (i=0 ; i < acl_dbs.elements ; i++)
  {
    ACL_DB *acl_db=dynamic_element(&acl_dbs,i,ACL_DB*);
    if (!acl_db->user || !strcmp(user,acl_db->user))
    {
      if (compare_hostname(&acl_db->host,host,ip))
      {
1185
	if (!acl_db->db || !wild_compare(db,acl_db->db,db_is_pattern))
unknown's avatar
unknown committed
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
	{
	  db_access=acl_db->access;
	  if (acl_db->host.hostname)
	    goto exit;				// Fully specified. Take it
	  break; /* purecov: tested */
	}
      }
    }
  }
  if (!db_access)
    goto exit;					// Can't be better

  /*
    No host specified for user. Get hostdata from host table
  */
  host_access=0;				// Host must be found
  for (i=0 ; i < acl_hosts.elements ; i++)
  {
    ACL_HOST *acl_host=dynamic_element(&acl_hosts,i,ACL_HOST*);
    if (compare_hostname(&acl_host->host,host,ip))
    {
1207
      if (!acl_host->db || !wild_compare(db,acl_host->db,db_is_pattern))
unknown's avatar
unknown committed
1208 1209 1210 1211 1212 1213 1214 1215
      {
	host_access=acl_host->access;		// Fully specified. Take it
	break;
      }
    }
  }
exit:
  /* Save entry in cache for quick retrieval */
1216 1217
  if (!db_is_pattern &&
      (entry= (acl_entry*) malloc(sizeof(acl_entry)+key_length)))
unknown's avatar
unknown committed
1218 1219 1220 1221 1222 1223 1224
  {
    entry->access=(db_access & host_access);
    entry->length=key_length;
    memcpy((gptr) entry->key,key,key_length);
    acl_cache->add(entry);
  }
  VOID(pthread_mutex_unlock(&acl_cache->lock));
unknown's avatar
unknown committed
1225 1226
  DBUG_PRINT("exit", ("access: 0x%lx", db_access & host_access));
  DBUG_RETURN(db_access & host_access);
unknown's avatar
unknown committed
1227 1228
}

1229 1230 1231 1232 1233 1234 1235
/*
  Check if there are any possible matching entries for this host

  NOTES
    All host names without wild cards are stored in a hash table,
    entries with wildcards are stored in a dynamic array
*/
unknown's avatar
unknown committed
1236 1237 1238 1239

static void init_check_host(void)
{
  DBUG_ENTER("init_check_host");
1240
  VOID(my_init_dynamic_array(&acl_wild_hosts,sizeof(struct acl_host_and_ip),
unknown's avatar
unknown committed
1241
			  acl_users.elements,1));
1242
  VOID(hash_init(&acl_check_hosts,system_charset_info,acl_users.elements,0,0,
unknown's avatar
unknown committed
1243
		 (hash_get_key) check_get_key,0,0));
unknown's avatar
unknown committed
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
  if (!allow_all_hosts)
  {
    for (uint i=0 ; i < acl_users.elements ; i++)
    {
      ACL_USER *acl_user=dynamic_element(&acl_users,i,ACL_USER*);
      if (strchr(acl_user->host.hostname,wild_many) ||
	  strchr(acl_user->host.hostname,wild_one) ||
	  acl_user->host.ip_mask)
      {						// Has wildcard
	uint j;
	for (j=0 ; j < acl_wild_hosts.elements ; j++)
	{					// Check if host already exists
	  acl_host_and_ip *acl=dynamic_element(&acl_wild_hosts,j,
					       acl_host_and_ip *);
1258
	  if (!my_strcasecmp(system_charset_info,
1259
                             acl_user->host.hostname, acl->hostname))
unknown's avatar
unknown committed
1260 1261 1262 1263 1264 1265
	    break;				// already stored
	}
	if (j == acl_wild_hosts.elements)	// If new
	  (void) push_dynamic(&acl_wild_hosts,(char*) &acl_user->host);
      }
      else if (!hash_search(&acl_check_hosts,(byte*) &acl_user->host,
unknown's avatar
unknown committed
1266
			    (uint) strlen(acl_user->host.hostname)))
unknown's avatar
unknown committed
1267
      {
unknown's avatar
SCRUM  
unknown committed
1268
	if (my_hash_insert(&acl_check_hosts,(byte*) acl_user))
unknown's avatar
unknown committed
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
	{					// End of memory
	  allow_all_hosts=1;			// Should never happen
	  DBUG_VOID_RETURN;
	}
      }
    }
  }
  freeze_size(&acl_wild_hosts);
  freeze_size(&acl_check_hosts.array);
  DBUG_VOID_RETURN;
}


/* Return true if there is no users that can match the given host */

bool acl_check_host(const char *host, const char *ip)
{
  if (allow_all_hosts)
    return 0;
  VOID(pthread_mutex_lock(&acl_cache->lock));

unknown's avatar
unknown committed
1290 1291
  if (host && hash_search(&acl_check_hosts,(byte*) host,(uint) strlen(host)) ||
      ip && hash_search(&acl_check_hosts,(byte*) ip,(uint) strlen(ip)))
unknown's avatar
unknown committed
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
  {
    VOID(pthread_mutex_unlock(&acl_cache->lock));
    return 0;					// Found host
  }
  for (uint i=0 ; i < acl_wild_hosts.elements ; i++)
  {
    acl_host_and_ip *acl=dynamic_element(&acl_wild_hosts,i,acl_host_and_ip*);
    if (compare_hostname(acl, host, ip))
    {
      VOID(pthread_mutex_unlock(&acl_cache->lock));
      return 0;					// Host ok
    }
  }
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  return 1;					// Host is not allowed
}


unknown's avatar
unknown committed
1310 1311 1312 1313 1314 1315 1316 1317
/*
  Check if the user is allowed to change password

  SYNOPSIS:
    check_change_password()
    thd		THD
    host	hostname for the user
    user	user name
1318 1319 1320 1321
    new_password new password

  NOTE:
    new_password cannot be NULL
unknown's avatar
merge  
unknown committed
1322

unknown's avatar
unknown committed
1323
    RETURN VALUE
1324 1325
      0		OK
      1		ERROR  ; In this case the error is sent to the client.
unknown's avatar
unknown committed
1326 1327
*/

1328
bool check_change_password(THD *thd, const char *host, const char *user,
1329
                           char *new_password, uint new_password_len)
unknown's avatar
unknown committed
1330
{
unknown's avatar
unknown committed
1331 1332
  if (!initialized)
  {
unknown's avatar
unknown committed
1333
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
1334
    return(1);
unknown's avatar
unknown committed
1335
  }
unknown's avatar
unknown committed
1336 1337
  if (!thd->slave_thread &&
      (strcmp(thd->user,user) ||
1338
       my_strcasecmp(system_charset_info, host, thd->priv_host)))
unknown's avatar
unknown committed
1339
  {
unknown's avatar
unknown committed
1340
    if (check_access(thd, UPDATE_ACL, "mysql",0,1,0))
unknown's avatar
unknown committed
1341
      return(1);
unknown's avatar
unknown committed
1342
  }
unknown's avatar
unknown committed
1343 1344
  if (!thd->slave_thread && !thd->user[0])
  {
unknown's avatar
unknown committed
1345 1346
    my_message(ER_PASSWORD_ANONYMOUS_USER, ER(ER_PASSWORD_ANONYMOUS_USER),
               MYF(0));
unknown's avatar
unknown committed
1347
    return(1);
unknown's avatar
unknown committed
1348
  }
1349
  uint len=strlen(new_password);
unknown's avatar
unknown committed
1350
  if (len && len != SCRAMBLED_PASSWORD_CHAR_LENGTH &&
1351 1352
      len != SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
  {
unknown's avatar
unknown committed
1353
    my_error(ER_PASSWD_LENGTH, MYF(0), SCRAMBLED_PASSWORD_CHAR_LENGTH);
1354 1355
    return -1;
  }
unknown's avatar
unknown committed
1356 1357 1358 1359
  return(0);
}


1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
/*
  Change a password for a user

  SYNOPSIS
    change_password()
    thd			Thread handle
    host		Hostname
    user		User name
    new_password	New password for host@user

  RETURN VALUES
    0	ok
    1	ERROR; In this case the error is sent to the client.
unknown's avatar
unknown committed
1373
*/
1374

unknown's avatar
unknown committed
1375 1376 1377
bool change_password(THD *thd, const char *host, const char *user,
		     char *new_password)
{
1378 1379 1380 1381 1382
  TABLE_LIST tables;
  TABLE *table;
  /* Buffer should be extended when password length is extended. */
  char buff[512];
  ulong query_length;
1383
  uint new_password_len= strlen(new_password);
1384
  bool result= 1;
unknown's avatar
unknown committed
1385 1386 1387 1388 1389
  DBUG_ENTER("change_password");
  DBUG_PRINT("enter",("host: '%s'  user: '%s'  new_password: '%s'",
		      host,user,new_password));
  DBUG_ASSERT(host != 0);			// Ensured by parent

1390
  if (check_change_password(thd, host, user, new_password, new_password_len))
unknown's avatar
unknown committed
1391 1392
    DBUG_RETURN(1);

1393
  bzero((char*) &tables, sizeof(tables));
1394
  tables.alias= tables.table_name= (char*) "user";
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
  tables.db= (char*) "mysql";

#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
  if (thd->slave_thread && table_rules_on)
  {
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.  It's ok to leave 'updating' set after tables_ok.
    */
    tables.updating= 1;
    /* Thanks to bzero, tables.next==0 */
1410
    if (!tables_ok(thd, &tables))
1411 1412 1413 1414 1415 1416 1417
      DBUG_RETURN(0);
  }
#endif

  if (!(table= open_ltable(thd, &tables, TL_WRITE)))
    DBUG_RETURN(1);

unknown's avatar
unknown committed
1418 1419
  VOID(pthread_mutex_lock(&acl_cache->lock));
  ACL_USER *acl_user;
1420
  if (!(acl_user= find_acl_user(host, user, TRUE)))
unknown's avatar
unknown committed
1421 1422
  {
    VOID(pthread_mutex_unlock(&acl_cache->lock));
unknown's avatar
unknown committed
1423
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH), MYF(0));
1424
    goto end;
unknown's avatar
unknown committed
1425
  }
1426 1427 1428
  /* update loaded acl entry: */
  set_user_salt(acl_user, new_password, new_password_len);

1429
  if (update_user_table(thd, table,
unknown's avatar
unknown committed
1430
			acl_user->host.hostname ? acl_user->host.hostname : "",
unknown's avatar
unknown committed
1431
			acl_user->user ? acl_user->user : "",
1432
			new_password, new_password_len))
unknown's avatar
unknown committed
1433 1434
  {
    VOID(pthread_mutex_unlock(&acl_cache->lock)); /* purecov: deadcode */
1435
    goto end;
unknown's avatar
unknown committed
1436
  }
unknown's avatar
unknown committed
1437

unknown's avatar
unknown committed
1438 1439
  acl_cache->clear(1);				// Clear locked hostname cache
  VOID(pthread_mutex_unlock(&acl_cache->lock));
1440 1441 1442
  result= 0;
  if (mysql_bin_log.is_open())
  {
1443 1444 1445 1446 1447 1448
    query_length=
      my_sprintf(buff,
                 (buff,"SET PASSWORD FOR \"%-.120s\"@\"%-.120s\"=\"%-.120s\"",
                  acl_user->user ? acl_user->user : "",
                  acl_user->host.hostname ? acl_user->host.hostname : "",
                  new_password));
1449 1450 1451 1452 1453 1454 1455
    thd->clear_error();
    Query_log_event qinfo(thd, buff, query_length, 0, FALSE);
    mysql_bin_log.write(&qinfo);
  }
end:
  close_thread_tables(thd);
  DBUG_RETURN(result);
unknown's avatar
unknown committed
1456 1457 1458
}


1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
/*
  Find user in ACL

  SYNOPSIS
    is_acl_user()
    host                 host name
    user                 user name

  RETURN
   FALSE  user not fond
   TRUE   there are such user
*/

bool is_acl_user(const char *host, const char *user)
{
  bool res;
  VOID(pthread_mutex_lock(&acl_cache->lock));
  res= find_acl_user(host, user, TRUE);
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  return res;
}


unknown's avatar
unknown committed
1482 1483 1484 1485 1486
/*
  Find first entry that matches the current user
*/

static ACL_USER *
1487
find_acl_user(const char *host, const char *user, my_bool exact)
unknown's avatar
unknown committed
1488
{
unknown's avatar
unknown committed
1489
  DBUG_ENTER("find_acl_user");
1490
  DBUG_PRINT("enter",("host: '%s'  user: '%s'",host,user));
unknown's avatar
unknown committed
1491 1492 1493
  for (uint i=0 ; i < acl_users.elements ; i++)
  {
    ACL_USER *acl_user=dynamic_element(&acl_users,i,ACL_USER*);
unknown's avatar
unknown committed
1494
    DBUG_PRINT("info",("strcmp('%s','%s'), compare_hostname('%s','%s'),",
1495 1496 1497 1498 1499
		       user,
		       acl_user->user ? acl_user->user : "",
		       host,
		       acl_user->host.hostname ? acl_user->host.hostname :
		       ""));
unknown's avatar
unknown committed
1500 1501 1502
    if (!acl_user->user && !user[0] ||
	acl_user->user && !strcmp(user,acl_user->user))
    {
1503 1504 1505
      if (exact ? !my_strcasecmp(&my_charset_latin1, host,
                                 acl_user->host.hostname) :
          compare_hostname(&acl_user->host,host,host))
unknown's avatar
unknown committed
1506 1507 1508
      {
	DBUG_RETURN(acl_user);
      }
unknown's avatar
unknown committed
1509 1510
    }
  }
unknown's avatar
unknown committed
1511
  DBUG_RETURN(0);
unknown's avatar
unknown committed
1512 1513 1514
}


1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
/*
  Comparing of hostnames

  NOTES
  A hostname may be of type:
  hostname   (May include wildcards);   monty.pp.sci.fi
  ip	   (May include wildcards);   192.168.0.0
  ip/netmask			      192.168.0.0/255.255.255.0

  A net mask of 0.0.0.0 is not allowed.
*/
unknown's avatar
unknown committed
1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548

static const char *calc_ip(const char *ip, long *val, char end)
{
  long ip_val,tmp;
  if (!(ip=str2int(ip,10,0,255,&ip_val)) || *ip != '.')
    return 0;
  ip_val<<=24;
  if (!(ip=str2int(ip+1,10,0,255,&tmp)) || *ip != '.')
    return 0;
  ip_val+=tmp<<16;
  if (!(ip=str2int(ip+1,10,0,255,&tmp)) || *ip != '.')
    return 0;
  ip_val+=tmp<<8;
  if (!(ip=str2int(ip+1,10,0,255,&tmp)) || *ip != end)
    return 0;
  *val=ip_val+tmp;
  return ip;
}


static void update_hostname(acl_host_and_ip *host, const char *hostname)
{
  host->hostname=(char*) hostname;		// This will not be modified!
1549
  if (!hostname ||
unknown's avatar
unknown committed
1550 1551 1552
      (!(hostname=calc_ip(hostname,&host->ip,'/')) ||
       !(hostname=calc_ip(hostname+1,&host->ip_mask,'\0'))))
  {
1553
    host->ip= host->ip_mask=0;			// Not a masked ip
unknown's avatar
unknown committed
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
  }
}


static bool compare_hostname(const acl_host_and_ip *host, const char *hostname,
			     const char *ip)
{
  long tmp;
  if (host->ip_mask && ip && calc_ip(ip,&tmp,'\0'))
  {
    return (tmp & host->ip_mask) == host->ip;
  }
  return (!host->hostname ||
1567
	  (hostname && !wild_case_compare(system_charset_info,
1568
                                          hostname,host->hostname)) ||
1569
	  (ip && !wild_compare(ip,host->hostname,0)));
unknown's avatar
unknown committed
1570 1571
}

unknown's avatar
SCRUM  
unknown committed
1572 1573 1574 1575
bool hostname_requires_resolving(const char *hostname)
{
  char cur;
  if (!hostname)
unknown's avatar
unknown committed
1576
    return FALSE;
unknown's avatar
SCRUM  
unknown committed
1577 1578 1579
  int namelen= strlen(hostname);
  int lhlen= strlen(my_localhost);
  if ((namelen == lhlen) &&
1580
      !my_strnncoll(system_charset_info, (const uchar *)hostname,  namelen,
unknown's avatar
SCRUM  
unknown committed
1581
		    (const uchar *)my_localhost, strlen(my_localhost)))
unknown's avatar
unknown committed
1582
    return FALSE;
unknown's avatar
SCRUM  
unknown committed
1583 1584
  for (; (cur=*hostname); hostname++)
  {
1585
    if ((cur != '%') && (cur != '_') && (cur != '.') && (cur != '/') &&
unknown's avatar
SCRUM  
unknown committed
1586
	((cur < '0') || (cur > '9')))
unknown's avatar
unknown committed
1587
      return TRUE;
unknown's avatar
SCRUM  
unknown committed
1588
  }
unknown's avatar
unknown committed
1589
  return FALSE;
unknown's avatar
SCRUM  
unknown committed
1590
}
unknown's avatar
unknown committed
1591

1592

1593
/*
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
  Update record for user in mysql.user privilege table with new password.

  SYNOPSIS
    update_user_table()
      thd               Thread handle
      table             Pointer to TABLE object for open mysql.user table
      host/user         Hostname/username pair identifying user for which
                        new password should be set
      new_password      New password
      new_password_len  Length of new password
1604
*/
unknown's avatar
unknown committed
1605

1606 1607
static bool update_user_table(THD *thd, TABLE *table,
                              const char *host, const char *user,
1608
			      const char *new_password, uint new_password_len)
unknown's avatar
unknown committed
1609
{
1610
  char user_key[MAX_KEY_LENGTH];
1611
  int error;
unknown's avatar
unknown committed
1612 1613 1614
  DBUG_ENTER("update_user_table");
  DBUG_PRINT("enter",("user: %s  host: %s",user,host));

1615 1616
  table->field[0]->store(host,(uint) strlen(host), system_charset_info);
  table->field[1]->store(user,(uint) strlen(user), system_charset_info);
unknown's avatar
unknown committed
1617
  key_copy((byte *) user_key, table->record[0], table->key_info,
1618
           table->key_info->key_length);
unknown's avatar
unknown committed
1619

1620
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
1621
  if (table->file->index_read_idx(table->record[0], 0,
unknown's avatar
unknown committed
1622
				  (byte *) user_key, table->key_info->key_length,
unknown's avatar
unknown committed
1623 1624
				  HA_READ_KEY_EXACT))
  {
unknown's avatar
unknown committed
1625 1626
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH),
               MYF(0));	/* purecov: deadcode */
unknown's avatar
unknown committed
1627 1628
    DBUG_RETURN(1);				/* purecov: deadcode */
  }
unknown's avatar
unknown committed
1629
  store_record(table,record[1]);
1630
  table->field[2]->store(new_password, new_password_len, system_charset_info);
unknown's avatar
unknown committed
1631 1632 1633
  if ((error=table->file->update_row(table->record[1],table->record[0])))
  {
    table->file->print_error(error,MYF(0));	/* purecov: deadcode */
1634
    DBUG_RETURN(1);
unknown's avatar
unknown committed
1635
  }
1636
  DBUG_RETURN(0);
unknown's avatar
unknown committed
1637 1638
}

unknown's avatar
unknown committed
1639

1640 1641 1642 1643 1644 1645
/*
  Return 1 if we are allowed to create new users
  the logic here is: INSERT_ACL is sufficient.
  It's also a requirement in opt_safe_user_create,
  otherwise CREATE_USER_ACL is enough.
*/
unknown's avatar
unknown committed
1646 1647 1648

static bool test_if_create_new_users(THD *thd)
{
1649 1650 1651 1652
  bool create_new_users= test(thd->master_access & INSERT_ACL) ||
                         (!opt_safe_user_create &&
                          test(thd->master_access & CREATE_USER_ACL));
  if (!create_new_users)
unknown's avatar
unknown committed
1653 1654
  {
    TABLE_LIST tl;
unknown's avatar
unknown committed
1655
    ulong db_access;
unknown's avatar
unknown committed
1656 1657
    bzero((char*) &tl,sizeof(tl));
    tl.db=	   (char*) "mysql";
1658
    tl.table_name=  (char*) "user";
1659
    create_new_users= 1;
unknown's avatar
unknown committed
1660

1661
    db_access=acl_get(thd->host, thd->ip,
1662
		      thd->priv_user, tl.db, 0);
unknown's avatar
unknown committed
1663 1664
    if (!(db_access & INSERT_ACL))
    {
unknown's avatar
unknown committed
1665
      if (check_grant(thd, INSERT_ACL, &tl, 0, UINT_MAX, 1))
unknown's avatar
unknown committed
1666 1667 1668 1669 1670 1671 1672
	create_new_users=0;
    }
  }
  return create_new_users;
}


unknown's avatar
unknown committed
1673
/****************************************************************************
1674
  Handle GRANT commands
unknown's avatar
unknown committed
1675 1676
****************************************************************************/

1677
static int replace_user_table(THD *thd, TABLE *table, const LEX_USER &combo,
unknown's avatar
unknown committed
1678
			      ulong rights, bool revoke_grant,
unknown's avatar
unknown committed
1679
			      bool can_create_user, bool no_auto_create)
unknown's avatar
unknown committed
1680 1681
{
  int error = -1;
unknown's avatar
unknown committed
1682
  bool old_row_exists=0;
1683
  const char *password= "";
1684
  uint password_len= 0;
unknown's avatar
unknown committed
1685
  char what= (revoke_grant) ? 'N' : 'Y';
1686
  byte user_key[MAX_KEY_LENGTH];
1687
  LEX *lex= thd->lex;
unknown's avatar
unknown committed
1688
  DBUG_ENTER("replace_user_table");
unknown's avatar
unknown committed
1689

1690
  safe_mutex_assert_owner(&acl_cache->lock);
unknown's avatar
unknown committed
1691 1692

  if (combo.password.str && combo.password.str[0])
1693
  {
1694 1695
    if (combo.password.length != SCRAMBLED_PASSWORD_CHAR_LENGTH &&
        combo.password.length != SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
1696
    {
1697
      my_error(ER_PASSWD_LENGTH, MYF(0), SCRAMBLED_PASSWORD_CHAR_LENGTH);
unknown's avatar
unknown committed
1698
      DBUG_RETURN(-1);
1699
    }
1700
    password_len= combo.password.length;
unknown's avatar
unknown committed
1701
    password=combo.password.str;
1702
  }
unknown's avatar
unknown committed
1703

1704 1705
  table->field[0]->store(combo.host.str,combo.host.length, system_charset_info);
  table->field[1]->store(combo.user.str,combo.user.length, system_charset_info);
1706 1707 1708
  key_copy(user_key, table->record[0], table->key_info,
           table->key_info->key_length);

1709
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
unknown's avatar
unknown committed
1710
  if (table->file->index_read_idx(table->record[0], 0,
1711 1712
                                  user_key, table->key_info->key_length,
                                  HA_READ_KEY_EXACT))
unknown's avatar
unknown committed
1713
  {
1714 1715
    /* what == 'N' means revoke */
    if (what == 'N')
unknown's avatar
unknown committed
1716
    {
1717 1718 1719 1720
      my_error(ER_NONEXISTING_GRANT, MYF(0), combo.user.str, combo.host.str);
      goto end;
    }
    /*
1721 1722
      There are four options which affect the process of creation of
      a new user (mysqld option --safe-create-user, 'insert' privilege
1723 1724 1725 1726 1727 1728 1729
      on 'mysql.user' table, using 'GRANT' with 'IDENTIFIED BY' and
      SQL_MODE flag NO_AUTO_CREATE_USER). Below is the simplified rule
      how it should work.
      if (safe-user-create && ! INSERT_priv) => reject
      else if (identified_by) => create
      else if (no_auto_create_user) => reject
      else create
1730 1731

      see also test_if_create_new_users()
1732
    */
unknown's avatar
unknown committed
1733 1734 1735 1736 1737 1738
    else if (!password_len && no_auto_create)
    {
      my_error(ER_PASSWORD_NO_MATCH, MYF(0), combo.user.str, combo.host.str);
      goto end;
    }
    else if (!can_create_user)
1739
    {
unknown's avatar
unknown committed
1740
      my_error(ER_CANT_CREATE_USER_WITH_GRANT, MYF(0),
1741
               thd->user, thd->host_or_ip);
unknown's avatar
unknown committed
1742 1743
      goto end;
    }
unknown's avatar
unknown committed
1744
    old_row_exists = 0;
1745
    restore_record(table,s->default_values);
1746
    table->field[0]->store(combo.host.str,combo.host.length,
1747
                           system_charset_info);
1748
    table->field[1]->store(combo.user.str,combo.user.length,
1749
                           system_charset_info);
1750
    table->field[2]->store(password, password_len,
1751
                           system_charset_info);
unknown's avatar
unknown committed
1752 1753 1754
  }
  else
  {
unknown's avatar
unknown committed
1755
    old_row_exists = 1;
unknown's avatar
unknown committed
1756
    store_record(table,record[1]);			// Save copy for update
unknown's avatar
unknown committed
1757
    if (combo.password.str)			// If password given
1758
      table->field[2]->store(password, password_len, system_charset_info);
1759
    else if (!rights && !revoke_grant &&
1760 1761
             lex->ssl_type == SSL_TYPE_NOT_SPECIFIED &&
             !lex->mqh.specified_limits)
unknown's avatar
unknown committed
1762 1763 1764
    {
      DBUG_RETURN(0);
    }
unknown's avatar
unknown committed
1765 1766
  }

unknown's avatar
unknown committed
1767 1768 1769 1770
  /* Update table columns with new privileges */

  Field **tmp_field;
  ulong priv;
1771
  uint next_field;
unknown's avatar
unknown committed
1772 1773 1774 1775
  for (tmp_field= table->field+3, priv = SELECT_ACL;
       *tmp_field && (*tmp_field)->real_type() == FIELD_TYPE_ENUM &&
	 ((Field_enum*) (*tmp_field))->typelib->count == 2 ;
       tmp_field++, priv <<= 1)
unknown's avatar
unknown committed
1776
  {
unknown's avatar
unknown committed
1777
    if (priv & rights)				 // set requested privileges
unknown's avatar
unknown committed
1778
      (*tmp_field)->store(&what, 1, &my_charset_latin1);
unknown's avatar
unknown committed
1779
  }
1780
  rights= get_access(table, 3, &next_field);
1781 1782
  DBUG_PRINT("info",("table fields: %d",table->s->fields));
  if (table->s->fields >= 31)		/* From 4.0.0 we have more fields */
1783
  {
unknown's avatar
unknown committed
1784
    /* We write down SSL related ACL stuff */
1785
    switch (lex->ssl_type) {
1786
    case SSL_TYPE_ANY:
1787 1788 1789 1790
      table->field[next_field]->store("ANY", 3, &my_charset_latin1);
      table->field[next_field+1]->store("", 0, &my_charset_latin1);
      table->field[next_field+2]->store("", 0, &my_charset_latin1);
      table->field[next_field+3]->store("", 0, &my_charset_latin1);
1791 1792
      break;
    case SSL_TYPE_X509:
1793 1794 1795 1796
      table->field[next_field]->store("X509", 4, &my_charset_latin1);
      table->field[next_field+1]->store("", 0, &my_charset_latin1);
      table->field[next_field+2]->store("", 0, &my_charset_latin1);
      table->field[next_field+3]->store("", 0, &my_charset_latin1);
1797 1798
      break;
    case SSL_TYPE_SPECIFIED:
1799 1800 1801 1802
      table->field[next_field]->store("SPECIFIED", 9, &my_charset_latin1);
      table->field[next_field+1]->store("", 0, &my_charset_latin1);
      table->field[next_field+2]->store("", 0, &my_charset_latin1);
      table->field[next_field+3]->store("", 0, &my_charset_latin1);
1803
      if (lex->ssl_cipher)
unknown's avatar
unknown committed
1804 1805
        table->field[next_field+1]->store(lex->ssl_cipher,
                                strlen(lex->ssl_cipher), system_charset_info);
1806
      if (lex->x509_issuer)
unknown's avatar
unknown committed
1807 1808
        table->field[next_field+2]->store(lex->x509_issuer,
                                strlen(lex->x509_issuer), system_charset_info);
1809
      if (lex->x509_subject)
unknown's avatar
unknown committed
1810 1811
        table->field[next_field+3]->store(lex->x509_subject,
                                strlen(lex->x509_subject), system_charset_info);
1812
      break;
unknown's avatar
unknown committed
1813
    case SSL_TYPE_NOT_SPECIFIED:
unknown's avatar
unknown committed
1814 1815
      break;
    case SSL_TYPE_NONE:
1816 1817 1818 1819
      table->field[next_field]->store("", 0, &my_charset_latin1);
      table->field[next_field+1]->store("", 0, &my_charset_latin1);
      table->field[next_field+2]->store("", 0, &my_charset_latin1);
      table->field[next_field+3]->store("", 0, &my_charset_latin1);
unknown's avatar
unknown committed
1820
      break;
1821
    }
unknown's avatar
unknown committed
1822
    next_field+=4;
unknown's avatar
unknown committed
1823

1824
    USER_RESOURCES mqh= lex->mqh;
1825
    if (mqh.specified_limits & USER_RESOURCES::QUERIES_PER_HOUR)
1826
      table->field[next_field]->store((longlong) mqh.questions, TRUE);
1827
    if (mqh.specified_limits & USER_RESOURCES::UPDATES_PER_HOUR)
1828
      table->field[next_field+1]->store((longlong) mqh.updates, TRUE);
1829
    if (mqh.specified_limits & USER_RESOURCES::CONNECTIONS_PER_HOUR)
1830
      table->field[next_field+2]->store((longlong) mqh.conn_per_hour, TRUE);
1831
    if (table->s->fields >= 36 &&
1832
        (mqh.specified_limits & USER_RESOURCES::USER_CONNECTIONS))
unknown's avatar
unknown committed
1833
      table->field[next_field+3]->store((longlong) mqh.user_conn);
1834
    mqh_used= mqh_used || mqh.questions || mqh.updates || mqh.conn_per_hour;
1835
  }
unknown's avatar
unknown committed
1836
  if (old_row_exists)
unknown's avatar
unknown committed
1837 1838 1839 1840 1841
  {
    /*
      We should NEVER delete from the user table, as a uses can still
      use mysqld even if he doesn't have any privileges in the user table!
    */
1842
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
unknown's avatar
unknown committed
1843
    if (cmp_record(table,record[1]) &&
unknown's avatar
unknown committed
1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862
	(error=table->file->update_row(table->record[1],table->record[0])))
    {						// This should never happen
      table->file->print_error(error,MYF(0));	/* purecov: deadcode */
      error= -1;				/* purecov: deadcode */
      goto end;					/* purecov: deadcode */
    }
  }
  else if ((error=table->file->write_row(table->record[0]))) // insert
  {						// This should never happen
    if (error && error != HA_ERR_FOUND_DUPP_KEY &&
	error != HA_ERR_FOUND_DUPP_UNIQUE)	/* purecov: inspected */
    {
      table->file->print_error(error,MYF(0));	/* purecov: deadcode */
      error= -1;				/* purecov: deadcode */
      goto end;					/* purecov: deadcode */
    }
  }
  error=0;					// Privileges granted / revoked

1863
end:
unknown's avatar
unknown committed
1864 1865 1866
  if (!error)
  {
    acl_cache->clear(1);			// Clear privilege cache
unknown's avatar
unknown committed
1867
    if (old_row_exists)
1868 1869
      acl_update_user(combo.user.str, combo.host.str,
                      combo.password.str, password_len,
1870 1871 1872 1873 1874
		      lex->ssl_type,
		      lex->ssl_cipher,
		      lex->x509_issuer,
		      lex->x509_subject,
		      &lex->mqh,
1875
		      rights);
unknown's avatar
unknown committed
1876
    else
1877
      acl_insert_user(combo.user.str, combo.host.str, password, password_len,
1878 1879 1880 1881 1882
		      lex->ssl_type,
		      lex->ssl_cipher,
		      lex->x509_issuer,
		      lex->x509_subject,
		      &lex->mqh,
1883
		      rights);
unknown's avatar
unknown committed
1884 1885 1886 1887 1888 1889
  }
  DBUG_RETURN(error);
}


/*
unknown's avatar
unknown committed
1890
  change grants in the mysql.db table
unknown's avatar
unknown committed
1891 1892 1893 1894
*/

static int replace_db_table(TABLE *table, const char *db,
			    const LEX_USER &combo,
unknown's avatar
unknown committed
1895
			    ulong rights, bool revoke_grant)
unknown's avatar
unknown committed
1896
{
unknown's avatar
unknown committed
1897 1898
  uint i;
  ulong priv,store_rights;
unknown's avatar
unknown committed
1899
  bool old_row_exists=0;
unknown's avatar
unknown committed
1900
  int error;
unknown's avatar
unknown committed
1901
  char what= (revoke_grant) ? 'N' : 'Y';
1902
  byte user_key[MAX_KEY_LENGTH];
unknown's avatar
unknown committed
1903 1904
  DBUG_ENTER("replace_db_table");

1905 1906
  if (!initialized)
  {
unknown's avatar
unknown committed
1907
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
1908 1909 1910
    DBUG_RETURN(-1);
  }

1911
  /* Check if there is such a user in user table in memory? */
1912
  if (!find_acl_user(combo.host.str,combo.user.str, FALSE))
unknown's avatar
unknown committed
1913
  {
unknown's avatar
unknown committed
1914
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH), MYF(0));
unknown's avatar
unknown committed
1915 1916 1917
    DBUG_RETURN(-1);
  }

1918 1919 1920
  table->field[0]->store(combo.host.str,combo.host.length, system_charset_info);
  table->field[1]->store(db,(uint) strlen(db), system_charset_info);
  table->field[2]->store(combo.user.str,combo.user.length, system_charset_info);
1921 1922 1923
  key_copy(user_key, table->record[0], table->key_info,
           table->key_info->key_length);

1924 1925
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
  if (table->file->index_read_idx(table->record[0],0,
1926 1927
                                  user_key, table->key_info->key_length,
                                  HA_READ_KEY_EXACT))
unknown's avatar
unknown committed
1928 1929 1930
  {
    if (what == 'N')
    { // no row, no revoke
unknown's avatar
unknown committed
1931
      my_error(ER_NONEXISTING_GRANT, MYF(0), combo.user.str, combo.host.str);
unknown's avatar
unknown committed
1932 1933
      goto abort;
    }
unknown's avatar
unknown committed
1934
    old_row_exists = 0;
1935
    restore_record(table, s->default_values);
1936 1937 1938
    table->field[0]->store(combo.host.str,combo.host.length, system_charset_info);
    table->field[1]->store(db,(uint) strlen(db), system_charset_info);
    table->field[2]->store(combo.user.str,combo.user.length, system_charset_info);
unknown's avatar
unknown committed
1939 1940 1941
  }
  else
  {
unknown's avatar
unknown committed
1942
    old_row_exists = 1;
unknown's avatar
unknown committed
1943
    store_record(table,record[1]);
unknown's avatar
unknown committed
1944 1945 1946
  }

  store_rights=get_rights_for_db(rights);
1947
  for (i= 3, priv= 1; i < table->s->fields; i++, priv <<= 1)
unknown's avatar
unknown committed
1948
  {
unknown's avatar
unknown committed
1949
    if (priv & store_rights)			// do it if priv is chosen
unknown's avatar
unknown committed
1950
      table->field [i]->store(&what,1, &my_charset_latin1);// set requested privileges
unknown's avatar
unknown committed
1951 1952 1953 1954
  }
  rights=get_access(table,3);
  rights=fix_rights_for_db(rights);

unknown's avatar
unknown committed
1955
  if (old_row_exists)
unknown's avatar
unknown committed
1956
  {
1957
    /* update old existing row */
unknown's avatar
unknown committed
1958 1959
    if (rights)
    {
1960
      table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
unknown's avatar
unknown committed
1961 1962 1963 1964 1965 1966 1967 1968 1969
      if ((error=table->file->update_row(table->record[1],table->record[0])))
	goto table_error;			/* purecov: deadcode */
    }
    else	/* must have been a revoke of all privileges */
    {
      if ((error = table->file->delete_row(table->record[1])))
	goto table_error;			/* purecov: deadcode */
    }
  }
1970
  else if (rights && (error=table->file->write_row(table->record[0])))
unknown's avatar
unknown committed
1971 1972 1973 1974 1975 1976
  {
    if (error && error != HA_ERR_FOUND_DUPP_KEY) /* purecov: inspected */
      goto table_error; /* purecov: deadcode */
  }

  acl_cache->clear(1);				// Clear privilege cache
unknown's avatar
unknown committed
1977
  if (old_row_exists)
unknown's avatar
unknown committed
1978 1979
    acl_update_db(combo.user.str,combo.host.str,db,rights);
  else
1980
  if (rights)
unknown's avatar
unknown committed
1981 1982 1983 1984
    acl_insert_db(combo.user.str,combo.host.str,db,rights);
  DBUG_RETURN(0);

  /* This could only happen if the grant tables got corrupted */
1985
table_error:
unknown's avatar
unknown committed
1986 1987
  table->file->print_error(error,MYF(0));	/* purecov: deadcode */

1988
abort:
unknown's avatar
unknown committed
1989 1990 1991 1992 1993 1994 1995 1996
  DBUG_RETURN(-1);
}


class GRANT_COLUMN :public Sql_alloc
{
public:
  char *column;
unknown's avatar
unknown committed
1997 1998 1999
  ulong rights;
  uint key_length;
  GRANT_COLUMN(String &c,  ulong y) :rights (y)
unknown's avatar
unknown committed
2000
  {
unknown's avatar
unknown committed
2001
    column= memdup_root(&memex,c.ptr(), key_length=c.length());
unknown's avatar
unknown committed
2002 2003 2004
  }
};

unknown's avatar
unknown committed
2005

unknown's avatar
unknown committed
2006 2007 2008 2009 2010 2011 2012
static byte* get_key_column(GRANT_COLUMN *buff,uint *length,
			    my_bool not_used __attribute__((unused)))
{
  *length=buff->key_length;
  return (byte*) buff->column;
}

unknown's avatar
unknown committed
2013

2014
class GRANT_NAME :public Sql_alloc
unknown's avatar
unknown committed
2015 2016
{
public:
2017 2018
  acl_host_and_ip host;
  char *db, *user, *tname, *hash_key;
2019
  ulong privs;
2020
  ulong sort;
unknown's avatar
unknown committed
2021
  uint key_length;
2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033
  GRANT_NAME(const char *h, const char *d,const char *u,
             const char *t, ulong p);
  GRANT_NAME (TABLE *form);
  virtual ~GRANT_NAME() {};
  virtual bool ok() { return privs != 0; }
};


class GRANT_TABLE :public GRANT_NAME
{
public:
  ulong cols;
unknown's avatar
unknown committed
2034
  HASH hash_columns;
unknown's avatar
unknown committed
2035 2036 2037 2038

  GRANT_TABLE(const char *h, const char *d,const char *u,
              const char *t, ulong p, ulong c);
  GRANT_TABLE (TABLE *form, TABLE *col_privs);
2039
  ~GRANT_TABLE();
2040 2041
  bool ok() { return privs != 0 || cols != 0; }
};
unknown's avatar
unknown committed
2042

2043

unknown's avatar
unknown committed
2044

2045 2046 2047
GRANT_NAME::GRANT_NAME(const char *h, const char *d,const char *u,
                       const char *t, ulong p)
  :privs(p)
2048 2049
{
  /* Host given by user */
2050
  update_hostname(&host, strdup_root(&memex, h));
2051 2052
  db =   strdup_root(&memex,d);
  user = strdup_root(&memex,u);
2053
  sort=  get_sort(3,host.hostname,db,user);
2054 2055
  tname= strdup_root(&memex,t);
  if (lower_case_table_names)
unknown's avatar
unknown committed
2056
  {
2057 2058
    my_casedn_str(files_charset_info, db);
    my_casedn_str(files_charset_info, tname);
2059 2060 2061 2062
  }
  key_length =(uint) strlen(d)+(uint) strlen(u)+(uint) strlen(t)+3;
  hash_key = (char*) alloc_root(&memex,key_length);
  strmov(strmov(strmov(hash_key,user)+1,db)+1,tname);
2063 2064 2065 2066 2067 2068 2069
}


GRANT_TABLE::GRANT_TABLE(const char *h, const char *d,const char *u,
                	 const char *t, ulong p, ulong c)
  :GRANT_NAME(h,d,u,t,p), cols(c)
{
2070
  (void) hash_init(&hash_columns,system_charset_info,
unknown's avatar
unknown committed
2071
                   0,0,0, (hash_get_key) get_key_column,0,0);
2072
}
unknown's avatar
unknown committed
2073

2074

2075
GRANT_NAME::GRANT_NAME(TABLE *form)
2076
{
2077
  update_hostname(&host, get_field(&memex, form->field[0]));
unknown's avatar
unknown committed
2078 2079
  db=    get_field(&memex,form->field[1]);
  user=  get_field(&memex,form->field[2]);
2080 2081
  if (!user)
    user= (char*) "";
2082
  sort=  get_sort(3, host.hostname, db, user);
unknown's avatar
unknown committed
2083
  tname= get_field(&memex,form->field[3]);
2084 2085 2086
  if (!db || !tname)
  {
    /* Wrong table row; Ignore it */
2087
    privs= 0;
2088 2089 2090 2091
    return;					/* purecov: inspected */
  }
  if (lower_case_table_names)
  {
2092 2093
    my_casedn_str(files_charset_info, db);
    my_casedn_str(files_charset_info, tname);
2094 2095 2096 2097 2098 2099 2100
  }
  key_length = ((uint) strlen(db) + (uint) strlen(user) +
                (uint) strlen(tname) + 3);
  hash_key = (char*) alloc_root(&memex,key_length);
  strmov(strmov(strmov(hash_key,user)+1,db)+1,tname);
  privs = (ulong) form->field[6]->val_int();
  privs = fix_rights_for_table(privs);
2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116
}


GRANT_TABLE::GRANT_TABLE(TABLE *form, TABLE *col_privs)
  :GRANT_NAME(form)
{
  byte key[MAX_KEY_LENGTH];

  if (!db || !tname)
  {
    /* Wrong table row; Ignore it */
    hash_clear(&hash_columns);                  /* allow for destruction */
    cols= 0;
    return;
  }
  cols= (ulong) form->field[7]->val_int();
2117 2118
  cols =  fix_rights_for_column(cols);

2119
  (void) hash_init(&hash_columns,system_charset_info,
unknown's avatar
unknown committed
2120
                   0,0,0, (hash_get_key) get_key_column,0,0);
2121 2122
  if (cols)
  {
2123 2124
    uint key_prefix_len;
    KEY_PART_INFO *key_part= col_privs->key_info->key_part;
2125 2126
    col_privs->field[0]->store(host.hostname,
                               host.hostname ? (uint) strlen(host.hostname) : 0,
2127 2128 2129 2130
                               system_charset_info);
    col_privs->field[1]->store(db,(uint) strlen(db), system_charset_info);
    col_privs->field[2]->store(user,(uint) strlen(user), system_charset_info);
    col_privs->field[3]->store(tname,(uint) strlen(tname), system_charset_info);
2131 2132 2133 2134 2135 2136

    key_prefix_len= (key_part[0].store_length +
                     key_part[1].store_length +
                     key_part[2].store_length +
                     key_part[3].store_length);
    key_copy(key, col_privs->record[0], col_privs->key_info, key_prefix_len);
unknown's avatar
unknown committed
2137
    col_privs->field[4]->store("",0, &my_charset_latin1);
2138

2139 2140
    col_privs->file->ha_index_init(0);
    if (col_privs->file->index_read(col_privs->record[0],
2141 2142
                                    (byte*) key,
                                    key_prefix_len, HA_READ_KEY_EXACT))
unknown's avatar
unknown committed
2143
    {
2144
      cols = 0; /* purecov: deadcode */
2145
      col_privs->file->ha_index_end();
2146
      return;
unknown's avatar
unknown committed
2147
    }
2148
    do
unknown's avatar
unknown committed
2149
    {
2150 2151 2152
      String *res,column_name;
      GRANT_COLUMN *mem_check;
      /* As column name is a string, we don't have to supply a buffer */
unknown's avatar
unknown committed
2153
      res=col_privs->field[4]->val_str(&column_name);
2154 2155 2156
      ulong priv= (ulong) col_privs->field[6]->val_int();
      if (!(mem_check = new GRANT_COLUMN(*res,
                                         fix_rights_for_column(priv))))
unknown's avatar
unknown committed
2157
      {
2158 2159 2160
        /* Don't use this entry */
        privs = cols = 0;			/* purecov: deadcode */
        return;				/* purecov: deadcode */
unknown's avatar
unknown committed
2161
      }
unknown's avatar
unknown committed
2162
      my_hash_insert(&hash_columns, (byte *) mem_check);
2163
    } while (!col_privs->file->index_next(col_privs->record[0]) &&
2164
             !key_cmp_if_same(col_privs,key,0,key_prefix_len));
2165
    col_privs->file->ha_index_end();
unknown's avatar
unknown committed
2166
  }
2167
}
unknown's avatar
unknown committed
2168

unknown's avatar
unknown committed
2169

2170 2171 2172 2173 2174 2175
GRANT_TABLE::~GRANT_TABLE()
{
  hash_free(&hash_columns);
}


2176
static byte* get_grant_table(GRANT_NAME *buff,uint *length,
unknown's avatar
unknown committed
2177 2178 2179 2180 2181 2182
			     my_bool not_used __attribute__((unused)))
{
  *length=buff->key_length;
  return (byte*) buff->hash_key;
}

unknown's avatar
unknown committed
2183

unknown's avatar
unknown committed
2184 2185 2186 2187 2188
void free_grant_table(GRANT_TABLE *grant_table)
{
  hash_free(&grant_table->hash_columns);
}

unknown's avatar
unknown committed
2189

unknown's avatar
unknown committed
2190 2191
/* Search after a matching grant. Prefer exact grants before not exact ones */

2192 2193
static GRANT_NAME *name_hash_search(HASH *name_hash,
				      const char *host,const char* ip,
unknown's avatar
unknown committed
2194 2195 2196 2197 2198 2199
				      const char *db,
				      const char *user, const char *tname,
				      bool exact)
{
  char helping [NAME_LEN*2+USERNAME_LENGTH+3];
  uint len;
2200
  GRANT_NAME *grant_name,*found=0;
unknown's avatar
unknown committed
2201 2202

  len  = (uint) (strmov(strmov(strmov(helping,user)+1,db)+1,tname)-helping)+ 1;
2203
  for (grant_name=(GRANT_NAME*) hash_search(name_hash,
2204
					      (byte*) helping,
unknown's avatar
unknown committed
2205
					      len) ;
2206 2207
       grant_name ;
       grant_name= (GRANT_NAME*) hash_next(name_hash,(byte*) helping,
2208
					     len))
unknown's avatar
unknown committed
2209 2210 2211
  {
    if (exact)
    {
2212
      if (compare_hostname(&grant_name->host, host, ip))
2213
	return grant_name;
unknown's avatar
unknown committed
2214 2215 2216
    }
    else
    {
2217
      if (compare_hostname(&grant_name->host, host, ip) &&
2218 2219
          (!found || found->sort < grant_name->sort))
	found=grant_name;					// Host ok
unknown's avatar
unknown committed
2220 2221 2222 2223 2224 2225
    }
  }
  return found;
}


2226
inline GRANT_NAME *
2227 2228
routine_hash_search(const char *host, const char *ip, const char *db,
                 const char *user, const char *tname, bool proc, bool exact)
2229
{
2230 2231 2232
  return (GRANT_TABLE*)
    name_hash_search(proc ? &proc_priv_hash : &func_priv_hash,
		     host, ip, db, user, tname, exact);
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243
}


inline GRANT_TABLE *
table_hash_search(const char *host, const char *ip, const char *db,
		  const char *user, const char *tname, bool exact)
{
  return (GRANT_TABLE*) name_hash_search(&column_priv_hash, host, ip, db,
					 user, tname, exact);
}

unknown's avatar
unknown committed
2244

unknown's avatar
unknown committed
2245
inline GRANT_COLUMN *
unknown's avatar
unknown committed
2246
column_hash_search(GRANT_TABLE *t, const char *cname, uint length)
unknown's avatar
unknown committed
2247 2248 2249 2250 2251 2252 2253 2254 2255
{
  return (GRANT_COLUMN*) hash_search(&t->hash_columns, (byte*) cname,length);
}


static int replace_column_table(GRANT_TABLE *g_t,
				TABLE *table, const LEX_USER &combo,
				List <LEX_COLUMN> &columns,
				const char *db, const char *table_name,
unknown's avatar
unknown committed
2256
				ulong rights, bool revoke_grant)
unknown's avatar
unknown committed
2257 2258 2259
{
  int error=0,result=0;
  byte key[MAX_KEY_LENGTH];
2260 2261
  uint key_prefix_length;
  KEY_PART_INFO *key_part= table->key_info->key_part;
unknown's avatar
unknown committed
2262 2263
  DBUG_ENTER("replace_column_table");

unknown's avatar
unknown committed
2264 2265 2266 2267 2268 2269 2270 2271
  table->field[0]->store(combo.host.str,combo.host.length,
                         system_charset_info);
  table->field[1]->store(db,(uint) strlen(db),
                         system_charset_info);
  table->field[2]->store(combo.user.str,combo.user.length,
                         system_charset_info);
  table->field[3]->store(table_name,(uint) strlen(table_name),
                         system_charset_info);
unknown's avatar
unknown committed
2272

2273 2274 2275 2276
  /* Get length of 3 first key parts */
  key_prefix_length= (key_part[0].store_length + key_part[1].store_length +
                      key_part[2].store_length + key_part[3].store_length);
  key_copy(key, table->record[0], table->key_info, key_prefix_length);
unknown's avatar
unknown committed
2277

2278
  rights&= COL_ACLS;				// Only ACL for columns
unknown's avatar
unknown committed
2279 2280 2281 2282

  /* first fix privileges for all columns in column list */

  List_iterator <LEX_COLUMN> iter(columns);
unknown's avatar
unknown committed
2283
  class LEX_COLUMN *column;
unknown's avatar
unknown committed
2284
  table->file->ha_index_init(0);
unknown's avatar
unknown committed
2285
  while ((column= iter++))
unknown's avatar
unknown committed
2286
  {
unknown's avatar
unknown committed
2287
    ulong privileges= column->rights;
unknown's avatar
unknown committed
2288
    bool old_row_exists=0;
2289 2290 2291 2292
    byte user_key[MAX_KEY_LENGTH];

    key_restore(table->record[0],key,table->key_info,
                key_prefix_length);
unknown's avatar
unknown committed
2293
    table->field[4]->store(column->column.ptr(), column->column.length(),
2294
                           system_charset_info);
2295 2296 2297
    /* Get key for the first 4 columns */
    key_copy(user_key, table->record[0], table->key_info,
             table->key_info->key_length);
unknown's avatar
unknown committed
2298

2299
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
2300 2301 2302
    if (table->file->index_read(table->record[0], user_key,
				table->key_info->key_length,
                                HA_READ_KEY_EXACT))
unknown's avatar
unknown committed
2303 2304 2305
    {
      if (revoke_grant)
      {
unknown's avatar
unknown committed
2306
	my_error(ER_NONEXISTING_TABLE_GRANT, MYF(0),
2307
                 combo.user.str, combo.host.str,
unknown's avatar
unknown committed
2308 2309 2310
                 table_name);                   /* purecov: inspected */
	result= -1;                             /* purecov: inspected */
	continue;                               /* purecov: inspected */
unknown's avatar
unknown committed
2311
      }
unknown's avatar
unknown committed
2312
      old_row_exists = 0;
2313
      restore_record(table, s->default_values);		// Get empty record
2314 2315
      key_restore(table->record[0],key,table->key_info,
                  key_prefix_length);
unknown's avatar
unknown committed
2316
      table->field[4]->store(column->column.ptr(),column->column.length(),
2317
                             system_charset_info);
unknown's avatar
unknown committed
2318 2319 2320
    }
    else
    {
unknown's avatar
unknown committed
2321
      ulong tmp= (ulong) table->field[6]->val_int();
unknown's avatar
unknown committed
2322 2323 2324 2325 2326 2327
      tmp=fix_rights_for_column(tmp);

      if (revoke_grant)
	privileges = tmp & ~(privileges | rights);
      else
	privileges |= tmp;
unknown's avatar
unknown committed
2328
      old_row_exists = 1;
unknown's avatar
unknown committed
2329
      store_record(table,record[1]);			// copy original row
unknown's avatar
unknown committed
2330 2331
    }

2332
    table->field[6]->store((longlong) get_rights_for_column(privileges), TRUE);
unknown's avatar
unknown committed
2333

unknown's avatar
unknown committed
2334
    if (old_row_exists)
unknown's avatar
unknown committed
2335
    {
unknown's avatar
unknown committed
2336
      GRANT_COLUMN *grant_column;
unknown's avatar
unknown committed
2337 2338 2339 2340 2341 2342 2343 2344 2345 2346
      if (privileges)
	error=table->file->update_row(table->record[1],table->record[0]);
      else
	error=table->file->delete_row(table->record[1]);
      if (error)
      {
	table->file->print_error(error,MYF(0)); /* purecov: inspected */
	result= -1;				/* purecov: inspected */
	goto end;				/* purecov: inspected */
      }
unknown's avatar
unknown committed
2347 2348
      grant_column= column_hash_search(g_t, column->column.ptr(),
                                       column->column.length());
unknown's avatar
unknown committed
2349
      if (grant_column)				// Should always be true
unknown's avatar
unknown committed
2350
	grant_column->rights= privileges;	// Update hash
unknown's avatar
unknown committed
2351 2352 2353
    }
    else					// new grant
    {
unknown's avatar
unknown committed
2354
      GRANT_COLUMN *grant_column;
unknown's avatar
unknown committed
2355 2356 2357 2358 2359 2360
      if ((error=table->file->write_row(table->record[0])))
      {
	table->file->print_error(error,MYF(0)); /* purecov: inspected */
	result= -1;				/* purecov: inspected */
	goto end;				/* purecov: inspected */
      }
unknown's avatar
unknown committed
2361
      grant_column= new GRANT_COLUMN(column->column,privileges);
unknown's avatar
SCRUM  
unknown committed
2362
      my_hash_insert(&g_t->hash_columns,(byte*) grant_column);
unknown's avatar
unknown committed
2363 2364 2365 2366 2367 2368 2369 2370 2371 2372
    }
  }

  /*
    If revoke of privileges on the table level, remove all such privileges
    for all columns
  */

  if (revoke_grant)
  {
2373 2374
    byte user_key[MAX_KEY_LENGTH];
    key_copy(user_key, table->record[0], table->key_info,
unknown's avatar
unknown committed
2375 2376
             key_prefix_length);

2377
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
2378
    if (table->file->index_read(table->record[0], user_key,
unknown's avatar
unknown committed
2379
				key_prefix_length,
2380
                                HA_READ_KEY_EXACT))
unknown's avatar
unknown committed
2381 2382
      goto end;

2383
    /* Scan through all rows with the same host,db,user and table */
unknown's avatar
unknown committed
2384 2385
    do
    {
unknown's avatar
unknown committed
2386
      ulong privileges = (ulong) table->field[6]->val_int();
unknown's avatar
unknown committed
2387
      privileges=fix_rights_for_column(privileges);
unknown's avatar
unknown committed
2388
      store_record(table,record[1]);
unknown's avatar
unknown committed
2389 2390 2391 2392 2393

      if (privileges & rights)	// is in this record the priv to be revoked ??
      {
	GRANT_COLUMN *grant_column = NULL;
	char  colum_name_buf[HOSTNAME_LENGTH+1];
2394
	String column_name(colum_name_buf,sizeof(colum_name_buf),
unknown's avatar
unknown committed
2395
                           system_charset_info);
unknown's avatar
unknown committed
2396 2397 2398

	privileges&= ~rights;
	table->field[6]->store((longlong)
2399
			       get_rights_for_column(privileges), TRUE);
2400
	table->field[4]->val_str(&column_name);
unknown's avatar
unknown committed
2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430
	grant_column = column_hash_search(g_t,
					  column_name.ptr(),
					  column_name.length());
	if (privileges)
	{
	  int tmp_error;
	  if ((tmp_error=table->file->update_row(table->record[1],
						 table->record[0])))
	  {					/* purecov: deadcode */
	    table->file->print_error(tmp_error,MYF(0)); /* purecov: deadcode */
	    result= -1;				/* purecov: deadcode */
	    goto end;				/* purecov: deadcode */
	  }
	  if (grant_column)
	    grant_column->rights  = privileges; // Update hash
	}
	else
	{
	  int tmp_error;
	  if ((tmp_error = table->file->delete_row(table->record[1])))
	  {					/* purecov: deadcode */
	    table->file->print_error(tmp_error,MYF(0)); /* purecov: deadcode */
	    result= -1;				/* purecov: deadcode */
	    goto end;				/* purecov: deadcode */
	  }
	  if (grant_column)
	    hash_delete(&g_t->hash_columns,(byte*) grant_column);
	}
      }
    } while (!table->file->index_next(table->record[0]) &&
2431
	     !key_cmp_if_same(table, key, 0, key_prefix_length));
unknown's avatar
unknown committed
2432 2433
  }

2434
end:
unknown's avatar
unknown committed
2435
  table->file->ha_index_end();
unknown's avatar
unknown committed
2436 2437 2438 2439 2440 2441 2442
  DBUG_RETURN(result);
}


static int replace_table_table(THD *thd, GRANT_TABLE *grant_table,
			       TABLE *table, const LEX_USER &combo,
			       const char *db, const char *table_name,
unknown's avatar
unknown committed
2443 2444
			       ulong rights, ulong col_rights,
			       bool revoke_grant)
unknown's avatar
unknown committed
2445
{
2446
  char grantor[HOSTNAME_LENGTH+USERNAME_LENGTH+2];
unknown's avatar
unknown committed
2447
  int old_row_exists = 1;
unknown's avatar
unknown committed
2448
  int error=0;
unknown's avatar
unknown committed
2449
  ulong store_table_rights, store_col_rights;
2450
  byte user_key[MAX_KEY_LENGTH];
unknown's avatar
unknown committed
2451 2452
  DBUG_ENTER("replace_table_table");

2453
  strxmov(grantor, thd->user, "@", thd->host_or_ip, NullS);
unknown's avatar
unknown committed
2454

unknown's avatar
unknown committed
2455 2456 2457 2458
  /*
    The following should always succeed as new users are created before
    this function is called!
  */
2459
  if (!find_acl_user(combo.host.str,combo.user.str, FALSE))
unknown's avatar
unknown committed
2460
  {
unknown's avatar
unknown committed
2461 2462
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH),
               MYF(0));	/* purecov: deadcode */
unknown's avatar
unknown committed
2463 2464 2465
    DBUG_RETURN(-1);				/* purecov: deadcode */
  }

2466
  restore_record(table, s->default_values);     // Get empty record
2467 2468 2469 2470
  table->field[0]->store(combo.host.str,combo.host.length, system_charset_info);
  table->field[1]->store(db,(uint) strlen(db), system_charset_info);
  table->field[2]->store(combo.user.str,combo.user.length, system_charset_info);
  table->field[3]->store(table_name,(uint) strlen(table_name), system_charset_info);
unknown's avatar
unknown committed
2471
  store_record(table,record[1]);			// store at pos 1
2472 2473
  key_copy(user_key, table->record[0], table->key_info,
           table->key_info->key_length);
unknown's avatar
unknown committed
2474

2475
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
2476 2477
  if (table->file->index_read_idx(table->record[0], 0,
                                  user_key, table->key_info->key_length,
unknown's avatar
unknown committed
2478 2479 2480 2481 2482 2483 2484 2485 2486
				  HA_READ_KEY_EXACT))
  {
    /*
      The following should never happen as we first check the in memory
      grant tables for the user.  There is however always a small change that
      the user has modified the grant tables directly.
    */
    if (revoke_grant)
    { // no row, no revoke
unknown's avatar
unknown committed
2487 2488
      my_error(ER_NONEXISTING_TABLE_GRANT, MYF(0),
               combo.user.str, combo.host.str,
2489
               table_name);		        /* purecov: deadcode */
unknown's avatar
unknown committed
2490 2491
      DBUG_RETURN(-1);				/* purecov: deadcode */
    }
unknown's avatar
unknown committed
2492
    old_row_exists = 0;
unknown's avatar
unknown committed
2493
    restore_record(table,record[1]);			// Get saved record
unknown's avatar
unknown committed
2494 2495
  }

unknown's avatar
unknown committed
2496 2497
  store_table_rights= get_rights_for_table(rights);
  store_col_rights=   get_rights_for_column(col_rights);
unknown's avatar
unknown committed
2498
  if (old_row_exists)
unknown's avatar
unknown committed
2499
  {
unknown's avatar
unknown committed
2500
    ulong j,k;
unknown's avatar
unknown committed
2501
    store_record(table,record[1]);
unknown's avatar
unknown committed
2502 2503
    j = (ulong) table->field[6]->val_int();
    k = (ulong) table->field[7]->val_int();
unknown's avatar
unknown committed
2504 2505 2506

    if (revoke_grant)
    {
2507
      /* column rights are already fixed in mysql_table_grant */
unknown's avatar
unknown committed
2508 2509 2510 2511
      store_table_rights=j & ~store_table_rights;
    }
    else
    {
unknown's avatar
unknown committed
2512 2513
      store_table_rights|= j;
      store_col_rights|=   k;
unknown's avatar
unknown committed
2514 2515 2516
    }
  }

2517
  table->field[4]->store(grantor,(uint) strlen(grantor), system_charset_info);
2518 2519
  table->field[6]->store((longlong) store_table_rights, TRUE);
  table->field[7]->store((longlong) store_col_rights, TRUE);
unknown's avatar
unknown committed
2520
  rights=fix_rights_for_table(store_table_rights);
unknown's avatar
unknown committed
2521
  col_rights=fix_rights_for_column(store_col_rights);
unknown's avatar
unknown committed
2522

unknown's avatar
unknown committed
2523
  if (old_row_exists)
unknown's avatar
unknown committed
2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539
  {
    if (store_table_rights || store_col_rights)
    {
      if ((error=table->file->update_row(table->record[1],table->record[0])))
	goto table_error;			/* purecov: deadcode */
    }
    else if ((error = table->file->delete_row(table->record[1])))
      goto table_error;				/* purecov: deadcode */
  }
  else
  {
    error=table->file->write_row(table->record[0]);
    if (error && error != HA_ERR_FOUND_DUPP_KEY)
      goto table_error;				/* purecov: deadcode */
  }

unknown's avatar
unknown committed
2540
  if (rights | col_rights)
unknown's avatar
unknown committed
2541
  {
unknown's avatar
unknown committed
2542
    grant_table->privs= rights;
2543
    grant_table->cols=	col_rights;
unknown's avatar
unknown committed
2544 2545 2546
  }
  else
  {
2547
    hash_delete(&column_priv_hash,(byte*) grant_table);
unknown's avatar
unknown committed
2548 2549 2550
  }
  DBUG_RETURN(0);

2551 2552
  /* This should never happen */
table_error:
unknown's avatar
unknown committed
2553 2554 2555 2556 2557
  table->file->print_error(error,MYF(0)); /* purecov: deadcode */
  DBUG_RETURN(-1); /* purecov: deadcode */
}


2558
static int replace_routine_table(THD *thd, GRANT_NAME *grant_name,
2559
			      TABLE *table, const LEX_USER &combo,
2560 2561
			      const char *db, const char *routine_name,
			      bool is_proc, ulong rights, bool revoke_grant)
2562 2563 2564 2565 2566
{
  char grantor[HOSTNAME_LENGTH+USERNAME_LENGTH+2];
  int old_row_exists= 1;
  int error=0;
  ulong store_proc_rights;
2567
  DBUG_ENTER("replace_routine_table");
2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580

  if (!initialized)
  {
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
    DBUG_RETURN(-1);
  }

  strxmov(grantor, thd->user, "@", thd->host_or_ip, NullS);

  /*
    The following should always succeed as new users are created before
    this function is called!
  */
unknown's avatar
unknown committed
2581
  if (!find_acl_user(combo.host.str, combo.user.str, FALSE))
2582 2583 2584 2585 2586
  {
    my_error(ER_PASSWORD_NO_MATCH,MYF(0));
    DBUG_RETURN(-1);
  }

2587
  restore_record(table, s->default_values);		// Get empty record
2588 2589 2590
  table->field[0]->store(combo.host.str,combo.host.length, &my_charset_latin1);
  table->field[1]->store(db,(uint) strlen(db), &my_charset_latin1);
  table->field[2]->store(combo.user.str,combo.user.length, &my_charset_latin1);
2591 2592 2593
  table->field[3]->store(routine_name,(uint) strlen(routine_name),
                         &my_charset_latin1);
  table->field[4]->store((longlong)(is_proc ? 
2594 2595
                                    TYPE_ENUM_PROCEDURE : TYPE_ENUM_FUNCTION),
                         TRUE);
2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609
  store_record(table,record[1]);			// store at pos 1

  if (table->file->index_read_idx(table->record[0],0,
				  (byte*) table->field[0]->ptr,0,
				  HA_READ_KEY_EXACT))
  {
    /*
      The following should never happen as we first check the in memory
      grant tables for the user.  There is however always a small change that
      the user has modified the grant tables directly.
    */
    if (revoke_grant)
    { // no row, no revoke
      my_error(ER_NONEXISTING_PROC_GRANT, MYF(0),
2610
               combo.user.str, combo.host.str, routine_name);
2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634
      DBUG_RETURN(-1);
    }
    old_row_exists= 0;
    restore_record(table,record[1]);			// Get saved record
  }

  store_proc_rights= get_rights_for_procedure(rights);
  if (old_row_exists)
  {
    ulong j;
    store_record(table,record[1]);
    j= (ulong) table->field[6]->val_int();

    if (revoke_grant)
    {
      /* column rights are already fixed in mysql_table_grant */
      store_proc_rights=j & ~store_proc_rights;
    }
    else
    {
      store_proc_rights|= j;
    }
  }

2635
  table->field[5]->store(grantor,(uint) strlen(grantor), &my_charset_latin1);
2636
  table->field[6]->store((longlong) store_proc_rights, TRUE);
2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661
  rights=fix_rights_for_procedure(store_proc_rights);

  if (old_row_exists)
  {
    if (store_proc_rights)
    {
      if ((error=table->file->update_row(table->record[1],table->record[0])))
	goto table_error;
    }
    else if ((error= table->file->delete_row(table->record[1])))
      goto table_error;
  }
  else
  {
    error=table->file->write_row(table->record[0]);
    if (error && error != HA_ERR_FOUND_DUPP_KEY)
      goto table_error;
  }

  if (rights)
  {
    grant_name->privs= rights;
  }
  else
  {
2662
    hash_delete(is_proc ? &proc_priv_hash : &func_priv_hash,(byte*) grant_name);
2663 2664 2665 2666 2667 2668 2669 2670 2671 2672
  }
  DBUG_RETURN(0);

  /* This should never happen */
table_error:
  table->file->print_error(error,MYF(0));
  DBUG_RETURN(-1);
}


2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685
/*
  Store table level and column level grants in the privilege tables

  SYNOPSIS
    mysql_table_grant()
    thd			Thread handle
    table_list		List of tables to give grant
    user_list		List of users to give grant
    columns		List of columns to give grant
    rights		Table level grant
    revoke_grant	Set to 1 if this is a REVOKE command

  RETURN
unknown's avatar
unknown committed
2686 2687
    FALSE ok
    TRUE  error
2688 2689
*/

unknown's avatar
unknown committed
2690
bool mysql_table_grant(THD *thd, TABLE_LIST *table_list,
unknown's avatar
unknown committed
2691 2692 2693
		      List <LEX_USER> &user_list,
		      List <LEX_COLUMN> &columns, ulong rights,
		      bool revoke_grant)
unknown's avatar
unknown committed
2694
{
2695
  ulong column_priv= 0;
unknown's avatar
unknown committed
2696 2697 2698
  List_iterator <LEX_USER> str_list (user_list);
  LEX_USER *Str;
  TABLE_LIST tables[3];
unknown's avatar
unknown committed
2699
  bool create_new_users=0;
2700
  char *db_name, *table_name;
unknown's avatar
unknown committed
2701 2702 2703 2704
  DBUG_ENTER("mysql_table_grant");

  if (!initialized)
  {
unknown's avatar
unknown committed
2705 2706
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0),
             "--skip-grant-tables");	/* purecov: inspected */
unknown's avatar
unknown committed
2707
    DBUG_RETURN(TRUE);				/* purecov: inspected */
unknown's avatar
unknown committed
2708 2709 2710
  }
  if (rights & ~TABLE_ACLS)
  {
unknown's avatar
unknown committed
2711 2712
    my_message(ER_ILLEGAL_GRANT_FOR_TABLE, ER(ER_ILLEGAL_GRANT_FOR_TABLE),
               MYF(0));
unknown's avatar
unknown committed
2713
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
2714 2715
  }

2716
  if (!revoke_grant)
unknown's avatar
unknown committed
2717
  {
unknown's avatar
unknown committed
2718
    if (columns.elements)
unknown's avatar
unknown committed
2719
    {
2720 2721
      class LEX_COLUMN *column;
      List_iterator <LEX_COLUMN> column_iter(columns);
unknown's avatar
unknown committed
2722 2723 2724

      if (open_and_lock_tables(thd, table_list))
        DBUG_RETURN(TRUE);
2725 2726

      while ((column = column_iter++))
unknown's avatar
unknown committed
2727
      {
unknown's avatar
unknown committed
2728
        uint unused_field_idx= NO_CACHED_FIELD_INDEX;
unknown's avatar
unknown committed
2729 2730 2731 2732 2733
        TABLE_LIST *dummy;
        Field *f=find_field_in_table_ref(thd, table_list, column->column.ptr(),
                                         column->column.ptr(), NULL, NULL,
                                         column->column.length(), 0, 1, 1, 0,
                                         &unused_field_idx, FALSE, &dummy);
unknown's avatar
unknown committed
2734
        if (f == (Field*)0)
2735
        {
unknown's avatar
unknown committed
2736 2737
          my_error(ER_BAD_FIELD_ERROR, MYF(0),
                   column->column.c_ptr(), table_list->alias);
unknown's avatar
unknown committed
2738
          DBUG_RETURN(TRUE);
2739
        }
unknown's avatar
unknown committed
2740 2741
        if (f == (Field *)-1)
          DBUG_RETURN(TRUE);
2742
        column_priv|= column->rights;
unknown's avatar
unknown committed
2743
      }
2744
      close_thread_tables(thd);
unknown's avatar
unknown committed
2745
    }
2746
    else
unknown's avatar
unknown committed
2747
    {
2748 2749 2750 2751
      if (!(rights & CREATE_ACL))
      {
        char buf[FN_REFLEN];
        sprintf(buf,"%s/%s/%s.frm",mysql_data_home, table_list->db,
2752
                table_list->table_name);
2753 2754 2755
        fn_format(buf,buf,"","",4+16+32);
        if (access(buf,F_OK))
        {
unknown's avatar
unknown committed
2756
          my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->alias);
unknown's avatar
unknown committed
2757
          DBUG_RETURN(TRUE);
2758 2759 2760 2761 2762 2763 2764 2765
        }
      }
      if (table_list->grant.want_privilege)
      {
        char command[128];
        get_privilege_desc(command, sizeof(command),
                           table_list->grant.want_privilege);
        my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0),
unknown's avatar
unknown committed
2766
                 command, thd->priv_user, thd->host_or_ip, table_list->alias);
2767 2768
        DBUG_RETURN(-1);
      }
unknown's avatar
unknown committed
2769 2770 2771 2772 2773 2774
    }
  }

  /* open the mysql.tables_priv and mysql.columns_priv tables */

  bzero((char*) &tables,sizeof(tables));
2775 2776 2777
  tables[0].alias=tables[0].table_name= (char*) "user";
  tables[1].alias=tables[1].table_name= (char*) "tables_priv";
  tables[2].alias=tables[2].table_name= (char*) "columns_priv";
unknown's avatar
VIEW  
unknown committed
2778
  tables[0].next_local= tables[0].next_global= tables+1;
unknown's avatar
unknown committed
2779
  /* Don't open column table if we don't need it ! */
unknown's avatar
VIEW  
unknown committed
2780 2781 2782 2783 2784
  tables[1].next_local=
    tables[1].next_global= ((column_priv ||
			     (revoke_grant &&
			      ((rights & COL_ACLS) || columns.elements)))
			    ? tables+2 : 0);
unknown's avatar
unknown committed
2785 2786 2787
  tables[0].lock_type=tables[1].lock_type=tables[2].lock_type=TL_WRITE;
  tables[0].db=tables[1].db=tables[2].db=(char*) "mysql";

2788 2789 2790 2791 2792
#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
2793 2794
  if (thd->slave_thread && table_rules_on)
  {
unknown's avatar
unknown committed
2795 2796 2797
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
2798
    */
2799
    tables[0].updating= tables[1].updating= tables[2].updating= 1;
2800
    if (!tables_ok(thd, tables))
unknown's avatar
unknown committed
2801
      DBUG_RETURN(FALSE);
2802
  }
2803 2804
#endif

2805
  if (simple_open_n_lock_tables(thd,tables))
unknown's avatar
unknown committed
2806 2807
  {						// Should never happen
    close_thread_tables(thd);			/* purecov: deadcode */
unknown's avatar
unknown committed
2808
    DBUG_RETURN(TRUE);				/* purecov: deadcode */
unknown's avatar
unknown committed
2809 2810
  }

unknown's avatar
unknown committed
2811 2812
  if (!revoke_grant)
    create_new_users= test_if_create_new_users(thd);
unknown's avatar
unknown committed
2813
  bool result= FALSE;
2814
  rw_wrlock(&LOCK_grant);
unknown's avatar
unknown committed
2815 2816
  MEM_ROOT *old_root= thd->mem_root;
  thd->mem_root= &memex;
2817
  grant_version++;
unknown's avatar
unknown committed
2818 2819 2820

  while ((Str = str_list++))
  {
2821
    int error;
unknown's avatar
unknown committed
2822 2823 2824 2825
    GRANT_TABLE *grant_table;
    if (Str->host.length > HOSTNAME_LENGTH ||
	Str->user.length > USERNAME_LENGTH)
    {
unknown's avatar
unknown committed
2826 2827
      my_message(ER_GRANT_WRONG_HOST_OR_USER, ER(ER_GRANT_WRONG_HOST_OR_USER),
                 MYF(0));
unknown's avatar
unknown committed
2828
      result= TRUE;
unknown's avatar
unknown committed
2829 2830 2831
      continue;
    }
    /* Create user if needed */
2832
    pthread_mutex_lock(&acl_cache->lock);
unknown's avatar
unknown committed
2833
    error=replace_user_table(thd, tables[0].table, *Str,
unknown's avatar
unknown committed
2834
			     0, revoke_grant, create_new_users,
unknown's avatar
unknown committed
2835 2836
                             test(thd->variables.sql_mode &
                                  MODE_NO_AUTO_CREATE_USER));
2837 2838
    pthread_mutex_unlock(&acl_cache->lock);
    if (error)
unknown's avatar
unknown committed
2839
    {
unknown's avatar
unknown committed
2840
      result= TRUE;				// Remember error
unknown's avatar
unknown committed
2841 2842 2843
      continue;					// Add next user
    }

unknown's avatar
VIEW  
unknown committed
2844 2845 2846
    db_name= (table_list->view_db.length ?
	      table_list->view_db.str :
	      table_list->db);
2847
    table_name= (table_list->view_name.length ?
unknown's avatar
VIEW  
unknown committed
2848
		table_list->view_name.str :
2849
		table_list->table_name);
unknown's avatar
VIEW  
unknown committed
2850

unknown's avatar
unknown committed
2851
    /* Find/create cached table grant */
unknown's avatar
VIEW  
unknown committed
2852
    grant_table= table_hash_search(Str->host.str, NullS, db_name,
2853
				   Str->user.str, table_name, 1);
unknown's avatar
unknown committed
2854 2855 2856 2857
    if (!grant_table)
    {
      if (revoke_grant)
      {
unknown's avatar
unknown committed
2858
	my_error(ER_NONEXISTING_TABLE_GRANT, MYF(0),
2859
                 Str->user.str, Str->host.str, table_list->table_name);
unknown's avatar
unknown committed
2860
	result= TRUE;
unknown's avatar
unknown committed
2861 2862
	continue;
      }
unknown's avatar
VIEW  
unknown committed
2863
      grant_table = new GRANT_TABLE (Str->host.str, db_name,
2864
				     Str->user.str, table_name,
unknown's avatar
unknown committed
2865 2866 2867 2868
				     rights,
				     column_priv);
      if (!grant_table)				// end of memory
      {
unknown's avatar
unknown committed
2869
	result= TRUE;				/* purecov: deadcode */
unknown's avatar
unknown committed
2870 2871
	continue;				/* purecov: deadcode */
      }
unknown's avatar
SCRUM  
unknown committed
2872
      my_hash_insert(&column_priv_hash,(byte*) grant_table);
unknown's avatar
unknown committed
2873 2874 2875 2876 2877
    }

    /* If revoke_grant, calculate the new column privilege for tables_priv */
    if (revoke_grant)
    {
2878 2879
      class LEX_COLUMN *column;
      List_iterator <LEX_COLUMN> column_iter(columns);
unknown's avatar
unknown committed
2880 2881 2882
      GRANT_COLUMN *grant_column;

      /* Fix old grants */
2883
      while ((column = column_iter++))
unknown's avatar
unknown committed
2884 2885
      {
	grant_column = column_hash_search(grant_table,
2886 2887
					  column->column.ptr(),
					  column->column.length());
unknown's avatar
unknown committed
2888
	if (grant_column)
2889
	  grant_column->rights&= ~(column->rights | rights);
unknown's avatar
unknown committed
2890 2891
      }
      /* scan trough all columns to get new column grant */
2892
      column_priv= 0;
unknown's avatar
unknown committed
2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908
      for (uint idx=0 ; idx < grant_table->hash_columns.records ; idx++)
      {
	grant_column= (GRANT_COLUMN*) hash_element(&grant_table->hash_columns,
						   idx);
	grant_column->rights&= ~rights;		// Fix other columns
	column_priv|= grant_column->rights;
      }
    }
    else
    {
      column_priv|= grant_table->cols;
    }


    /* update table and columns */

unknown's avatar
VIEW  
unknown committed
2909
    if (replace_table_table(thd, grant_table, tables[1].table, *Str,
2910
			    db_name, table_name,
unknown's avatar
unknown committed
2911
			    rights, column_priv, revoke_grant))
2912 2913
    {
      /* Should only happen if table is crashed */
unknown's avatar
unknown committed
2914
      result= TRUE;			       /* purecov: deadcode */
unknown's avatar
unknown committed
2915 2916 2917
    }
    else if (tables[2].table)
    {
unknown's avatar
VIEW  
unknown committed
2918
      if ((replace_column_table(grant_table, tables[2].table, *Str,
unknown's avatar
unknown committed
2919
				columns,
2920
				db_name, table_name,
unknown's avatar
unknown committed
2921 2922
				rights, revoke_grant)))
      {
unknown's avatar
unknown committed
2923
	result= TRUE;
unknown's avatar
unknown committed
2924 2925 2926 2927
      }
    }
  }
  grant_option=TRUE;
unknown's avatar
unknown committed
2928
  thd->mem_root= old_root;
2929
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
2930
  if (!result)
2931
    send_ok(thd);
2932
  /* Tables are automatically closed */
unknown's avatar
unknown committed
2933 2934 2935 2936
  DBUG_RETURN(result);
}


2937
/*
2938
  Store routine level grants in the privilege tables
2939 2940

  SYNOPSIS
2941
    mysql_routine_grant()
2942
    thd			Thread handle
2943 2944
    table_list		List of routines to give grant
    is_proc             true indicates routine list are procedures
2945 2946 2947 2948 2949 2950 2951 2952 2953
    user_list		List of users to give grant
    rights		Table level grant
    revoke_grant	Set to 1 if this is a REVOKE command

  RETURN
    0	ok
    1	error
*/

2954 2955 2956
bool mysql_routine_grant(THD *thd, TABLE_LIST *table_list, bool is_proc,
			 List <LEX_USER> &user_list, ulong rights,
			 bool revoke_grant, bool no_error)
2957 2958 2959 2960 2961
{
  List_iterator <LEX_USER> str_list (user_list);
  LEX_USER *Str;
  TABLE_LIST tables[2];
  bool create_new_users=0, result=0;
2962
  char *db_name, *table_name;
2963
  DBUG_ENTER("mysql_routine_grant");
2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981

  if (!initialized)
  {
    if (!no_error)
      my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0),
               "--skip-grant-tables");
    DBUG_RETURN(TRUE);
  }
  if (rights & ~PROC_ACLS)
  {
    if (!no_error)
      my_message(ER_ILLEGAL_GRANT_FOR_TABLE, ER(ER_ILLEGAL_GRANT_FOR_TABLE),
        	 MYF(0));
    DBUG_RETURN(TRUE);
  }

  if (!revoke_grant)
  {
2982
    if (sp_exists_routine(thd, table_list, is_proc, no_error)<0)
2983 2984 2985 2986 2987 2988
      DBUG_RETURN(TRUE);
  }

  /* open the mysql.user and mysql.procs_priv tables */

  bzero((char*) &tables,sizeof(tables));
2989 2990
  tables[0].alias=tables[0].table_name= (char*) "user";
  tables[1].alias=tables[1].table_name= (char*) "procs_priv";
2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006
  tables[0].next_local= tables[0].next_global= tables+1;
  tables[0].lock_type=tables[1].lock_type=TL_WRITE;
  tables[0].db=tables[1].db=(char*) "mysql";

#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
  if (thd->slave_thread && table_rules_on)
  {
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
    */
    tables[0].updating= tables[1].updating= 1;
3007
    if (!tables_ok(thd, tables))
3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041
      DBUG_RETURN(FALSE);
  }
#endif

  if (simple_open_n_lock_tables(thd,tables))
  {						// Should never happen
    close_thread_tables(thd);
    DBUG_RETURN(TRUE);
  }

  if (!revoke_grant)
    create_new_users= test_if_create_new_users(thd);
  rw_wrlock(&LOCK_grant);
  MEM_ROOT *old_root= thd->mem_root;
  thd->mem_root= &memex;

  DBUG_PRINT("info",("now time to iterate and add users"));

  while ((Str= str_list++))
  {
    int error;
    GRANT_NAME *grant_name;
    if (Str->host.length > HOSTNAME_LENGTH ||
	Str->user.length > USERNAME_LENGTH)
    {
      if (!no_error)
	my_message(ER_GRANT_WRONG_HOST_OR_USER, ER(ER_GRANT_WRONG_HOST_OR_USER),
                   MYF(0));
      result= TRUE;
      continue;
    }
    /* Create user if needed */
    pthread_mutex_lock(&acl_cache->lock);
    error=replace_user_table(thd, tables[0].table, *Str,
unknown's avatar
unknown committed
3042
			     0, revoke_grant, create_new_users,
unknown's avatar
unknown committed
3043 3044
                             test(thd->variables.sql_mode &
                                  MODE_NO_AUTO_CREATE_USER));
3045 3046 3047 3048 3049 3050 3051 3052
    pthread_mutex_unlock(&acl_cache->lock);
    if (error)
    {
      result= TRUE;				// Remember error
      continue;					// Add next user
    }

    db_name= table_list->db;
3053
    table_name= table_list->table_name;
3054

3055 3056
    grant_name= routine_hash_search(Str->host.str, NullS, db_name,
                                    Str->user.str, table_name, is_proc, 1);
3057 3058 3059 3060 3061 3062
    if (!grant_name)
    {
      if (revoke_grant)
      {
        if (!no_error)
          my_error(ER_NONEXISTING_PROC_GRANT, MYF(0),
3063
		   Str->user.str, Str->host.str, table_name);
3064 3065 3066 3067
	result= TRUE;
	continue;
      }
      grant_name= new GRANT_NAME(Str->host.str, db_name,
3068
				 Str->user.str, table_name,
3069 3070 3071 3072 3073 3074
				 rights);
      if (!grant_name)
      {
        result= TRUE;
	continue;
      }
3075
      my_hash_insert(is_proc ? &proc_priv_hash : &func_priv_hash,(byte*) grant_name);
3076
    }
3077

3078 3079
    if (replace_routine_table(thd, grant_name, tables[1].table, *Str,
			   db_name, table_name, is_proc, rights, revoke_grant))
3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094
    {
      result= TRUE;
      continue;
    }
  }
  grant_option=TRUE;
  thd->mem_root= old_root;
  rw_unlock(&LOCK_grant);
  if (!result && !no_error)
    send_ok(thd);
  /* Tables are automatically closed */
  DBUG_RETURN(result);
}


unknown's avatar
unknown committed
3095 3096
bool mysql_grant(THD *thd, const char *db, List <LEX_USER> &list,
                 ulong rights, bool revoke_grant)
unknown's avatar
unknown committed
3097 3098 3099
{
  List_iterator <LEX_USER> str_list (list);
  LEX_USER *Str;
unknown's avatar
unknown committed
3100
  char tmp_db[NAME_LEN+1];
unknown's avatar
unknown committed
3101
  bool create_new_users=0;
unknown's avatar
unknown committed
3102 3103 3104 3105
  TABLE_LIST tables[2];
  DBUG_ENTER("mysql_grant");
  if (!initialized)
  {
unknown's avatar
unknown committed
3106 3107
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0),
             "--skip-grant-tables");	/* purecov: tested */
unknown's avatar
unknown committed
3108
    DBUG_RETURN(TRUE);				/* purecov: tested */
unknown's avatar
unknown committed
3109 3110
  }

unknown's avatar
unknown committed
3111 3112 3113
  if (lower_case_table_names && db)
  {
    strmov(tmp_db,db);
3114
    my_casedn_str(files_charset_info, tmp_db);
unknown's avatar
unknown committed
3115 3116
    db=tmp_db;
  }
unknown's avatar
unknown committed
3117 3118

  /* open the mysql.user and mysql.db tables */
3119
  bzero((char*) &tables,sizeof(tables));
3120 3121
  tables[0].alias=tables[0].table_name=(char*) "user";
  tables[1].alias=tables[1].table_name=(char*) "db";
unknown's avatar
VIEW  
unknown committed
3122
  tables[0].next_local= tables[0].next_global= tables+1;
unknown's avatar
unknown committed
3123 3124
  tables[0].lock_type=tables[1].lock_type=TL_WRITE;
  tables[0].db=tables[1].db=(char*) "mysql";
3125 3126 3127 3128 3129 3130

#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
3131 3132
  if (thd->slave_thread && table_rules_on)
  {
unknown's avatar
unknown committed
3133 3134 3135
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
3136
    */
3137
    tables[0].updating= tables[1].updating= 1;
3138
    if (!tables_ok(thd, tables))
unknown's avatar
unknown committed
3139
      DBUG_RETURN(FALSE);
3140
  }
3141 3142
#endif

3143
  if (simple_open_n_lock_tables(thd,tables))
unknown's avatar
unknown committed
3144 3145
  {						// This should never happen
    close_thread_tables(thd);			/* purecov: deadcode */
unknown's avatar
unknown committed
3146
    DBUG_RETURN(TRUE);				/* purecov: deadcode */
unknown's avatar
unknown committed
3147 3148
  }

unknown's avatar
unknown committed
3149 3150
  if (!revoke_grant)
    create_new_users= test_if_create_new_users(thd);
unknown's avatar
unknown committed
3151

3152
  /* go through users in user_list */
3153
  rw_wrlock(&LOCK_grant);
unknown's avatar
unknown committed
3154 3155 3156 3157 3158 3159 3160 3161 3162
  VOID(pthread_mutex_lock(&acl_cache->lock));
  grant_version++;

  int result=0;
  while ((Str = str_list++))
  {
    if (Str->host.length > HOSTNAME_LENGTH ||
	Str->user.length > USERNAME_LENGTH)
    {
unknown's avatar
unknown committed
3163 3164
      my_message(ER_GRANT_WRONG_HOST_OR_USER, ER(ER_GRANT_WRONG_HOST_OR_USER),
                 MYF(0));
unknown's avatar
unknown committed
3165 3166 3167
      result= -1;
      continue;
    }
unknown's avatar
unknown committed
3168 3169
    if (replace_user_table(thd, tables[0].table, *Str,
                           (!db ? rights : 0), revoke_grant, create_new_users,
unknown's avatar
unknown committed
3170 3171
                           test(thd->variables.sql_mode &
                                MODE_NO_AUTO_CREATE_USER)))
3172
      result= -1;
unknown's avatar
unknown committed
3173
    else if (db)
unknown's avatar
unknown committed
3174
    {
unknown's avatar
unknown committed
3175 3176 3177 3178 3179 3180 3181 3182 3183
      ulong db_rights= rights & DB_ACLS;
      if (db_rights  == rights)
      {
	if (replace_db_table(tables[1].table, db, *Str, db_rights,
			     revoke_grant))
	  result= -1;
      }
      else
      {
unknown's avatar
unknown committed
3184
	my_error(ER_WRONG_USAGE, MYF(0), "DB GRANT", "GLOBAL PRIVILEGES");
unknown's avatar
unknown committed
3185
	result= -1;
unknown's avatar
unknown committed
3186
      }
unknown's avatar
unknown committed
3187
    }
unknown's avatar
unknown committed
3188 3189
  }
  VOID(pthread_mutex_unlock(&acl_cache->lock));
3190
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
3191 3192 3193
  close_thread_tables(thd);

  if (!result)
3194
    send_ok(thd);
unknown's avatar
unknown committed
3195 3196 3197
  DBUG_RETURN(result);
}

unknown's avatar
unknown committed
3198 3199

/* Free grant array if possible */
unknown's avatar
unknown committed
3200 3201 3202 3203 3204

void  grant_free(void)
{
  DBUG_ENTER("grant_free");
  grant_option = FALSE;
3205
  hash_free(&column_priv_hash);
3206
  hash_free(&proc_priv_hash);
unknown's avatar
unknown committed
3207
  hash_free(&func_priv_hash);
3208
  free_root(&memex,MYF(0));
unknown's avatar
unknown committed
3209 3210 3211 3212
  DBUG_VOID_RETURN;
}


3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223
/*
  Initialize structures responsible for table/column-level privilege checking
  and load information for them from tables in the 'mysql' database.

  SYNOPSIS
    grant_init()

  RETURN VALUES
    0	ok
    1	Could not initialize grant's
*/
unknown's avatar
unknown committed
3224

3225
my_bool grant_init()
unknown's avatar
unknown committed
3226
{
unknown's avatar
unknown committed
3227
  THD  *thd;
3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258
  my_bool return_val;
  DBUG_ENTER("grant_init");

  if (!(thd= new THD))
    DBUG_RETURN(1);				/* purecov: deadcode */
  thd->store_globals();
  return_val=  grant_reload(thd);
  delete thd;
  /* Remember that we don't have a THD */
  my_pthread_setspecific_ptr(THR_THD,  0);
  DBUG_RETURN(return_val);
}


/*
  Initialize structures responsible for table/column-level privilege
  checking and load information about grants from open privilege tables.

  SYNOPSIS
    grant_load()
      thd     Current thread
      tables  List containing open "mysql.tables_priv" and
              "mysql.columns_priv" tables.

  RETURN VALUES
    FALSE - success
    TRUE  - error
*/

static my_bool grant_load(TABLE_LIST *tables)
{
unknown's avatar
unknown committed
3259
  MEM_ROOT *memex_ptr;
3260
  my_bool return_val= 1;
3261
  TABLE *t_table, *c_table, *p_table;
unknown's avatar
SCRUM  
unknown committed
3262
  bool check_no_resolve= specialflag & SPECIAL_NO_RESOLVE;
3263 3264 3265
  MEM_ROOT **save_mem_root_ptr= my_pthread_getspecific_ptr(MEM_ROOT**,
                                                           THR_MALLOC);
  DBUG_ENTER("grant_load");
unknown's avatar
unknown committed
3266 3267

  grant_option = FALSE;
3268
  (void) hash_init(&column_priv_hash,system_charset_info,
unknown's avatar
unknown committed
3269
		   0,0,0, (hash_get_key) get_grant_table,
unknown's avatar
unknown committed
3270
		   (hash_free_key) free_grant_table,0);
3271 3272 3273
  (void) hash_init(&proc_priv_hash,system_charset_info,
		   0,0,0, (hash_get_key) get_grant_table,
		   0,0);
3274 3275 3276
  (void) hash_init(&func_priv_hash,system_charset_info,
		   0,0,0, (hash_get_key) get_grant_table,
		   0,0);
3277
  init_sql_alloc(&memex, ACL_ALLOC_BLOCK_SIZE, 0);
unknown's avatar
unknown committed
3278 3279

  t_table = tables[0].table; c_table = tables[1].table;
3280
  p_table= tables[2].table;
unknown's avatar
unknown committed
3281
  t_table->file->ha_index_init(0);
3282 3283
  p_table->file->ha_index_init(0);
  if (!t_table->file->index_first(t_table->record[0]))
unknown's avatar
unknown committed
3284
  {
3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295
    memex_ptr= &memex;
    my_pthread_setspecific_ptr(THR_MALLOC, &memex_ptr);
    do
    {
      GRANT_TABLE *mem_check;
      if (!(mem_check=new GRANT_TABLE(t_table,c_table)))
      {
	/* This could only happen if we are out memory */
	grant_option= FALSE;
	goto end_unlock;
      }
unknown's avatar
unknown committed
3296

3297 3298
      if (check_no_resolve)
      {
3299
	if (hostname_requires_resolving(mem_check->host.hostname))
3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320
	{
          sql_print_warning("'tables_priv' entry '%s %s@%s' "
                            "ignored in --skip-name-resolve mode.",
                            mem_check->tname, mem_check->user,
                            mem_check->host, mem_check->host);
	  continue;
	}
      }

      if (! mem_check->ok())
	delete mem_check;
      else if (my_hash_insert(&column_priv_hash,(byte*) mem_check))
      {
	delete mem_check;
	grant_option= FALSE;
	goto end_unlock;
      }
    }
    while (!t_table->file->index_next(t_table->record[0]));
  }
  if (!p_table->file->index_first(p_table->record[0]))
unknown's avatar
unknown committed
3321
  {
3322 3323 3324
    memex_ptr= &memex;
    my_pthread_setspecific_ptr(THR_MALLOC, &memex_ptr);
    do
unknown's avatar
unknown committed
3325
    {
3326
      GRANT_NAME *mem_check;
3327
      HASH *hash;
3328 3329 3330 3331 3332 3333
      if (!(mem_check=new GRANT_NAME(p_table)))
      {
	/* This could only happen if we are out memory */
	grant_option= FALSE;
	goto end_unlock;
      }
unknown's avatar
SCRUM  
unknown committed
3334

3335
      if (check_no_resolve)
unknown's avatar
SCRUM  
unknown committed
3336
      {
unknown's avatar
unknown committed
3337
	if (hostname_requires_resolving(mem_check->host.hostname))
3338 3339 3340 3341
	{
          sql_print_warning("'procs_priv' entry '%s %s@%s' "
                            "ignored in --skip-name-resolve mode.",
                            mem_check->tname, mem_check->user,
unknown's avatar
Merge  
unknown committed
3342
                            mem_check->host);
3343 3344
	  continue;
	}
unknown's avatar
SCRUM  
unknown committed
3345
      }
3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361
      if (p_table->field[4]->val_int() == TYPE_ENUM_PROCEDURE)
      {
        hash= &proc_priv_hash;
      }
      else
      if (p_table->field[4]->val_int() == TYPE_ENUM_FUNCTION)
      {
        hash= &func_priv_hash;
      }
      else
      {
        sql_print_warning("'procs_priv' entry '%s' "
                          "ignored, bad routine type",
                          mem_check->tname);
	continue;
      }
unknown's avatar
SCRUM  
unknown committed
3362

3363 3364 3365
      mem_check->privs= fix_rights_for_procedure(mem_check->privs);
      if (! mem_check->ok())
	delete mem_check;
3366
      else if (my_hash_insert(hash, (byte*) mem_check))
3367 3368 3369 3370 3371
      {
	delete mem_check;
	grant_option= FALSE;
	goto end_unlock;
      }
unknown's avatar
SCRUM  
unknown committed
3372
    }
3373
    while (!p_table->file->index_next(p_table->record[0]));
unknown's avatar
unknown committed
3374
  }
3375
  grant_option= TRUE;
3376 3377 3378
  return_val=0;					// Return ok

end_unlock:
unknown's avatar
unknown committed
3379
  t_table->file->ha_index_end();
3380
  p_table->file->ha_index_end();
3381
  my_pthread_setspecific_ptr(THR_MALLOC, save_mem_root_ptr);
3382
  DBUG_RETURN(return_val);
unknown's avatar
unknown committed
3383 3384 3385
}


3386
/*
3387
  Reload information about table and column level privileges if possible.
3388 3389 3390

  SYNOPSIS
    grant_reload()
3391
      thd  Current thread
3392 3393

  NOTES
3394 3395 3396 3397 3398 3399 3400 3401
    Locked tables are checked by acl_reload() and doesn't have to be checked
    in this call.
    This function is also used for initialization of structures responsible
    for table/column-level privilege checking.

  RETURN VALUE
    FALSE Success
    TRUE  Error
3402
*/
unknown's avatar
unknown committed
3403

3404
my_bool grant_reload(THD *thd)
unknown's avatar
unknown committed
3405
{
3406
  TABLE_LIST tables[3];
3407
  HASH old_column_priv_hash, old_proc_priv_hash, old_func_priv_hash;
3408
  bool old_grant_option;
unknown's avatar
unknown committed
3409
  MEM_ROOT old_mem;
3410
  my_bool return_val= 1;
unknown's avatar
unknown committed
3411 3412
  DBUG_ENTER("grant_reload");

3413 3414 3415 3416 3417
  /* Don't do anything if running with --skip-grant-tables */
  if (!initialized)
    DBUG_RETURN(0);

  bzero((char*) tables, sizeof(tables));
3418 3419 3420 3421 3422 3423 3424
  tables[0].alias= tables[0].table_name= (char*) "tables_priv";
  tables[1].alias= tables[1].table_name= (char*) "columns_priv";
  tables[2].alias= tables[2].table_name= (char*) "procs_priv";
  tables[0].db= tables[1].db= tables[2].db= (char *) "mysql";
  tables[0].next_local= tables[0].next_global= tables+1;
  tables[1].next_local= tables[1].next_global= tables+2;
  tables[0].lock_type= tables[1].lock_type= tables[2].lock_type= TL_READ;
3425 3426 3427 3428 3429 3430 3431 3432

  /*
    To avoid deadlocks we should obtain table locks before
    obtaining LOCK_grant rwlock.
  */
  if (simple_open_n_lock_tables(thd, tables))
    goto end;

3433
  rw_wrlock(&LOCK_grant);
unknown's avatar
unknown committed
3434
  grant_version++;
3435
  old_column_priv_hash= column_priv_hash;
3436
  old_proc_priv_hash= proc_priv_hash;
3437
  old_func_priv_hash= func_priv_hash;
unknown's avatar
unknown committed
3438
  old_grant_option= grant_option;
unknown's avatar
unknown committed
3439
  old_mem= memex;
unknown's avatar
unknown committed
3440

3441
  if ((return_val= grant_load(tables)))
unknown's avatar
unknown committed
3442
  {						// Error. Revert to old hash
3443
    DBUG_PRINT("error",("Reverting to old privileges"));
unknown's avatar
unknown committed
3444
    grant_free();				/* purecov: deadcode */
3445
    column_priv_hash= old_column_priv_hash;	/* purecov: deadcode */
3446
    proc_priv_hash= old_proc_priv_hash;
3447
    func_priv_hash= old_func_priv_hash;
unknown's avatar
unknown committed
3448
    grant_option= old_grant_option;		/* purecov: deadcode */
unknown's avatar
unknown committed
3449
    memex= old_mem;				/* purecov: deadcode */
unknown's avatar
unknown committed
3450 3451 3452
  }
  else
  {
3453
    hash_free(&old_column_priv_hash);
3454
    hash_free(&old_proc_priv_hash);
3455
    hash_free(&old_func_priv_hash);
3456
    free_root(&old_mem,MYF(0));
unknown's avatar
unknown committed
3457
  }
3458
  rw_unlock(&LOCK_grant);
3459 3460 3461
end:
  close_thread_tables(thd);
  DBUG_RETURN(return_val);
unknown's avatar
unknown committed
3462 3463 3464 3465
}


/****************************************************************************
3466
  Check table level grants
3467

3468
  SYNOPSIS
3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481
   bool check_grant()
   thd		Thread handler
   want_access  Bits of privileges user needs to have
   tables	List of tables to check. The user should have 'want_access'
		to all tables in list.
   show_table	<> 0 if we are in show table. In this case it's enough to have
	        any privilege for the table
   number	Check at most this number of tables.
   no_errors	If 0 then we write an error. The error is sent directly to
		the client

   RETURN
     0  ok
3482
     1  Error: User did not have the requested privileges
unknown's avatar
unknown committed
3483 3484
****************************************************************************/

unknown's avatar
unknown committed
3485
bool check_grant(THD *thd, ulong want_access, TABLE_LIST *tables,
unknown's avatar
unknown committed
3486
		 uint show_table, uint number, bool no_errors)
unknown's avatar
unknown committed
3487 3488 3489
{
  TABLE_LIST *table;
  char *user = thd->priv_user;
3490 3491
  DBUG_ENTER("check_grant");
  DBUG_ASSERT(number > 0);
unknown's avatar
unknown committed
3492

3493
  want_access&= ~thd->master_access;
unknown's avatar
unknown committed
3494
  if (!want_access)
3495
    DBUG_RETURN(0);                             // ok
unknown's avatar
unknown committed
3496

3497
  rw_rdlock(&LOCK_grant);
unknown's avatar
VIEW  
unknown committed
3498
  for (table= tables; table && number--; table= table->next_global)
unknown's avatar
unknown committed
3499
  {
3500
    GRANT_TABLE *grant_table;
3501
    if (!(~table->grant.privilege & want_access) || 
3502
        table->derived || table->schema_table || table->belong_to_view)
unknown's avatar
unknown committed
3503
    {
unknown's avatar
VIEW  
unknown committed
3504 3505 3506 3507 3508
      /*
        It is subquery in the FROM clause. VIEW set table->derived after
        table opening, but this function always called before table opening.
      */
      table->grant.want_privilege= 0;
unknown's avatar
unknown committed
3509 3510
      continue;					// Already checked
    }
3511
    if (!(grant_table= table_hash_search(thd->host,thd->ip,
3512
                                         table->db,user, table->table_name,0)))
unknown's avatar
unknown committed
3513 3514 3515 3516
    {
      want_access &= ~table->grant.privilege;
      goto err;					// No grants
    }
unknown's avatar
unknown committed
3517 3518
    if (show_table)
      continue;					// We have some priv on this
unknown's avatar
unknown committed
3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534

    table->grant.grant_table=grant_table;	// Remember for column test
    table->grant.version=grant_version;
    table->grant.privilege|= grant_table->privs;
    table->grant.want_privilege= ((want_access & COL_ACLS)
				  & ~table->grant.privilege);

    if (!(~table->grant.privilege & want_access))
      continue;

    if (want_access & ~(grant_table->cols | table->grant.privilege))
    {
      want_access &= ~(grant_table->cols | table->grant.privilege);
      goto err;					// impossible
    }
  }
3535
  rw_unlock(&LOCK_grant);
3536
  DBUG_RETURN(0);
unknown's avatar
unknown committed
3537

3538
err:
3539
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
3540
  if (!no_errors)				// Not a silent skip of table
unknown's avatar
unknown committed
3541
  {
3542 3543
    char command[128];
    get_privilege_desc(command, sizeof(command), want_access);
3544 3545 3546 3547
    my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0),
             command,
             thd->priv_user,
             thd->host_or_ip,
3548
             table ? table->table_name : "unknown");
unknown's avatar
unknown committed
3549
  }
3550
  DBUG_RETURN(1);
unknown's avatar
unknown committed
3551 3552 3553
}


unknown's avatar
VIEW  
unknown committed
3554
bool check_grant_column(THD *thd, GRANT_INFO *grant,
3555
			const char *db_name, const char *table_name,
unknown's avatar
VIEW  
unknown committed
3556
			const char *name, uint length, uint show_tables)
unknown's avatar
unknown committed
3557 3558 3559
{
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;
unknown's avatar
VIEW  
unknown committed
3560
  ulong want_access= grant->want_privilege & ~grant->privilege;
unknown's avatar
unknown committed
3561 3562 3563
  DBUG_ENTER("check_grant_column");
  DBUG_PRINT("enter", ("table: %s  want_access: %u", table_name, want_access));

unknown's avatar
unknown committed
3564
  if (!want_access)
unknown's avatar
unknown committed
3565
    DBUG_RETURN(0);				// Already checked
unknown's avatar
unknown committed
3566

3567
  rw_rdlock(&LOCK_grant);
unknown's avatar
unknown committed
3568

3569
  /* reload table if someone has modified any grants */
unknown's avatar
unknown committed
3570

unknown's avatar
VIEW  
unknown committed
3571
  if (grant->version != grant_version)
unknown's avatar
unknown committed
3572
  {
unknown's avatar
VIEW  
unknown committed
3573 3574
    grant->grant_table=
      table_hash_search(thd->host, thd->ip, db_name,
unknown's avatar
unknown committed
3575
			thd->priv_user,
unknown's avatar
unknown committed
3576
			table_name, 0);         /* purecov: inspected */
unknown's avatar
VIEW  
unknown committed
3577
    grant->version= grant_version;		/* purecov: inspected */
unknown's avatar
unknown committed
3578
  }
unknown's avatar
VIEW  
unknown committed
3579
  if (!(grant_table= grant->grant_table))
unknown's avatar
unknown committed
3580 3581 3582 3583 3584
    goto err;					/* purecov: deadcode */

  grant_column=column_hash_search(grant_table, name, length);
  if (grant_column && !(~grant_column->rights & want_access))
  {
3585
    rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
3586
    DBUG_RETURN(0);
unknown's avatar
unknown committed
3587 3588
  }
#ifdef NOT_USED
unknown's avatar
VIEW  
unknown committed
3589
  if (show_tables && (grant_column || grant->privilege & COL_ACLS))
unknown's avatar
unknown committed
3590
  {
3591
    rw_unlock(&LOCK_grant);			/* purecov: deadcode */
unknown's avatar
unknown committed
3592
    DBUG_RETURN(0);				/* purecov: deadcode */
unknown's avatar
unknown committed
3593 3594 3595
  }
#endif

3596
err:
3597
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
3598 3599
  if (!show_tables)
  {
unknown's avatar
unknown committed
3600 3601
    char command[128];
    get_privilege_desc(command, sizeof(command), want_access);
3602 3603 3604 3605 3606 3607
    my_error(ER_COLUMNACCESS_DENIED_ERROR, MYF(0),
             command,
             thd->priv_user,
             thd->host_or_ip,
             name,
             table_name);
unknown's avatar
unknown committed
3608
  }
unknown's avatar
unknown committed
3609
  DBUG_RETURN(1);
unknown's avatar
unknown committed
3610 3611 3612
}


unknown's avatar
VIEW  
unknown committed
3613
bool check_grant_all_columns(THD *thd, ulong want_access, GRANT_INFO *grant,
3614
                             const char* db_name, const char *table_name,
unknown's avatar
VIEW  
unknown committed
3615
                             Field_iterator *fields)
unknown's avatar
unknown committed
3616 3617 3618 3619
{
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;

unknown's avatar
VIEW  
unknown committed
3620
  want_access &= ~grant->privilege;
unknown's avatar
unknown committed
3621
  if (!want_access)
unknown's avatar
unknown committed
3622
    return 0;				// Already checked
unknown's avatar
unknown committed
3623 3624
  if (!grant_option)
    goto err2;
unknown's avatar
unknown committed
3625

3626
  rw_rdlock(&LOCK_grant);
unknown's avatar
unknown committed
3627

3628
  /* reload table if someone has modified any grants */
unknown's avatar
unknown committed
3629

unknown's avatar
VIEW  
unknown committed
3630
  if (grant->version != grant_version)
unknown's avatar
unknown committed
3631
  {
unknown's avatar
VIEW  
unknown committed
3632 3633
    grant->grant_table=
      table_hash_search(thd->host, thd->ip, db_name,
unknown's avatar
unknown committed
3634
			thd->priv_user,
unknown's avatar
VIEW  
unknown committed
3635 3636
			table_name, 0);	/* purecov: inspected */
    grant->version= grant_version;		/* purecov: inspected */
unknown's avatar
unknown committed
3637
  }
3638
  /* The following should always be true */
unknown's avatar
VIEW  
unknown committed
3639
  if (!(grant_table= grant->grant_table))
unknown's avatar
unknown committed
3640 3641
    goto err;					/* purecov: inspected */

3642
  for (; !fields->end_of_fields(); fields->next())
unknown's avatar
unknown committed
3643
  {
unknown's avatar
VIEW  
unknown committed
3644 3645 3646
    const char *field_name= fields->name();
    grant_column= column_hash_search(grant_table, field_name,
				    (uint) strlen(field_name));
unknown's avatar
unknown committed
3647 3648 3649
    if (!grant_column || (~grant_column->rights & want_access))
      goto err;
  }
3650
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
3651 3652
  return 0;

unknown's avatar
unknown committed
3653
err:
3654
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
3655
err2:
3656 3657
  char command[128];
  get_privilege_desc(command, sizeof(command), want_access);
3658 3659 3660 3661 3662 3663
  my_error(ER_COLUMNACCESS_DENIED_ERROR, MYF(0),
           command,
           thd->priv_user,
           thd->host_or_ip,
           fields->name(),
           table_name);
unknown's avatar
unknown committed
3664 3665 3666 3667
  return 1;
}


3668
/*
unknown's avatar
unknown committed
3669
  Check if a user has the right to access a database
3670
  Access is accepted if he has a grant for any table/routine in the database
unknown's avatar
unknown committed
3671
  Return 1 if access is denied
3672
*/
unknown's avatar
unknown committed
3673 3674 3675 3676 3677

bool check_grant_db(THD *thd,const char *db)
{
  char helping [NAME_LEN+USERNAME_LENGTH+2];
  uint len;
unknown's avatar
unknown committed
3678
  bool error= 1;
unknown's avatar
unknown committed
3679

unknown's avatar
unknown committed
3680
  len= (uint) (strmov(strmov(helping,thd->priv_user)+1,db)-helping)+ 1;
3681
  rw_rdlock(&LOCK_grant);
unknown's avatar
unknown committed
3682

3683
  for (uint idx=0 ; idx < column_priv_hash.records ; idx++)
unknown's avatar
unknown committed
3684
  {
3685 3686
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  idx);
unknown's avatar
unknown committed
3687 3688
    if (len < grant_table->key_length &&
	!memcmp(grant_table->hash_key,helping,len) &&
3689
        compare_hostname(&grant_table->host, thd->host, thd->ip))
unknown's avatar
unknown committed
3690 3691 3692 3693 3694
    {
      error=0;					// Found match
      break;
    }
  }
3695
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
3696 3697 3698
  return error;
}

3699 3700

/****************************************************************************
3701
  Check routine level grants
3702 3703

  SYNPOSIS
3704
   bool check_grant_routine()
3705 3706
   thd		Thread handler
   want_access  Bits of privileges user needs to have
3707 3708
   procs	List of routines to check. The user should have 'want_access'
   is_proc	True if the list is all procedures, else functions
3709 3710 3711 3712 3713 3714 3715 3716
   no_errors	If 0 then we write an error. The error is sent directly to
		the client

   RETURN
     0  ok
     1  Error: User did not have the requested privielges
****************************************************************************/

3717 3718
bool check_grant_routine(THD *thd, ulong want_access, 
			 TABLE_LIST *procs, bool is_proc, bool no_errors)
3719 3720 3721 3722
{
  TABLE_LIST *table;
  char *user= thd->priv_user;
  char *host= thd->priv_host;
3723
  DBUG_ENTER("check_grant_routine");
3724 3725 3726 3727 3728 3729 3730 3731 3732

  want_access&= ~thd->master_access;
  if (!want_access)
    DBUG_RETURN(0);                             // ok

  rw_rdlock(&LOCK_grant);
  for (table= procs; table; table= table->next_global)
  {
    GRANT_NAME *grant_proc;
3733 3734
    if ((grant_proc= routine_hash_search(host,thd->ip, table->db, user,
					 table->table_name, is_proc, 0)))
3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751
      table->grant.privilege|= grant_proc->privs;

    if (want_access & ~table->grant.privilege)
    {
      want_access &= ~table->grant.privilege;
      goto err;
    }
  }
  rw_unlock(&LOCK_grant);
  DBUG_RETURN(0);
err:
  rw_unlock(&LOCK_grant);
  if (!no_errors)
  {
    char buff[1024];
    const char *command="";
    if (table)
3752
      strxmov(buff, table->db, ".", table->table_name, NullS);
3753 3754 3755
    if (want_access & EXECUTE_ACL)
      command= "execute";
    else if (want_access & ALTER_PROC_ACL)
3756
      command= "alter routine";
3757 3758 3759 3760 3761 3762 3763 3764 3765
    else if (want_access & GRANT_ACL)
      command= "grant";
    my_error(ER_PROCACCESS_DENIED_ERROR, MYF(0),
             command, user, host, table ? buff : "unknown");
  }
  DBUG_RETURN(1);
}


3766 3767
/*
  Check if routine has any of the 
3768
  routine level grants
3769 3770 3771 3772 3773 3774 3775 3776 3777
  
  SYNPOSIS
   bool    check_routine_level_acl()
   thd	        Thread handler
   db           Database name
   name         Routine name

  RETURN
   0            Ok 
3778
   1            error
3779 3780
*/

unknown's avatar
unknown committed
3781 3782
bool check_routine_level_acl(THD *thd, const char *db, const char *name, 
                             bool is_proc)
3783 3784 3785 3786 3787 3788
{
  bool no_routine_acl= 1;
  if (grant_option)
  {
    GRANT_NAME *grant_proc;
    rw_rdlock(&LOCK_grant);
3789 3790
    if ((grant_proc= routine_hash_search(thd->priv_host, thd->ip, db,
                                         thd->priv_user, name, is_proc, 0)))
3791 3792 3793 3794 3795 3796 3797
      no_routine_acl= !(grant_proc->privs & SHOW_PROC_ACLS);
    rw_unlock(&LOCK_grant);
  }
  return no_routine_acl;
}


unknown's avatar
unknown committed
3798
/*****************************************************************************
unknown's avatar
unknown committed
3799
  Functions to retrieve the grant for a table/column  (for SHOW functions)
unknown's avatar
unknown committed
3800 3801
*****************************************************************************/

unknown's avatar
unknown committed
3802
ulong get_table_grant(THD *thd, TABLE_LIST *table)
unknown's avatar
unknown committed
3803
{
unknown's avatar
unknown committed
3804
  ulong privilege;
unknown's avatar
unknown committed
3805 3806 3807 3808
  char *user = thd->priv_user;
  const char *db = table->db ? table->db : thd->db;
  GRANT_TABLE *grant_table;

3809
  rw_rdlock(&LOCK_grant);
3810 3811 3812
#ifdef EMBEDDED_LIBRARY
  grant_table= NULL;
#else
unknown's avatar
unknown committed
3813
  grant_table= table_hash_search(thd->host, thd->ip, db, user,
3814
				 table->table_name, 0);
3815
#endif
unknown's avatar
unknown committed
3816 3817 3818 3819
  table->grant.grant_table=grant_table; // Remember for column test
  table->grant.version=grant_version;
  if (grant_table)
    table->grant.privilege|= grant_table->privs;
3820
  privilege= table->grant.privilege;
3821
  rw_unlock(&LOCK_grant);
3822
  return privilege;
unknown's avatar
unknown committed
3823 3824 3825
}


unknown's avatar
unknown committed
3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843
/*
  Determine the access priviliges for a field.

  SYNOPSIS
    get_column_grant()
    thd         thread handler
    grant       grants table descriptor
    db_name     name of database that the field belongs to
    table_name  name of table that the field belongs to
    field_name  name of field

  DESCRIPTION
    The procedure may also modify: grant->grant_table and grant->version.

  RETURN
    The access priviliges for the field db_name.table_name.field_name
*/

unknown's avatar
VIEW  
unknown committed
3844 3845 3846
ulong get_column_grant(THD *thd, GRANT_INFO *grant,
                       const char *db_name, const char *table_name,
                       const char *field_name)
unknown's avatar
unknown committed
3847 3848 3849
{
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;
unknown's avatar
unknown committed
3850
  ulong priv;
unknown's avatar
unknown committed
3851

3852
  rw_rdlock(&LOCK_grant);
3853
  /* reload table if someone has modified any grants */
unknown's avatar
VIEW  
unknown committed
3854
  if (grant->version != grant_version)
unknown's avatar
unknown committed
3855
  {
unknown's avatar
VIEW  
unknown committed
3856 3857
    grant->grant_table=
      table_hash_search(thd->host, thd->ip, db_name,
unknown's avatar
unknown committed
3858
			thd->priv_user,
unknown's avatar
VIEW  
unknown committed
3859 3860
			table_name, 0);	        /* purecov: inspected */
    grant->version= grant_version;              /* purecov: inspected */
unknown's avatar
unknown committed
3861 3862
  }

unknown's avatar
VIEW  
unknown committed
3863 3864
  if (!(grant_table= grant->grant_table))
    priv= grant->privilege;
unknown's avatar
unknown committed
3865 3866
  else
  {
unknown's avatar
VIEW  
unknown committed
3867 3868
    grant_column= column_hash_search(grant_table, field_name,
                                     (uint) strlen(field_name));
unknown's avatar
unknown committed
3869
    if (!grant_column)
3870
      priv= (grant->privilege | grant_table->privs);
unknown's avatar
unknown committed
3871
    else
3872
      priv= (grant->privilege | grant_table->privs | grant_column->rights);
unknown's avatar
unknown committed
3873
  }
3874
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
3875 3876 3877
  return priv;
}

unknown's avatar
VIEW  
unknown committed
3878

3879
/* Help function for mysql_show_grants */
unknown's avatar
unknown committed
3880

3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892
static void add_user_option(String *grant, ulong value, const char *name)
{
  if (value)
  {
    char buff[22], *p; // just as in int2str
    grant->append(' ');
    grant->append(name, strlen(name));
    grant->append(' ');
    p=int10_to_str(value, buff, 10);
    grant->append(buff,p-buff);
  }
}
unknown's avatar
unknown committed
3893 3894

static const char *command_array[]=
unknown's avatar
unknown committed
3895
{
unknown's avatar
VIEW  
unknown committed
3896 3897 3898 3899
  "SELECT", "INSERT", "UPDATE", "DELETE", "CREATE", "DROP", "RELOAD",
  "SHUTDOWN", "PROCESS","FILE", "GRANT", "REFERENCES", "INDEX",
  "ALTER", "SHOW DATABASES", "SUPER", "CREATE TEMPORARY TABLES",
  "LOCK TABLES", "EXECUTE", "REPLICATION SLAVE", "REPLICATION CLIENT",
3900
  "CREATE VIEW", "SHOW VIEW", "CREATE ROUTINE", "ALTER ROUTINE",
3901
  "CREATE USER"
unknown's avatar
unknown committed
3902
};
3903

unknown's avatar
unknown committed
3904 3905
static uint command_lengths[]=
{
3906 3907
  6, 6, 6, 6, 6, 4, 6, 8, 7, 4, 5, 10, 5, 5, 14, 5, 23, 11, 7, 17, 18, 11, 9,
  14, 13, 11
unknown's avatar
unknown committed
3908 3909
};

unknown's avatar
unknown committed
3910

3911 3912 3913 3914 3915
static int show_routine_grants(THD *thd, LEX_USER *lex_user, HASH *hash,
                               const char *type, int typelen,
                               char *buff, int buffsize);


3916 3917 3918 3919 3920 3921 3922
/*
  SHOW GRANTS;  Send grants for a user to the client

  IMPLEMENTATION
   Send to client grant-like strings depicting user@host privileges
*/

unknown's avatar
unknown committed
3923
bool mysql_show_grants(THD *thd,LEX_USER *lex_user)
unknown's avatar
unknown committed
3924
{
unknown's avatar
unknown committed
3925 3926
  ulong want_access;
  uint counter,index;
unknown's avatar
unknown committed
3927
  int  error = 0;
unknown's avatar
unknown committed
3928 3929
  ACL_USER *acl_user;
  ACL_DB *acl_db;
unknown's avatar
unknown committed
3930
  char buff[1024];
3931
  Protocol *protocol= thd->protocol;
unknown's avatar
unknown committed
3932
  DBUG_ENTER("mysql_show_grants");
unknown's avatar
unknown committed
3933 3934 3935 3936

  LINT_INIT(acl_user);
  if (!initialized)
  {
unknown's avatar
unknown committed
3937
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
unknown's avatar
unknown committed
3938
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
3939
  }
unknown's avatar
unknown committed
3940 3941 3942 3943 3944 3945

  if (!lex_user->host.str)
  {
    lex_user->host.str= (char*) "%";
    lex_user->host.length=1;
  }
unknown's avatar
unknown committed
3946 3947 3948
  if (lex_user->host.length > HOSTNAME_LENGTH ||
      lex_user->user.length > USERNAME_LENGTH)
  {
unknown's avatar
unknown committed
3949 3950
    my_message(ER_GRANT_WRONG_HOST_OR_USER, ER(ER_GRANT_WRONG_HOST_OR_USER),
               MYF(0));
unknown's avatar
unknown committed
3951
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
3952 3953 3954 3955 3956 3957 3958
  }

  for (counter=0 ; counter < acl_users.elements ; counter++)
  {
    const char *user,*host;
    acl_user=dynamic_element(&acl_users,counter,ACL_USER*);
    if (!(user=acl_user->user))
unknown's avatar
unknown committed
3959
      user= "";
unknown's avatar
unknown committed
3960
    if (!(host=acl_user->host.hostname))
unknown's avatar
unknown committed
3961
      host= "";
unknown's avatar
unknown committed
3962
    if (!strcmp(lex_user->user.str,user) &&
3963
	!my_strcasecmp(system_charset_info, lex_user->host.str, host))
unknown's avatar
unknown committed
3964 3965
      break;
  }
unknown's avatar
unknown committed
3966
  if (counter == acl_users.elements)
unknown's avatar
unknown committed
3967
  {
unknown's avatar
unknown committed
3968 3969
    my_error(ER_NONEXISTING_GRANT, MYF(0),
             lex_user->user.str, lex_user->host.str);
unknown's avatar
unknown committed
3970
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
3971 3972
  }

unknown's avatar
unknown committed
3973
  Item_string *field=new Item_string("",0,&my_charset_latin1);
unknown's avatar
unknown committed
3974 3975 3976 3977 3978 3979
  List<Item> field_list;
  field->name=buff;
  field->max_length=1024;
  strxmov(buff,"Grants for ",lex_user->user.str,"@",
	  lex_user->host.str,NullS);
  field_list.push_back(field);
3980 3981
  if (protocol->send_fields(&field_list,
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
unknown's avatar
unknown committed
3982
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
3983

unknown's avatar
unknown committed
3984
  rw_wrlock(&LOCK_grant);
unknown's avatar
unknown committed
3985 3986 3987 3988
  VOID(pthread_mutex_lock(&acl_cache->lock));

  /* Add first global access grants */
  {
3989
    String global(buff,sizeof(buff),system_charset_info);
unknown's avatar
unknown committed
3990 3991 3992
    global.length(0);
    global.append("GRANT ",6);

unknown's avatar
unknown committed
3993
    want_access= acl_user->access;
unknown's avatar
unknown committed
3994 3995 3996 3997
    if (test_all_bits(want_access, (GLOBAL_ACLS & ~ GRANT_ACL)))
      global.append("ALL PRIVILEGES",14);
    else if (!(want_access & ~GRANT_ACL))
      global.append("USAGE",5);
unknown's avatar
unknown committed
3998
    else
unknown's avatar
unknown committed
3999 4000
    {
      bool found=0;
unknown's avatar
unknown committed
4001
      ulong j,test_access= want_access & ~GRANT_ACL;
unknown's avatar
unknown committed
4002 4003
      for (counter=0, j = SELECT_ACL;j <= GLOBAL_ACLS;counter++,j <<= 1)
      {
unknown's avatar
unknown committed
4004
	if (test_access & j)
unknown's avatar
unknown committed
4005 4006 4007 4008 4009 4010 4011 4012 4013
	{
	  if (found)
	    global.append(", ",2);
	  found=1;
	  global.append(command_array[counter],command_lengths[counter]);
	}
      }
    }
    global.append (" ON *.* TO '",12);
4014 4015
    global.append(lex_user->user.str, lex_user->user.length,
		  system_charset_info);
unknown's avatar
unknown committed
4016
    global.append ("'@'",3);
4017 4018
    global.append(lex_user->host.str,lex_user->host.length,
		  system_charset_info);
unknown's avatar
unknown committed
4019
    global.append ('\'');
4020
    if (acl_user->salt_len)
unknown's avatar
unknown committed
4021
    {
4022 4023 4024 4025 4026
      char passwd_buff[SCRAMBLED_PASSWORD_CHAR_LENGTH+1];
      if (acl_user->salt_len == SCRAMBLE_LENGTH)
        make_password_from_salt(passwd_buff, acl_user->salt);
      else
        make_password_from_salt_323(passwd_buff, (ulong *) acl_user->salt);
unknown's avatar
unknown committed
4027
      global.append(" IDENTIFIED BY PASSWORD '",25);
4028
      global.append(passwd_buff);
unknown's avatar
unknown committed
4029 4030
      global.append('\'');
    }
4031 4032
    /* "show grants" SSL related stuff */
    if (acl_user->ssl_type == SSL_TYPE_ANY)
4033
      global.append(" REQUIRE SSL",12);
4034
    else if (acl_user->ssl_type == SSL_TYPE_X509)
4035
      global.append(" REQUIRE X509",13);
4036
    else if (acl_user->ssl_type == SSL_TYPE_SPECIFIED)
4037
    {
4038
      int ssl_options = 0;
4039
      global.append(" REQUIRE ",9);
4040 4041
      if (acl_user->x509_issuer)
      {
4042 4043 4044
	ssl_options++;
	global.append("ISSUER \'",8);
	global.append(acl_user->x509_issuer,strlen(acl_user->x509_issuer));
4045
	global.append('\'');
4046
      }
4047 4048
      if (acl_user->x509_subject)
      {
4049 4050 4051
	if (ssl_options++)
	  global.append(' ');
	global.append("SUBJECT \'",9);
4052 4053
	global.append(acl_user->x509_subject,strlen(acl_user->x509_subject),
                      system_charset_info);
4054
	global.append('\'');
unknown's avatar
unknown committed
4055
      }
4056 4057
      if (acl_user->ssl_cipher)
      {
4058 4059 4060
	if (ssl_options++)
	  global.append(' ');
	global.append("CIPHER '",8);
4061 4062
	global.append(acl_user->ssl_cipher,strlen(acl_user->ssl_cipher),
                      system_charset_info);
4063
	global.append('\'');
4064 4065
      }
    }
unknown's avatar
unknown committed
4066
    if ((want_access & GRANT_ACL) ||
4067 4068 4069 4070
	(acl_user->user_resource.questions ||
         acl_user->user_resource.updates ||
         acl_user->user_resource.conn_per_hour ||
         acl_user->user_resource.user_conn))
4071
    {
unknown's avatar
unknown committed
4072
      global.append(" WITH",5);
unknown's avatar
unknown committed
4073
      if (want_access & GRANT_ACL)
unknown's avatar
unknown committed
4074
	global.append(" GRANT OPTION",13);
4075 4076 4077 4078
      add_user_option(&global, acl_user->user_resource.questions,
		      "MAX_QUERIES_PER_HOUR");
      add_user_option(&global, acl_user->user_resource.updates,
		      "MAX_UPDATES_PER_HOUR");
4079
      add_user_option(&global, acl_user->user_resource.conn_per_hour,
4080
		      "MAX_CONNECTIONS_PER_HOUR");
4081 4082
      add_user_option(&global, acl_user->user_resource.user_conn,
		      "MAX_USER_CONNECTIONS");
unknown's avatar
unknown committed
4083
    }
4084
    protocol->prepare_for_resend();
4085
    protocol->store(global.ptr(),global.length(),global.charset());
4086
    if (protocol->write())
unknown's avatar
unknown committed
4087
    {
unknown's avatar
unknown committed
4088
      error= -1;
4089
      goto end;
unknown's avatar
unknown committed
4090 4091 4092 4093 4094 4095
    }
  }

  /* Add database access */
  for (counter=0 ; counter < acl_dbs.elements ; counter++)
  {
unknown's avatar
unknown committed
4096
    const char *user, *host;
unknown's avatar
unknown committed
4097 4098 4099

    acl_db=dynamic_element(&acl_dbs,counter,ACL_DB*);
    if (!(user=acl_db->user))
unknown's avatar
unknown committed
4100
      user= "";
unknown's avatar
unknown committed
4101
    if (!(host=acl_db->host.hostname))
unknown's avatar
unknown committed
4102
      host= "";
unknown's avatar
unknown committed
4103 4104

    if (!strcmp(lex_user->user.str,user) &&
4105
	!my_strcasecmp(system_charset_info, lex_user->host.str, host))
unknown's avatar
unknown committed
4106 4107
    {
      want_access=acl_db->access;
unknown's avatar
unknown committed
4108
      if (want_access)
unknown's avatar
unknown committed
4109
      {
4110
	String db(buff,sizeof(buff),system_charset_info);
unknown's avatar
unknown committed
4111 4112 4113 4114 4115
	db.length(0);
	db.append("GRANT ",6);

	if (test_all_bits(want_access,(DB_ACLS & ~GRANT_ACL)))
	  db.append("ALL PRIVILEGES",14);
4116
	else if (!(want_access & ~GRANT_ACL))
4117
	  db.append("USAGE",5);
unknown's avatar
unknown committed
4118 4119 4120
	else
	{
	  int found=0, cnt;
unknown's avatar
unknown committed
4121
	  ulong j,test_access= want_access & ~GRANT_ACL;
unknown's avatar
unknown committed
4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132
	  for (cnt=0, j = SELECT_ACL; j <= DB_ACLS; cnt++,j <<= 1)
	  {
	    if (test_access & j)
	    {
	      if (found)
		db.append(", ",2);
	      found = 1;
	      db.append(command_array[cnt],command_lengths[cnt]);
	    }
	  }
	}
4133 4134 4135
	db.append (" ON ",4);
	append_identifier(thd, &db, acl_db->db, strlen(acl_db->db));
	db.append (".* TO '",7);
4136 4137
	db.append(lex_user->user.str, lex_user->user.length,
		  system_charset_info);
unknown's avatar
unknown committed
4138
	db.append ("'@'",3);
4139 4140
	db.append(lex_user->host.str, lex_user->host.length,
                  system_charset_info);
unknown's avatar
unknown committed
4141
	db.append ('\'');
unknown's avatar
unknown committed
4142
	if (want_access & GRANT_ACL)
unknown's avatar
unknown committed
4143
	  db.append(" WITH GRANT OPTION",18);
4144
	protocol->prepare_for_resend();
4145
	protocol->store(db.ptr(),db.length(),db.charset());
4146
	if (protocol->write())
unknown's avatar
unknown committed
4147
	{
unknown's avatar
unknown committed
4148
	  error= -1;
unknown's avatar
unknown committed
4149 4150 4151 4152 4153 4154
	  goto end;
	}
      }
    }
  }

4155
  /* Add table & column access */
4156
  for (index=0 ; index < column_priv_hash.records ; index++)
unknown's avatar
unknown committed
4157
  {
unknown's avatar
unknown committed
4158
    const char *user;
4159 4160
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  index);
unknown's avatar
unknown committed
4161 4162

    if (!(user=grant_table->user))
4163
      user= "";
unknown's avatar
unknown committed
4164 4165

    if (!strcmp(lex_user->user.str,user) &&
4166
	!my_strcasecmp(system_charset_info, lex_user->host.str,
4167
                       grant_table->host.hostname))
unknown's avatar
unknown committed
4168
    {
4169 4170
      ulong table_access= grant_table->privs;
      if ((table_access | grant_table->cols) != 0)
unknown's avatar
unknown committed
4171
      {
4172
	String global(buff, sizeof(buff), system_charset_info);
unknown's avatar
unknown committed
4173 4174
	ulong test_access= (table_access | grant_table->cols) & ~GRANT_ACL;

unknown's avatar
unknown committed
4175 4176 4177
	global.length(0);
	global.append("GRANT ",6);

4178
	if (test_all_bits(table_access, (TABLE_ACLS & ~GRANT_ACL)))
unknown's avatar
unknown committed
4179
	  global.append("ALL PRIVILEGES",14);
unknown's avatar
unknown committed
4180
	else if (!test_access)
4181
 	  global.append("USAGE",5);
unknown's avatar
unknown committed
4182
	else
unknown's avatar
unknown committed
4183
	{
4184
          /* Add specific column access */
4185
	  int found= 0;
unknown's avatar
unknown committed
4186
	  ulong j;
unknown's avatar
unknown committed
4187

4188
	  for (counter= 0, j= SELECT_ACL; j <= TABLE_ACLS; counter++, j<<= 1)
unknown's avatar
unknown committed
4189
	  {
unknown's avatar
unknown committed
4190
	    if (test_access & j)
unknown's avatar
unknown committed
4191 4192 4193
	    {
	      if (found)
		global.append(", ",2);
4194
	      found= 1;
unknown's avatar
unknown committed
4195 4196
	      global.append(command_array[counter],command_lengths[counter]);

unknown's avatar
unknown committed
4197
	      if (grant_table->cols)
unknown's avatar
unknown committed
4198
	      {
4199
		uint found_col= 0;
unknown's avatar
unknown committed
4200 4201 4202 4203 4204 4205
		for (uint col_index=0 ;
		     col_index < grant_table->hash_columns.records ;
		     col_index++)
		{
		  GRANT_COLUMN *grant_column = (GRANT_COLUMN*)
		    hash_element(&grant_table->hash_columns,col_index);
unknown's avatar
unknown committed
4206
		  if (grant_column->rights & j)
unknown's avatar
unknown committed
4207
		  {
unknown's avatar
unknown committed
4208
		    if (!found_col)
unknown's avatar
unknown committed
4209
		    {
4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220
		      found_col= 1;
		      /*
			If we have a duplicated table level privilege, we
			must write the access privilege name again.
		      */
		      if (table_access & j)
		      {
			global.append(", ", 2);
			global.append(command_array[counter],
				      command_lengths[counter]);
		      }
unknown's avatar
unknown committed
4221 4222 4223 4224 4225
		      global.append(" (",2);
		    }
		    else
		      global.append(", ",2);
		    global.append(grant_column->column,
4226 4227
				  grant_column->key_length,
				  system_charset_info);
unknown's avatar
unknown committed
4228 4229 4230 4231 4232 4233 4234 4235
		  }
		}
		if (found_col)
		  global.append(')');
	      }
	    }
	  }
	}
4236 4237 4238 4239 4240 4241 4242
	global.append(" ON ",4);
	append_identifier(thd, &global, grant_table->db,
			  strlen(grant_table->db));
	global.append('.');
	append_identifier(thd, &global, grant_table->tname,
			  strlen(grant_table->tname));
	global.append(" TO '",5);
4243 4244
	global.append(lex_user->user.str, lex_user->user.length,
		      system_charset_info);
unknown's avatar
unknown committed
4245
	global.append("'@'",3);
4246 4247
	global.append(lex_user->host.str,lex_user->host.length,
		      system_charset_info);
unknown's avatar
unknown committed
4248
	global.append('\'');
4249
	if (table_access & GRANT_ACL)
unknown's avatar
unknown committed
4250
	  global.append(" WITH GRANT OPTION",18);
4251
	protocol->prepare_for_resend();
4252
	protocol->store(global.ptr(),global.length(),global.charset());
4253
	if (protocol->write())
unknown's avatar
unknown committed
4254
	{
unknown's avatar
unknown committed
4255
	  error= -1;
4256
	  break;
unknown's avatar
unknown committed
4257 4258 4259 4260
	}
      }
    }
  }
4261

4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292
  if (show_routine_grants(thd, lex_user, &proc_priv_hash, 
                          "PROCEDURE", 9, buff, sizeof(buff)))
  {
    error= -1;
    goto end;
  }

  if (show_routine_grants(thd, lex_user, &func_priv_hash,
                          "FUNCTION", 8, buff, sizeof(buff)))
  {
    error= -1;
    goto end;
  }

end:
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  rw_unlock(&LOCK_grant);

  send_eof(thd);
  DBUG_RETURN(error);
}

static int show_routine_grants(THD* thd, LEX_USER *lex_user, HASH *hash,
                               const char *type, int typelen,
                               char *buff, int buffsize)
{
  uint counter, index;
  int error= 0;
  Protocol *protocol= thd->protocol;
  /* Add routine access */
  for (index=0 ; index < hash->records ; index++)
4293 4294
  {
    const char *user;
4295
    GRANT_NAME *grant_proc= (GRANT_NAME*) hash_element(hash, index);
4296 4297 4298 4299 4300 4301

    if (!(user=grant_proc->user))
      user= "";

    if (!strcmp(lex_user->user.str,user) &&
	!my_strcasecmp(system_charset_info, lex_user->host.str,
4302
                       grant_proc->host.hostname))
4303 4304 4305 4306
    {
      ulong proc_access= grant_proc->privs;
      if (proc_access != 0)
      {
4307
	String global(buff, buffsize, system_charset_info);
4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332
	ulong test_access= proc_access & ~GRANT_ACL;

	global.length(0);
	global.append("GRANT ",6);

	if (!test_access)
 	  global.append("USAGE",5);
	else
	{
          /* Add specific procedure access */
	  int found= 0;
	  ulong j;

	  for (counter= 0, j= SELECT_ACL; j <= PROC_ACLS; counter++, j<<= 1)
	  {
	    if (test_access & j)
	    {
	      if (found)
		global.append(", ",2);
	      found= 1;
	      global.append(command_array[counter],command_lengths[counter]);
	    }
	  }
	}
	global.append(" ON ",4);
4333 4334
        global.append(type,typelen);
        global.append(' ');
4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358
	append_identifier(thd, &global, grant_proc->db,
			  strlen(grant_proc->db));
	global.append('.');
	append_identifier(thd, &global, grant_proc->tname,
			  strlen(grant_proc->tname));
	global.append(" TO '",5);
	global.append(lex_user->user.str, lex_user->user.length,
		      system_charset_info);
	global.append("'@'",3);
	global.append(lex_user->host.str,lex_user->host.length,
		      system_charset_info);
	global.append('\'');
	if (proc_access & GRANT_ACL)
	  global.append(" WITH GRANT OPTION",18);
	protocol->prepare_for_resend();
	protocol->store(global.ptr(),global.length(),global.charset());
	if (protocol->write())
	{
	  error= -1;
	  break;
	}
      }
    }
  }
4359
  return error;
unknown's avatar
unknown committed
4360 4361
}

unknown's avatar
unknown committed
4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389
/*
  Make a clear-text version of the requested privilege.
*/

void get_privilege_desc(char *to, uint max_length, ulong access)
{
  uint pos;
  char *start=to;
  DBUG_ASSERT(max_length >= 30);		// For end ',' removal

  if (access)
  {
    max_length--;				// Reserve place for end-zero
    for (pos=0 ; access ; pos++, access>>=1)
    {
      if ((access & 1) &&
	  command_lengths[pos] + (uint) (to-start) < max_length)
      {
	to= strmov(to, command_array[pos]);
	*to++=',';
      }
    }
    to--;					// Remove end ','
  }
  *to=0;
}


4390
void get_mqh(const char *user, const char *host, USER_CONN *uc)
unknown's avatar
unknown committed
4391 4392
{
  ACL_USER *acl_user;
4393
  if (initialized && (acl_user= find_acl_user(host,user, FALSE)))
4394 4395 4396
    uc->user_resources= acl_user->user_resource;
  else
    bzero((char*) &uc->user_resources, sizeof(uc->user_resources));
unknown's avatar
unknown committed
4397 4398
}

4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419
/*
  Open the grant tables.

  SYNOPSIS
    open_grant_tables()
    thd                         The current thread.
    tables (out)                The 4 elements array for the opened tables.

  DESCRIPTION
    Tables are numbered as follows:
    0 user
    1 db
    2 tables_priv
    3 columns_priv

  RETURN
    1           Skip GRANT handling during replication.
    0           OK.
    < 0         Error.
*/

4420
#define GRANT_TABLES 5
4421 4422 4423 4424 4425 4426
int open_grant_tables(THD *thd, TABLE_LIST *tables)
{
  DBUG_ENTER("open_grant_tables");

  if (!initialized)
  {
unknown's avatar
unknown committed
4427
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
4428 4429 4430
    DBUG_RETURN(-1);
  }

4431
  bzero((char*) tables, GRANT_TABLES*sizeof(*tables));
4432 4433 4434 4435 4436
  tables->alias= tables->table_name= (char*) "user";
  (tables+1)->alias= (tables+1)->table_name= (char*) "db";
  (tables+2)->alias= (tables+2)->table_name= (char*) "tables_priv";
  (tables+3)->alias= (tables+3)->table_name= (char*) "columns_priv";
  (tables+4)->alias= (tables+4)->table_name= (char*) "procs_priv";
unknown's avatar
VIEW  
unknown committed
4437 4438 4439
  tables->next_local= tables->next_global= tables+1;
  (tables+1)->next_local= (tables+1)->next_global= tables+2;
  (tables+2)->next_local= (tables+2)->next_global= tables+3;
4440
  (tables+3)->next_local= (tables+3)->next_global= tables+4;
4441
  tables->lock_type= (tables+1)->lock_type=
4442 4443 4444 4445
    (tables+2)->lock_type= (tables+3)->lock_type= 
    (tables+4)->lock_type= TL_WRITE;
  tables->db= (tables+1)->db= (tables+2)->db= 
    (tables+3)->db= (tables+4)->db= (char*) "mysql";
4446 4447 4448 4449 4450 4451

#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
4452 4453
  if (thd->slave_thread && table_rules_on)
  {
unknown's avatar
unknown committed
4454 4455 4456
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
4457
    */
4458 4459
    tables[0].updating=tables[1].updating=tables[2].updating=
      tables[3].updating=tables[4].updating=1;
4460
    if (!tables_ok(thd, tables))
4461
      DBUG_RETURN(1);
4462 4463
    tables[0].updating=tables[1].updating=tables[2].updating=
      tables[3].updating=tables[4].updating=0;;
4464
  }
4465 4466
#endif

4467
  if (simple_open_n_lock_tables(thd, tables))
4468 4469 4470 4471 4472 4473 4474 4475 4476
  {						// This should never happen
    close_thread_tables(thd);
    DBUG_RETURN(-1);
  }

  DBUG_RETURN(0);
}

ACL_USER *check_acl_user(LEX_USER *user_name,
unknown's avatar
merge  
unknown committed
4477
			 uint *acl_acl_userdx)
4478 4479 4480 4481 4482 4483 4484 4485 4486
{
  ACL_USER *acl_user= 0;
  uint counter;

  for (counter= 0 ; counter < acl_users.elements ; counter++)
  {
    const char *user,*host;
    acl_user= dynamic_element(&acl_users, counter, ACL_USER*);
    if (!(user=acl_user->user))
unknown's avatar
unknown committed
4487
      user= "";
4488
    if (!(host=acl_user->host.hostname))
unknown's avatar
unknown committed
4489
      host= "%";
4490 4491 4492 4493 4494 4495 4496
    if (!strcmp(user_name->user.str,user) &&
	!my_strcasecmp(system_charset_info, user_name->host.str, host))
      break;
  }
  if (counter == acl_users.elements)
    return 0;

unknown's avatar
merge  
unknown committed
4497
  *acl_acl_userdx= counter;
unknown's avatar
unknown committed
4498
  return acl_user;
4499 4500
}

unknown's avatar
unknown committed
4501

4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523
/*
  Modify a privilege table.

  SYNOPSIS
    modify_grant_table()
    table                       The table to modify.
    host_field                  The host name field.
    user_field                  The user name field.
    user_to                     The new name for the user if to be renamed,
                                NULL otherwise.

  DESCRIPTION
  Update user/host in the current record if user_to is not NULL.
  Delete the current record if user_to is NULL.

  RETURN
    0           OK.
    != 0        Error.
*/

static int modify_grant_table(TABLE *table, Field *host_field,
                              Field *user_field, LEX_USER *user_to)
4524
{
4525 4526
  int error;
  DBUG_ENTER("modify_grant_table");
4527

4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544
  if (user_to)
  {
    /* rename */
    store_record(table, record[1]);
    host_field->store(user_to->host.str, user_to->host.length,
                      system_charset_info);
    user_field->store(user_to->user.str, user_to->user.length,
                      system_charset_info);
    if ((error= table->file->update_row(table->record[1], table->record[0])))
      table->file->print_error(error, MYF(0));
  }
  else
  {
    /* delete */
    if ((error=table->file->delete_row(table->record[0])))
      table->file->print_error(error, MYF(0));
  }
4545

4546 4547
  DBUG_RETURN(error);
}
4548 4549


4550 4551 4552 4553 4554 4555
/*
  Handle a privilege table.

  SYNOPSIS
    handle_grant_table()
    tables                      The array with the four open tables.
4556
    table_no                    The number of the table to handle (0..4).
4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573
    drop                        If user_from is to be dropped.
    user_from                   The the user to be searched/dropped/renamed.
    user_to                     The new name for the user if to be renamed,
                                NULL otherwise.

  DESCRIPTION
    Scan through all records in a grant table and apply the requested
    operation. For the "user" table, a single index access is sufficient,
    since there is an unique index on (host, user).
    Delete from grant table if drop is true.
    Update in grant table if drop is false and user_to is not NULL.
    Search in grant table if drop is false and user_to is NULL.
    Tables are numbered as follows:
    0 user
    1 db
    2 tables_priv
    3 columns_priv
4574
    4 procs_priv
4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593

  RETURN
    > 0         At least one record matched.
    0           OK, but no record matched.
    < 0         Error.
*/

static int handle_grant_table(TABLE_LIST *tables, uint table_no, bool drop,
                              LEX_USER *user_from, LEX_USER *user_to)
{
  int result= 0;
  int error;
  TABLE *table= tables[table_no].table;
  Field *host_field= table->field[0];
  Field *user_field= table->field[table_no ? 2 : 1];
  char *host_str= user_from->host.str;
  char *user_str= user_from->user.str;
  const char *host;
  const char *user;
4594
  byte user_key[MAX_KEY_LENGTH];
unknown's avatar
unknown committed
4595
  uint key_prefix_length;
4596 4597
  DBUG_ENTER("handle_grant_table");

unknown's avatar
unknown committed
4598
  if (! table_no) // mysql.user table
4599
  {
4600 4601 4602 4603 4604 4605 4606 4607 4608 4609
    /*
      The 'user' table has an unique index on (host, user).
      Thus, we can handle everything with a single index access.
      The host- and user fields are consecutive in the user table records.
      So we set host- and user fields of table->record[0] and use the
      pointer to the host field as key.
      index_read_idx() will replace table->record[0] (its first argument)
      by the searched record, if it exists.
    */
    DBUG_PRINT("info",("read table: '%s'  search: '%s'@'%s'",
4610
                       table->s->table_name, user_str, host_str));
4611 4612
    host_field->store(host_str, user_from->host.length, system_charset_info);
    user_field->store(user_str, user_from->user.length, system_charset_info);
unknown's avatar
unknown committed
4613 4614 4615 4616 4617

    key_prefix_length= (table->key_info->key_part[0].store_length +
                        table->key_info->key_part[1].store_length);
    key_copy(user_key, table->record[0], table->key_info, key_prefix_length);

4618
    if ((error= table->file->index_read_idx(table->record[0], 0,
unknown's avatar
unknown committed
4619
                                            user_key, key_prefix_length,
4620
                                            HA_READ_KEY_EXACT)))
4621
    {
4622 4623 4624 4625 4626
      if (error != HA_ERR_KEY_NOT_FOUND)
      {
        table->file->print_error(error, MYF(0));
        result= -1;
      }
4627
    }
4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644
    else
    {
      /* If requested, delete or update the record. */
      result= ((drop || user_to) &&
               modify_grant_table(table, host_field, user_field, user_to)) ?
        -1 : 1; /* Error or found. */
    }
    DBUG_PRINT("info",("read result: %d", result));
  }
  else
  {
    /*
      The non-'user' table do not have indexes on (host, user).
      And their host- and user fields are not consecutive.
      Thus, we need to do a table scan to find all matching records.
    */
    if ((error= table->file->ha_rnd_init(1)))
4645
    {
4646
      table->file->print_error(error, MYF(0));
4647
      result= -1;
4648 4649 4650 4651 4652
    }
    else
    {
#ifdef EXTRA_DEBUG
      DBUG_PRINT("info",("scan table: '%s'  search: '%s'@'%s'",
4653
                         table->s->table_name, user_str, host_str));
4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701
#endif
      while ((error= table->file->rnd_next(table->record[0])) != 
             HA_ERR_END_OF_FILE)
      {
        if (error)
        {
          /* Most probable 'deleted record'. */
          DBUG_PRINT("info",("scan error: %d", error));
          continue;
        }
        if (! (host= get_field(&mem, host_field)))
          host= "";
        if (! (user= get_field(&mem, user_field)))
          user= "";

#ifdef EXTRA_DEBUG
        DBUG_PRINT("loop",("scan fields: '%s'@'%s' '%s' '%s' '%s'",
                           user, host,
                           get_field(&mem, table->field[1]) /*db*/,
                           get_field(&mem, table->field[3]) /*table*/,
                           get_field(&mem, table->field[4]) /*column*/));
#endif
        if (strcmp(user_str, user) ||
            my_strcasecmp(system_charset_info, host_str, host))
          continue;

        /* If requested, delete or update the record. */
        result= ((drop || user_to) &&
                 modify_grant_table(table, host_field, user_field, user_to)) ?
          -1 : result ? result : 1; /* Error or keep result or found. */
        /* If search is requested, we do not need to search further. */
        if (! drop && ! user_to)
          break ;
      }
      (void) table->file->ha_rnd_end();
      DBUG_PRINT("info",("scan result: %d", result));
    }
  }

  DBUG_RETURN(result);
}


/*
  Handle an in-memory privilege structure.

  SYNOPSIS
    handle_grant_struct()
4702
    struct_no                   The number of the structure to handle (0..3).
4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717
    drop                        If user_from is to be dropped.
    user_from                   The the user to be searched/dropped/renamed.
    user_to                     The new name for the user if to be renamed,
                                NULL otherwise.

  DESCRIPTION
    Scan through all elements in an in-memory grant structure and apply
    the requested operation.
    Delete from grant structure if drop is true.
    Update in grant structure if drop is false and user_to is not NULL.
    Search in grant structure if drop is false and user_to is NULL.
    Structures are numbered as follows:
    0 acl_users
    1 acl_dbs
    2 column_priv_hash
4718
    3 procs_priv_hash
4719 4720 4721 4722

  RETURN
    > 0         At least one element matched.
    0           OK, but no element matched.
4723
    -1		Wrong arguments to function
4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735
*/

static int handle_grant_struct(uint struct_no, bool drop,
                               LEX_USER *user_from, LEX_USER *user_to)
{
  int result= 0;
  uint idx;
  uint elements;
  const char *user;
  const char *host;
  ACL_USER *acl_user;
  ACL_DB *acl_db;
4736
  GRANT_NAME *grant_name;
4737
  DBUG_ENTER("handle_grant_struct");
unknown's avatar
unknown committed
4738 4739 4740
  DBUG_PRINT("info",("scan struct: %u  search: '%s'@'%s'",
                     struct_no, user_from->user.str, user_from->host.str));

4741 4742
  LINT_INIT(acl_user);
  LINT_INIT(acl_db);
4743
  LINT_INIT(grant_name);
4744 4745

  /* Get the number of elements in the in-memory structure. */
4746
  switch (struct_no) {
4747 4748 4749 4750 4751 4752
  case 0:
    elements= acl_users.elements;
    break;
  case 1:
    elements= acl_dbs.elements;
    break;
4753
  case 2:
4754
    elements= column_priv_hash.records;
4755 4756 4757 4758 4759 4760
    break;
  case 3:
    elements= proc_priv_hash.records;
    break;
  default:
    return -1;
4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773
  }

#ifdef EXTRA_DEBUG
    DBUG_PRINT("loop",("scan struct: %u  search    user: '%s'  host: '%s'",
                       struct_no, user_from->user.str, user_from->host.str));
#endif
  /* Loop over all elements. */
  for (idx= 0; idx < elements; idx++)
  {
    /*
      Get a pointer to the element.
      Unfortunaltely, the host default differs for the structures.
    */
4774
    switch (struct_no) {
4775 4776 4777 4778 4779 4780 4781 4782 4783 4784
    case 0:
      acl_user= dynamic_element(&acl_users, idx, ACL_USER*);
      user= acl_user->user;
      if (!(host= acl_user->host.hostname))
        host= "%";
      break;

    case 1:
      acl_db= dynamic_element(&acl_dbs, idx, ACL_DB*);
      user= acl_db->user;
4785 4786
      if (!(host= acl_db->host.hostname))
        host= "%";
4787 4788
      break;

4789 4790 4791
    case 2:
      grant_name= (GRANT_NAME*) hash_element(&column_priv_hash, idx);
      user= grant_name->user;
4792 4793
      if (!(host= grant_name->host.hostname))
        host= "%";
4794 4795 4796 4797 4798
      break;

    case 3:
      grant_name= (GRANT_NAME*) hash_element(&proc_priv_hash, idx);
      user= grant_name->user;
4799 4800
      if (!(host= grant_name->host.hostname))
        host= "%";
4801
      break;
4802 4803
    }
    if (! user)
4804
      user= "";
4805
    if (! host)
4806
      host= "";
4807 4808 4809 4810 4811 4812
#ifdef EXTRA_DEBUG
    DBUG_PRINT("loop",("scan struct: %u  index: %u  user: '%s'  host: '%s'",
                       struct_no, idx, user, host));
#endif
    if (strcmp(user_from->user.str, user) ||
        my_strcasecmp(system_charset_info, user_from->host.str, host))
4813
      continue;
4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827

    result= 1; /* At least one element found. */
    if ( drop )
    {
      switch ( struct_no )
      {
      case 0:
        delete_dynamic_element(&acl_users, idx);
        break;

      case 1:
        delete_dynamic_element(&acl_dbs, idx);
        break;

4828 4829 4830 4831 4832 4833 4834
      case 2:
        hash_delete(&column_priv_hash, (byte*) grant_name);
	break;

      case 3:
        hash_delete(&proc_priv_hash, (byte*) grant_name);
	break;
4835 4836 4837
      }
      elements--;
      idx--;
4838
    }
4839 4840
    else if ( user_to )
    {
4841
      switch ( struct_no ) {
4842 4843 4844 4845
      case 0:
        acl_user->user= strdup_root(&mem, user_to->user.str);
        acl_user->host.hostname= strdup_root(&mem, user_to->host.str);
        break;
4846

4847 4848 4849 4850 4851
      case 1:
        acl_db->user= strdup_root(&mem, user_to->user.str);
        acl_db->host.hostname= strdup_root(&mem, user_to->host.str);
        break;

4852 4853 4854
      case 2:
      case 3:
        grant_name->user= strdup_root(&mem, user_to->user.str);
4855 4856
        update_hostname(&grant_name->host,
                        strdup_root(&mem, user_to->host.str));
4857
	break;
4858 4859 4860
      }
    }
    else
4861
    {
4862 4863 4864 4865 4866 4867 4868
      /* If search is requested, we do not need to search further. */
      break;
    }
  }
#ifdef EXTRA_DEBUG
  DBUG_PRINT("loop",("scan struct: %u  result %d", struct_no, result));
#endif
4869

4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913
  DBUG_RETURN(result);
}


/*
  Handle all privilege tables and in-memory privilege structures.

  SYNOPSIS
    handle_grant_data()
    tables                      The array with the four open tables.
    drop                        If user_from is to be dropped.
    user_from                   The the user to be searched/dropped/renamed.
    user_to                     The new name for the user if to be renamed,
                                NULL otherwise.

  DESCRIPTION
    Go through all grant tables and in-memory grant structures and apply
    the requested operation.
    Delete from grant data if drop is true.
    Update in grant data if drop is false and user_to is not NULL.
    Search in grant data if drop is false and user_to is NULL.

  RETURN
    > 0         At least one element matched.
    0           OK, but no element matched.
    < 0         Error.
*/

static int handle_grant_data(TABLE_LIST *tables, bool drop,
                             LEX_USER *user_from, LEX_USER *user_to)
{
  int result= 0;
  int found;
  DBUG_ENTER("handle_grant_data");

  /* Handle user table. */
  if ((found= handle_grant_table(tables, 0, drop, user_from, user_to)) < 0)
  {
    /* Handle of table failed, don't touch the in-memory array. */
    result= -1;
  }
  else
  {
    /* Handle user array. */
unknown's avatar
unknown committed
4914 4915
    if ((handle_grant_struct(0, drop, user_from, user_to) && ! result) ||
        found)
4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942
    {
      result= 1; /* At least one record/element found. */
      /* If search is requested, we do not need to search further. */
      if (! drop && ! user_to)
        goto end;
    }
  }

  /* Handle db table. */
  if ((found= handle_grant_table(tables, 1, drop, user_from, user_to)) < 0)
  {
    /* Handle of table failed, don't touch the in-memory array. */
    result= -1;
  }
  else
  {
    /* Handle db array. */
    if (((handle_grant_struct(1, drop, user_from, user_to) && ! result) ||
         found) && ! result)
    {
      result= 1; /* At least one record/element found. */
      /* If search is requested, we do not need to search further. */
      if (! drop && ! user_to)
        goto end;
    }
  }

4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961
  /* Handle procedures table. */
  if ((found= handle_grant_table(tables, 4, drop, user_from, user_to)) < 0)
  {
    /* Handle of table failed, don't touch in-memory array. */
    result= -1;
  }
  else
  {
    /* Handle procs array. */
    if (((handle_grant_struct(3, drop, user_from, user_to) && ! result) ||
         found) && ! result)
    {
      result= 1; /* At least one record/element found. */
      /* If search is requested, we do not need to search further. */
      if (! drop && ! user_to)
        goto end;
    }
  }

4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975
  /* Handle tables table. */
  if ((found= handle_grant_table(tables, 2, drop, user_from, user_to)) < 0)
  {
    /* Handle of table failed, don't touch columns and in-memory array. */
    result= -1;
  }
  else
  {
    if (found && ! result)
    {
      result= 1; /* At least one record found. */
      /* If search is requested, we do not need to search further. */
      if (! drop && ! user_to)
        goto end;
4976
    }
4977 4978 4979

    /* Handle columns table. */
    if ((found= handle_grant_table(tables, 3, drop, user_from, user_to)) < 0)
4980
    {
4981
      /* Handle of table failed, don't touch the in-memory array. */
4982 4983
      result= -1;
    }
4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995
    else
    {
      /* Handle columns hash. */
      if (((handle_grant_struct(2, drop, user_from, user_to) && ! result) ||
           found) && ! result)
        result= 1; /* At least one record/element found. */
    }
  }
 end:
  DBUG_RETURN(result);
}

unknown's avatar
unknown committed
4996

unknown's avatar
unknown committed
4997 4998 4999 5000 5001 5002 5003 5004 5005 5006
static void append_user(String *str, LEX_USER *user)
{
  if (str->length())
    str->append(',');
  str->append('\'');
  str->append(user->user.str);
  str->append("'@'");
  str->append(user->host.str);
  str->append('\'');
}
5007

unknown's avatar
unknown committed
5008

5009 5010 5011 5012 5013 5014 5015
/*
  Create a list of users.

  SYNOPSIS
    mysql_create_user()
    thd                         The current thread.
    list                        The users to create.
5016

5017 5018 5019 5020 5021 5022 5023 5024
  RETURN
    FALSE       OK.
    TRUE        Error.
*/

bool mysql_create_user(THD *thd, List <LEX_USER> &list)
{
  int result;
unknown's avatar
unknown committed
5025
  String wrong_users;
5026 5027 5028
  ulong sql_mode;
  LEX_USER *user_name;
  List_iterator <LEX_USER> user_list(list);
5029
  TABLE_LIST tables[GRANT_TABLES];
5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044
  DBUG_ENTER("mysql_create_user");

  /* CREATE USER may be skipped on replication client. */
  if ((result= open_grant_tables(thd, tables)))
    DBUG_RETURN(result != 1);

  rw_wrlock(&LOCK_grant);
  VOID(pthread_mutex_lock(&acl_cache->lock));

  while ((user_name= user_list++))
  {
    /*
      Search all in-memory structures and grant tables
      for a mention of the new user name.
    */
5045
    if (handle_grant_data(tables, 0, user_name, NULL))
5046
    {
unknown's avatar
unknown committed
5047
      append_user(&wrong_users, user_name);
5048
      result= TRUE;
unknown's avatar
unknown committed
5049
      continue;
5050
    }
5051

5052
    sql_mode= thd->variables.sql_mode;
unknown's avatar
unknown committed
5053
    if (replace_user_table(thd, tables[0].table, *user_name, 0, 0, 1, 0))
5054
    {
unknown's avatar
unknown committed
5055
      append_user(&wrong_users, user_name);
5056 5057 5058 5059 5060 5061 5062 5063
      result= TRUE;
    }
  }

  VOID(pthread_mutex_unlock(&acl_cache->lock));
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
  if (result)
5064
    my_error(ER_CANNOT_USER, MYF(0), "CREATE USER", wrong_users.c_ptr_safe());
5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084
  DBUG_RETURN(result);
}


/*
  Drop a list of users and all their privileges.

  SYNOPSIS
    mysql_drop_user()
    thd                         The current thread.
    list                        The users to drop.

  RETURN
    FALSE       OK.
    TRUE        Error.
*/

bool mysql_drop_user(THD *thd, List <LEX_USER> &list)
{
  int result;
unknown's avatar
unknown committed
5085
  String wrong_users;
5086 5087
  LEX_USER *user_name;
  List_iterator <LEX_USER> user_list(list);
5088
  TABLE_LIST tables[GRANT_TABLES];
5089 5090
  DBUG_ENTER("mysql_drop_user");

unknown's avatar
unknown committed
5091
  /* DROP USER may be skipped on replication client. */
5092 5093 5094 5095 5096 5097 5098 5099
  if ((result= open_grant_tables(thd, tables)))
    DBUG_RETURN(result != 1);

  rw_wrlock(&LOCK_grant);
  VOID(pthread_mutex_lock(&acl_cache->lock));

  while ((user_name= user_list++))
  {
5100
    if (handle_grant_data(tables, 1, user_name, NULL) <= 0)
5101
    {
unknown's avatar
unknown committed
5102
      append_user(&wrong_users, user_name);
5103
      result= TRUE;
5104
    }
5105
  }
5106

5107 5108 5109 5110
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
  if (result)
unknown's avatar
unknown committed
5111
    my_error(ER_CANNOT_USER, MYF(0), "DROP USER", wrong_users.c_ptr_safe());
5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131
  DBUG_RETURN(result);
}


/*
  Rename a user.

  SYNOPSIS
    mysql_rename_user()
    thd                         The current thread.
    list                        The user name pairs: (from, to).

  RETURN
    FALSE       OK.
    TRUE        Error.
*/

bool mysql_rename_user(THD *thd, List <LEX_USER> &list)
{
  int result= 0;
unknown's avatar
unknown committed
5132
  String wrong_users;
5133 5134 5135
  LEX_USER *user_from;
  LEX_USER *user_to;
  List_iterator <LEX_USER> user_list(list);
5136
  TABLE_LIST tables[GRANT_TABLES];
5137 5138
  DBUG_ENTER("mysql_rename_user");

unknown's avatar
unknown committed
5139
  /* RENAME USER may be skipped on replication client. */
5140 5141 5142 5143 5144 5145 5146 5147 5148
  if ((result= open_grant_tables(thd, tables)))
    DBUG_RETURN(result != 1);

  rw_wrlock(&LOCK_grant);
  VOID(pthread_mutex_lock(&acl_cache->lock));

  while ((user_from= user_list++))
  {
    user_to= user_list++;
5149
    DBUG_ASSERT(user_to != 0); /* Syntax enforces pairs of users. */
5150 5151 5152 5153 5154

    /*
      Search all in-memory structures and grant tables
      for a mention of the new user name.
    */
unknown's avatar
unknown committed
5155 5156
    if (handle_grant_data(tables, 0, user_to, NULL) ||
        handle_grant_data(tables, 0, user_from, user_to) <= 0)
5157
    {
unknown's avatar
unknown committed
5158
      append_user(&wrong_users, user_from);
5159 5160
      result= TRUE;
    }
5161
  }
5162

5163 5164 5165 5166
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
  if (result)
5167
    my_error(ER_CANNOT_USER, MYF(0), "RENAME USER", wrong_users.c_ptr_safe());
5168 5169 5170
  DBUG_RETURN(result);
}

5171

5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185
/*
  Revoke all privileges from a list of users.

  SYNOPSIS
    mysql_revoke_all()
    thd                         The current thread.
    list                        The users to revoke all privileges from.

  RETURN
    > 0         Error. Error message already sent.
    0           OK.
    < 0         Error. Error message not yet sent.
*/

unknown's avatar
unknown committed
5186
bool mysql_revoke_all(THD *thd,  List <LEX_USER> &list)
5187
{
5188
  uint counter, revoked, is_proc;
5189
  int result;
unknown's avatar
unknown committed
5190
  ACL_DB *acl_db;
5191
  TABLE_LIST tables[GRANT_TABLES];
5192 5193 5194
  DBUG_ENTER("mysql_revoke_all");

  if ((result= open_grant_tables(thd, tables)))
unknown's avatar
unknown committed
5195
    DBUG_RETURN(result != 1);
5196 5197 5198 5199 5200 5201 5202 5203

  rw_wrlock(&LOCK_grant);
  VOID(pthread_mutex_lock(&acl_cache->lock));

  LEX_USER *lex_user;
  List_iterator <LEX_USER> user_list(list);
  while ((lex_user=user_list++))
  {
unknown's avatar
unknown committed
5204
    if (!check_acl_user(lex_user, &counter))
5205
    {
unknown's avatar
unknown committed
5206 5207
      sql_print_error("REVOKE ALL PRIVILEGES, GRANT: User '%s'@'%s' does not "
                      "exists", lex_user->user.str, lex_user->host.str);
5208 5209 5210
      result= -1;
      continue;
    }
unknown's avatar
unknown committed
5211

5212
    if (replace_user_table(thd, tables[0].table,
5213
			   *lex_user, ~(ulong)0, 1, 0, 0))
5214 5215 5216 5217 5218 5219
    {
      result= -1;
      continue;
    }

    /* Remove db access privileges */
unknown's avatar
unknown committed
5220 5221 5222 5223 5224
    /*
      Because acl_dbs and column_priv_hash shrink and may re-order
      as privileges are removed, removal occurs in a repeated loop
      until no more privileges are revoked.
     */
unknown's avatar
unknown committed
5225
    do
5226
    {
unknown's avatar
unknown committed
5227
      for (counter= 0, revoked= 0 ; counter < acl_dbs.elements ; )
5228
      {
unknown's avatar
unknown committed
5229
	const char *user,*host;
unknown's avatar
unknown committed
5230

unknown's avatar
unknown committed
5231 5232 5233 5234 5235
	acl_db=dynamic_element(&acl_dbs,counter,ACL_DB*);
	if (!(user=acl_db->user))
	  user= "";
	if (!(host=acl_db->host.hostname))
	  host= "";
unknown's avatar
unknown committed
5236

unknown's avatar
unknown committed
5237 5238 5239
	if (!strcmp(lex_user->user.str,user) &&
	    !my_strcasecmp(system_charset_info, lex_user->host.str, host))
	{
5240
	  if (!replace_db_table(tables[1].table, acl_db->db, *lex_user, ~(ulong)0, 1))
unknown's avatar
unknown committed
5241
	  {
unknown's avatar
unknown committed
5242 5243 5244 5245 5246
	    /*
	      Don't increment counter as replace_db_table deleted the
	      current element in acl_dbs.
	     */
	    revoked= 1;
unknown's avatar
unknown committed
5247 5248
	    continue;
	  }
unknown's avatar
unknown committed
5249
	  result= -1; // Something went wrong
unknown's avatar
unknown committed
5250
	}
unknown's avatar
unknown committed
5251
	counter++;
5252
      }
unknown's avatar
unknown committed
5253
    } while (revoked);
5254 5255

    /* Remove column access */
unknown's avatar
unknown committed
5256
    do
5257
    {
unknown's avatar
unknown committed
5258
      for (counter= 0, revoked= 0 ; counter < column_priv_hash.records ; )
5259
      {
unknown's avatar
unknown committed
5260 5261 5262 5263 5264
	const char *user,*host;
	GRANT_TABLE *grant_table= (GRANT_TABLE*)hash_element(&column_priv_hash,
							     counter);
	if (!(user=grant_table->user))
	  user= "";
5265
	if (!(host=grant_table->host.hostname))
unknown's avatar
unknown committed
5266
	  host= "";
unknown's avatar
unknown committed
5267

unknown's avatar
unknown committed
5268 5269
	if (!strcmp(lex_user->user.str,user) &&
	    !my_strcasecmp(system_charset_info, lex_user->host.str, host))
5270
	{
unknown's avatar
unknown committed
5271 5272 5273
	  if (replace_table_table(thd,grant_table,tables[2].table,*lex_user,
				  grant_table->db,
				  grant_table->tname,
5274
				  ~(ulong)0, 0, 1))
unknown's avatar
unknown committed
5275
	  {
unknown's avatar
unknown committed
5276
	    result= -1;
unknown's avatar
unknown committed
5277
	  }
unknown's avatar
unknown committed
5278
	  else
unknown's avatar
unknown committed
5279
	  {
unknown's avatar
unknown committed
5280
	    if (!grant_table->cols)
unknown's avatar
unknown committed
5281
	    {
unknown's avatar
unknown committed
5282 5283
	      revoked= 1;
	      continue;
unknown's avatar
unknown committed
5284
	    }
unknown's avatar
unknown committed
5285 5286
	    List<LEX_COLUMN> columns;
	    if (!replace_column_table(grant_table,tables[3].table, *lex_user,
unknown's avatar
unknown committed
5287 5288 5289
				      columns,
				      grant_table->db,
				      grant_table->tname,
5290
				      ~(ulong)0, 1))
unknown's avatar
unknown committed
5291
	    {
unknown's avatar
unknown committed
5292
	      revoked= 1;
5293
	      continue;
unknown's avatar
unknown committed
5294
	    }
5295
	    result= -1;
unknown's avatar
unknown committed
5296
	  }
5297
	}
unknown's avatar
unknown committed
5298
	counter++;
5299
      }
unknown's avatar
unknown committed
5300
    } while (revoked);
5301 5302

    /* Remove procedure access */
5303 5304 5305
    for (is_proc=0; is_proc<2; is_proc++) do {
      HASH *hash= is_proc ? &proc_priv_hash : &func_priv_hash;
      for (counter= 0, revoked= 0 ; counter < hash->records ; )
5306 5307
      {
	const char *user,*host;
5308
	GRANT_NAME *grant_proc= (GRANT_NAME*) hash_element(hash, counter);
5309 5310
	if (!(user=grant_proc->user))
	  user= "";
5311
	if (!(host=grant_proc->host.hostname))
5312 5313 5314 5315 5316
	  host= "";

	if (!strcmp(lex_user->user.str,user) &&
	    !my_strcasecmp(system_charset_info, lex_user->host.str, host))
	{
5317
	  if (!replace_routine_table(thd,grant_proc,tables[4].table,*lex_user,
5318 5319
				  grant_proc->db,
				  grant_proc->tname,
5320
                                  is_proc,
unknown's avatar
unknown committed
5321
				  ~(ulong)0, 1))
5322 5323 5324 5325 5326 5327 5328 5329 5330
	  {
	    revoked= 1;
	    continue;
	  }
	  result= -1;	// Something went wrong
	}
	counter++;
      }
    } while (revoked);
5331
  }
unknown's avatar
unknown committed
5332

5333 5334 5335
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
unknown's avatar
unknown committed
5336

5337
  if (result)
unknown's avatar
unknown committed
5338
    my_message(ER_REVOKE_GRANTS, ER(ER_REVOKE_GRANTS), MYF(0));
unknown's avatar
unknown committed
5339

5340 5341
  DBUG_RETURN(result);
}
unknown's avatar
unknown committed
5342

5343

5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357
/*
  Revoke privileges for all users on a stored procedure

  SYNOPSIS
    sp_revoke_privileges()
    thd                         The current thread.
    db				DB of the stored procedure
    name			Name of the stored procedure

  RETURN
    0           OK.
    < 0         Error. Error message not yet sent.
*/

5358 5359
bool sp_revoke_privileges(THD *thd, const char *sp_db, const char *sp_name,
                          bool is_proc)
5360 5361 5362 5363
{
  uint counter, revoked;
  int result;
  TABLE_LIST tables[GRANT_TABLES];
5364
  HASH *hash= is_proc ? &proc_priv_hash : &func_priv_hash;
5365 5366 5367 5368 5369 5370 5371 5372 5373
  DBUG_ENTER("sp_revoke_privileges");

  if ((result= open_grant_tables(thd, tables)))
    DBUG_RETURN(result != 1);

  rw_wrlock(&LOCK_grant);
  VOID(pthread_mutex_lock(&acl_cache->lock));

  /* Remove procedure access */
5374 5375
  do
  {
5376
    for (counter= 0, revoked= 0 ; counter < hash->records ; )
5377
    {
5378
      GRANT_NAME *grant_proc= (GRANT_NAME*) hash_element(hash, counter);
5379 5380 5381 5382 5383 5384
      if (!my_strcasecmp(system_charset_info, grant_proc->db, sp_db) &&
	  !my_strcasecmp(system_charset_info, grant_proc->tname, sp_name))
      {
        LEX_USER lex_user;
	lex_user.user.str= grant_proc->user;
	lex_user.user.length= strlen(grant_proc->user);
5385 5386
	lex_user.host.str= grant_proc->host.hostname;
	lex_user.host.length= strlen(grant_proc->host.hostname);
5387 5388
	if (!replace_routine_table(thd,grant_proc,tables[4].table,lex_user,
				   grant_proc->db, grant_proc->tname,
unknown's avatar
unknown committed
5389
                                   is_proc, ~(ulong)0, 1))
5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424
	{
	  revoked= 1;
	  continue;
	}
	result= -1;	// Something went wrong
      }
      counter++;
    }
  } while (revoked);

  VOID(pthread_mutex_unlock(&acl_cache->lock));
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);

  if (result)
    my_message(ER_REVOKE_GRANTS, ER(ER_REVOKE_GRANTS), MYF(0));

  DBUG_RETURN(result);
}


/*
  Grant EXECUTE,ALTER privilege for a stored procedure

  SYNOPSIS
    sp_grant_privileges()
    thd                         The current thread.
    db				DB of the stored procedure
    name			Name of the stored procedure

  RETURN
    0           OK.
    < 0         Error. Error message not yet sent.
*/

5425 5426
bool sp_grant_privileges(THD *thd, const char *sp_db, const char *sp_name,
                         bool is_proc)
5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438
{
  LEX_USER *combo;
  TABLE_LIST tables[1];
  List<LEX_USER> user_list;
  bool result;
  DBUG_ENTER("sp_grant_privileges");  

  if (!(combo=(LEX_USER*) thd->alloc(sizeof(st_lex_user))))
    DBUG_RETURN(TRUE);

  combo->user.str= thd->user;
  
unknown's avatar
unknown committed
5439 5440 5441 5442 5443 5444
  if (!find_acl_user(combo->host.str=(char*)thd->host_or_ip, combo->user.str,
                     FALSE) &&
      !find_acl_user(combo->host.str=(char*)thd->host, combo->user.str,
                     FALSE) &&
      !find_acl_user(combo->host.str=(char*)thd->ip, combo->user.str, FALSE) &&
      !find_acl_user(combo->host.str=(char*)"%", combo->user.str, FALSE))
5445 5446 5447 5448 5449 5450
    DBUG_RETURN(TRUE);

  bzero((char*)tables, sizeof(TABLE_LIST));
  user_list.empty();

  tables->db= (char*)sp_db;
5451
  tables->table_name= tables->alias= (char*)sp_name;
5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463
  
  combo->host.length= strlen(combo->host.str);
  combo->user.length= strlen(combo->user.str);
  combo->host.str= thd->strmake(combo->host.str,combo->host.length);
  combo->user.str= thd->strmake(combo->user.str,combo->user.length);
  combo->password.str= (char*)"";
  combo->password.length= 0;

  if (user_list.push_back(combo))
    DBUG_RETURN(TRUE);

  thd->lex->ssl_type= SSL_TYPE_NOT_SPECIFIED;
5464
  bzero((char*) &thd->lex->mqh, sizeof(thd->lex->mqh));
5465

5466
  result= mysql_routine_grant(thd, tables, is_proc, user_list,
5467 5468 5469 5470 5471
  				DEFAULT_CREATE_PROC_ACLS, 0, 1);
  DBUG_RETURN(result);
}


unknown's avatar
unknown committed
5472
/*****************************************************************************
unknown's avatar
unknown committed
5473
  Instantiate used templates
unknown's avatar
unknown committed
5474 5475
*****************************************************************************/

5476
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
unknown's avatar
unknown committed
5477 5478 5479 5480 5481
template class List_iterator<LEX_COLUMN>;
template class List_iterator<LEX_USER>;
template class List<LEX_COLUMN>;
template class List<LEX_USER>;
#endif
unknown's avatar
unknown committed
5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528

#endif /*NO_EMBEDDED_ACCESS_CHECKS */


int wild_case_compare(CHARSET_INFO *cs, const char *str,const char *wildstr)
{
  reg3 int flag;
  DBUG_ENTER("wild_case_compare");
  DBUG_PRINT("enter",("str: '%s'  wildstr: '%s'",str,wildstr));
  while (*wildstr)
  {
    while (*wildstr && *wildstr != wild_many && *wildstr != wild_one)
    {
      if (*wildstr == wild_prefix && wildstr[1])
	wildstr++;
      if (my_toupper(cs, *wildstr++) !=
          my_toupper(cs, *str++)) DBUG_RETURN(1);
    }
    if (! *wildstr ) DBUG_RETURN (*str != 0);
    if (*wildstr++ == wild_one)
    {
      if (! *str++) DBUG_RETURN (1);	/* One char; skip */
    }
    else
    {						/* Found '*' */
      if (!*wildstr) DBUG_RETURN(0);		/* '*' as last char: OK */
      flag=(*wildstr != wild_many && *wildstr != wild_one);
      do
      {
	if (flag)
	{
	  char cmp;
	  if ((cmp= *wildstr) == wild_prefix && wildstr[1])
	    cmp=wildstr[1];
	  cmp=my_toupper(cs, cmp);
	  while (*str && my_toupper(cs, *str) != cmp)
	    str++;
	  if (!*str) DBUG_RETURN (1);
	}
	if (wild_case_compare(cs, str,wildstr) == 0) DBUG_RETURN (0);
      } while (*str++);
      DBUG_RETURN(1);
    }
  }
  DBUG_RETURN (*str != '\0');
}

5529 5530 5531 5532 5533 5534 5535 5536

void update_schema_privilege(TABLE *table, char *buff, const char* db,
                             const char* t_name, const char* column,
                             uint col_length, const char *priv, 
                             uint priv_length, const char* is_grantable)
{
  int i= 2;
  CHARSET_INFO *cs= system_charset_info;
5537
  restore_record(table, s->default_values);
5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558
  table->field[0]->store(buff, strlen(buff), cs);
  if (db)
    table->field[i++]->store(db, strlen(db), cs);
  if (t_name)
    table->field[i++]->store(t_name, strlen(t_name), cs);
  if (column)
    table->field[i++]->store(column, col_length, cs);
  table->field[i++]->store(priv, priv_length, cs);
  table->field[i]->store(is_grantable, strlen(is_grantable), cs);
  table->file->write_row(table->record[0]);
}


int fill_schema_user_privileges(THD *thd, TABLE_LIST *tables, COND *cond)
{
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  uint counter;
  ACL_USER *acl_user;
  ulong want_access;
  char buff[100];
  TABLE *table= tables->table;
5559 5560
  bool no_global_access= check_access(thd, SELECT_ACL, "mysql",0,1,1);
  char *curr_host= thd->priv_host ? thd->priv_host : (char *) "%";
5561
  DBUG_ENTER("fill_schema_user_privileges");
5562

5563 5564 5565 5566 5567 5568 5569 5570
  for (counter=0 ; counter < acl_users.elements ; counter++)
  {
    const char *user,*host, *is_grantable="YES";
    acl_user=dynamic_element(&acl_users,counter,ACL_USER*);
    if (!(user=acl_user->user))
      user= "";
    if (!(host=acl_user->host.hostname))
      host= "";
5571 5572 5573 5574 5575 5576

    if (no_global_access &&
        (strcmp(thd->priv_user, user) ||
         my_strcasecmp(system_charset_info, curr_host, host)))
      continue;
      
5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597
    want_access= acl_user->access;
    if (!(want_access & GRANT_ACL))
      is_grantable= "NO";

    strxmov(buff,"'",user,"'@'",host,"'",NullS);
    if (!(want_access & ~GRANT_ACL))
      update_schema_privilege(table, buff, 0, 0, 0, 0, "USAGE", 5, is_grantable);
    else
    {
      uint priv_id;
      ulong j,test_access= want_access & ~GRANT_ACL;
      for (priv_id=0, j = SELECT_ACL;j <= GLOBAL_ACLS; priv_id++,j <<= 1)
      {
	if (test_access & j)
          update_schema_privilege(table, buff, 0, 0, 0, 0, 
                                  command_array[priv_id],
                                  command_lengths[priv_id], is_grantable);
      }
    }
  }
  DBUG_RETURN(0);
5598 5599 5600
#else
  return(0);
#endif
5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611
}


int fill_schema_schema_privileges(THD *thd, TABLE_LIST *tables, COND *cond)
{
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  uint counter;
  ACL_DB *acl_db;
  ulong want_access;
  char buff[100];
  TABLE *table= tables->table;
5612 5613
  bool no_global_access= check_access(thd, SELECT_ACL, "mysql",0,1,1);
  char *curr_host= thd->priv_host ? thd->priv_host : (char *) "%";
5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625
  DBUG_ENTER("fill_schema_schema_privileges");

  for (counter=0 ; counter < acl_dbs.elements ; counter++)
  {
    const char *user, *host, *is_grantable="YES";

    acl_db=dynamic_element(&acl_dbs,counter,ACL_DB*);
    if (!(user=acl_db->user))
      user= "";
    if (!(host=acl_db->host.hostname))
      host= "";

5626 5627 5628 5629 5630
    if (no_global_access &&
        (strcmp(thd->priv_user, user) ||
         my_strcasecmp(system_charset_info, curr_host, host)))
      continue;

5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654
    want_access=acl_db->access;
    if (want_access)
    {
      if (!(want_access & GRANT_ACL))
      {
        is_grantable= "NO";
      }
      strxmov(buff,"'",user,"'@'",host,"'",NullS);
      if (!(want_access & ~GRANT_ACL))
        update_schema_privilege(table, buff, acl_db->db, 0, 0,
                                0, "USAGE", 5, is_grantable);
      else
      {
        int cnt;
        ulong j,test_access= want_access & ~GRANT_ACL;
        for (cnt=0, j = SELECT_ACL; j <= DB_ACLS; cnt++,j <<= 1)
          if (test_access & j)
            update_schema_privilege(table, buff, acl_db->db, 0, 0, 0,
                                    command_array[cnt], command_lengths[cnt],
                                    is_grantable);
      }
    }
  }
  DBUG_RETURN(0);
5655 5656 5657
#else
  return (0);
#endif
5658 5659 5660 5661 5662 5663 5664 5665 5666
}


int fill_schema_table_privileges(THD *thd, TABLE_LIST *tables, COND *cond)
{
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  uint index;
  char buff[100];
  TABLE *table= tables->table;
5667 5668
  bool no_global_access= check_access(thd, SELECT_ACL, "mysql",0,1,1);
  char *curr_host= thd->priv_host ? thd->priv_host : (char *) "%";
5669 5670 5671 5672 5673 5674 5675 5676 5677
  DBUG_ENTER("fill_schema_table_privileges");

  for (index=0 ; index < column_priv_hash.records ; index++)
  {
    const char *user, *is_grantable= "YES";
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  index);
    if (!(user=grant_table->user))
      user= "";
5678 5679 5680 5681 5682 5683 5684

    if (no_global_access &&
        (strcmp(thd->priv_user, user) ||
         my_strcasecmp(system_charset_info, curr_host,
                       grant_table->host.hostname)))
      continue;

5685
    ulong table_access= grant_table->privs;
5686
    if (table_access)
5687 5688
    {
      ulong test_access= table_access & ~GRANT_ACL;
unknown's avatar
unknown committed
5689 5690 5691 5692
      /*
        We should skip 'usage' privilege on table if
        we have any privileges on column(s) of this table
      */
5693 5694
      if (!test_access && grant_table->cols)
        continue;
5695 5696 5697
      if (!(table_access & GRANT_ACL))
        is_grantable= "NO";

5698
      strxmov(buff,"'",user,"'@'",grant_table->host.hostname,"'",NullS);
5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716
      if (!test_access)
        update_schema_privilege(table, buff, grant_table->db, grant_table->tname,
                                0, 0, "USAGE", 5, is_grantable);
      else
      {
        ulong j;
        int cnt;
        for (cnt= 0, j= SELECT_ACL; j <= TABLE_ACLS; cnt++, j<<= 1)
        {
          if (test_access & j)
            update_schema_privilege(table, buff, grant_table->db, 
                                    grant_table->tname, 0, 0, command_array[cnt],
                                    command_lengths[cnt], is_grantable);
        }
      }
    }
  }
  DBUG_RETURN(0);
5717 5718 5719
#else
  return (0);
#endif
5720 5721 5722 5723 5724 5725 5726 5727 5728
}


int fill_schema_column_privileges(THD *thd, TABLE_LIST *tables, COND *cond)
{
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  uint index;
  char buff[100];
  TABLE *table= tables->table;
5729 5730
  bool no_global_access= check_access(thd, SELECT_ACL, "mysql",0,1,1);
  char *curr_host= thd->priv_host ? thd->priv_host : (char *) "%";
5731 5732 5733 5734 5735 5736 5737 5738 5739
  DBUG_ENTER("fill_schema_table_privileges");

  for (index=0 ; index < column_priv_hash.records ; index++)
  {
    const char *user, *is_grantable= "YES";
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  index);
    if (!(user=grant_table->user))
      user= "";
5740 5741 5742 5743 5744 5745 5746

    if (no_global_access &&
        (strcmp(thd->priv_user, user) ||
         my_strcasecmp(system_charset_info, curr_host,
                       grant_table->host.hostname)))
      continue;

5747 5748 5749
    ulong table_access= grant_table->cols;
    if (table_access != 0)
    {
unknown's avatar
unknown committed
5750
      if (!(grant_table->privs & GRANT_ACL))
5751 5752
        is_grantable= "NO";

unknown's avatar
unknown committed
5753
      ulong test_access= table_access & ~GRANT_ACL;
5754
      strxmov(buff,"'",user,"'@'",grant_table->host.hostname,"'",NullS);
5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784
      if (!test_access)
        continue;
      else
      {
        ulong j;
        int cnt;
        for (cnt= 0, j= SELECT_ACL; j <= TABLE_ACLS; cnt++, j<<= 1)
        {
          if (test_access & j)
          {
            for (uint col_index=0 ;
                 col_index < grant_table->hash_columns.records ;
                 col_index++)
            {
              GRANT_COLUMN *grant_column = (GRANT_COLUMN*)
                hash_element(&grant_table->hash_columns,col_index);
              if ((grant_column->rights & j) && (table_access & j))
                  update_schema_privilege(table, buff, grant_table->db,
                                          grant_table->tname,
                                          grant_column->column,
                                          grant_column->key_length,
                                          command_array[cnt],
                                          command_lengths[cnt], is_grantable);
            }
          }
        }
      }
    }
  }
  DBUG_RETURN(0);
5785 5786 5787
#else
  return (0);
#endif
5788 5789 5790
}


unknown's avatar
VIEW  
unknown committed
5791 5792 5793 5794 5795
#ifndef NO_EMBEDDED_ACCESS_CHECKS
/*
  fill effective privileges for table

  SYNOPSIS
5796 5797
    fill_effective_table_privileges()
    thd     thread handler
unknown's avatar
VIEW  
unknown committed
5798 5799 5800 5801 5802 5803 5804 5805
    grant   grants table descriptor
    db      db name
    table   table name
*/

void fill_effective_table_privileges(THD *thd, GRANT_INFO *grant,
                                     const char *db, const char *table)
{
5806 5807 5808 5809 5810 5811 5812
  /* --skip-grants */
  if (!initialized)
  {
    grant->privilege= ~NO_ACCESS;             // everything is allowed
    return;
  }

unknown's avatar
VIEW  
unknown committed
5813 5814
  /* global privileges */
  grant->privilege= thd->master_access;
5815

5816 5817 5818
  if (!thd->priv_user)
    return;                                   // it is slave

5819 5820 5821
  /* db privileges */
  grant->privilege|= acl_get(thd->host, thd->ip, thd->priv_user, db, 0);

5822 5823 5824
  if (!grant_option)
    return;

unknown's avatar
VIEW  
unknown committed
5825 5826 5827
  /* table privileges */
  if (grant->version != grant_version)
  {
5828
    rw_rdlock(&LOCK_grant);
unknown's avatar
VIEW  
unknown committed
5829 5830 5831 5832 5833
    grant->grant_table=
      table_hash_search(thd->host, thd->ip, db,
			thd->priv_user,
			table, 0);              /* purecov: inspected */
    grant->version= grant_version;              /* purecov: inspected */
5834
    rw_unlock(&LOCK_grant);
unknown's avatar
VIEW  
unknown committed
5835 5836 5837 5838 5839 5840
  }
  if (grant->grant_table != 0)
  {
    grant->privilege|= grant->grant_table->privs;
  }
}
5841 5842 5843 5844 5845 5846 5847

#else /* NO_EMBEDDED_ACCESS_CHECKS */

/****************************************************************************
 Dummy wrappers when we don't have any access checks
****************************************************************************/

unknown's avatar
unknown committed
5848 5849
bool check_routine_level_acl(THD *thd, const char *db, const char *name,
                             bool is_proc)
5850 5851 5852 5853
{
  return FALSE;
}

unknown's avatar
VIEW  
unknown committed
5854
#endif