sql_acl.cc 173 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
static void rebuild_check_host(void);
72 73
static ACL_USER *find_acl_user(const char *host, const char *user,
                               my_bool exact);
74 75
static bool update_user_table(THD *thd, TABLE *table,
                              const char *host, const char *user,
76
			      const char *new_password, uint new_password_len);
unknown's avatar
unknown committed
77
static void update_hostname(acl_host_and_ip *host, const char *hostname);
78
static bool compare_hostname(const acl_host_and_ip *host,const char *hostname,
unknown's avatar
unknown committed
79
			     const char *ip);
80 81
static my_bool acl_load(THD *thd, TABLE_LIST *tables);
static my_bool grant_load(TABLE_LIST *tables);
unknown's avatar
unknown committed
82

83 84 85 86 87 88 89 90 91 92 93 94 95 96
/*
  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;
  }
97
  else if (password_len == SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
98 99
  {
    get_salt_from_password_323((ulong *) acl_user->salt, password);
100
    acl_user->salt_len= SCRAMBLE_LENGTH_323;
101 102 103 104 105
  }
  else
    acl_user->salt_len= 0;
}

106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
/*
  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;
}

124

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

  SYNOPSIS
    acl_init()
131 132 133 134 135 136
      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().
137 138 139 140 141 142

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

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

149 150
  acl_cache= new hash_filo(ACL_CACHE_SIZE, 0, 0,
                           (hash_get_key) acl_entry_get_key,
151 152 153
                           (hash_free_key) free,
                           /* Use the case sensitive "binary" charset */
                           &my_charset_bin);
unknown's avatar
unknown committed
154
  if (dont_read_acl_tables)
155
  {
unknown's avatar
unknown committed
156
    DBUG_RETURN(0); /* purecov: tested */
unknown's avatar
unknown committed
157 158
  }

159 160 161
  /*
    To be able to run this from boot, we allocate a temporary THD
  */
unknown's avatar
unknown committed
162 163
  if (!(thd=new THD))
    DBUG_RETURN(1); /* purecov: inspected */
164
  thd->thread_stack= (char*) &thd;
165
  thd->store_globals();
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 199 200
  /*
    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];
201
  int password_length;
202 203
  DBUG_ENTER("acl_load");

204 205
  grant_version++; /* Privileges updated */
  mysql_proc_table_exists= 1;			// Assume mysql.proc exists
206

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

209
  init_sql_alloc(&mem, ACL_ALLOC_BLOCK_SIZE, 0);
unknown's avatar
unknown committed
210
  init_read_record(&read_record_info,thd,table= tables[0].table,NULL,1,0);
211
  VOID(my_init_dynamic_array(&acl_hosts,sizeof(ACL_HOST),20,50));
unknown's avatar
unknown committed
212 213 214
  while (!(read_record_info.read_record(&read_record_info)))
  {
    ACL_HOST host;
215 216
    update_hostname(&host.host,get_field(&mem, table->field[0]));
    host.db=	 get_field(&mem, table->field[1]);
217
    if (lower_case_table_names && host.db)
218 219
    {
      /*
220 221
        convert db to lower case and give a warning if the db wasn't
        already in lower case
222
      */
223 224
      (void) strmov(tmp_name, host.db);
      my_casedn_str(files_charset_info, host.db);
225 226 227
      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 "
228 229
                          "lower_case_table_names is set. It will not be "
                          "possible to remove this privilege using REVOKE.",
230 231
                          host.host.hostname, host.db);
    }
unknown's avatar
unknown committed
232 233
    host.access= get_access(table,2);
    host.access= fix_rights_for_db(host.access);
234
    host.sort=	 get_sort(2,host.host.hostname,host.db);
unknown's avatar
SCRUM  
unknown committed
235 236
    if (check_no_resolve && hostname_requires_resolving(host.host.hostname))
    {
unknown's avatar
unknown committed
237
      sql_print_warning("'host' entry '%s|%s' "
unknown's avatar
SCRUM  
unknown committed
238
		      "ignored in --skip-name-resolve mode.",
239
		      host.host.hostname, host.db?host.db:"");
unknown's avatar
SCRUM  
unknown committed
240 241
      continue;
    }
unknown's avatar
unknown committed
242
#ifndef TO_BE_REMOVED
243
    if (table->s->fields == 8)
unknown's avatar
unknown committed
244 245
    {						// Without grant
      if (host.access & CREATE_ACL)
246
	host.access|=REFERENCES_ACL | INDEX_ACL | ALTER_ACL | CREATE_TMP_ACL;
unknown's avatar
unknown committed
247 248 249 250 251 252 253 254 255 256
    }
#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);
257
  VOID(my_init_dynamic_array(&acl_users,sizeof(ACL_USER),50,100));
258 259 260
  password_length= table->field[2]->field_length /
    table->field[2]->charset()->mbmaxlen;
  if (password_length < SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
unknown's avatar
unknown committed
261
  {
262 263 264
    sql_print_error("Fatal error: mysql.user table is damaged or in "
                    "unsupported 3.20 format.");
    goto end;
unknown's avatar
unknown committed
265 266
  }

267
  DBUG_PRINT("info",("user table fields: %d, password length: %d",
268
		     table->s->fields, password_length));
269

270
  pthread_mutex_lock(&LOCK_global_system_variables);
271
  if (password_length < SCRAMBLED_PASSWORD_CHAR_LENGTH)
272
  {
273 274 275 276 277 278 279 280 281 282 283 284 285 286
    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);
287 288 289
      sql_print_warning("mysql.user table is not updated to new password format; "
                        "Disabling new password usage until "
                        "mysql_fix_privilege_tables is run");
290 291 292 293
    }
    thd->variables.old_passwords= 1;
  }
  else
294
  {
295 296
    sys_old_passwords.after_update= 0;
    pthread_mutex_unlock(&LOCK_global_system_variables);
297 298
  }

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

313 314 315 316
    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
317
    {
318 319
      switch (password_len) {
      case 45: /* 4.1: to be removed */
unknown's avatar
unknown committed
320 321 322 323 324
        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 : "");
325 326
        break;
      default:
unknown's avatar
unknown committed
327 328 329
        sql_print_warning("Found invalid password for user: '%s@%s'; "
                          "Ignoring user", user.user ? user.user : "",
                           user.host.hostname ? user.host.hostname : "");
330 331
        break;
      }
unknown's avatar
unknown committed
332
    }
333
    else                                        // password is correct
unknown's avatar
unknown committed
334
    {
unknown's avatar
unknown committed
335 336
      uint next_field;
      user.access= get_access(table,3,&next_field) & GLOBAL_ACLS;
337 338 339 340
      /*
        if it is pre 5.0.1 privilege table then map CREATE privilege on
        CREATE VIEW & SHOW VIEW privileges
      */
341
      if (table->s->fields <= 31 && (user.access & CREATE_ACL))
342
        user.access|= (CREATE_VIEW_ACL | SHOW_VIEW_ACL);
343 344 345 346 347

      /*
        if it is pre 5.0.2 privilege table then map CREATE/ALTER privilege on
        CREATE PROCEDURE & ALTER PROCEDURE privileges
      */
348
      if (table->s->fields <= 33 && (user.access & CREATE_ACL))
349
        user.access|= CREATE_PROC_ACL;
350
      if (table->s->fields <= 33 && (user.access & ALTER_ACL))
351 352
        user.access|= ALTER_PROC_ACL;

353 354 355 356 357 358
      /*
        pre 5.0.3 did not have CREATE_USER_ACL
      */
      if (table->s->fields <= 36 && (user.access & GRANT_ACL))
        user.access|= CREATE_USER_ACL;

359 360 361
      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
362

363 364
      /* Starting from 4.0.2 we have more fields */
      if (table->s->fields >= 31)
365
      {
unknown's avatar
unknown committed
366
        char *ssl_type=get_field(&mem, table->field[next_field++]);
367 368 369 370 371 372 373 374 375
        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
376 377 378
        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++]);
379

unknown's avatar
unknown committed
380 381 382 383 384
        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++]);
385
        user.user_resource.conn_per_hour= ptr ? atoi(ptr) : 0;
386
        if (user.user_resource.questions || user.user_resource.updates ||
387
            user.user_resource.conn_per_hour)
388
          mqh_used=1;
389

390
        if (table->s->fields >= 36)
391 392 393 394 395 396 397
        {
          /* 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;
398
      }
399 400 401
      else
      {
        user.ssl_type=SSL_TYPE_NONE;
402
        bzero((char *)&(user.user_resource),sizeof(user.user_resource));
unknown's avatar
unknown committed
403
#ifndef TO_BE_REMOVED
404
        if (table->s->fields <= 13)
405 406 407 408 409 410 411 412 413 414
        {						// 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
415
#endif
416 417 418 419 420
      }
      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
421
    }
unknown's avatar
unknown committed
422 423 424 425 426
  }
  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
427

unknown's avatar
unknown committed
428
  init_read_record(&read_record_info,thd,table=tables[2].table,NULL,1,0);
429
  VOID(my_init_dynamic_array(&acl_dbs,sizeof(ACL_DB),50,100));
unknown's avatar
unknown committed
430 431 432
  while (!(read_record_info.read_record(&read_record_info)))
  {
    ACL_DB db;
433 434
    update_hostname(&db.host,get_field(&mem, table->field[0]));
    db.db=get_field(&mem, table->field[1]);
435 436
    if (!db.db)
    {
unknown's avatar
unknown committed
437
      sql_print_warning("Found an entry in the 'db' table with empty database name; Skipped");
438
      continue;
439
    }
440
    db.user=get_field(&mem, table->field[2]);
unknown's avatar
SCRUM  
unknown committed
441 442
    if (check_no_resolve && hostname_requires_resolving(db.host.hostname))
    {
unknown's avatar
unknown committed
443 444
      sql_print_warning("'db' entry '%s %s@%s' "
		        "ignored in --skip-name-resolve mode.",
445
		        db.db, db.user, db.host.hostname);
unknown's avatar
SCRUM  
unknown committed
446 447
      continue;
    }
unknown's avatar
unknown committed
448 449
    db.access=get_access(table,3);
    db.access=fix_rights_for_db(db.access);
450 451 452
    if (lower_case_table_names)
    {
      /*
453 454
        convert db to lower case and give a warning if the db wasn't
        already in lower case
455 456
      */
      (void)strmov(tmp_name, db.db);
457
      my_casedn_str(files_charset_info, db.db);
458 459 460 461
      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 "
462 463
                          "lower_case_table_names is set. It will not be "
                          "possible to remove this privilege using REVOKE.",
464 465 466
		          db.db, db.user, db.host.hostname, db.host.hostname);
      }
    }
unknown's avatar
unknown committed
467 468
    db.sort=get_sort(3,db.host.hostname,db.db,db.user);
#ifndef TO_BE_REMOVED
469
    if (table->s->fields <=  9)
unknown's avatar
unknown committed
470 471 472 473 474 475 476 477 478 479 480 481 482
    {						// 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();

483 484 485 486 487
  initialized=1;
  return_val=0;

end:
  DBUG_RETURN(return_val);
unknown's avatar
unknown committed
488 489 490 491 492
}


void acl_free(bool end)
{
493
  free_root(&mem,MYF(0));
unknown's avatar
unknown committed
494 495 496 497 498 499 500 501 502 503 504 505 506 507
  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;
  }
}

508 509

/*
510 511
  Forget current user/db-level privileges and read new privileges
  from the privilege tables.
512 513 514

  SYNOPSIS
    acl_reload()
515 516 517 518 519 520 521 522 523 524 525
      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
526
*/
unknown's avatar
unknown committed
527

528
my_bool acl_reload(THD *thd)
unknown's avatar
unknown committed
529
{
530
  TABLE_LIST tables[3];
unknown's avatar
unknown committed
531 532 533
  DYNAMIC_ARRAY old_acl_hosts,old_acl_users,old_acl_dbs;
  MEM_ROOT old_mem;
  bool old_initialized;
534
  my_bool return_val= 1;
unknown's avatar
unknown committed
535 536
  DBUG_ENTER("acl_reload");

537
  if (thd->locked_tables)
unknown's avatar
unknown committed
538
  {					// Can't have locked tables here
539 540 541
    thd->lock=thd->locked_tables;
    thd->locked_tables=0;
    close_thread_tables(thd);
unknown's avatar
unknown committed
542
  }
543 544 545 546 547 548

  /*
    To avoid deadlocks we should obtain table locks before
    obtaining acl_cache->lock mutex.
  */
  bzero((char*) tables, sizeof(tables));
549 550 551 552 553 554
  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;
555 556 557 558 559 560 561 562 563
  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
564 565 566 567 568 569 570 571 572 573
  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);

574
  if ((return_val= acl_load(thd, tables)))
unknown's avatar
unknown committed
575
  {					// Error. Revert to old list
576
    DBUG_PRINT("error",("Reverting to old privileges"));
577
    acl_free();				/* purecov: inspected */
unknown's avatar
unknown committed
578 579 580 581 582 583 584 585
    acl_hosts=old_acl_hosts;
    acl_users=old_acl_users;
    acl_dbs=old_acl_dbs;
    mem=old_mem;
    init_check_host();
  }
  else
  {
586
    free_root(&old_mem,MYF(0));
unknown's avatar
unknown committed
587 588 589 590 591 592
    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));
593 594 595
end:
  close_thread_tables(thd);
  DBUG_RETURN(return_val);
unknown's avatar
unknown committed
596 597 598
}


unknown's avatar
unknown committed
599 600
/*
  Get all access bits from table after fieldnr
unknown's avatar
unknown committed
601 602

  IMPLEMENTATION
unknown's avatar
unknown committed
603 604
  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
605 606 607 608 609 610 611 612 613 614 615

  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
616
*/
unknown's avatar
unknown committed
617

unknown's avatar
unknown committed
618
static ulong get_access(TABLE *form, uint fieldnr, uint *next_field)
unknown's avatar
unknown committed
619
{
unknown's avatar
unknown committed
620
  ulong access_bits=0,bit;
unknown's avatar
unknown committed
621
  char buff[2];
unknown's avatar
unknown committed
622
  String res(buff,sizeof(buff),&my_charset_latin1);
unknown's avatar
unknown committed
623 624
  Field **pos;

unknown's avatar
unknown committed
625 626 627
  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
628
       pos++, fieldnr++, bit<<=1)
unknown's avatar
unknown committed
629
  {
630
    (*pos)->val_str(&res);
unknown's avatar
unknown committed
631
    if (my_toupper(&my_charset_latin1, res[0]) == 'Y')
unknown's avatar
unknown committed
632
      access_bits|= bit;
unknown's avatar
unknown committed
633
  }
unknown's avatar
unknown committed
634 635
  if (next_field)
    *next_field=fieldnr;
unknown's avatar
unknown committed
636 637 638 639 640
  return access_bits;
}


/*
unknown's avatar
unknown committed
641 642 643 644 645
  Return a number which, if sorted 'desc', puts strings in this order:
    no wildcards
    wildcards
    empty string
*/
unknown's avatar
unknown committed
646 647 648 649 650 651 652

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

653 654 655
  /* Should not use this function with more than 4 arguments for compare. */
  DBUG_ASSERT(count <= 4);

unknown's avatar
unknown committed
656 657
  while (count--)
  {
658 659 660
    char *start, *str= va_arg(args,char*);
    uint chars= 0;
    uint wild_pos= 0;           /* first wildcard position */
unknown's avatar
unknown committed
661

unknown's avatar
unknown committed
662
    if ((start= str))
unknown's avatar
unknown committed
663 664 665 666
    {
      for (; *str ; str++)
      {
	if (*str == wild_many || *str == wild_one || *str == wild_prefix)
667
        {
unknown's avatar
unknown committed
668
          wild_pos= (uint) (str - start) + 1;
669 670
          break;
        }
unknown's avatar
unknown committed
671
        chars= 128;                             // Marker that chars existed
unknown's avatar
unknown committed
672 673
      }
    }
unknown's avatar
unknown committed
674
    sort= (sort << 8) + (wild_pos ? min(wild_pos, 127) : chars);
unknown's avatar
unknown committed
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
  }
  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;
}

690

691
/*
unknown's avatar
unknown committed
692 693
  Seek ACL entry for a user, check password, SSL cypher, and if
  everything is OK, update THD user data and USER_RESOURCES struct.
694

unknown's avatar
unknown committed
695 696 697 698
  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
699

700
  SYNOPSIS
701 702
    acl_getroot()
    thd         thread handle. If all checks are OK,
703 704
                thd->security_ctx->priv_user/master_access are updated.
                thd->security_ctx->host/ip/user are used for checks.
705 706
    mqh         user resources; on success mqh is reset, else
                unchanged
707
    passwd      scrambled & crypted password, received from client
708 709 710 711 712 713 714
                (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
715
  RETURN VALUE
716 717
    0  success: thd->priv_user, thd->priv_host, thd->master_access, mqh are
       updated
718
    1  user not found or authentication failure
unknown's avatar
unknown committed
719
    2  user found, has long (4.1.1) salt, but passwd is in old (3.23) format.
720
   -1  user found, has short (3.23) salt, but passwd is in new (4.1.1) format.
unknown's avatar
unknown committed
721 722
*/

723 724
int acl_getroot(THD *thd, USER_RESOURCES  *mqh,
                const char *passwd, uint passwd_len)
unknown's avatar
unknown committed
725
{
unknown's avatar
merge  
unknown committed
726 727 728
  ulong user_access= NO_ACCESS;
  int res= 1;
  ACL_USER *acl_user= 0;
729
  Security_context *sctx= thd->security_ctx;
730
  DBUG_ENTER("acl_getroot");
unknown's avatar
unknown committed
731 732

  if (!initialized)
733
  {
734 735 736
    /* 
      here if mysqld's been started with --skip-grant-tables option.
    */
737
    sctx->skip_grants();
738
    bzero((char*) mqh, sizeof(*mqh));
739
    DBUG_RETURN(0);
740
  }
741

unknown's avatar
unknown committed
742
  VOID(pthread_mutex_lock(&acl_cache->lock));
unknown's avatar
unknown committed
743

unknown's avatar
unknown committed
744
  /*
745 746 747
    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
748
  */
unknown's avatar
unknown committed
749

750
  for (uint i=0 ; i < acl_users.elements ; i++)
751
  {
unknown's avatar
unknown committed
752
    ACL_USER *acl_user_tmp= dynamic_element(&acl_users,i,ACL_USER*);
753
    if (!acl_user_tmp->user || !strcmp(sctx->user, acl_user_tmp->user))
unknown's avatar
unknown committed
754
    {
755
      if (compare_hostname(&acl_user_tmp->host, sctx->host, sctx->ip))
unknown's avatar
unknown committed
756
      {
757
        /* check password: it should be empty or valid */
unknown's avatar
unknown committed
758
        if (passwd_len == acl_user_tmp->salt_len)
unknown's avatar
unknown committed
759
        {
unknown's avatar
unknown committed
760
          if (acl_user_tmp->salt_len == 0 ||
unknown's avatar
unknown committed
761 762
              (acl_user_tmp->salt_len == SCRAMBLE_LENGTH ?
              check_scramble(passwd, thd->scramble, acl_user_tmp->salt) :
763
              check_scramble_323(passwd, thd->scramble,
unknown's avatar
unknown committed
764
                                 (ulong *) acl_user_tmp->salt)) == 0)
765
          {
unknown's avatar
unknown committed
766
            acl_user= acl_user_tmp;
767 768
            res= 0;
          }
unknown's avatar
unknown committed
769
        }
770
        else if (passwd_len == SCRAMBLE_LENGTH &&
unknown's avatar
unknown committed
771
                 acl_user_tmp->salt_len == SCRAMBLE_LENGTH_323)
772
          res= -1;
unknown's avatar
unknown committed
773
        else if (passwd_len == SCRAMBLE_LENGTH_323 &&
unknown's avatar
unknown committed
774
                 acl_user_tmp->salt_len == SCRAMBLE_LENGTH)
unknown's avatar
unknown committed
775
          res= 2;
776 777
        /* linear search complete: */
        break;
unknown's avatar
unknown committed
778
      }
unknown's avatar
unknown committed
779
    }
780
  }
781 782 783 784
  /*
    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
785 786 787

  if (acl_user)
  {
788
    /* OK. User found and password checked continue validation */
789
#ifdef HAVE_OPENSSL
unknown's avatar
unknown committed
790
    Vio *vio=thd->net.vio;
unknown's avatar
unknown committed
791
    SSL *ssl= (SSL*) vio->ssl_arg;
792
#endif
unknown's avatar
merge  
unknown committed
793

794
    /*
unknown's avatar
unknown committed
795
      At this point we know that user is allowed to connect
796 797 798 799 800 801
      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
802 803
    case SSL_TYPE_NONE:				// SSL is not required
      user_access= acl_user->access;
804
      break;
805
#ifdef HAVE_OPENSSL
unknown's avatar
merge  
unknown committed
806
    case SSL_TYPE_ANY:				// Any kind of SSL is ok
807
      if (vio_type(vio) == VIO_TYPE_SSL)
unknown's avatar
merge  
unknown committed
808
	user_access= acl_user->access;
809 810 811 812 813
      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
814

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

906
    if (acl_user->host.hostname)
907
      strmake(sctx->priv_host, acl_user->host.hostname, MAX_HOSTNAME);
908
    else
909
      *sctx->priv_host= 0;
910
  }
unknown's avatar
unknown committed
911
  VOID(pthread_mutex_unlock(&acl_cache->lock));
912
  DBUG_RETURN(res);
unknown's avatar
unknown committed
913 914 915
}


916
/*
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
  This is like acl_getroot() above, but it doesn't check password,
  and we don't care about the user resources.

  SYNOPSIS
    acl_getroot_no_password()
      sctx               Context which should be initialized
      user               user name
      host               host name
      ip                 IP
      db                 current data base name

  RETURN
    FALSE  OK
    TRUE   Error
*/

bool acl_getroot_no_password(Security_context *sctx, char *user, char *host,
                             char *ip, char *db)
935 936
{
  int res= 1;
937
  uint i;
938 939 940
  ACL_USER *acl_user= 0;
  DBUG_ENTER("acl_getroot_no_password");

941 942
  DBUG_PRINT("enter", ("Host: '%s', Ip: '%s', User: '%s', db: '%s'",
                       (host ? host : "(NULL)"), (ip ? ip : "(NULL)"),
943
                       user, (db ? db : "(NULL)")));
944 945 946 947 948
  sctx->user= user;
  sctx->host= host;
  sctx->ip= ip;
  sctx->host_or_ip= host ? host : (ip ? ip : "");

949 950
  if (!initialized)
  {
951
    /*
952 953
      here if mysqld's been started with --skip-grant-tables option.
    */
954
    sctx->skip_grants();
955
    DBUG_RETURN(FALSE);
956 957 958 959
  }

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

960 961
  sctx->master_access= 0;
  sctx->db_access= 0;
962

963 964 965
  /*
     Find acl entry in user database.
     This is specially tailored to suit the check we do for CALL of
966
     a stored procedure; user is set to what is actually a
967 968
     priv_user, which can be ''.
  */
969
  for (i=0 ; i < acl_users.elements ; i++)
970 971
  {
    acl_user= dynamic_element(&acl_users,i,ACL_USER*);
972
    if ((!acl_user->user && !user[0]) ||
973
	(acl_user->user && strcmp(user, acl_user->user) == 0))
974
    {
975
      if (compare_hostname(&acl_user->host, host, ip))
976 977 978 979 980 981 982 983 984
      {
	res= 0;
	break;
      }
    }
  }

  if (acl_user)
  {
985 986 987 988
    for (i=0 ; i < acl_dbs.elements ; i++)
    {
      ACL_DB *acl_db= dynamic_element(&acl_dbs, i, ACL_DB*);
      if (!acl_db->user ||
989
	  (user && user[0] && !strcmp(user, acl_db->user)))
990
      {
991
	if (compare_hostname(&acl_db->host, host, ip))
992
	{
993
	  if (!acl_db->db || (db && !wild_compare(db, acl_db->db, 0)))
994
	  {
995
	    sctx->db_access= acl_db->access;
996 997 998 999 1000
	    break;
	  }
	}
      }
    }
1001 1002
    sctx->master_access= acl_user->access;
    sctx->priv_user= acl_user->user ? user : (char *) "";
1003 1004

    if (acl_user->host.hostname)
1005
      strmake(sctx->priv_host, acl_user->host.hostname, MAX_HOSTNAME);
1006
    else
1007
      *sctx->priv_host= 0;
1008 1009 1010 1011 1012
  }
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  DBUG_RETURN(res);
}

unknown's avatar
unknown committed
1013 1014 1015 1016 1017 1018 1019
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;
}

1020

unknown's avatar
unknown committed
1021
static void acl_update_user(const char *user, const char *host,
1022
			    const char *password, uint password_len,
1023 1024 1025 1026
			    enum SSL_type ssl_type,
			    const char *ssl_cipher,
			    const char *x509_issuer,
			    const char *x509_subject,
unknown's avatar
unknown committed
1027
			    USER_RESOURCES  *mqh,
unknown's avatar
unknown committed
1028
			    ulong privileges)
unknown's avatar
unknown committed
1029 1030 1031 1032 1033 1034 1035 1036 1037
{
  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
1038
	  acl_user->host.hostname &&
1039
	  !my_strcasecmp(system_charset_info, host, acl_user->host.hostname))
unknown's avatar
unknown committed
1040 1041
      {
	acl_user->access=privileges;
1042
	if (mqh->specified_limits & USER_RESOURCES::QUERIES_PER_HOUR)
1043
	  acl_user->user_resource.questions=mqh->questions;
1044
	if (mqh->specified_limits & USER_RESOURCES::UPDATES_PER_HOUR)
1045
	  acl_user->user_resource.updates=mqh->updates;
1046 1047 1048 1049
	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;
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
	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
1060 1061
	if (password)
	  set_user_salt(acl_user, password, password_len);
1062
        /* search complete: */
unknown's avatar
unknown committed
1063 1064 1065 1066 1067 1068 1069 1070
	break;
      }
    }
  }
}


static void acl_insert_user(const char *user, const char *host,
1071
			    const char *password, uint password_len,
1072 1073 1074 1075
			    enum SSL_type ssl_type,
			    const char *ssl_cipher,
			    const char *x509_issuer,
			    const char *x509_subject,
1076
			    USER_RESOURCES *mqh,
unknown's avatar
unknown committed
1077
			    ulong privileges)
unknown's avatar
unknown committed
1078 1079
{
  ACL_USER acl_user;
1080
  acl_user.user=*user ? strdup_root(&mem,user) : 0;
unknown's avatar
unknown committed
1081
  update_hostname(&acl_user.host, *host ? strdup_root(&mem, host): 0);
unknown's avatar
unknown committed
1082
  acl_user.access=privileges;
1083
  acl_user.user_resource = *mqh;
unknown's avatar
unknown committed
1084
  acl_user.sort=get_sort(2,acl_user.host.hostname,acl_user.user);
1085
  acl_user.hostname_length=(uint) strlen(host);
1086 1087 1088 1089 1090
  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;
1091 1092

  set_user_salt(&acl_user, password, password_len);
unknown's avatar
unknown committed
1093 1094 1095 1096

  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
1097
    allow_all_hosts=1;		// Anyone can connect /* purecov: tested */
unknown's avatar
unknown committed
1098 1099 1100
  qsort((gptr) dynamic_element(&acl_users,0,ACL_USER*),acl_users.elements,
	sizeof(ACL_USER),(qsort_cmp) acl_compare);

1101 1102
  /* Rebuild 'acl_check_hosts' since 'acl_users' has been modified */
  rebuild_check_host();
unknown's avatar
unknown committed
1103 1104 1105 1106
}


static void acl_update_db(const char *user, const char *host, const char *db,
unknown's avatar
unknown committed
1107
			  ulong privileges)
unknown's avatar
unknown committed
1108 1109 1110 1111 1112 1113 1114 1115 1116
{
  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] ||
1117
	  acl_db->host.hostname &&
1118
	  !my_strcasecmp(system_charset_info, host, acl_db->host.hostname))
unknown's avatar
unknown committed
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
      {
	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);
	}
      }
    }
  }
}


1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
/*
  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
1148
static void acl_insert_db(const char *user, const char *host, const char *db,
unknown's avatar
unknown committed
1149
			  ulong privileges)
unknown's avatar
unknown committed
1150 1151
{
  ACL_DB acl_db;
1152
  safe_mutex_assert_owner(&acl_cache->lock);
unknown's avatar
unknown committed
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
  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);
}


1164 1165 1166

/*
  Get privilege for a host, user and db combination
1167 1168 1169

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

1172
ulong acl_get(const char *host, const char *ip,
1173
              const char *user, const char *db, my_bool db_is_pattern)
unknown's avatar
unknown committed
1174
{
1175
  ulong host_access= ~(ulong)0, db_access= 0;
unknown's avatar
unknown committed
1176
  uint i,key_length;
unknown's avatar
unknown committed
1177
  char key[ACL_KEY_LENGTH],*tmp_db,*end;
unknown's avatar
unknown committed
1178
  acl_entry *entry;
unknown's avatar
unknown committed
1179
  DBUG_ENTER("acl_get");
unknown's avatar
unknown committed
1180 1181

  VOID(pthread_mutex_lock(&acl_cache->lock));
1182
  end=strmov((tmp_db=strmov(strmov(key, ip ? ip : "")+1,user)+1),db);
unknown's avatar
unknown committed
1183 1184
  if (lower_case_table_names)
  {
1185
    my_casedn_str(files_charset_info, tmp_db);
unknown's avatar
unknown committed
1186 1187
    db=tmp_db;
  }
unknown's avatar
unknown committed
1188
  key_length=(uint) (end-key);
1189
  if (!db_is_pattern && (entry=(acl_entry*) acl_cache->search(key,key_length)))
unknown's avatar
unknown committed
1190 1191 1192
  {
    db_access=entry->access;
    VOID(pthread_mutex_unlock(&acl_cache->lock));
unknown's avatar
unknown committed
1193 1194
    DBUG_PRINT("exit", ("access: 0x%lx", db_access));
    DBUG_RETURN(db_access);
unknown's avatar
unknown committed
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
  }

  /*
    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))
      {
1207
	if (!acl_db->db || !wild_compare(db,acl_db->db,db_is_pattern))
unknown's avatar
unknown committed
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
	{
	  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))
    {
1229
      if (!acl_host->db || !wild_compare(db,acl_host->db,db_is_pattern))
unknown's avatar
unknown committed
1230 1231 1232 1233 1234 1235 1236 1237
      {
	host_access=acl_host->access;		// Fully specified. Take it
	break;
      }
    }
  }
exit:
  /* Save entry in cache for quick retrieval */
1238 1239
  if (!db_is_pattern &&
      (entry= (acl_entry*) malloc(sizeof(acl_entry)+key_length)))
unknown's avatar
unknown committed
1240 1241 1242 1243 1244 1245 1246
  {
    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
1247 1248
  DBUG_PRINT("exit", ("access: 0x%lx", db_access & host_access));
  DBUG_RETURN(db_access & host_access);
unknown's avatar
unknown committed
1249 1250
}

1251 1252 1253 1254 1255 1256 1257
/*
  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
1258 1259 1260 1261

static void init_check_host(void)
{
  DBUG_ENTER("init_check_host");
1262
  VOID(my_init_dynamic_array(&acl_wild_hosts,sizeof(struct acl_host_and_ip),
unknown's avatar
unknown committed
1263
			  acl_users.elements,1));
1264
  VOID(hash_init(&acl_check_hosts,system_charset_info,acl_users.elements,0,0,
unknown's avatar
unknown committed
1265
		 (hash_get_key) check_get_key,0,0));
unknown's avatar
unknown committed
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
  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 *);
1280
	  if (!my_strcasecmp(system_charset_info,
1281
                             acl_user->host.hostname, acl->hostname))
unknown's avatar
unknown committed
1282 1283 1284 1285 1286
	    break;				// already stored
	}
	if (j == acl_wild_hosts.elements)	// If new
	  (void) push_dynamic(&acl_wild_hosts,(char*) &acl_user->host);
      }
1287
      else if (!hash_search(&acl_check_hosts,(byte*) acl_user->host.hostname,
unknown's avatar
unknown committed
1288
			    (uint) strlen(acl_user->host.hostname)))
unknown's avatar
unknown committed
1289
      {
unknown's avatar
SCRUM  
unknown committed
1290
	if (my_hash_insert(&acl_check_hosts,(byte*) acl_user))
unknown's avatar
unknown committed
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
	{					// 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;
}


1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
/*
  Rebuild lists used for checking of allowed hosts

  We need to rebuild 'acl_check_hosts' and 'acl_wild_hosts' after adding,
  dropping or renaming user, since they contain pointers to elements of
  'acl_user' array, which are invalidated by drop operation, and use
  ACL_USER::host::hostname as a key, which is changed by rename.
*/
void rebuild_check_host(void)
{
  delete_dynamic(&acl_wild_hosts);
  hash_free(&acl_check_hosts);
  init_check_host();
}


unknown's avatar
unknown committed
1320 1321 1322 1323 1324 1325 1326 1327
/* 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
1328 1329
  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
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
  {
    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
1348 1349 1350 1351 1352 1353 1354 1355
/*
  Check if the user is allowed to change password

  SYNOPSIS:
    check_change_password()
    thd		THD
    host	hostname for the user
    user	user name
1356 1357 1358 1359
    new_password new password

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

unknown's avatar
unknown committed
1361
    RETURN VALUE
1362 1363
      0		OK
      1		ERROR  ; In this case the error is sent to the client.
unknown's avatar
unknown committed
1364 1365
*/

1366
bool check_change_password(THD *thd, const char *host, const char *user,
1367
                           char *new_password, uint new_password_len)
unknown's avatar
unknown committed
1368
{
unknown's avatar
unknown committed
1369 1370
  if (!initialized)
  {
unknown's avatar
unknown committed
1371
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
1372
    return(1);
unknown's avatar
unknown committed
1373
  }
unknown's avatar
unknown committed
1374
  if (!thd->slave_thread &&
1375 1376 1377
      (strcmp(thd->security_ctx->user, user) ||
       my_strcasecmp(system_charset_info, host,
                     thd->security_ctx->priv_host)))
unknown's avatar
unknown committed
1378
  {
1379
    if (check_access(thd, UPDATE_ACL, "mysql",0,1,0,0))
unknown's avatar
unknown committed
1380
      return(1);
unknown's avatar
unknown committed
1381
  }
1382
  if (!thd->slave_thread && !thd->security_ctx->user[0])
unknown's avatar
unknown committed
1383
  {
unknown's avatar
unknown committed
1384 1385
    my_message(ER_PASSWORD_ANONYMOUS_USER, ER(ER_PASSWORD_ANONYMOUS_USER),
               MYF(0));
unknown's avatar
unknown committed
1386
    return(1);
unknown's avatar
unknown committed
1387
  }
1388
  uint len=strlen(new_password);
unknown's avatar
unknown committed
1389
  if (len && len != SCRAMBLED_PASSWORD_CHAR_LENGTH &&
1390 1391
      len != SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
  {
unknown's avatar
unknown committed
1392
    my_error(ER_PASSWD_LENGTH, MYF(0), SCRAMBLED_PASSWORD_CHAR_LENGTH);
1393 1394
    return -1;
  }
unknown's avatar
unknown committed
1395 1396 1397 1398
  return(0);
}


1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
/*
  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
1412
*/
1413

unknown's avatar
unknown committed
1414 1415 1416
bool change_password(THD *thd, const char *host, const char *user,
		     char *new_password)
{
1417 1418 1419 1420 1421
  TABLE_LIST tables;
  TABLE *table;
  /* Buffer should be extended when password length is extended. */
  char buff[512];
  ulong query_length;
1422
  uint new_password_len= strlen(new_password);
1423
  bool result= 1;
unknown's avatar
unknown committed
1424 1425 1426 1427 1428
  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

1429
  if (check_change_password(thd, host, user, new_password, new_password_len))
unknown's avatar
unknown committed
1430 1431
    DBUG_RETURN(1);

1432
  bzero((char*) &tables, sizeof(tables));
1433
  tables.alias= tables.table_name= (char*) "user";
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
  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 */
1449
    if (!tables_ok(thd, &tables))
1450 1451 1452 1453 1454 1455 1456
      DBUG_RETURN(0);
  }
#endif

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

unknown's avatar
unknown committed
1457 1458
  VOID(pthread_mutex_lock(&acl_cache->lock));
  ACL_USER *acl_user;
1459
  if (!(acl_user= find_acl_user(host, user, TRUE)))
unknown's avatar
unknown committed
1460 1461
  {
    VOID(pthread_mutex_unlock(&acl_cache->lock));
unknown's avatar
unknown committed
1462
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH), MYF(0));
1463
    goto end;
unknown's avatar
unknown committed
1464
  }
1465 1466 1467
  /* update loaded acl entry: */
  set_user_salt(acl_user, new_password, new_password_len);

1468
  if (update_user_table(thd, table,
unknown's avatar
unknown committed
1469
			acl_user->host.hostname ? acl_user->host.hostname : "",
unknown's avatar
unknown committed
1470
			acl_user->user ? acl_user->user : "",
1471
			new_password, new_password_len))
unknown's avatar
unknown committed
1472 1473
  {
    VOID(pthread_mutex_unlock(&acl_cache->lock)); /* purecov: deadcode */
1474
    goto end;
unknown's avatar
unknown committed
1475
  }
unknown's avatar
unknown committed
1476

unknown's avatar
unknown committed
1477 1478
  acl_cache->clear(1);				// Clear locked hostname cache
  VOID(pthread_mutex_unlock(&acl_cache->lock));
1479 1480 1481
  result= 0;
  if (mysql_bin_log.is_open())
  {
1482 1483 1484 1485 1486 1487
    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));
1488 1489 1490 1491 1492 1493 1494
    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
1495 1496 1497
}


1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
/*
  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;
1514 1515 1516 1517 1518

  /* --skip-grants */
  if (!initialized)
    return TRUE;

1519
  VOID(pthread_mutex_lock(&acl_cache->lock));
1520
  res= find_acl_user(host, user, TRUE) != NULL;
1521 1522 1523 1524 1525
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  return res;
}


unknown's avatar
unknown committed
1526 1527 1528 1529 1530
/*
  Find first entry that matches the current user
*/

static ACL_USER *
1531
find_acl_user(const char *host, const char *user, my_bool exact)
unknown's avatar
unknown committed
1532
{
unknown's avatar
unknown committed
1533
  DBUG_ENTER("find_acl_user");
1534
  DBUG_PRINT("enter",("host: '%s'  user: '%s'",host,user));
unknown's avatar
unknown committed
1535 1536 1537
  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
1538
    DBUG_PRINT("info",("strcmp('%s','%s'), compare_hostname('%s','%s'),",
1539 1540 1541 1542 1543
		       user,
		       acl_user->user ? acl_user->user : "",
		       host,
		       acl_user->host.hostname ? acl_user->host.hostname :
		       ""));
unknown's avatar
unknown committed
1544 1545 1546
    if (!acl_user->user && !user[0] ||
	acl_user->user && !strcmp(user,acl_user->user))
    {
1547
      if (exact ? !my_strcasecmp(&my_charset_latin1, host,
1548 1549
                                 acl_user->host.hostname ?
				 acl_user->host.hostname : "") :
1550
          compare_hostname(&acl_user->host,host,host))
unknown's avatar
unknown committed
1551 1552 1553
      {
	DBUG_RETURN(acl_user);
      }
unknown's avatar
unknown committed
1554 1555
    }
  }
unknown's avatar
unknown committed
1556
  DBUG_RETURN(0);
unknown's avatar
unknown committed
1557 1558 1559
}


1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
/*
  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
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593

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!
1594
  if (!hostname ||
unknown's avatar
unknown committed
1595 1596 1597
      (!(hostname=calc_ip(hostname,&host->ip,'/')) ||
       !(hostname=calc_ip(hostname+1,&host->ip_mask,'\0'))))
  {
1598
    host->ip= host->ip_mask=0;			// Not a masked ip
unknown's avatar
unknown committed
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
  }
}


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 ||
1612
	  (hostname && !wild_case_compare(system_charset_info,
1613
                                          hostname,host->hostname)) ||
1614
	  (ip && !wild_compare(ip,host->hostname,0)));
unknown's avatar
unknown committed
1615 1616
}

unknown's avatar
SCRUM  
unknown committed
1617 1618 1619 1620
bool hostname_requires_resolving(const char *hostname)
{
  char cur;
  if (!hostname)
unknown's avatar
unknown committed
1621
    return FALSE;
unknown's avatar
SCRUM  
unknown committed
1622 1623 1624
  int namelen= strlen(hostname);
  int lhlen= strlen(my_localhost);
  if ((namelen == lhlen) &&
1625
      !my_strnncoll(system_charset_info, (const uchar *)hostname,  namelen,
unknown's avatar
SCRUM  
unknown committed
1626
		    (const uchar *)my_localhost, strlen(my_localhost)))
unknown's avatar
unknown committed
1627
    return FALSE;
unknown's avatar
SCRUM  
unknown committed
1628 1629
  for (; (cur=*hostname); hostname++)
  {
1630
    if ((cur != '%') && (cur != '_') && (cur != '.') && (cur != '/') &&
unknown's avatar
SCRUM  
unknown committed
1631
	((cur < '0') || (cur > '9')))
unknown's avatar
unknown committed
1632
      return TRUE;
unknown's avatar
SCRUM  
unknown committed
1633
  }
unknown's avatar
unknown committed
1634
  return FALSE;
unknown's avatar
SCRUM  
unknown committed
1635
}
unknown's avatar
unknown committed
1636

1637

1638
/*
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
  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
1649
*/
unknown's avatar
unknown committed
1650

1651 1652
static bool update_user_table(THD *thd, TABLE *table,
                              const char *host, const char *user,
1653
			      const char *new_password, uint new_password_len)
unknown's avatar
unknown committed
1654
{
1655
  char user_key[MAX_KEY_LENGTH];
1656
  int error;
unknown's avatar
unknown committed
1657 1658 1659
  DBUG_ENTER("update_user_table");
  DBUG_PRINT("enter",("user: %s  host: %s",user,host));

1660 1661
  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
1662
  key_copy((byte *) user_key, table->record[0], table->key_info,
1663
           table->key_info->key_length);
unknown's avatar
unknown committed
1664

1665
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
1666
  if (table->file->index_read_idx(table->record[0], 0,
unknown's avatar
unknown committed
1667
				  (byte *) user_key, table->key_info->key_length,
unknown's avatar
unknown committed
1668 1669
				  HA_READ_KEY_EXACT))
  {
unknown's avatar
unknown committed
1670 1671
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH),
               MYF(0));	/* purecov: deadcode */
unknown's avatar
unknown committed
1672 1673
    DBUG_RETURN(1);				/* purecov: deadcode */
  }
unknown's avatar
unknown committed
1674
  store_record(table,record[1]);
1675
  table->field[2]->store(new_password, new_password_len, system_charset_info);
unknown's avatar
unknown committed
1676 1677 1678
  if ((error=table->file->update_row(table->record[1],table->record[0])))
  {
    table->file->print_error(error,MYF(0));	/* purecov: deadcode */
1679
    DBUG_RETURN(1);
unknown's avatar
unknown committed
1680
  }
1681
  DBUG_RETURN(0);
unknown's avatar
unknown committed
1682 1683
}

unknown's avatar
unknown committed
1684

1685 1686 1687 1688 1689 1690
/*
  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
1691 1692 1693

static bool test_if_create_new_users(THD *thd)
{
1694
  Security_context *sctx= thd->security_ctx;
1695
  bool create_new_users= test(sctx->master_access & INSERT_ACL) ||
1696
                         (!opt_safe_user_create &&
1697
                          test(sctx->master_access & CREATE_USER_ACL));
1698
  if (!create_new_users)
unknown's avatar
unknown committed
1699 1700
  {
    TABLE_LIST tl;
unknown's avatar
unknown committed
1701
    ulong db_access;
unknown's avatar
unknown committed
1702 1703
    bzero((char*) &tl,sizeof(tl));
    tl.db=	   (char*) "mysql";
1704
    tl.table_name=  (char*) "user";
1705
    create_new_users= 1;
unknown's avatar
unknown committed
1706

1707 1708
    db_access=acl_get(sctx->host, sctx->ip,
		      sctx->priv_user, tl.db, 0);
unknown's avatar
unknown committed
1709 1710
    if (!(db_access & INSERT_ACL))
    {
unknown's avatar
unknown committed
1711
      if (check_grant(thd, INSERT_ACL, &tl, 0, UINT_MAX, 1))
unknown's avatar
unknown committed
1712 1713 1714 1715 1716 1717 1718
	create_new_users=0;
    }
  }
  return create_new_users;
}


unknown's avatar
unknown committed
1719
/****************************************************************************
1720
  Handle GRANT commands
unknown's avatar
unknown committed
1721 1722
****************************************************************************/

1723
static int replace_user_table(THD *thd, TABLE *table, const LEX_USER &combo,
unknown's avatar
unknown committed
1724
			      ulong rights, bool revoke_grant,
unknown's avatar
unknown committed
1725
			      bool can_create_user, bool no_auto_create)
unknown's avatar
unknown committed
1726 1727
{
  int error = -1;
unknown's avatar
unknown committed
1728
  bool old_row_exists=0;
1729
  const char *password= "";
1730
  uint password_len= 0;
unknown's avatar
unknown committed
1731
  char what= (revoke_grant) ? 'N' : 'Y';
1732
  byte user_key[MAX_KEY_LENGTH];
1733
  LEX *lex= thd->lex;
unknown's avatar
unknown committed
1734
  DBUG_ENTER("replace_user_table");
unknown's avatar
unknown committed
1735

1736
  safe_mutex_assert_owner(&acl_cache->lock);
unknown's avatar
unknown committed
1737 1738

  if (combo.password.str && combo.password.str[0])
1739
  {
1740 1741
    if (combo.password.length != SCRAMBLED_PASSWORD_CHAR_LENGTH &&
        combo.password.length != SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
1742
    {
1743
      my_error(ER_PASSWD_LENGTH, MYF(0), SCRAMBLED_PASSWORD_CHAR_LENGTH);
unknown's avatar
unknown committed
1744
      DBUG_RETURN(-1);
1745
    }
1746
    password_len= combo.password.length;
unknown's avatar
unknown committed
1747
    password=combo.password.str;
1748
  }
unknown's avatar
unknown committed
1749

1750 1751
  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);
1752 1753 1754
  key_copy(user_key, table->record[0], table->key_info,
           table->key_info->key_length);

1755
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
unknown's avatar
unknown committed
1756
  if (table->file->index_read_idx(table->record[0], 0,
1757 1758
                                  user_key, table->key_info->key_length,
                                  HA_READ_KEY_EXACT))
unknown's avatar
unknown committed
1759
  {
1760 1761
    /* what == 'N' means revoke */
    if (what == 'N')
unknown's avatar
unknown committed
1762
    {
1763 1764 1765 1766
      my_error(ER_NONEXISTING_GRANT, MYF(0), combo.user.str, combo.host.str);
      goto end;
    }
    /*
1767 1768
      There are four options which affect the process of creation of
      a new user (mysqld option --safe-create-user, 'insert' privilege
1769 1770 1771 1772 1773 1774 1775
      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
1776 1777

      see also test_if_create_new_users()
1778
    */
unknown's avatar
unknown committed
1779 1780 1781 1782 1783 1784
    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)
1785
    {
unknown's avatar
unknown committed
1786
      my_error(ER_CANT_CREATE_USER_WITH_GRANT, MYF(0),
1787
               thd->security_ctx->user, thd->security_ctx->host_or_ip);
unknown's avatar
unknown committed
1788 1789
      goto end;
    }
unknown's avatar
unknown committed
1790
    old_row_exists = 0;
1791
    restore_record(table,s->default_values);
1792
    table->field[0]->store(combo.host.str,combo.host.length,
1793
                           system_charset_info);
1794
    table->field[1]->store(combo.user.str,combo.user.length,
1795
                           system_charset_info);
1796
    table->field[2]->store(password, password_len,
1797
                           system_charset_info);
unknown's avatar
unknown committed
1798 1799 1800
  }
  else
  {
unknown's avatar
unknown committed
1801
    old_row_exists = 1;
unknown's avatar
unknown committed
1802
    store_record(table,record[1]);			// Save copy for update
unknown's avatar
unknown committed
1803
    if (combo.password.str)			// If password given
1804
      table->field[2]->store(password, password_len, system_charset_info);
1805
    else if (!rights && !revoke_grant &&
1806 1807
             lex->ssl_type == SSL_TYPE_NOT_SPECIFIED &&
             !lex->mqh.specified_limits)
unknown's avatar
unknown committed
1808 1809 1810
    {
      DBUG_RETURN(0);
    }
unknown's avatar
unknown committed
1811 1812
  }

unknown's avatar
unknown committed
1813 1814 1815 1816
  /* Update table columns with new privileges */

  Field **tmp_field;
  ulong priv;
1817
  uint next_field;
unknown's avatar
unknown committed
1818 1819 1820 1821
  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
1822
  {
unknown's avatar
unknown committed
1823
    if (priv & rights)				 // set requested privileges
unknown's avatar
unknown committed
1824
      (*tmp_field)->store(&what, 1, &my_charset_latin1);
unknown's avatar
unknown committed
1825
  }
1826
  rights= get_access(table, 3, &next_field);
1827 1828
  DBUG_PRINT("info",("table fields: %d",table->s->fields));
  if (table->s->fields >= 31)		/* From 4.0.0 we have more fields */
1829
  {
unknown's avatar
unknown committed
1830
    /* We write down SSL related ACL stuff */
1831
    switch (lex->ssl_type) {
1832
    case SSL_TYPE_ANY:
1833 1834
      table->field[next_field]->store(STRING_WITH_LEN("ANY"),
                                      &my_charset_latin1);
1835 1836 1837
      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);
1838 1839
      break;
    case SSL_TYPE_X509:
1840 1841
      table->field[next_field]->store(STRING_WITH_LEN("X509"),
                                      &my_charset_latin1);
1842 1843 1844
      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);
1845 1846
      break;
    case SSL_TYPE_SPECIFIED:
1847 1848
      table->field[next_field]->store(STRING_WITH_LEN("SPECIFIED"),
                                      &my_charset_latin1);
1849 1850 1851
      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);
1852
      if (lex->ssl_cipher)
unknown's avatar
unknown committed
1853 1854
        table->field[next_field+1]->store(lex->ssl_cipher,
                                strlen(lex->ssl_cipher), system_charset_info);
1855
      if (lex->x509_issuer)
unknown's avatar
unknown committed
1856 1857
        table->field[next_field+2]->store(lex->x509_issuer,
                                strlen(lex->x509_issuer), system_charset_info);
1858
      if (lex->x509_subject)
unknown's avatar
unknown committed
1859 1860
        table->field[next_field+3]->store(lex->x509_subject,
                                strlen(lex->x509_subject), system_charset_info);
1861
      break;
unknown's avatar
unknown committed
1862
    case SSL_TYPE_NOT_SPECIFIED:
unknown's avatar
unknown committed
1863 1864
      break;
    case SSL_TYPE_NONE:
1865 1866 1867 1868
      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
1869
      break;
1870
    }
unknown's avatar
unknown committed
1871
    next_field+=4;
unknown's avatar
unknown committed
1872

1873
    USER_RESOURCES mqh= lex->mqh;
1874
    if (mqh.specified_limits & USER_RESOURCES::QUERIES_PER_HOUR)
1875
      table->field[next_field]->store((longlong) mqh.questions, TRUE);
1876
    if (mqh.specified_limits & USER_RESOURCES::UPDATES_PER_HOUR)
1877
      table->field[next_field+1]->store((longlong) mqh.updates, TRUE);
1878
    if (mqh.specified_limits & USER_RESOURCES::CONNECTIONS_PER_HOUR)
1879
      table->field[next_field+2]->store((longlong) mqh.conn_per_hour, TRUE);
1880
    if (table->s->fields >= 36 &&
1881
        (mqh.specified_limits & USER_RESOURCES::USER_CONNECTIONS))
unknown's avatar
unknown committed
1882
      table->field[next_field+3]->store((longlong) mqh.user_conn);
1883
    mqh_used= mqh_used || mqh.questions || mqh.updates || mqh.conn_per_hour;
1884
  }
unknown's avatar
unknown committed
1885
  if (old_row_exists)
unknown's avatar
unknown committed
1886 1887 1888 1889 1890
  {
    /*
      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!
    */
1891
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
unknown's avatar
unknown committed
1892
    if (cmp_record(table,record[1]) &&
unknown's avatar
unknown committed
1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911
	(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

1912
end:
unknown's avatar
unknown committed
1913 1914 1915
  if (!error)
  {
    acl_cache->clear(1);			// Clear privilege cache
unknown's avatar
unknown committed
1916
    if (old_row_exists)
1917 1918
      acl_update_user(combo.user.str, combo.host.str,
                      combo.password.str, password_len,
1919 1920 1921 1922 1923
		      lex->ssl_type,
		      lex->ssl_cipher,
		      lex->x509_issuer,
		      lex->x509_subject,
		      &lex->mqh,
1924
		      rights);
unknown's avatar
unknown committed
1925
    else
1926
      acl_insert_user(combo.user.str, combo.host.str, password, password_len,
1927 1928 1929 1930 1931
		      lex->ssl_type,
		      lex->ssl_cipher,
		      lex->x509_issuer,
		      lex->x509_subject,
		      &lex->mqh,
1932
		      rights);
unknown's avatar
unknown committed
1933 1934 1935 1936 1937 1938
  }
  DBUG_RETURN(error);
}


/*
unknown's avatar
unknown committed
1939
  change grants in the mysql.db table
unknown's avatar
unknown committed
1940 1941 1942 1943
*/

static int replace_db_table(TABLE *table, const char *db,
			    const LEX_USER &combo,
unknown's avatar
unknown committed
1944
			    ulong rights, bool revoke_grant)
unknown's avatar
unknown committed
1945
{
unknown's avatar
unknown committed
1946 1947
  uint i;
  ulong priv,store_rights;
unknown's avatar
unknown committed
1948
  bool old_row_exists=0;
unknown's avatar
unknown committed
1949
  int error;
unknown's avatar
unknown committed
1950
  char what= (revoke_grant) ? 'N' : 'Y';
1951
  byte user_key[MAX_KEY_LENGTH];
unknown's avatar
unknown committed
1952 1953
  DBUG_ENTER("replace_db_table");

1954 1955
  if (!initialized)
  {
unknown's avatar
unknown committed
1956
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
1957 1958 1959
    DBUG_RETURN(-1);
  }

1960
  /* Check if there is such a user in user table in memory? */
1961
  if (!find_acl_user(combo.host.str,combo.user.str, FALSE))
unknown's avatar
unknown committed
1962
  {
unknown's avatar
unknown committed
1963
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH), MYF(0));
unknown's avatar
unknown committed
1964 1965 1966
    DBUG_RETURN(-1);
  }

1967 1968 1969
  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);
1970 1971 1972
  key_copy(user_key, table->record[0], table->key_info,
           table->key_info->key_length);

1973 1974
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
  if (table->file->index_read_idx(table->record[0],0,
1975 1976
                                  user_key, table->key_info->key_length,
                                  HA_READ_KEY_EXACT))
unknown's avatar
unknown committed
1977 1978 1979
  {
    if (what == 'N')
    { // no row, no revoke
unknown's avatar
unknown committed
1980
      my_error(ER_NONEXISTING_GRANT, MYF(0), combo.user.str, combo.host.str);
unknown's avatar
unknown committed
1981 1982
      goto abort;
    }
unknown's avatar
unknown committed
1983
    old_row_exists = 0;
1984
    restore_record(table, s->default_values);
1985 1986 1987
    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
1988 1989 1990
  }
  else
  {
unknown's avatar
unknown committed
1991
    old_row_exists = 1;
unknown's avatar
unknown committed
1992
    store_record(table,record[1]);
unknown's avatar
unknown committed
1993 1994 1995
  }

  store_rights=get_rights_for_db(rights);
1996
  for (i= 3, priv= 1; i < table->s->fields; i++, priv <<= 1)
unknown's avatar
unknown committed
1997
  {
unknown's avatar
unknown committed
1998
    if (priv & store_rights)			// do it if priv is chosen
unknown's avatar
unknown committed
1999
      table->field [i]->store(&what,1, &my_charset_latin1);// set requested privileges
unknown's avatar
unknown committed
2000 2001 2002 2003
  }
  rights=get_access(table,3);
  rights=fix_rights_for_db(rights);

unknown's avatar
unknown committed
2004
  if (old_row_exists)
unknown's avatar
unknown committed
2005
  {
2006
    /* update old existing row */
unknown's avatar
unknown committed
2007 2008
    if (rights)
    {
2009
      table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
unknown's avatar
unknown committed
2010 2011 2012 2013 2014 2015 2016 2017 2018
      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 */
    }
  }
2019
  else if (rights && (error=table->file->write_row(table->record[0])))
unknown's avatar
unknown committed
2020 2021 2022 2023 2024 2025
  {
    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
2026
  if (old_row_exists)
unknown's avatar
unknown committed
2027 2028
    acl_update_db(combo.user.str,combo.host.str,db,rights);
  else
2029
  if (rights)
unknown's avatar
unknown committed
2030 2031 2032 2033
    acl_insert_db(combo.user.str,combo.host.str,db,rights);
  DBUG_RETURN(0);

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

2037
abort:
unknown's avatar
unknown committed
2038 2039 2040 2041 2042 2043 2044 2045
  DBUG_RETURN(-1);
}


class GRANT_COLUMN :public Sql_alloc
{
public:
  char *column;
unknown's avatar
unknown committed
2046 2047 2048
  ulong rights;
  uint key_length;
  GRANT_COLUMN(String &c,  ulong y) :rights (y)
unknown's avatar
unknown committed
2049
  {
unknown's avatar
unknown committed
2050
    column= memdup_root(&memex,c.ptr(), key_length=c.length());
unknown's avatar
unknown committed
2051 2052 2053
  }
};

unknown's avatar
unknown committed
2054

unknown's avatar
unknown committed
2055 2056 2057 2058 2059 2060 2061
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
2062

2063
class GRANT_NAME :public Sql_alloc
unknown's avatar
unknown committed
2064 2065
{
public:
2066 2067
  acl_host_and_ip host;
  char *db, *user, *tname, *hash_key;
2068
  ulong privs;
2069
  ulong sort;
unknown's avatar
unknown committed
2070
  uint key_length;
2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082
  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
2083
  HASH hash_columns;
unknown's avatar
unknown committed
2084 2085 2086 2087

  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);
2088
  ~GRANT_TABLE();
2089 2090
  bool ok() { return privs != 0 || cols != 0; }
};
unknown's avatar
unknown committed
2091

2092

unknown's avatar
unknown committed
2093

2094 2095 2096
GRANT_NAME::GRANT_NAME(const char *h, const char *d,const char *u,
                       const char *t, ulong p)
  :privs(p)
2097 2098
{
  /* Host given by user */
2099
  update_hostname(&host, strdup_root(&memex, h));
2100 2101
  db =   strdup_root(&memex,d);
  user = strdup_root(&memex,u);
2102
  sort=  get_sort(3,host.hostname,db,user);
2103 2104
  tname= strdup_root(&memex,t);
  if (lower_case_table_names)
unknown's avatar
unknown committed
2105
  {
2106 2107
    my_casedn_str(files_charset_info, db);
    my_casedn_str(files_charset_info, tname);
2108 2109 2110 2111
  }
  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);
2112 2113 2114 2115 2116 2117 2118
}


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)
{
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
}
unknown's avatar
unknown committed
2122

2123

2124
GRANT_NAME::GRANT_NAME(TABLE *form)
2125
{
2126
  update_hostname(&host, get_field(&memex, form->field[0]));
unknown's avatar
unknown committed
2127 2128
  db=    get_field(&memex,form->field[1]);
  user=  get_field(&memex,form->field[2]);
2129 2130
  if (!user)
    user= (char*) "";
2131
  sort=  get_sort(3, host.hostname, db, user);
unknown's avatar
unknown committed
2132
  tname= get_field(&memex,form->field[3]);
2133 2134 2135
  if (!db || !tname)
  {
    /* Wrong table row; Ignore it */
2136
    privs= 0;
2137 2138 2139 2140
    return;					/* purecov: inspected */
  }
  if (lower_case_table_names)
  {
2141 2142
    my_casedn_str(files_charset_info, db);
    my_casedn_str(files_charset_info, tname);
2143 2144 2145 2146 2147 2148 2149
  }
  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);
2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165
}


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();
2166 2167
  cols =  fix_rights_for_column(cols);

2168
  (void) hash_init(&hash_columns,system_charset_info,
unknown's avatar
unknown committed
2169
                   0,0,0, (hash_get_key) get_key_column,0,0);
2170 2171
  if (cols)
  {
2172 2173
    uint key_prefix_len;
    KEY_PART_INFO *key_part= col_privs->key_info->key_part;
2174 2175
    col_privs->field[0]->store(host.hostname,
                               host.hostname ? (uint) strlen(host.hostname) : 0,
2176 2177 2178 2179
                               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);
2180 2181 2182 2183 2184 2185

    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
2186
    col_privs->field[4]->store("",0, &my_charset_latin1);
2187

2188 2189
    col_privs->file->ha_index_init(0);
    if (col_privs->file->index_read(col_privs->record[0],
2190 2191
                                    (byte*) key,
                                    key_prefix_len, HA_READ_KEY_EXACT))
unknown's avatar
unknown committed
2192
    {
2193
      cols = 0; /* purecov: deadcode */
2194
      col_privs->file->ha_index_end();
2195
      return;
unknown's avatar
unknown committed
2196
    }
2197
    do
unknown's avatar
unknown committed
2198
    {
2199 2200 2201
      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
2202
      res=col_privs->field[4]->val_str(&column_name);
2203 2204 2205
      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
2206
      {
2207 2208 2209
        /* Don't use this entry */
        privs = cols = 0;			/* purecov: deadcode */
        return;				/* purecov: deadcode */
unknown's avatar
unknown committed
2210
      }
unknown's avatar
unknown committed
2211
      my_hash_insert(&hash_columns, (byte *) mem_check);
2212
    } while (!col_privs->file->index_next(col_privs->record[0]) &&
2213
             !key_cmp_if_same(col_privs,key,0,key_prefix_len));
2214
    col_privs->file->ha_index_end();
unknown's avatar
unknown committed
2215
  }
2216
}
unknown's avatar
unknown committed
2217

unknown's avatar
unknown committed
2218

2219 2220 2221 2222 2223 2224
GRANT_TABLE::~GRANT_TABLE()
{
  hash_free(&hash_columns);
}


2225
static byte* get_grant_table(GRANT_NAME *buff,uint *length,
unknown's avatar
unknown committed
2226 2227 2228 2229 2230 2231
			     my_bool not_used __attribute__((unused)))
{
  *length=buff->key_length;
  return (byte*) buff->hash_key;
}

unknown's avatar
unknown committed
2232

unknown's avatar
unknown committed
2233 2234 2235 2236 2237
void free_grant_table(GRANT_TABLE *grant_table)
{
  hash_free(&grant_table->hash_columns);
}

unknown's avatar
unknown committed
2238

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

2241 2242
static GRANT_NAME *name_hash_search(HASH *name_hash,
				      const char *host,const char* ip,
unknown's avatar
unknown committed
2243 2244 2245 2246 2247 2248
				      const char *db,
				      const char *user, const char *tname,
				      bool exact)
{
  char helping [NAME_LEN*2+USERNAME_LENGTH+3];
  uint len;
2249
  GRANT_NAME *grant_name,*found=0;
2250
  HASH_SEARCH_STATE state;
unknown's avatar
unknown committed
2251 2252

  len  = (uint) (strmov(strmov(strmov(helping,user)+1,db)+1,tname)-helping)+ 1;
2253 2254
  for (grant_name= (GRANT_NAME*) hash_first(name_hash, (byte*) helping,
                                            len, &state);
2255 2256
       grant_name ;
       grant_name= (GRANT_NAME*) hash_next(name_hash,(byte*) helping,
2257
                                           len, &state))
unknown's avatar
unknown committed
2258 2259 2260
  {
    if (exact)
    {
2261 2262
      if ((host &&
	   !my_strcasecmp(system_charset_info, host,
unknown's avatar
unknown committed
2263 2264
                          grant_name->host.hostname)) ||
	  (ip && !strcmp(ip, grant_name->host.hostname)))
2265
	return grant_name;
unknown's avatar
unknown committed
2266 2267 2268
    }
    else
    {
2269
      if (compare_hostname(&grant_name->host, host, ip) &&
2270 2271
          (!found || found->sort < grant_name->sort))
	found=grant_name;					// Host ok
unknown's avatar
unknown committed
2272 2273 2274 2275 2276 2277
    }
  }
  return found;
}


2278
inline GRANT_NAME *
2279 2280
routine_hash_search(const char *host, const char *ip, const char *db,
                 const char *user, const char *tname, bool proc, bool exact)
2281
{
2282 2283 2284
  return (GRANT_TABLE*)
    name_hash_search(proc ? &proc_priv_hash : &func_priv_hash,
		     host, ip, db, user, tname, exact);
2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295
}


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
2296

unknown's avatar
unknown committed
2297
inline GRANT_COLUMN *
unknown's avatar
unknown committed
2298
column_hash_search(GRANT_TABLE *t, const char *cname, uint length)
unknown's avatar
unknown committed
2299 2300 2301 2302 2303 2304 2305 2306 2307
{
  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
2308
				ulong rights, bool revoke_grant)
unknown's avatar
unknown committed
2309 2310 2311
{
  int error=0,result=0;
  byte key[MAX_KEY_LENGTH];
2312 2313
  uint key_prefix_length;
  KEY_PART_INFO *key_part= table->key_info->key_part;
unknown's avatar
unknown committed
2314 2315
  DBUG_ENTER("replace_column_table");

unknown's avatar
unknown committed
2316 2317 2318 2319 2320 2321 2322 2323
  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
2324

2325 2326 2327 2328
  /* 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
2329

2330
  rights&= COL_ACLS;				// Only ACL for columns
unknown's avatar
unknown committed
2331 2332 2333 2334

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

  List_iterator <LEX_COLUMN> iter(columns);
unknown's avatar
unknown committed
2335
  class LEX_COLUMN *column;
unknown's avatar
unknown committed
2336
  table->file->ha_index_init(0);
unknown's avatar
unknown committed
2337
  while ((column= iter++))
unknown's avatar
unknown committed
2338
  {
unknown's avatar
unknown committed
2339
    ulong privileges= column->rights;
unknown's avatar
unknown committed
2340
    bool old_row_exists=0;
2341 2342 2343 2344
    byte user_key[MAX_KEY_LENGTH];

    key_restore(table->record[0],key,table->key_info,
                key_prefix_length);
unknown's avatar
unknown committed
2345
    table->field[4]->store(column->column.ptr(), column->column.length(),
2346
                           system_charset_info);
2347 2348 2349
    /* 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
2350

2351
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
2352 2353 2354
    if (table->file->index_read(table->record[0], user_key,
				table->key_info->key_length,
                                HA_READ_KEY_EXACT))
unknown's avatar
unknown committed
2355 2356 2357
    {
      if (revoke_grant)
      {
unknown's avatar
unknown committed
2358
	my_error(ER_NONEXISTING_TABLE_GRANT, MYF(0),
2359
                 combo.user.str, combo.host.str,
unknown's avatar
unknown committed
2360 2361 2362
                 table_name);                   /* purecov: inspected */
	result= -1;                             /* purecov: inspected */
	continue;                               /* purecov: inspected */
unknown's avatar
unknown committed
2363
      }
unknown's avatar
unknown committed
2364
      old_row_exists = 0;
2365
      restore_record(table, s->default_values);		// Get empty record
2366 2367
      key_restore(table->record[0],key,table->key_info,
                  key_prefix_length);
unknown's avatar
unknown committed
2368
      table->field[4]->store(column->column.ptr(),column->column.length(),
2369
                             system_charset_info);
unknown's avatar
unknown committed
2370 2371 2372
    }
    else
    {
unknown's avatar
unknown committed
2373
      ulong tmp= (ulong) table->field[6]->val_int();
unknown's avatar
unknown committed
2374 2375 2376 2377 2378 2379
      tmp=fix_rights_for_column(tmp);

      if (revoke_grant)
	privileges = tmp & ~(privileges | rights);
      else
	privileges |= tmp;
unknown's avatar
unknown committed
2380
      old_row_exists = 1;
unknown's avatar
unknown committed
2381
      store_record(table,record[1]);			// copy original row
unknown's avatar
unknown committed
2382 2383
    }

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

unknown's avatar
unknown committed
2386
    if (old_row_exists)
unknown's avatar
unknown committed
2387
    {
unknown's avatar
unknown committed
2388
      GRANT_COLUMN *grant_column;
unknown's avatar
unknown committed
2389 2390 2391 2392 2393 2394 2395 2396 2397 2398
      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
2399 2400
      grant_column= column_hash_search(g_t, column->column.ptr(),
                                       column->column.length());
unknown's avatar
unknown committed
2401
      if (grant_column)				// Should always be true
unknown's avatar
unknown committed
2402
	grant_column->rights= privileges;	// Update hash
unknown's avatar
unknown committed
2403 2404 2405
    }
    else					// new grant
    {
unknown's avatar
unknown committed
2406
      GRANT_COLUMN *grant_column;
unknown's avatar
unknown committed
2407 2408 2409 2410 2411 2412
      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
2413
      grant_column= new GRANT_COLUMN(column->column,privileges);
unknown's avatar
SCRUM  
unknown committed
2414
      my_hash_insert(&g_t->hash_columns,(byte*) grant_column);
unknown's avatar
unknown committed
2415 2416 2417 2418 2419 2420 2421 2422 2423 2424
    }
  }

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

  if (revoke_grant)
  {
2425 2426
    byte user_key[MAX_KEY_LENGTH];
    key_copy(user_key, table->record[0], table->key_info,
unknown's avatar
unknown committed
2427 2428
             key_prefix_length);

2429
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
2430
    if (table->file->index_read(table->record[0], user_key,
unknown's avatar
unknown committed
2431
				key_prefix_length,
2432
                                HA_READ_KEY_EXACT))
unknown's avatar
unknown committed
2433 2434
      goto end;

2435
    /* Scan through all rows with the same host,db,user and table */
unknown's avatar
unknown committed
2436 2437
    do
    {
unknown's avatar
unknown committed
2438
      ulong privileges = (ulong) table->field[6]->val_int();
unknown's avatar
unknown committed
2439
      privileges=fix_rights_for_column(privileges);
unknown's avatar
unknown committed
2440
      store_record(table,record[1]);
unknown's avatar
unknown committed
2441 2442 2443 2444 2445

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

	privileges&= ~rights;
	table->field[6]->store((longlong)
2451
			       get_rights_for_column(privileges), TRUE);
2452
	table->field[4]->val_str(&column_name);
unknown's avatar
unknown committed
2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482
	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]) &&
2483
	     !key_cmp_if_same(table, key, 0, key_prefix_length));
unknown's avatar
unknown committed
2484 2485
  }

2486
end:
unknown's avatar
unknown committed
2487
  table->file->ha_index_end();
unknown's avatar
unknown committed
2488 2489 2490 2491 2492 2493 2494
  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
2495 2496
			       ulong rights, ulong col_rights,
			       bool revoke_grant)
unknown's avatar
unknown committed
2497
{
2498
  char grantor[USER_HOST_BUFF_SIZE];
unknown's avatar
unknown committed
2499
  int old_row_exists = 1;
unknown's avatar
unknown committed
2500
  int error=0;
unknown's avatar
unknown committed
2501
  ulong store_table_rights, store_col_rights;
2502
  byte user_key[MAX_KEY_LENGTH];
unknown's avatar
unknown committed
2503 2504
  DBUG_ENTER("replace_table_table");

2505 2506
  strxmov(grantor, thd->security_ctx->user, "@",
          thd->security_ctx->host_or_ip, NullS);
unknown's avatar
unknown committed
2507

unknown's avatar
unknown committed
2508 2509 2510 2511
  /*
    The following should always succeed as new users are created before
    this function is called!
  */
2512
  if (!find_acl_user(combo.host.str,combo.user.str, FALSE))
unknown's avatar
unknown committed
2513
  {
unknown's avatar
unknown committed
2514 2515
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH),
               MYF(0));	/* purecov: deadcode */
unknown's avatar
unknown committed
2516 2517 2518
    DBUG_RETURN(-1);				/* purecov: deadcode */
  }

2519
  restore_record(table, s->default_values);     // Get empty record
2520 2521 2522 2523
  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
2524
  store_record(table,record[1]);			// store at pos 1
2525 2526
  key_copy(user_key, table->record[0], table->key_info,
           table->key_info->key_length);
unknown's avatar
unknown committed
2527

2528
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
2529 2530
  if (table->file->index_read_idx(table->record[0], 0,
                                  user_key, table->key_info->key_length,
unknown's avatar
unknown committed
2531 2532 2533 2534 2535 2536 2537 2538 2539
				  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
2540 2541
      my_error(ER_NONEXISTING_TABLE_GRANT, MYF(0),
               combo.user.str, combo.host.str,
2542
               table_name);		        /* purecov: deadcode */
unknown's avatar
unknown committed
2543 2544
      DBUG_RETURN(-1);				/* purecov: deadcode */
    }
unknown's avatar
unknown committed
2545
    old_row_exists = 0;
unknown's avatar
unknown committed
2546
    restore_record(table,record[1]);			// Get saved record
unknown's avatar
unknown committed
2547 2548
  }

unknown's avatar
unknown committed
2549 2550
  store_table_rights= get_rights_for_table(rights);
  store_col_rights=   get_rights_for_column(col_rights);
unknown's avatar
unknown committed
2551
  if (old_row_exists)
unknown's avatar
unknown committed
2552
  {
unknown's avatar
unknown committed
2553
    ulong j,k;
unknown's avatar
unknown committed
2554
    store_record(table,record[1]);
unknown's avatar
unknown committed
2555 2556
    j = (ulong) table->field[6]->val_int();
    k = (ulong) table->field[7]->val_int();
unknown's avatar
unknown committed
2557 2558 2559

    if (revoke_grant)
    {
2560
      /* column rights are already fixed in mysql_table_grant */
unknown's avatar
unknown committed
2561 2562 2563 2564
      store_table_rights=j & ~store_table_rights;
    }
    else
    {
unknown's avatar
unknown committed
2565 2566
      store_table_rights|= j;
      store_col_rights|=   k;
unknown's avatar
unknown committed
2567 2568 2569
    }
  }

2570
  table->field[4]->store(grantor,(uint) strlen(grantor), system_charset_info);
2571 2572
  table->field[6]->store((longlong) store_table_rights, TRUE);
  table->field[7]->store((longlong) store_col_rights, TRUE);
unknown's avatar
unknown committed
2573
  rights=fix_rights_for_table(store_table_rights);
unknown's avatar
unknown committed
2574
  col_rights=fix_rights_for_column(store_col_rights);
unknown's avatar
unknown committed
2575

unknown's avatar
unknown committed
2576
  if (old_row_exists)
unknown's avatar
unknown committed
2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592
  {
    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
2593
  if (rights | col_rights)
unknown's avatar
unknown committed
2594
  {
unknown's avatar
unknown committed
2595
    grant_table->privs= rights;
2596
    grant_table->cols=	col_rights;
unknown's avatar
unknown committed
2597 2598 2599
  }
  else
  {
2600
    hash_delete(&column_priv_hash,(byte*) grant_table);
unknown's avatar
unknown committed
2601 2602 2603
  }
  DBUG_RETURN(0);

2604 2605
  /* This should never happen */
table_error:
unknown's avatar
unknown committed
2606 2607 2608 2609 2610
  table->file->print_error(error,MYF(0)); /* purecov: deadcode */
  DBUG_RETURN(-1); /* purecov: deadcode */
}


2611
static int replace_routine_table(THD *thd, GRANT_NAME *grant_name,
2612
			      TABLE *table, const LEX_USER &combo,
2613 2614
			      const char *db, const char *routine_name,
			      bool is_proc, ulong rights, bool revoke_grant)
2615
{
2616
  char grantor[USER_HOST_BUFF_SIZE];
2617 2618 2619
  int old_row_exists= 1;
  int error=0;
  ulong store_proc_rights;
2620
  DBUG_ENTER("replace_routine_table");
2621 2622 2623 2624 2625 2626 2627

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

2628 2629
  strxmov(grantor, thd->security_ctx->user, "@",
          thd->security_ctx->host_or_ip, NullS);
2630 2631 2632 2633 2634

  /*
    The following should always succeed as new users are created before
    this function is called!
  */
unknown's avatar
unknown committed
2635
  if (!find_acl_user(combo.host.str, combo.user.str, FALSE))
2636 2637 2638 2639 2640
  {
    my_error(ER_PASSWORD_NO_MATCH,MYF(0));
    DBUG_RETURN(-1);
  }

2641
  restore_record(table, s->default_values);		// Get empty record
2642 2643 2644
  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);
2645 2646 2647
  table->field[3]->store(routine_name,(uint) strlen(routine_name),
                         &my_charset_latin1);
  table->field[4]->store((longlong)(is_proc ? 
2648 2649
                                    TYPE_ENUM_PROCEDURE : TYPE_ENUM_FUNCTION),
                         TRUE);
2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663
  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),
2664
               combo.user.str, combo.host.str, routine_name);
2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688
      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;
    }
  }

2689
  table->field[5]->store(grantor,(uint) strlen(grantor), &my_charset_latin1);
2690
  table->field[6]->store((longlong) store_proc_rights, TRUE);
2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715
  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
  {
2716
    hash_delete(is_proc ? &proc_priv_hash : &func_priv_hash,(byte*) grant_name);
2717 2718 2719 2720 2721 2722 2723 2724 2725 2726
  }
  DBUG_RETURN(0);

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


2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739
/*
  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
2740 2741
    FALSE ok
    TRUE  error
2742 2743
*/

unknown's avatar
unknown committed
2744
bool mysql_table_grant(THD *thd, TABLE_LIST *table_list,
unknown's avatar
unknown committed
2745 2746 2747
		      List <LEX_USER> &user_list,
		      List <LEX_COLUMN> &columns, ulong rights,
		      bool revoke_grant)
unknown's avatar
unknown committed
2748
{
2749
  ulong column_priv= 0;
unknown's avatar
unknown committed
2750 2751 2752
  List_iterator <LEX_USER> str_list (user_list);
  LEX_USER *Str;
  TABLE_LIST tables[3];
unknown's avatar
unknown committed
2753
  bool create_new_users=0;
2754
  char *db_name, *table_name;
unknown's avatar
unknown committed
2755 2756 2757 2758
  DBUG_ENTER("mysql_table_grant");

  if (!initialized)
  {
unknown's avatar
unknown committed
2759 2760
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0),
             "--skip-grant-tables");	/* purecov: inspected */
unknown's avatar
unknown committed
2761
    DBUG_RETURN(TRUE);				/* purecov: inspected */
unknown's avatar
unknown committed
2762 2763 2764
  }
  if (rights & ~TABLE_ACLS)
  {
unknown's avatar
unknown committed
2765 2766
    my_message(ER_ILLEGAL_GRANT_FOR_TABLE, ER(ER_ILLEGAL_GRANT_FOR_TABLE),
               MYF(0));
unknown's avatar
unknown committed
2767
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
2768 2769
  }

2770
  if (!revoke_grant)
unknown's avatar
unknown committed
2771
  {
unknown's avatar
unknown committed
2772
    if (columns.elements)
unknown's avatar
unknown committed
2773
    {
2774 2775
      class LEX_COLUMN *column;
      List_iterator <LEX_COLUMN> column_iter(columns);
unknown's avatar
unknown committed
2776 2777 2778

      if (open_and_lock_tables(thd, table_list))
        DBUG_RETURN(TRUE);
2779 2780

      while ((column = column_iter++))
unknown's avatar
unknown committed
2781
      {
unknown's avatar
unknown committed
2782
        uint unused_field_idx= NO_CACHED_FIELD_INDEX;
unknown's avatar
unknown committed
2783 2784
        TABLE_LIST *dummy;
        Field *f=find_field_in_table_ref(thd, table_list, column->column.ptr(),
2785
                                         column->column.length(),
unknown's avatar
unknown committed
2786
                                         column->column.ptr(), NULL, NULL,
2787
                                         NULL, TRUE, FALSE,
unknown's avatar
unknown committed
2788
                                         &unused_field_idx, FALSE, &dummy);
unknown's avatar
unknown committed
2789
        if (f == (Field*)0)
2790
        {
unknown's avatar
unknown committed
2791 2792
          my_error(ER_BAD_FIELD_ERROR, MYF(0),
                   column->column.c_ptr(), table_list->alias);
unknown's avatar
unknown committed
2793
          DBUG_RETURN(TRUE);
2794
        }
unknown's avatar
unknown committed
2795 2796
        if (f == (Field *)-1)
          DBUG_RETURN(TRUE);
2797
        column_priv|= column->rights;
unknown's avatar
unknown committed
2798
      }
2799
      close_thread_tables(thd);
unknown's avatar
unknown committed
2800
    }
2801
    else
unknown's avatar
unknown committed
2802
    {
2803 2804 2805 2806
      if (!(rights & CREATE_ACL))
      {
        char buf[FN_REFLEN];
        sprintf(buf,"%s/%s/%s.frm",mysql_data_home, table_list->db,
2807
                table_list->table_name);
2808 2809 2810
        fn_format(buf,buf,"","",4+16+32);
        if (access(buf,F_OK))
        {
unknown's avatar
unknown committed
2811
          my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->alias);
unknown's avatar
unknown committed
2812
          DBUG_RETURN(TRUE);
2813 2814 2815 2816 2817 2818 2819 2820
        }
      }
      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),
2821 2822
                 command, thd->security_ctx->priv_user,
                 thd->security_ctx->host_or_ip, table_list->alias);
2823 2824
        DBUG_RETURN(-1);
      }
unknown's avatar
unknown committed
2825 2826 2827 2828 2829 2830
    }
  }

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

  bzero((char*) &tables,sizeof(tables));
2831 2832 2833
  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
2834
  tables[0].next_local= tables[0].next_global= tables+1;
unknown's avatar
unknown committed
2835
  /* Don't open column table if we don't need it ! */
unknown's avatar
VIEW  
unknown committed
2836 2837 2838 2839 2840
  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
2841 2842 2843
  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";

2844 2845 2846 2847 2848
#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
2849 2850
  if (thd->slave_thread && table_rules_on)
  {
unknown's avatar
unknown committed
2851 2852 2853
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
2854
    */
2855
    tables[0].updating= tables[1].updating= tables[2].updating= 1;
2856
    if (!tables_ok(thd, tables))
unknown's avatar
unknown committed
2857
      DBUG_RETURN(FALSE);
2858
  }
2859 2860
#endif

2861
  if (simple_open_n_lock_tables(thd,tables))
unknown's avatar
unknown committed
2862 2863
  {						// Should never happen
    close_thread_tables(thd);			/* purecov: deadcode */
unknown's avatar
unknown committed
2864
    DBUG_RETURN(TRUE);				/* purecov: deadcode */
unknown's avatar
unknown committed
2865 2866
  }

unknown's avatar
unknown committed
2867 2868
  if (!revoke_grant)
    create_new_users= test_if_create_new_users(thd);
unknown's avatar
unknown committed
2869
  bool result= FALSE;
2870
  rw_wrlock(&LOCK_grant);
unknown's avatar
unknown committed
2871 2872
  MEM_ROOT *old_root= thd->mem_root;
  thd->mem_root= &memex;
2873
  grant_version++;
unknown's avatar
unknown committed
2874 2875 2876

  while ((Str = str_list++))
  {
2877
    int error;
unknown's avatar
unknown committed
2878 2879 2880 2881
    GRANT_TABLE *grant_table;
    if (Str->host.length > HOSTNAME_LENGTH ||
	Str->user.length > USERNAME_LENGTH)
    {
unknown's avatar
unknown committed
2882 2883
      my_message(ER_GRANT_WRONG_HOST_OR_USER, ER(ER_GRANT_WRONG_HOST_OR_USER),
                 MYF(0));
unknown's avatar
unknown committed
2884
      result= TRUE;
unknown's avatar
unknown committed
2885 2886 2887
      continue;
    }
    /* Create user if needed */
2888
    pthread_mutex_lock(&acl_cache->lock);
unknown's avatar
unknown committed
2889
    error=replace_user_table(thd, tables[0].table, *Str,
unknown's avatar
unknown committed
2890
			     0, revoke_grant, create_new_users,
unknown's avatar
unknown committed
2891 2892
                             test(thd->variables.sql_mode &
                                  MODE_NO_AUTO_CREATE_USER));
2893 2894
    pthread_mutex_unlock(&acl_cache->lock);
    if (error)
unknown's avatar
unknown committed
2895
    {
unknown's avatar
unknown committed
2896
      result= TRUE;				// Remember error
unknown's avatar
unknown committed
2897 2898 2899
      continue;					// Add next user
    }

unknown's avatar
VIEW  
unknown committed
2900 2901 2902
    db_name= (table_list->view_db.length ?
	      table_list->view_db.str :
	      table_list->db);
2903
    table_name= (table_list->view_name.length ?
unknown's avatar
VIEW  
unknown committed
2904
		table_list->view_name.str :
2905
		table_list->table_name);
unknown's avatar
VIEW  
unknown committed
2906

unknown's avatar
unknown committed
2907
    /* Find/create cached table grant */
unknown's avatar
VIEW  
unknown committed
2908
    grant_table= table_hash_search(Str->host.str, NullS, db_name,
2909
				   Str->user.str, table_name, 1);
unknown's avatar
unknown committed
2910 2911 2912 2913
    if (!grant_table)
    {
      if (revoke_grant)
      {
unknown's avatar
unknown committed
2914
	my_error(ER_NONEXISTING_TABLE_GRANT, MYF(0),
2915
                 Str->user.str, Str->host.str, table_list->table_name);
unknown's avatar
unknown committed
2916
	result= TRUE;
unknown's avatar
unknown committed
2917 2918
	continue;
      }
unknown's avatar
VIEW  
unknown committed
2919
      grant_table = new GRANT_TABLE (Str->host.str, db_name,
2920
				     Str->user.str, table_name,
unknown's avatar
unknown committed
2921 2922 2923 2924
				     rights,
				     column_priv);
      if (!grant_table)				// end of memory
      {
unknown's avatar
unknown committed
2925
	result= TRUE;				/* purecov: deadcode */
unknown's avatar
unknown committed
2926 2927
	continue;				/* purecov: deadcode */
      }
unknown's avatar
SCRUM  
unknown committed
2928
      my_hash_insert(&column_priv_hash,(byte*) grant_table);
unknown's avatar
unknown committed
2929 2930 2931 2932 2933
    }

    /* If revoke_grant, calculate the new column privilege for tables_priv */
    if (revoke_grant)
    {
2934 2935
      class LEX_COLUMN *column;
      List_iterator <LEX_COLUMN> column_iter(columns);
unknown's avatar
unknown committed
2936 2937 2938
      GRANT_COLUMN *grant_column;

      /* Fix old grants */
2939
      while ((column = column_iter++))
unknown's avatar
unknown committed
2940 2941
      {
	grant_column = column_hash_search(grant_table,
2942 2943
					  column->column.ptr(),
					  column->column.length());
unknown's avatar
unknown committed
2944
	if (grant_column)
2945
	  grant_column->rights&= ~(column->rights | rights);
unknown's avatar
unknown committed
2946 2947
      }
      /* scan trough all columns to get new column grant */
2948
      column_priv= 0;
unknown's avatar
unknown committed
2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964
      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
2965
    if (replace_table_table(thd, grant_table, tables[1].table, *Str,
2966
			    db_name, table_name,
unknown's avatar
unknown committed
2967
			    rights, column_priv, revoke_grant))
2968 2969
    {
      /* Should only happen if table is crashed */
unknown's avatar
unknown committed
2970
      result= TRUE;			       /* purecov: deadcode */
unknown's avatar
unknown committed
2971 2972 2973
    }
    else if (tables[2].table)
    {
unknown's avatar
VIEW  
unknown committed
2974
      if ((replace_column_table(grant_table, tables[2].table, *Str,
unknown's avatar
unknown committed
2975
				columns,
2976
				db_name, table_name,
unknown's avatar
unknown committed
2977 2978
				rights, revoke_grant)))
      {
unknown's avatar
unknown committed
2979
	result= TRUE;
unknown's avatar
unknown committed
2980 2981 2982 2983
      }
    }
  }
  grant_option=TRUE;
unknown's avatar
unknown committed
2984
  thd->mem_root= old_root;
2985
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
2986
  if (!result)
2987
    send_ok(thd);
2988
  /* Tables are automatically closed */
unknown's avatar
unknown committed
2989 2990 2991 2992
  DBUG_RETURN(result);
}


2993
/*
2994
  Store routine level grants in the privilege tables
2995 2996

  SYNOPSIS
2997
    mysql_routine_grant()
2998
    thd			Thread handle
2999 3000
    table_list		List of routines to give grant
    is_proc             true indicates routine list are procedures
3001 3002 3003 3004 3005 3006 3007 3008 3009
    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
*/

3010 3011 3012
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)
3013 3014 3015 3016 3017
{
  List_iterator <LEX_USER> str_list (user_list);
  LEX_USER *Str;
  TABLE_LIST tables[2];
  bool create_new_users=0, result=0;
3018
  char *db_name, *table_name;
3019
  DBUG_ENTER("mysql_routine_grant");
3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037

  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)
  {
3038
    if (sp_exist_routines(thd, table_list, is_proc, no_error)<0)
3039 3040 3041 3042 3043 3044
      DBUG_RETURN(TRUE);
  }

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

  bzero((char*) &tables,sizeof(tables));
3045 3046
  tables[0].alias=tables[0].table_name= (char*) "user";
  tables[1].alias=tables[1].table_name= (char*) "procs_priv";
3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062
  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;
3063
    if (!tables_ok(thd, tables))
3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097
      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
3098
			     0, revoke_grant, create_new_users,
unknown's avatar
unknown committed
3099 3100
                             test(thd->variables.sql_mode &
                                  MODE_NO_AUTO_CREATE_USER));
3101 3102 3103 3104 3105 3106 3107 3108
    pthread_mutex_unlock(&acl_cache->lock);
    if (error)
    {
      result= TRUE;				// Remember error
      continue;					// Add next user
    }

    db_name= table_list->db;
3109
    table_name= table_list->table_name;
3110

3111 3112
    grant_name= routine_hash_search(Str->host.str, NullS, db_name,
                                    Str->user.str, table_name, is_proc, 1);
3113 3114 3115 3116 3117 3118
    if (!grant_name)
    {
      if (revoke_grant)
      {
        if (!no_error)
          my_error(ER_NONEXISTING_PROC_GRANT, MYF(0),
3119
		   Str->user.str, Str->host.str, table_name);
3120 3121 3122 3123
	result= TRUE;
	continue;
      }
      grant_name= new GRANT_NAME(Str->host.str, db_name,
3124
				 Str->user.str, table_name,
3125 3126 3127 3128 3129 3130
				 rights);
      if (!grant_name)
      {
        result= TRUE;
	continue;
      }
3131
      my_hash_insert(is_proc ? &proc_priv_hash : &func_priv_hash,(byte*) grant_name);
3132
    }
3133

3134 3135
    if (replace_routine_table(thd, grant_name, tables[1].table, *Str,
			   db_name, table_name, is_proc, rights, revoke_grant))
3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150
    {
      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
3151 3152
bool mysql_grant(THD *thd, const char *db, List <LEX_USER> &list,
                 ulong rights, bool revoke_grant)
unknown's avatar
unknown committed
3153 3154 3155
{
  List_iterator <LEX_USER> str_list (list);
  LEX_USER *Str;
unknown's avatar
unknown committed
3156
  char tmp_db[NAME_LEN+1];
unknown's avatar
unknown committed
3157
  bool create_new_users=0;
unknown's avatar
unknown committed
3158 3159 3160 3161
  TABLE_LIST tables[2];
  DBUG_ENTER("mysql_grant");
  if (!initialized)
  {
unknown's avatar
unknown committed
3162 3163
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0),
             "--skip-grant-tables");	/* purecov: tested */
unknown's avatar
unknown committed
3164
    DBUG_RETURN(TRUE);				/* purecov: tested */
unknown's avatar
unknown committed
3165 3166
  }

unknown's avatar
unknown committed
3167 3168 3169
  if (lower_case_table_names && db)
  {
    strmov(tmp_db,db);
3170
    my_casedn_str(files_charset_info, tmp_db);
unknown's avatar
unknown committed
3171 3172
    db=tmp_db;
  }
unknown's avatar
unknown committed
3173 3174

  /* open the mysql.user and mysql.db tables */
3175
  bzero((char*) &tables,sizeof(tables));
3176 3177
  tables[0].alias=tables[0].table_name=(char*) "user";
  tables[1].alias=tables[1].table_name=(char*) "db";
unknown's avatar
VIEW  
unknown committed
3178
  tables[0].next_local= tables[0].next_global= tables+1;
unknown's avatar
unknown committed
3179 3180
  tables[0].lock_type=tables[1].lock_type=TL_WRITE;
  tables[0].db=tables[1].db=(char*) "mysql";
3181 3182 3183 3184 3185 3186

#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
3187 3188
  if (thd->slave_thread && table_rules_on)
  {
unknown's avatar
unknown committed
3189 3190 3191
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
3192
    */
3193
    tables[0].updating= tables[1].updating= 1;
3194
    if (!tables_ok(thd, tables))
unknown's avatar
unknown committed
3195
      DBUG_RETURN(FALSE);
3196
  }
3197 3198
#endif

3199
  if (simple_open_n_lock_tables(thd,tables))
unknown's avatar
unknown committed
3200 3201
  {						// This should never happen
    close_thread_tables(thd);			/* purecov: deadcode */
unknown's avatar
unknown committed
3202
    DBUG_RETURN(TRUE);				/* purecov: deadcode */
unknown's avatar
unknown committed
3203 3204
  }

unknown's avatar
unknown committed
3205 3206
  if (!revoke_grant)
    create_new_users= test_if_create_new_users(thd);
unknown's avatar
unknown committed
3207

3208
  /* go through users in user_list */
3209
  rw_wrlock(&LOCK_grant);
unknown's avatar
unknown committed
3210 3211 3212 3213 3214 3215 3216 3217 3218
  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
3219 3220
      my_message(ER_GRANT_WRONG_HOST_OR_USER, ER(ER_GRANT_WRONG_HOST_OR_USER),
                 MYF(0));
unknown's avatar
unknown committed
3221 3222 3223
      result= -1;
      continue;
    }
unknown's avatar
unknown committed
3224 3225
    if (replace_user_table(thd, tables[0].table, *Str,
                           (!db ? rights : 0), revoke_grant, create_new_users,
unknown's avatar
unknown committed
3226 3227
                           test(thd->variables.sql_mode &
                                MODE_NO_AUTO_CREATE_USER)))
3228
      result= -1;
unknown's avatar
unknown committed
3229
    else if (db)
unknown's avatar
unknown committed
3230
    {
unknown's avatar
unknown committed
3231 3232 3233 3234 3235 3236 3237 3238 3239
      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
3240
	my_error(ER_WRONG_USAGE, MYF(0), "DB GRANT", "GLOBAL PRIVILEGES");
unknown's avatar
unknown committed
3241
	result= -1;
unknown's avatar
unknown committed
3242
      }
unknown's avatar
unknown committed
3243
    }
unknown's avatar
unknown committed
3244 3245
  }
  VOID(pthread_mutex_unlock(&acl_cache->lock));
3246
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
3247 3248 3249
  close_thread_tables(thd);

  if (!result)
3250
    send_ok(thd);
unknown's avatar
unknown committed
3251 3252 3253
  DBUG_RETURN(result);
}

unknown's avatar
unknown committed
3254 3255

/* Free grant array if possible */
unknown's avatar
unknown committed
3256 3257 3258 3259 3260

void  grant_free(void)
{
  DBUG_ENTER("grant_free");
  grant_option = FALSE;
3261
  hash_free(&column_priv_hash);
3262
  hash_free(&proc_priv_hash);
unknown's avatar
unknown committed
3263
  hash_free(&func_priv_hash);
3264
  free_root(&memex,MYF(0));
unknown's avatar
unknown committed
3265 3266 3267 3268
  DBUG_VOID_RETURN;
}


3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279
/*
  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
3280

3281
my_bool grant_init()
unknown's avatar
unknown committed
3282
{
unknown's avatar
unknown committed
3283
  THD  *thd;
3284 3285 3286 3287 3288
  my_bool return_val;
  DBUG_ENTER("grant_init");

  if (!(thd= new THD))
    DBUG_RETURN(1);				/* purecov: deadcode */
3289
  thd->thread_stack= (char*) &thd;
3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315
  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
3316
  MEM_ROOT *memex_ptr;
3317
  my_bool return_val= 1;
3318
  TABLE *t_table, *c_table, *p_table;
unknown's avatar
SCRUM  
unknown committed
3319
  bool check_no_resolve= specialflag & SPECIAL_NO_RESOLVE;
3320 3321 3322
  MEM_ROOT **save_mem_root_ptr= my_pthread_getspecific_ptr(MEM_ROOT**,
                                                           THR_MALLOC);
  DBUG_ENTER("grant_load");
unknown's avatar
unknown committed
3323 3324

  grant_option = FALSE;
3325
  (void) hash_init(&column_priv_hash,system_charset_info,
unknown's avatar
unknown committed
3326
		   0,0,0, (hash_get_key) get_grant_table,
unknown's avatar
unknown committed
3327
		   (hash_free_key) free_grant_table,0);
3328 3329 3330
  (void) hash_init(&proc_priv_hash,system_charset_info,
		   0,0,0, (hash_get_key) get_grant_table,
		   0,0);
3331 3332 3333
  (void) hash_init(&func_priv_hash,system_charset_info,
		   0,0,0, (hash_get_key) get_grant_table,
		   0,0);
3334
  init_sql_alloc(&memex, ACL_ALLOC_BLOCK_SIZE, 0);
unknown's avatar
unknown committed
3335 3336

  t_table = tables[0].table; c_table = tables[1].table;
3337
  p_table= tables[2].table;
unknown's avatar
unknown committed
3338
  t_table->file->ha_index_init(0);
3339 3340
  p_table->file->ha_index_init(0);
  if (!t_table->file->index_first(t_table->record[0]))
unknown's avatar
unknown committed
3341
  {
3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352
    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
3353

3354 3355
      if (check_no_resolve)
      {
3356
	if (hostname_requires_resolving(mem_check->host.hostname))
3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377
	{
          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
3378
  {
3379 3380 3381
    memex_ptr= &memex;
    my_pthread_setspecific_ptr(THR_MALLOC, &memex_ptr);
    do
unknown's avatar
unknown committed
3382
    {
3383
      GRANT_NAME *mem_check;
3384
      HASH *hash;
3385 3386 3387 3388 3389 3390
      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
3391

3392
      if (check_no_resolve)
unknown's avatar
SCRUM  
unknown committed
3393
      {
unknown's avatar
unknown committed
3394
	if (hostname_requires_resolving(mem_check->host.hostname))
3395 3396 3397 3398
	{
          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
3399
                            mem_check->host);
3400 3401
	  continue;
	}
unknown's avatar
SCRUM  
unknown committed
3402
      }
3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418
      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
3419

3420 3421 3422
      mem_check->privs= fix_rights_for_procedure(mem_check->privs);
      if (! mem_check->ok())
	delete mem_check;
3423
      else if (my_hash_insert(hash, (byte*) mem_check))
3424 3425 3426 3427 3428
      {
	delete mem_check;
	grant_option= FALSE;
	goto end_unlock;
      }
unknown's avatar
SCRUM  
unknown committed
3429
    }
3430
    while (!p_table->file->index_next(p_table->record[0]));
unknown's avatar
unknown committed
3431
  }
3432
  grant_option= TRUE;
3433 3434 3435
  return_val=0;					// Return ok

end_unlock:
unknown's avatar
unknown committed
3436
  t_table->file->ha_index_end();
3437
  p_table->file->ha_index_end();
3438
  my_pthread_setspecific_ptr(THR_MALLOC, save_mem_root_ptr);
3439
  DBUG_RETURN(return_val);
unknown's avatar
unknown committed
3440 3441 3442
}


3443
/*
3444
  Reload information about table and column level privileges if possible.
3445 3446 3447

  SYNOPSIS
    grant_reload()
3448
      thd  Current thread
3449 3450

  NOTES
3451 3452 3453 3454 3455 3456 3457 3458
    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
3459
*/
unknown's avatar
unknown committed
3460

3461
my_bool grant_reload(THD *thd)
unknown's avatar
unknown committed
3462
{
3463
  TABLE_LIST tables[3];
3464
  HASH old_column_priv_hash, old_proc_priv_hash, old_func_priv_hash;
3465
  bool old_grant_option;
unknown's avatar
unknown committed
3466
  MEM_ROOT old_mem;
3467
  my_bool return_val= 1;
unknown's avatar
unknown committed
3468 3469
  DBUG_ENTER("grant_reload");

3470 3471 3472 3473 3474
  /* Don't do anything if running with --skip-grant-tables */
  if (!initialized)
    DBUG_RETURN(0);

  bzero((char*) tables, sizeof(tables));
3475 3476 3477 3478 3479 3480 3481
  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;
3482 3483 3484 3485 3486 3487 3488 3489

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

3490
  rw_wrlock(&LOCK_grant);
unknown's avatar
unknown committed
3491
  grant_version++;
3492
  old_column_priv_hash= column_priv_hash;
3493
  old_proc_priv_hash= proc_priv_hash;
3494
  old_func_priv_hash= func_priv_hash;
unknown's avatar
unknown committed
3495
  old_grant_option= grant_option;
unknown's avatar
unknown committed
3496
  old_mem= memex;
unknown's avatar
unknown committed
3497

3498
  if ((return_val= grant_load(tables)))
unknown's avatar
unknown committed
3499
  {						// Error. Revert to old hash
3500
    DBUG_PRINT("error",("Reverting to old privileges"));
unknown's avatar
unknown committed
3501
    grant_free();				/* purecov: deadcode */
3502
    column_priv_hash= old_column_priv_hash;	/* purecov: deadcode */
3503
    proc_priv_hash= old_proc_priv_hash;
3504
    func_priv_hash= old_func_priv_hash;
unknown's avatar
unknown committed
3505
    grant_option= old_grant_option;		/* purecov: deadcode */
unknown's avatar
unknown committed
3506
    memex= old_mem;				/* purecov: deadcode */
unknown's avatar
unknown committed
3507 3508 3509
  }
  else
  {
3510
    hash_free(&old_column_priv_hash);
3511
    hash_free(&old_proc_priv_hash);
3512
    hash_free(&old_func_priv_hash);
3513
    free_root(&old_mem,MYF(0));
unknown's avatar
unknown committed
3514
  }
3515
  rw_unlock(&LOCK_grant);
3516 3517 3518
end:
  close_thread_tables(thd);
  DBUG_RETURN(return_val);
unknown's avatar
unknown committed
3519 3520 3521 3522
}


/****************************************************************************
3523
  Check table level grants
3524

3525
  SYNOPSIS
3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538
   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
3539
     1  Error: User did not have the requested privileges
unknown's avatar
unknown committed
3540 3541
****************************************************************************/

unknown's avatar
unknown committed
3542
bool check_grant(THD *thd, ulong want_access, TABLE_LIST *tables,
unknown's avatar
unknown committed
3543
		 uint show_table, uint number, bool no_errors)
unknown's avatar
unknown committed
3544
{
3545
  TABLE_LIST *table, *first_not_own_table= thd->lex->first_not_own_table();
3546
  Security_context *sctx= thd->security_ctx;
3547
  uint i;
3548 3549
  DBUG_ENTER("check_grant");
  DBUG_ASSERT(number > 0);
unknown's avatar
unknown committed
3550

3551
  /*
unknown's avatar
unknown committed
3552 3553 3554 3555 3556 3557 3558 3559
    Walk through the list of tables that belong to the query and save the
    requested access (orig_want_privilege) to be able to use it when
    checking access rights to the underlying tables of a view. Our grant
    system gradually eliminates checked bits from want_privilege and thus
    after all checks are done we can no longer use it.
    The check that first_not_own_table is not reached is for the case when
    the given table list refers to the list for prelocking (contains tables
    of other queries). For simple queries first_not_own_table is 0.
3560 3561
  */
  for (i= 0, table= tables;
unknown's avatar
unknown committed
3562
       table != first_not_own_table && i < number;
3563 3564 3565 3566 3567 3568
       table= table->next_global, i++)
  {
    /* Remove SHOW_VIEW_ACL, because it will be checked during making view */
    table->grant.orig_want_privilege= (want_access & ~SHOW_VIEW_ACL);
  }

3569
  want_access&= ~sctx->master_access;
unknown's avatar
unknown committed
3570
  if (!want_access)
3571
    DBUG_RETURN(0);                             // ok
unknown's avatar
unknown committed
3572

3573
  rw_rdlock(&LOCK_grant);
3574 3575 3576
  for (table= tables;
       table && number-- && table != first_not_own_table;
       table= table->next_global)
unknown's avatar
unknown committed
3577
  {
3578
    GRANT_TABLE *grant_table;
3579
    if (!(~table->grant.privilege & want_access) || 
3580
        table->derived || table->schema_table || table->belong_to_view)
unknown's avatar
unknown committed
3581
    {
unknown's avatar
VIEW  
unknown committed
3582 3583 3584 3585
      /*
        It is subquery in the FROM clause. VIEW set table->derived after
        table opening, but this function always called before table opening.
      */
3586 3587 3588 3589 3590 3591 3592 3593 3594 3595
      if (!table->referencing_view)
      {
        /*
          If it's a temporary table created for a subquery in the FROM
          clause, or an INFORMATION_SCHEMA table, drop the request for
          a privilege.
        */
        table->grant.want_privilege= 0;
      }
      continue;
unknown's avatar
unknown committed
3596
    }
3597 3598 3599
    if (!(grant_table= table_hash_search(sctx->host, sctx->ip,
                                         table->db, sctx->priv_user,
                                         table->table_name,0)))
unknown's avatar
unknown committed
3600 3601 3602 3603
    {
      want_access &= ~table->grant.privilege;
      goto err;					// No grants
    }
unknown's avatar
unknown committed
3604 3605
    if (show_table)
      continue;					// We have some priv on this
unknown's avatar
unknown committed
3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621

    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
    }
  }
3622
  rw_unlock(&LOCK_grant);
3623
  DBUG_RETURN(0);
unknown's avatar
unknown committed
3624

3625
err:
3626
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
3627
  if (!no_errors)				// Not a silent skip of table
unknown's avatar
unknown committed
3628
  {
3629 3630
    char command[128];
    get_privilege_desc(command, sizeof(command), want_access);
3631 3632
    my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0),
             command,
3633 3634
             sctx->priv_user,
             sctx->host_or_ip,
3635
             table ? table->table_name : "unknown");
unknown's avatar
unknown committed
3636
  }
3637
  DBUG_RETURN(1);
unknown's avatar
unknown committed
3638 3639 3640
}


3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658
/*
  Check column rights in given security context

  SYNOPSIS
    check_grant_column()
    thd                  thread handler
    grant                grant information structure
    db_name              db name
    table_name           table  name
    name                 column name
    length               column name length
    sctx                 security context

  RETURN
    FALSE OK
    TRUE  access denied
*/

unknown's avatar
VIEW  
unknown committed
3659
bool check_grant_column(THD *thd, GRANT_INFO *grant,
3660
			const char *db_name, const char *table_name,
3661
			const char *name, uint length,  Security_context *sctx)
unknown's avatar
unknown committed
3662 3663 3664
{
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;
unknown's avatar
VIEW  
unknown committed
3665
  ulong want_access= grant->want_privilege & ~grant->privilege;
unknown's avatar
unknown committed
3666 3667 3668
  DBUG_ENTER("check_grant_column");
  DBUG_PRINT("enter", ("table: %s  want_access: %u", table_name, want_access));

unknown's avatar
unknown committed
3669
  if (!want_access)
unknown's avatar
unknown committed
3670
    DBUG_RETURN(0);				// Already checked
unknown's avatar
unknown committed
3671

3672
  rw_rdlock(&LOCK_grant);
unknown's avatar
unknown committed
3673

3674
  /* reload table if someone has modified any grants */
unknown's avatar
unknown committed
3675

unknown's avatar
VIEW  
unknown committed
3676
  if (grant->version != grant_version)
unknown's avatar
unknown committed
3677
  {
unknown's avatar
VIEW  
unknown committed
3678
    grant->grant_table=
3679 3680
      table_hash_search(sctx->host, sctx->ip, db_name,
			sctx->priv_user,
unknown's avatar
unknown committed
3681
			table_name, 0);         /* purecov: inspected */
unknown's avatar
VIEW  
unknown committed
3682
    grant->version= grant_version;		/* purecov: inspected */
unknown's avatar
unknown committed
3683
  }
unknown's avatar
VIEW  
unknown committed
3684
  if (!(grant_table= grant->grant_table))
unknown's avatar
unknown committed
3685 3686 3687 3688 3689
    goto err;					/* purecov: deadcode */

  grant_column=column_hash_search(grant_table, name, length);
  if (grant_column && !(~grant_column->rights & want_access))
  {
3690
    rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
3691
    DBUG_RETURN(0);
unknown's avatar
unknown committed
3692 3693
  }

3694
err:
3695
  rw_unlock(&LOCK_grant);
3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739
  char command[128];
  get_privilege_desc(command, sizeof(command), want_access);
  my_error(ER_COLUMNACCESS_DENIED_ERROR, MYF(0),
           command,
           sctx->priv_user,
           sctx->host_or_ip,
           name,
           table_name);
  DBUG_RETURN(1);
}


/*
  Check the access right to a column depending on the type of table.

  SYNOPSIS
    check_column_grant_in_table_ref()
    thd              thread handler
    table_ref        table reference where to check the field
    name             name of field to check
    length           length of name

  DESCRIPTION
    Check the access rights to a column depending on the type of table
    reference where the column is checked. The function provides a
    generic interface to check column access rights that hides the
    heterogeneity of the column representation - whether it is a view
    or a stored table colum.

  RETURN
    FALSE OK
    TRUE  access denied
*/

bool check_column_grant_in_table_ref(THD *thd, TABLE_LIST * table_ref,
                                     const char *name, uint length)
{
  GRANT_INFO *grant;
  const char *db_name;
  const char *table_name;
  Security_context *sctx= test(table_ref->security_ctx) ?
                          table_ref->security_ctx : thd->security_ctx;

  if (table_ref->view || table_ref->field_translation)
unknown's avatar
unknown committed
3740
  {
3741 3742 3743 3744
    /* View or derived information schema table. */
    grant= &(table_ref->grant);
    db_name= table_ref->view_db.str;
    table_name= table_ref->view_name.str;
unknown's avatar
unknown committed
3745
  }
3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760
  else
  {
    /* Normal or temporary table. */
    TABLE *table= table_ref->table;
    grant= &(table->grant);
    db_name= table->s->db;
    table_name= table->s->table_name;
  }

  if (grant->want_privilege)
    return check_grant_column(thd, grant, db_name, table_name, name,
                              length, sctx);
  else
    return FALSE;

unknown's avatar
unknown committed
3761 3762 3763
}


unknown's avatar
VIEW  
unknown committed
3764
bool check_grant_all_columns(THD *thd, ulong want_access, GRANT_INFO *grant,
3765
                             const char* db_name, const char *table_name,
unknown's avatar
VIEW  
unknown committed
3766
                             Field_iterator *fields)
unknown's avatar
unknown committed
3767
{
3768
  Security_context *sctx= thd->security_ctx;
unknown's avatar
unknown committed
3769 3770 3771
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;

unknown's avatar
VIEW  
unknown committed
3772
  want_access &= ~grant->privilege;
unknown's avatar
unknown committed
3773
  if (!want_access)
unknown's avatar
unknown committed
3774
    return 0;				// Already checked
unknown's avatar
unknown committed
3775 3776
  if (!grant_option)
    goto err2;
unknown's avatar
unknown committed
3777

3778
  rw_rdlock(&LOCK_grant);
unknown's avatar
unknown committed
3779

3780
  /* reload table if someone has modified any grants */
unknown's avatar
unknown committed
3781

unknown's avatar
VIEW  
unknown committed
3782
  if (grant->version != grant_version)
unknown's avatar
unknown committed
3783
  {
unknown's avatar
VIEW  
unknown committed
3784
    grant->grant_table=
3785 3786
      table_hash_search(sctx->host, sctx->ip, db_name,
			sctx->priv_user,
unknown's avatar
VIEW  
unknown committed
3787 3788
			table_name, 0);	/* purecov: inspected */
    grant->version= grant_version;		/* purecov: inspected */
unknown's avatar
unknown committed
3789
  }
3790
  /* The following should always be true */
unknown's avatar
VIEW  
unknown committed
3791
  if (!(grant_table= grant->grant_table))
unknown's avatar
unknown committed
3792 3793
    goto err;					/* purecov: inspected */

3794
  for (; !fields->end_of_fields(); fields->next())
unknown's avatar
unknown committed
3795
  {
unknown's avatar
VIEW  
unknown committed
3796 3797 3798
    const char *field_name= fields->name();
    grant_column= column_hash_search(grant_table, field_name,
				    (uint) strlen(field_name));
unknown's avatar
unknown committed
3799 3800 3801
    if (!grant_column || (~grant_column->rights & want_access))
      goto err;
  }
3802
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
3803 3804
  return 0;

unknown's avatar
unknown committed
3805
err:
3806
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
3807
err2:
3808 3809
  char command[128];
  get_privilege_desc(command, sizeof(command), want_access);
3810 3811
  my_error(ER_COLUMNACCESS_DENIED_ERROR, MYF(0),
           command,
3812 3813
           sctx->priv_user,
           sctx->host_or_ip,
3814 3815
           fields->name(),
           table_name);
unknown's avatar
unknown committed
3816 3817 3818 3819
  return 1;
}


3820
/*
unknown's avatar
unknown committed
3821
  Check if a user has the right to access a database
3822
  Access is accepted if he has a grant for any table/routine in the database
unknown's avatar
unknown committed
3823
  Return 1 if access is denied
3824
*/
unknown's avatar
unknown committed
3825 3826 3827

bool check_grant_db(THD *thd,const char *db)
{
3828
  Security_context *sctx= thd->security_ctx;
unknown's avatar
unknown committed
3829 3830
  char helping [NAME_LEN+USERNAME_LENGTH+2];
  uint len;
unknown's avatar
unknown committed
3831
  bool error= 1;
unknown's avatar
unknown committed
3832

3833
  len= (uint) (strmov(strmov(helping, sctx->priv_user) + 1, db) - helping) + 1;
3834
  rw_rdlock(&LOCK_grant);
unknown's avatar
unknown committed
3835

3836
  for (uint idx=0 ; idx < column_priv_hash.records ; idx++)
unknown's avatar
unknown committed
3837
  {
3838 3839
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  idx);
unknown's avatar
unknown committed
3840 3841
    if (len < grant_table->key_length &&
	!memcmp(grant_table->hash_key,helping,len) &&
3842
        compare_hostname(&grant_table->host, sctx->host, sctx->ip))
unknown's avatar
unknown committed
3843 3844 3845 3846 3847
    {
      error=0;					// Found match
      break;
    }
  }
3848
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
3849 3850 3851
  return error;
}

3852 3853

/****************************************************************************
3854
  Check routine level grants
3855 3856

  SYNPOSIS
3857
   bool check_grant_routine()
3858 3859
   thd		Thread handler
   want_access  Bits of privileges user needs to have
3860 3861
   procs	List of routines to check. The user should have 'want_access'
   is_proc	True if the list is all procedures, else functions
3862 3863 3864 3865 3866 3867 3868 3869
   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
****************************************************************************/

3870
bool check_grant_routine(THD *thd, ulong want_access,
3871
			 TABLE_LIST *procs, bool is_proc, bool no_errors)
3872 3873
{
  TABLE_LIST *table;
3874
  Security_context *sctx= thd->security_ctx;
3875 3876
  char *user= sctx->priv_user;
  char *host= sctx->priv_host;
3877
  DBUG_ENTER("check_grant_routine");
3878

3879
  want_access&= ~sctx->master_access;
3880 3881 3882 3883 3884 3885 3886
  if (!want_access)
    DBUG_RETURN(0);                             // ok

  rw_rdlock(&LOCK_grant);
  for (table= procs; table; table= table->next_global)
  {
    GRANT_NAME *grant_proc;
3887
    if ((grant_proc= routine_hash_search(host, sctx->ip, table->db, user,
3888
					 table->table_name, is_proc, 0)))
3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905
      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)
3906
      strxmov(buff, table->db, ".", table->table_name, NullS);
3907 3908 3909
    if (want_access & EXECUTE_ACL)
      command= "execute";
    else if (want_access & ALTER_PROC_ACL)
3910
      command= "alter routine";
3911 3912 3913 3914 3915 3916 3917 3918 3919
    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);
}


3920 3921
/*
  Check if routine has any of the 
3922
  routine level grants
3923 3924 3925 3926 3927 3928 3929 3930 3931
  
  SYNPOSIS
   bool    check_routine_level_acl()
   thd	        Thread handler
   db           Database name
   name         Routine name

  RETURN
   0            Ok 
3932
   1            error
3933 3934
*/

unknown's avatar
unknown committed
3935 3936
bool check_routine_level_acl(THD *thd, const char *db, const char *name, 
                             bool is_proc)
3937 3938 3939 3940 3941
{
  bool no_routine_acl= 1;
  if (grant_option)
  {
    GRANT_NAME *grant_proc;
3942
    Security_context *sctx= thd->security_ctx;
3943
    rw_rdlock(&LOCK_grant);
3944 3945 3946
    if ((grant_proc= routine_hash_search(sctx->priv_host,
                                         sctx->ip, db,
                                         sctx->priv_user,
3947
                                         name, is_proc, 0)))
3948 3949 3950 3951 3952 3953 3954
      no_routine_acl= !(grant_proc->privs & SHOW_PROC_ACLS);
    rw_unlock(&LOCK_grant);
  }
  return no_routine_acl;
}


unknown's avatar
unknown committed
3955
/*****************************************************************************
unknown's avatar
unknown committed
3956
  Functions to retrieve the grant for a table/column  (for SHOW functions)
unknown's avatar
unknown committed
3957 3958
*****************************************************************************/

unknown's avatar
unknown committed
3959
ulong get_table_grant(THD *thd, TABLE_LIST *table)
unknown's avatar
unknown committed
3960
{
unknown's avatar
unknown committed
3961
  ulong privilege;
3962
  Security_context *sctx= thd->security_ctx;
unknown's avatar
unknown committed
3963 3964 3965
  const char *db = table->db ? table->db : thd->db;
  GRANT_TABLE *grant_table;

3966
  rw_rdlock(&LOCK_grant);
3967 3968 3969
#ifdef EMBEDDED_LIBRARY
  grant_table= NULL;
#else
3970
  grant_table= table_hash_search(sctx->host, sctx->ip, db, sctx->priv_user,
3971
				 table->table_name, 0);
3972
#endif
unknown's avatar
unknown committed
3973 3974 3975 3976
  table->grant.grant_table=grant_table; // Remember for column test
  table->grant.version=grant_version;
  if (grant_table)
    table->grant.privilege|= grant_table->privs;
3977
  privilege= table->grant.privilege;
3978
  rw_unlock(&LOCK_grant);
3979
  return privilege;
unknown's avatar
unknown committed
3980 3981 3982
}


unknown's avatar
unknown committed
3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000
/*
  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
4001 4002 4003
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
4004 4005 4006
{
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;
unknown's avatar
unknown committed
4007
  ulong priv;
unknown's avatar
unknown committed
4008

4009
  rw_rdlock(&LOCK_grant);
4010
  /* reload table if someone has modified any grants */
unknown's avatar
VIEW  
unknown committed
4011
  if (grant->version != grant_version)
unknown's avatar
unknown committed
4012
  {
4013
    Security_context *sctx= thd->security_ctx;
unknown's avatar
VIEW  
unknown committed
4014
    grant->grant_table=
4015 4016
      table_hash_search(sctx->host, sctx->ip,
                        db_name, sctx->priv_user,
unknown's avatar
VIEW  
unknown committed
4017 4018
			table_name, 0);	        /* purecov: inspected */
    grant->version= grant_version;              /* purecov: inspected */
unknown's avatar
unknown committed
4019 4020
  }

unknown's avatar
VIEW  
unknown committed
4021 4022
  if (!(grant_table= grant->grant_table))
    priv= grant->privilege;
unknown's avatar
unknown committed
4023 4024
  else
  {
unknown's avatar
VIEW  
unknown committed
4025 4026
    grant_column= column_hash_search(grant_table, field_name,
                                     (uint) strlen(field_name));
unknown's avatar
unknown committed
4027
    if (!grant_column)
4028
      priv= (grant->privilege | grant_table->privs);
unknown's avatar
unknown committed
4029
    else
4030
      priv= (grant->privilege | grant_table->privs | grant_column->rights);
unknown's avatar
unknown committed
4031
  }
4032
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
4033 4034 4035
  return priv;
}

unknown's avatar
VIEW  
unknown committed
4036

4037
/* Help function for mysql_show_grants */
unknown's avatar
unknown committed
4038

4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050
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
4051 4052

static const char *command_array[]=
unknown's avatar
unknown committed
4053
{
unknown's avatar
VIEW  
unknown committed
4054 4055 4056 4057
  "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",
4058
  "CREATE VIEW", "SHOW VIEW", "CREATE ROUTINE", "ALTER ROUTINE",
4059
  "CREATE USER"
unknown's avatar
unknown committed
4060
};
4061

unknown's avatar
unknown committed
4062 4063
static uint command_lengths[]=
{
4064 4065
  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
4066 4067
};

unknown's avatar
unknown committed
4068

4069 4070 4071 4072 4073
static int show_routine_grants(THD *thd, LEX_USER *lex_user, HASH *hash,
                               const char *type, int typelen,
                               char *buff, int buffsize);


4074 4075 4076 4077 4078 4079 4080
/*
  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
4081
bool mysql_show_grants(THD *thd,LEX_USER *lex_user)
unknown's avatar
unknown committed
4082
{
unknown's avatar
unknown committed
4083 4084
  ulong want_access;
  uint counter,index;
unknown's avatar
unknown committed
4085
  int  error = 0;
unknown's avatar
unknown committed
4086 4087
  ACL_USER *acl_user;
  ACL_DB *acl_db;
unknown's avatar
unknown committed
4088
  char buff[1024];
4089
  Protocol *protocol= thd->protocol;
unknown's avatar
unknown committed
4090
  DBUG_ENTER("mysql_show_grants");
unknown's avatar
unknown committed
4091 4092 4093 4094

  LINT_INIT(acl_user);
  if (!initialized)
  {
unknown's avatar
unknown committed
4095
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
unknown's avatar
unknown committed
4096
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
4097
  }
unknown's avatar
unknown committed
4098 4099 4100 4101 4102 4103

  if (!lex_user->host.str)
  {
    lex_user->host.str= (char*) "%";
    lex_user->host.length=1;
  }
unknown's avatar
unknown committed
4104 4105 4106
  if (lex_user->host.length > HOSTNAME_LENGTH ||
      lex_user->user.length > USERNAME_LENGTH)
  {
unknown's avatar
unknown committed
4107 4108
    my_message(ER_GRANT_WRONG_HOST_OR_USER, ER(ER_GRANT_WRONG_HOST_OR_USER),
               MYF(0));
unknown's avatar
unknown committed
4109
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
4110 4111 4112 4113 4114 4115 4116
  }

  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
4117
      user= "";
unknown's avatar
unknown committed
4118
    if (!(host=acl_user->host.hostname))
unknown's avatar
unknown committed
4119
      host= "";
unknown's avatar
unknown committed
4120
    if (!strcmp(lex_user->user.str,user) &&
4121
	!my_strcasecmp(system_charset_info, lex_user->host.str, host))
unknown's avatar
unknown committed
4122 4123
      break;
  }
unknown's avatar
unknown committed
4124
  if (counter == acl_users.elements)
unknown's avatar
unknown committed
4125
  {
unknown's avatar
unknown committed
4126 4127
    my_error(ER_NONEXISTING_GRANT, MYF(0),
             lex_user->user.str, lex_user->host.str);
unknown's avatar
unknown committed
4128
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
4129 4130
  }

unknown's avatar
unknown committed
4131
  Item_string *field=new Item_string("",0,&my_charset_latin1);
unknown's avatar
unknown committed
4132 4133 4134 4135 4136 4137
  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);
4138 4139
  if (protocol->send_fields(&field_list,
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
unknown's avatar
unknown committed
4140
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
4141

unknown's avatar
unknown committed
4142
  rw_wrlock(&LOCK_grant);
unknown's avatar
unknown committed
4143 4144 4145 4146
  VOID(pthread_mutex_lock(&acl_cache->lock));

  /* Add first global access grants */
  {
4147
    String global(buff,sizeof(buff),system_charset_info);
unknown's avatar
unknown committed
4148
    global.length(0);
4149
    global.append(STRING_WITH_LEN("GRANT "));
unknown's avatar
unknown committed
4150

unknown's avatar
unknown committed
4151
    want_access= acl_user->access;
unknown's avatar
unknown committed
4152
    if (test_all_bits(want_access, (GLOBAL_ACLS & ~ GRANT_ACL)))
4153
      global.append(STRING_WITH_LEN("ALL PRIVILEGES"));
unknown's avatar
unknown committed
4154
    else if (!(want_access & ~GRANT_ACL))
4155
      global.append(STRING_WITH_LEN("USAGE"));
unknown's avatar
unknown committed
4156
    else
unknown's avatar
unknown committed
4157 4158
    {
      bool found=0;
unknown's avatar
unknown committed
4159
      ulong j,test_access= want_access & ~GRANT_ACL;
unknown's avatar
unknown committed
4160 4161
      for (counter=0, j = SELECT_ACL;j <= GLOBAL_ACLS;counter++,j <<= 1)
      {
unknown's avatar
unknown committed
4162
	if (test_access & j)
unknown's avatar
unknown committed
4163 4164
	{
	  if (found)
4165
	    global.append(STRING_WITH_LEN(", "));
unknown's avatar
unknown committed
4166 4167 4168 4169 4170
	  found=1;
	  global.append(command_array[counter],command_lengths[counter]);
	}
      }
    }
4171
    global.append (STRING_WITH_LEN(" ON *.* TO '"));
4172 4173
    global.append(lex_user->user.str, lex_user->user.length,
		  system_charset_info);
4174
    global.append (STRING_WITH_LEN("'@'"));
4175 4176
    global.append(lex_user->host.str,lex_user->host.length,
		  system_charset_info);
unknown's avatar
unknown committed
4177
    global.append ('\'');
4178
    if (acl_user->salt_len)
unknown's avatar
unknown committed
4179
    {
4180 4181 4182 4183 4184
      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);
4185
      global.append(STRING_WITH_LEN(" IDENTIFIED BY PASSWORD '"));
4186
      global.append(passwd_buff);
unknown's avatar
unknown committed
4187 4188
      global.append('\'');
    }
4189 4190
    /* "show grants" SSL related stuff */
    if (acl_user->ssl_type == SSL_TYPE_ANY)
4191
      global.append(STRING_WITH_LEN(" REQUIRE SSL"));
4192
    else if (acl_user->ssl_type == SSL_TYPE_X509)
4193
      global.append(STRING_WITH_LEN(" REQUIRE X509"));
4194
    else if (acl_user->ssl_type == SSL_TYPE_SPECIFIED)
4195
    {
4196
      int ssl_options = 0;
4197
      global.append(STRING_WITH_LEN(" REQUIRE "));
4198 4199
      if (acl_user->x509_issuer)
      {
4200
	ssl_options++;
4201
	global.append(STRING_WITH_LEN("ISSUER \'"));
4202
	global.append(acl_user->x509_issuer,strlen(acl_user->x509_issuer));
4203
	global.append('\'');
4204
      }
4205 4206
      if (acl_user->x509_subject)
      {
4207 4208
	if (ssl_options++)
	  global.append(' ');
4209
	global.append(STRING_WITH_LEN("SUBJECT \'"));
4210 4211
	global.append(acl_user->x509_subject,strlen(acl_user->x509_subject),
                      system_charset_info);
4212
	global.append('\'');
unknown's avatar
unknown committed
4213
      }
4214 4215
      if (acl_user->ssl_cipher)
      {
4216 4217
	if (ssl_options++)
	  global.append(' ');
4218
	global.append(STRING_WITH_LEN("CIPHER '"));
4219 4220
	global.append(acl_user->ssl_cipher,strlen(acl_user->ssl_cipher),
                      system_charset_info);
4221
	global.append('\'');
4222 4223
      }
    }
unknown's avatar
unknown committed
4224
    if ((want_access & GRANT_ACL) ||
4225 4226 4227 4228
	(acl_user->user_resource.questions ||
         acl_user->user_resource.updates ||
         acl_user->user_resource.conn_per_hour ||
         acl_user->user_resource.user_conn))
4229
    {
4230
      global.append(STRING_WITH_LEN(" WITH"));
unknown's avatar
unknown committed
4231
      if (want_access & GRANT_ACL)
4232
	global.append(STRING_WITH_LEN(" GRANT OPTION"));
4233 4234 4235 4236
      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");
4237
      add_user_option(&global, acl_user->user_resource.conn_per_hour,
4238
		      "MAX_CONNECTIONS_PER_HOUR");
4239 4240
      add_user_option(&global, acl_user->user_resource.user_conn,
		      "MAX_USER_CONNECTIONS");
unknown's avatar
unknown committed
4241
    }
4242
    protocol->prepare_for_resend();
4243
    protocol->store(global.ptr(),global.length(),global.charset());
4244
    if (protocol->write())
unknown's avatar
unknown committed
4245
    {
unknown's avatar
unknown committed
4246
      error= -1;
4247
      goto end;
unknown's avatar
unknown committed
4248 4249 4250 4251 4252 4253
    }
  }

  /* Add database access */
  for (counter=0 ; counter < acl_dbs.elements ; counter++)
  {
unknown's avatar
unknown committed
4254
    const char *user, *host;
unknown's avatar
unknown committed
4255 4256 4257

    acl_db=dynamic_element(&acl_dbs,counter,ACL_DB*);
    if (!(user=acl_db->user))
unknown's avatar
unknown committed
4258
      user= "";
unknown's avatar
unknown committed
4259
    if (!(host=acl_db->host.hostname))
unknown's avatar
unknown committed
4260
      host= "";
unknown's avatar
unknown committed
4261 4262

    if (!strcmp(lex_user->user.str,user) &&
4263
	!my_strcasecmp(system_charset_info, lex_user->host.str, host))
unknown's avatar
unknown committed
4264 4265
    {
      want_access=acl_db->access;
unknown's avatar
unknown committed
4266
      if (want_access)
unknown's avatar
unknown committed
4267
      {
4268
	String db(buff,sizeof(buff),system_charset_info);
unknown's avatar
unknown committed
4269
	db.length(0);
4270
	db.append(STRING_WITH_LEN("GRANT "));
unknown's avatar
unknown committed
4271 4272

	if (test_all_bits(want_access,(DB_ACLS & ~GRANT_ACL)))
4273
	  db.append(STRING_WITH_LEN("ALL PRIVILEGES"));
4274
	else if (!(want_access & ~GRANT_ACL))
4275
	  db.append(STRING_WITH_LEN("USAGE"));
unknown's avatar
unknown committed
4276 4277 4278
	else
	{
	  int found=0, cnt;
unknown's avatar
unknown committed
4279
	  ulong j,test_access= want_access & ~GRANT_ACL;
unknown's avatar
unknown committed
4280 4281 4282 4283 4284
	  for (cnt=0, j = SELECT_ACL; j <= DB_ACLS; cnt++,j <<= 1)
	  {
	    if (test_access & j)
	    {
	      if (found)
4285
		db.append(STRING_WITH_LEN(", "));
unknown's avatar
unknown committed
4286 4287 4288 4289 4290
	      found = 1;
	      db.append(command_array[cnt],command_lengths[cnt]);
	    }
	  }
	}
4291
	db.append (STRING_WITH_LEN(" ON "));
4292
	append_identifier(thd, &db, acl_db->db, strlen(acl_db->db));
4293
	db.append (STRING_WITH_LEN(".* TO '"));
4294 4295
	db.append(lex_user->user.str, lex_user->user.length,
		  system_charset_info);
4296
	db.append (STRING_WITH_LEN("'@'"));
4297 4298
	db.append(lex_user->host.str, lex_user->host.length,
                  system_charset_info);
unknown's avatar
unknown committed
4299
	db.append ('\'');
unknown's avatar
unknown committed
4300
	if (want_access & GRANT_ACL)
4301
	  db.append(STRING_WITH_LEN(" WITH GRANT OPTION"));
4302
	protocol->prepare_for_resend();
4303
	protocol->store(db.ptr(),db.length(),db.charset());
4304
	if (protocol->write())
unknown's avatar
unknown committed
4305
	{
unknown's avatar
unknown committed
4306
	  error= -1;
unknown's avatar
unknown committed
4307 4308 4309 4310 4311 4312
	  goto end;
	}
      }
    }
  }

4313
  /* Add table & column access */
4314
  for (index=0 ; index < column_priv_hash.records ; index++)
unknown's avatar
unknown committed
4315
  {
unknown's avatar
unknown committed
4316
    const char *user;
4317 4318
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  index);
unknown's avatar
unknown committed
4319 4320

    if (!(user=grant_table->user))
4321
      user= "";
unknown's avatar
unknown committed
4322 4323

    if (!strcmp(lex_user->user.str,user) &&
4324
	!my_strcasecmp(system_charset_info, lex_user->host.str,
4325
                       grant_table->host.hostname))
unknown's avatar
unknown committed
4326
    {
4327 4328
      ulong table_access= grant_table->privs;
      if ((table_access | grant_table->cols) != 0)
unknown's avatar
unknown committed
4329
      {
4330
	String global(buff, sizeof(buff), system_charset_info);
unknown's avatar
unknown committed
4331 4332
	ulong test_access= (table_access | grant_table->cols) & ~GRANT_ACL;

unknown's avatar
unknown committed
4333
	global.length(0);
4334
	global.append(STRING_WITH_LEN("GRANT "));
unknown's avatar
unknown committed
4335

4336
	if (test_all_bits(table_access, (TABLE_ACLS & ~GRANT_ACL)))
4337
	  global.append(STRING_WITH_LEN("ALL PRIVILEGES"));
unknown's avatar
unknown committed
4338
	else if (!test_access)
4339
	  global.append(STRING_WITH_LEN("USAGE"));
unknown's avatar
unknown committed
4340
	else
unknown's avatar
unknown committed
4341
	{
4342
          /* Add specific column access */
4343
	  int found= 0;
unknown's avatar
unknown committed
4344
	  ulong j;
unknown's avatar
unknown committed
4345

4346
	  for (counter= 0, j= SELECT_ACL; j <= TABLE_ACLS; counter++, j<<= 1)
unknown's avatar
unknown committed
4347
	  {
unknown's avatar
unknown committed
4348
	    if (test_access & j)
unknown's avatar
unknown committed
4349 4350
	    {
	      if (found)
4351
		global.append(STRING_WITH_LEN(", "));
4352
	      found= 1;
unknown's avatar
unknown committed
4353 4354
	      global.append(command_array[counter],command_lengths[counter]);

unknown's avatar
unknown committed
4355
	      if (grant_table->cols)
unknown's avatar
unknown committed
4356
	      {
4357
		uint found_col= 0;
unknown's avatar
unknown committed
4358 4359 4360 4361 4362 4363
		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
4364
		  if (grant_column->rights & j)
unknown's avatar
unknown committed
4365
		  {
unknown's avatar
unknown committed
4366
		    if (!found_col)
unknown's avatar
unknown committed
4367
		    {
4368 4369 4370 4371 4372 4373 4374
		      found_col= 1;
		      /*
			If we have a duplicated table level privilege, we
			must write the access privilege name again.
		      */
		      if (table_access & j)
		      {
4375
			global.append(STRING_WITH_LEN(", "));
4376 4377 4378
			global.append(command_array[counter],
				      command_lengths[counter]);
		      }
4379
		      global.append(STRING_WITH_LEN(" ("));
unknown's avatar
unknown committed
4380 4381
		    }
		    else
4382
		      global.append(STRING_WITH_LEN(", "));
unknown's avatar
unknown committed
4383
		    global.append(grant_column->column,
4384 4385
				  grant_column->key_length,
				  system_charset_info);
unknown's avatar
unknown committed
4386 4387 4388 4389 4390 4391 4392 4393
		  }
		}
		if (found_col)
		  global.append(')');
	      }
	    }
	  }
	}
4394
	global.append(STRING_WITH_LEN(" ON "));
4395 4396 4397 4398 4399
	append_identifier(thd, &global, grant_table->db,
			  strlen(grant_table->db));
	global.append('.');
	append_identifier(thd, &global, grant_table->tname,
			  strlen(grant_table->tname));
4400
	global.append(STRING_WITH_LEN(" TO '"));
4401 4402
	global.append(lex_user->user.str, lex_user->user.length,
		      system_charset_info);
4403
	global.append(STRING_WITH_LEN("'@'"));
4404 4405
	global.append(lex_user->host.str,lex_user->host.length,
		      system_charset_info);
unknown's avatar
unknown committed
4406
	global.append('\'');
4407
	if (table_access & GRANT_ACL)
4408
	  global.append(STRING_WITH_LEN(" WITH GRANT OPTION"));
4409
	protocol->prepare_for_resend();
4410
	protocol->store(global.ptr(),global.length(),global.charset());
4411
	if (protocol->write())
unknown's avatar
unknown committed
4412
	{
unknown's avatar
unknown committed
4413
	  error= -1;
4414
	  break;
unknown's avatar
unknown committed
4415 4416 4417 4418
	}
      }
    }
  }
4419

4420
  if (show_routine_grants(thd, lex_user, &proc_priv_hash, 
4421
                          STRING_WITH_LEN("PROCEDURE"), buff, sizeof(buff)))
4422 4423 4424 4425 4426 4427
  {
    error= -1;
    goto end;
  }

  if (show_routine_grants(thd, lex_user, &func_priv_hash,
4428
                          STRING_WITH_LEN("FUNCTION"), buff, sizeof(buff)))
4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450
  {
    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++)
4451 4452
  {
    const char *user;
4453
    GRANT_NAME *grant_proc= (GRANT_NAME*) hash_element(hash, index);
4454 4455 4456 4457 4458 4459

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

    if (!strcmp(lex_user->user.str,user) &&
	!my_strcasecmp(system_charset_info, lex_user->host.str,
4460
                       grant_proc->host.hostname))
4461 4462 4463 4464
    {
      ulong proc_access= grant_proc->privs;
      if (proc_access != 0)
      {
4465
	String global(buff, buffsize, system_charset_info);
4466 4467 4468
	ulong test_access= proc_access & ~GRANT_ACL;

	global.length(0);
4469
	global.append(STRING_WITH_LEN("GRANT "));
4470 4471

	if (!test_access)
4472
 	  global.append(STRING_WITH_LEN("USAGE"));
4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483
	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)
4484
		global.append(STRING_WITH_LEN(", "));
4485 4486 4487 4488 4489
	      found= 1;
	      global.append(command_array[counter],command_lengths[counter]);
	    }
	  }
	}
4490
	global.append(STRING_WITH_LEN(" ON "));
4491 4492
        global.append(type,typelen);
        global.append(' ');
4493 4494 4495 4496 4497
	append_identifier(thd, &global, grant_proc->db,
			  strlen(grant_proc->db));
	global.append('.');
	append_identifier(thd, &global, grant_proc->tname,
			  strlen(grant_proc->tname));
4498
	global.append(STRING_WITH_LEN(" TO '"));
4499 4500
	global.append(lex_user->user.str, lex_user->user.length,
		      system_charset_info);
4501
	global.append(STRING_WITH_LEN("'@'"));
4502 4503 4504 4505
	global.append(lex_user->host.str,lex_user->host.length,
		      system_charset_info);
	global.append('\'');
	if (proc_access & GRANT_ACL)
4506
	  global.append(STRING_WITH_LEN(" WITH GRANT OPTION"));
4507 4508 4509 4510 4511 4512 4513 4514 4515 4516
	protocol->prepare_for_resend();
	protocol->store(global.ptr(),global.length(),global.charset());
	if (protocol->write())
	{
	  error= -1;
	  break;
	}
      }
    }
  }
4517
  return error;
unknown's avatar
unknown committed
4518 4519
}

unknown's avatar
unknown committed
4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547
/*
  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;
}


4548
void get_mqh(const char *user, const char *host, USER_CONN *uc)
unknown's avatar
unknown committed
4549 4550
{
  ACL_USER *acl_user;
4551
  if (initialized && (acl_user= find_acl_user(host,user, FALSE)))
4552 4553 4554
    uc->user_resources= acl_user->user_resource;
  else
    bzero((char*) &uc->user_resources, sizeof(uc->user_resources));
unknown's avatar
unknown committed
4555 4556
}

4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577
/*
  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.
*/

4578
#define GRANT_TABLES 5
4579 4580 4581 4582 4583 4584
int open_grant_tables(THD *thd, TABLE_LIST *tables)
{
  DBUG_ENTER("open_grant_tables");

  if (!initialized)
  {
unknown's avatar
unknown committed
4585
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
4586 4587 4588
    DBUG_RETURN(-1);
  }

4589
  bzero((char*) tables, GRANT_TABLES*sizeof(*tables));
4590 4591 4592 4593 4594
  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
4595 4596 4597
  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;
4598
  (tables+3)->next_local= (tables+3)->next_global= tables+4;
4599
  tables->lock_type= (tables+1)->lock_type=
4600 4601 4602 4603
    (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";
4604 4605 4606 4607 4608 4609

#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
4610 4611
  if (thd->slave_thread && table_rules_on)
  {
unknown's avatar
unknown committed
4612 4613 4614
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
4615
    */
4616 4617
    tables[0].updating=tables[1].updating=tables[2].updating=
      tables[3].updating=tables[4].updating=1;
4618
    if (!tables_ok(thd, tables))
4619
      DBUG_RETURN(1);
4620 4621
    tables[0].updating=tables[1].updating=tables[2].updating=
      tables[3].updating=tables[4].updating=0;;
4622
  }
4623 4624
#endif

4625
  if (simple_open_n_lock_tables(thd, tables))
4626 4627 4628 4629 4630 4631 4632 4633 4634
  {						// 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
4635
			 uint *acl_acl_userdx)
4636 4637 4638 4639 4640 4641 4642 4643 4644
{
  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
4645
      user= "";
4646
    if (!(host=acl_user->host.hostname))
4647
      host= "";
4648 4649 4650 4651 4652 4653 4654
    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
4655
  *acl_acl_userdx= counter;
unknown's avatar
unknown committed
4656
  return acl_user;
4657 4658
}

unknown's avatar
unknown committed
4659

4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681
/*
  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)
4682
{
4683 4684
  int error;
  DBUG_ENTER("modify_grant_table");
4685

4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702
  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));
  }
4703

4704 4705
  DBUG_RETURN(error);
}
4706 4707


4708 4709 4710 4711 4712 4713
/*
  Handle a privilege table.

  SYNOPSIS
    handle_grant_table()
    tables                      The array with the four open tables.
4714
    table_no                    The number of the table to handle (0..4).
4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731
    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
4732
    4 procs_priv
4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751

  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;
4752
  byte user_key[MAX_KEY_LENGTH];
unknown's avatar
unknown committed
4753
  uint key_prefix_length;
4754 4755
  DBUG_ENTER("handle_grant_table");

unknown's avatar
unknown committed
4756
  if (! table_no) // mysql.user table
4757
  {
4758 4759 4760 4761 4762 4763 4764 4765 4766 4767
    /*
      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'",
4768
                       table->s->table_name, user_str, host_str));
4769 4770
    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
4771 4772 4773 4774 4775

    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);

4776
    if ((error= table->file->index_read_idx(table->record[0], 0,
unknown's avatar
unknown committed
4777
                                            user_key, key_prefix_length,
4778
                                            HA_READ_KEY_EXACT)))
4779
    {
4780 4781 4782 4783 4784
      if (error != HA_ERR_KEY_NOT_FOUND)
      {
        table->file->print_error(error, MYF(0));
        result= -1;
      }
4785
    }
4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802
    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)))
4803
    {
4804
      table->file->print_error(error, MYF(0));
4805
      result= -1;
4806 4807 4808 4809 4810
    }
    else
    {
#ifdef EXTRA_DEBUG
      DBUG_PRINT("info",("scan table: '%s'  search: '%s'@'%s'",
4811
                         table->s->table_name, user_str, host_str));
4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859
#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()
4860
    struct_no                   The number of the structure to handle (0..3).
4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875
    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
4876
    3 procs_priv_hash
4877 4878 4879 4880

  RETURN
    > 0         At least one element matched.
    0           OK, but no element matched.
4881
    -1		Wrong arguments to function
4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893
*/

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;
4894
  GRANT_NAME *grant_name;
4895
  DBUG_ENTER("handle_grant_struct");
unknown's avatar
unknown committed
4896 4897 4898
  DBUG_PRINT("info",("scan struct: %u  search: '%s'@'%s'",
                     struct_no, user_from->user.str, user_from->host.str));

4899 4900
  LINT_INIT(acl_user);
  LINT_INIT(acl_db);
4901
  LINT_INIT(grant_name);
4902 4903

  /* Get the number of elements in the in-memory structure. */
4904
  switch (struct_no) {
4905 4906 4907 4908 4909 4910
  case 0:
    elements= acl_users.elements;
    break;
  case 1:
    elements= acl_dbs.elements;
    break;
4911
  case 2:
4912
    elements= column_priv_hash.records;
4913 4914 4915 4916 4917 4918
    break;
  case 3:
    elements= proc_priv_hash.records;
    break;
  default:
    return -1;
4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931
  }

#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.
    */
4932
    switch (struct_no) {
4933 4934 4935 4936 4937 4938 4939 4940 4941 4942
    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;
4943 4944
      if (!(host= acl_db->host.hostname))
        host= "%";
4945 4946
      break;

4947 4948 4949
    case 2:
      grant_name= (GRANT_NAME*) hash_element(&column_priv_hash, idx);
      user= grant_name->user;
4950 4951
      if (!(host= grant_name->host.hostname))
        host= "%";
4952 4953 4954 4955 4956
      break;

    case 3:
      grant_name= (GRANT_NAME*) hash_element(&proc_priv_hash, idx);
      user= grant_name->user;
4957 4958
      if (!(host= grant_name->host.hostname))
        host= "%";
4959
      break;
4960 4961
    }
    if (! user)
4962
      user= "";
4963 4964 4965 4966 4967 4968
#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))
4969
      continue;
4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983

    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;

4984 4985 4986 4987 4988 4989 4990
      case 2:
        hash_delete(&column_priv_hash, (byte*) grant_name);
	break;

      case 3:
        hash_delete(&proc_priv_hash, (byte*) grant_name);
	break;
4991 4992 4993
      }
      elements--;
      idx--;
4994
    }
4995 4996
    else if ( user_to )
    {
4997
      switch ( struct_no ) {
4998 4999 5000 5001
      case 0:
        acl_user->user= strdup_root(&mem, user_to->user.str);
        acl_user->host.hostname= strdup_root(&mem, user_to->host.str);
        break;
5002

5003 5004 5005 5006 5007
      case 1:
        acl_db->user= strdup_root(&mem, user_to->user.str);
        acl_db->host.hostname= strdup_root(&mem, user_to->host.str);
        break;

5008 5009 5010
      case 2:
      case 3:
        grant_name->user= strdup_root(&mem, user_to->user.str);
5011 5012
        update_hostname(&grant_name->host,
                        strdup_root(&mem, user_to->host.str));
5013
	break;
5014 5015 5016
      }
    }
    else
5017
    {
5018 5019 5020 5021 5022 5023 5024
      /* 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
5025

5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069
  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
5070 5071
    if ((handle_grant_struct(0, drop, user_from, user_to) && ! result) ||
        found)
5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098
    {
      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;
    }
  }

5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117
  /* 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;
    }
  }

5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131
  /* 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;
5132
    }
5133 5134 5135

    /* Handle columns table. */
    if ((found= handle_grant_table(tables, 3, drop, user_from, user_to)) < 0)
5136
    {
5137
      /* Handle of table failed, don't touch the in-memory array. */
5138 5139
      result= -1;
    }
5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151
    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
5152

unknown's avatar
unknown committed
5153 5154 5155 5156 5157 5158
static void append_user(String *str, LEX_USER *user)
{
  if (str->length())
    str->append(',');
  str->append('\'');
  str->append(user->user.str);
5159
  str->append(STRING_WITH_LEN("'@'"));
unknown's avatar
unknown committed
5160 5161 5162
  str->append(user->host.str);
  str->append('\'');
}
5163

unknown's avatar
unknown committed
5164

5165 5166 5167 5168 5169 5170 5171
/*
  Create a list of users.

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

5173 5174 5175 5176 5177 5178 5179 5180
  RETURN
    FALSE       OK.
    TRUE        Error.
*/

bool mysql_create_user(THD *thd, List <LEX_USER> &list)
{
  int result;
unknown's avatar
unknown committed
5181
  String wrong_users;
5182 5183 5184
  ulong sql_mode;
  LEX_USER *user_name;
  List_iterator <LEX_USER> user_list(list);
5185
  TABLE_LIST tables[GRANT_TABLES];
5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200
  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.
    */
5201
    if (handle_grant_data(tables, 0, user_name, NULL))
5202
    {
unknown's avatar
unknown committed
5203
      append_user(&wrong_users, user_name);
5204
      result= TRUE;
unknown's avatar
unknown committed
5205
      continue;
5206
    }
5207

5208
    sql_mode= thd->variables.sql_mode;
unknown's avatar
unknown committed
5209
    if (replace_user_table(thd, tables[0].table, *user_name, 0, 0, 1, 0))
5210
    {
unknown's avatar
unknown committed
5211
      append_user(&wrong_users, user_name);
5212 5213 5214 5215 5216 5217 5218 5219
      result= TRUE;
    }
  }

  VOID(pthread_mutex_unlock(&acl_cache->lock));
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
  if (result)
5220
    my_error(ER_CANNOT_USER, MYF(0), "CREATE USER", wrong_users.c_ptr_safe());
5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240
  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
5241
  String wrong_users;
5242 5243
  LEX_USER *user_name;
  List_iterator <LEX_USER> user_list(list);
5244
  TABLE_LIST tables[GRANT_TABLES];
5245 5246
  DBUG_ENTER("mysql_drop_user");

unknown's avatar
unknown committed
5247
  /* DROP USER may be skipped on replication client. */
5248 5249 5250 5251 5252 5253 5254 5255
  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++))
  {
5256
    if (handle_grant_data(tables, 1, user_name, NULL) <= 0)
5257
    {
unknown's avatar
unknown committed
5258
      append_user(&wrong_users, user_name);
5259
      result= TRUE;
5260
    }
5261
  }
5262

5263 5264 5265
  /* Rebuild 'acl_check_hosts' since 'acl_users' has been modified */
  rebuild_check_host();

5266 5267 5268 5269
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
  if (result)
unknown's avatar
unknown committed
5270
    my_error(ER_CANNOT_USER, MYF(0), "DROP USER", wrong_users.c_ptr_safe());
5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289
  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)
{
5290
  int result;
unknown's avatar
unknown committed
5291
  String wrong_users;
5292 5293 5294
  LEX_USER *user_from;
  LEX_USER *user_to;
  List_iterator <LEX_USER> user_list(list);
5295
  TABLE_LIST tables[GRANT_TABLES];
5296 5297
  DBUG_ENTER("mysql_rename_user");

unknown's avatar
unknown committed
5298
  /* RENAME USER may be skipped on replication client. */
5299 5300 5301 5302 5303 5304 5305 5306 5307
  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++;
5308
    DBUG_ASSERT(user_to != 0); /* Syntax enforces pairs of users. */
5309 5310 5311 5312 5313

    /*
      Search all in-memory structures and grant tables
      for a mention of the new user name.
    */
unknown's avatar
unknown committed
5314 5315
    if (handle_grant_data(tables, 0, user_to, NULL) ||
        handle_grant_data(tables, 0, user_from, user_to) <= 0)
5316
    {
unknown's avatar
unknown committed
5317
      append_user(&wrong_users, user_from);
5318 5319
      result= TRUE;
    }
5320
  }
5321

5322 5323 5324
  /* Rebuild 'acl_check_hosts' since 'acl_users' has been modified */
  rebuild_check_host();

5325 5326 5327 5328
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
  if (result)
5329
    my_error(ER_CANNOT_USER, MYF(0), "RENAME USER", wrong_users.c_ptr_safe());
5330 5331 5332
  DBUG_RETURN(result);
}

5333

5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347
/*
  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
5348
bool mysql_revoke_all(THD *thd,  List <LEX_USER> &list)
5349
{
5350
  uint counter, revoked, is_proc;
5351
  int result;
unknown's avatar
unknown committed
5352
  ACL_DB *acl_db;
5353
  TABLE_LIST tables[GRANT_TABLES];
5354 5355 5356
  DBUG_ENTER("mysql_revoke_all");

  if ((result= open_grant_tables(thd, tables)))
unknown's avatar
unknown committed
5357
    DBUG_RETURN(result != 1);
5358 5359 5360 5361 5362 5363 5364 5365

  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
5366
    if (!check_acl_user(lex_user, &counter))
5367
    {
unknown's avatar
unknown committed
5368 5369
      sql_print_error("REVOKE ALL PRIVILEGES, GRANT: User '%s'@'%s' does not "
                      "exists", lex_user->user.str, lex_user->host.str);
5370 5371 5372
      result= -1;
      continue;
    }
unknown's avatar
unknown committed
5373

5374
    if (replace_user_table(thd, tables[0].table,
5375
			   *lex_user, ~(ulong)0, 1, 0, 0))
5376 5377 5378 5379 5380 5381
    {
      result= -1;
      continue;
    }

    /* Remove db access privileges */
unknown's avatar
unknown committed
5382 5383 5384 5385 5386
    /*
      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
5387
    do
5388
    {
unknown's avatar
unknown committed
5389
      for (counter= 0, revoked= 0 ; counter < acl_dbs.elements ; )
5390
      {
unknown's avatar
unknown committed
5391
	const char *user,*host;
unknown's avatar
unknown committed
5392

unknown's avatar
unknown committed
5393 5394 5395 5396 5397
	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
5398

unknown's avatar
unknown committed
5399 5400 5401
	if (!strcmp(lex_user->user.str,user) &&
	    !my_strcasecmp(system_charset_info, lex_user->host.str, host))
	{
5402
	  if (!replace_db_table(tables[1].table, acl_db->db, *lex_user, ~(ulong)0, 1))
unknown's avatar
unknown committed
5403
	  {
unknown's avatar
unknown committed
5404 5405 5406 5407 5408
	    /*
	      Don't increment counter as replace_db_table deleted the
	      current element in acl_dbs.
	     */
	    revoked= 1;
unknown's avatar
unknown committed
5409 5410
	    continue;
	  }
unknown's avatar
unknown committed
5411
	  result= -1; // Something went wrong
unknown's avatar
unknown committed
5412
	}
unknown's avatar
unknown committed
5413
	counter++;
5414
      }
unknown's avatar
unknown committed
5415
    } while (revoked);
5416 5417

    /* Remove column access */
unknown's avatar
unknown committed
5418
    do
5419
    {
unknown's avatar
unknown committed
5420
      for (counter= 0, revoked= 0 ; counter < column_priv_hash.records ; )
5421
      {
unknown's avatar
unknown committed
5422 5423 5424 5425 5426
	const char *user,*host;
	GRANT_TABLE *grant_table= (GRANT_TABLE*)hash_element(&column_priv_hash,
							     counter);
	if (!(user=grant_table->user))
	  user= "";
5427
	if (!(host=grant_table->host.hostname))
unknown's avatar
unknown committed
5428
	  host= "";
unknown's avatar
unknown committed
5429

unknown's avatar
unknown committed
5430 5431
	if (!strcmp(lex_user->user.str,user) &&
	    !my_strcasecmp(system_charset_info, lex_user->host.str, host))
5432
	{
unknown's avatar
unknown committed
5433 5434 5435
	  if (replace_table_table(thd,grant_table,tables[2].table,*lex_user,
				  grant_table->db,
				  grant_table->tname,
5436
				  ~(ulong)0, 0, 1))
unknown's avatar
unknown committed
5437
	  {
unknown's avatar
unknown committed
5438
	    result= -1;
unknown's avatar
unknown committed
5439
	  }
unknown's avatar
unknown committed
5440
	  else
unknown's avatar
unknown committed
5441
	  {
unknown's avatar
unknown committed
5442
	    if (!grant_table->cols)
unknown's avatar
unknown committed
5443
	    {
unknown's avatar
unknown committed
5444 5445
	      revoked= 1;
	      continue;
unknown's avatar
unknown committed
5446
	    }
unknown's avatar
unknown committed
5447 5448
	    List<LEX_COLUMN> columns;
	    if (!replace_column_table(grant_table,tables[3].table, *lex_user,
unknown's avatar
unknown committed
5449 5450 5451
				      columns,
				      grant_table->db,
				      grant_table->tname,
5452
				      ~(ulong)0, 1))
unknown's avatar
unknown committed
5453
	    {
unknown's avatar
unknown committed
5454
	      revoked= 1;
5455
	      continue;
unknown's avatar
unknown committed
5456
	    }
5457
	    result= -1;
unknown's avatar
unknown committed
5458
	  }
5459
	}
unknown's avatar
unknown committed
5460
	counter++;
5461
      }
unknown's avatar
unknown committed
5462
    } while (revoked);
5463 5464

    /* Remove procedure access */
5465 5466 5467
    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 ; )
5468 5469
      {
	const char *user,*host;
5470
	GRANT_NAME *grant_proc= (GRANT_NAME*) hash_element(hash, counter);
5471 5472
	if (!(user=grant_proc->user))
	  user= "";
5473
	if (!(host=grant_proc->host.hostname))
5474 5475 5476 5477 5478
	  host= "";

	if (!strcmp(lex_user->user.str,user) &&
	    !my_strcasecmp(system_charset_info, lex_user->host.str, host))
	{
5479
	  if (!replace_routine_table(thd,grant_proc,tables[4].table,*lex_user,
5480 5481
				  grant_proc->db,
				  grant_proc->tname,
5482
                                  is_proc,
unknown's avatar
unknown committed
5483
				  ~(ulong)0, 1))
5484 5485 5486 5487 5488 5489 5490 5491 5492
	  {
	    revoked= 1;
	    continue;
	  }
	  result= -1;	// Something went wrong
	}
	counter++;
      }
    } while (revoked);
5493
  }
unknown's avatar
unknown committed
5494

5495 5496 5497
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
unknown's avatar
unknown committed
5498

5499
  if (result)
unknown's avatar
unknown committed
5500
    my_message(ER_REVOKE_GRANTS, ER(ER_REVOKE_GRANTS), MYF(0));
unknown's avatar
unknown committed
5501

5502 5503
  DBUG_RETURN(result);
}
unknown's avatar
unknown committed
5504

5505

5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519
/*
  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.
*/

5520 5521
bool sp_revoke_privileges(THD *thd, const char *sp_db, const char *sp_name,
                          bool is_proc)
5522 5523 5524 5525
{
  uint counter, revoked;
  int result;
  TABLE_LIST tables[GRANT_TABLES];
5526
  HASH *hash= is_proc ? &proc_priv_hash : &func_priv_hash;
5527 5528 5529 5530 5531 5532 5533 5534 5535
  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 */
5536 5537
  do
  {
5538
    for (counter= 0, revoked= 0 ; counter < hash->records ; )
5539
    {
5540
      GRANT_NAME *grant_proc= (GRANT_NAME*) hash_element(hash, counter);
5541 5542 5543 5544 5545 5546
      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);
5547 5548
	lex_user.host.str= grant_proc->host.hostname;
	lex_user.host.length= strlen(grant_proc->host.hostname);
5549 5550
	if (!replace_routine_table(thd,grant_proc,tables[4].table,lex_user,
				   grant_proc->db, grant_proc->tname,
unknown's avatar
unknown committed
5551
                                   is_proc, ~(ulong)0, 1))
5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586
	{
	  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.
*/

5587 5588
bool sp_grant_privileges(THD *thd, const char *sp_db, const char *sp_name,
                         bool is_proc)
5589
{
5590
  Security_context *sctx= thd->security_ctx;
5591 5592 5593 5594
  LEX_USER *combo;
  TABLE_LIST tables[1];
  List<LEX_USER> user_list;
  bool result;
5595
  DBUG_ENTER("sp_grant_privileges");
5596 5597 5598 5599

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

5600
  combo->user.str= sctx->user;
5601
  
5602 5603 5604
  if (!find_acl_user(combo->host.str=(char*)sctx->host_or_ip, combo->user.str,
                     FALSE) &&
      !find_acl_user(combo->host.str=(char*)sctx->host, combo->user.str,
unknown's avatar
unknown committed
5605
                     FALSE) &&
5606
      !find_acl_user(combo->host.str=(char*)sctx->ip, combo->user.str,
unknown's avatar
unknown committed
5607 5608
                     FALSE) &&
      !find_acl_user(combo->host.str=(char*)"%", combo->user.str, FALSE))
5609 5610 5611 5612 5613 5614
    DBUG_RETURN(TRUE);

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

  tables->db= (char*)sp_db;
5615
  tables->table_name= tables->alias= (char*)sp_name;
5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627
  
  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;
5628
  bzero((char*) &thd->lex->mqh, sizeof(thd->lex->mqh));
5629

5630
  result= mysql_routine_grant(thd, tables, is_proc, user_list,
5631 5632 5633 5634 5635
  				DEFAULT_CREATE_PROC_ACLS, 0, 1);
  DBUG_RETURN(result);
}


unknown's avatar
unknown committed
5636
/*****************************************************************************
unknown's avatar
unknown committed
5637
  Instantiate used templates
unknown's avatar
unknown committed
5638 5639
*****************************************************************************/

5640
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
unknown's avatar
unknown committed
5641 5642 5643 5644 5645
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
5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692

#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');
}

5693 5694 5695 5696 5697 5698 5699 5700

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;
5701
  restore_record(table, s->default_values);
5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722
  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;
5723
  bool no_global_access= check_access(thd, SELECT_ACL, "mysql",0,1,1,0);
5724
  char *curr_host= thd->security_ctx->priv_host_name();
5725
  DBUG_ENTER("fill_schema_user_privileges");
5726

5727 5728 5729 5730 5731 5732 5733 5734
  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= "";
5735 5736

    if (no_global_access &&
5737
        (strcmp(thd->security_ctx->priv_user, user) ||
5738 5739 5740
         my_strcasecmp(system_charset_info, curr_host, host)))
      continue;
      
5741 5742 5743 5744 5745 5746
    want_access= acl_user->access;
    if (!(want_access & GRANT_ACL))
      is_grantable= "NO";

    strxmov(buff,"'",user,"'@'",host,"'",NullS);
    if (!(want_access & ~GRANT_ACL))
5747 5748
      update_schema_privilege(table, buff, 0, 0, 0, 0,
                              STRING_WITH_LEN("USAGE"), is_grantable);
5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762
    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);
5763 5764 5765
#else
  return(0);
#endif
5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776
}


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;
5777
  bool no_global_access= check_access(thd, SELECT_ACL, "mysql",0,1,1,0);
5778
  char *curr_host= thd->security_ctx->priv_host_name();
5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790
  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= "";

5791
    if (no_global_access &&
5792
        (strcmp(thd->security_ctx->priv_user, user) ||
5793 5794 5795
         my_strcasecmp(system_charset_info, curr_host, host)))
      continue;

5796 5797 5798 5799 5800 5801 5802 5803 5804 5805
    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,
5806
                                0, STRING_WITH_LEN("USAGE"), is_grantable);
5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819
      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);
5820 5821 5822
#else
  return (0);
#endif
5823 5824 5825 5826 5827 5828 5829 5830 5831
}


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;
5832
  bool no_global_access= check_access(thd, SELECT_ACL, "mysql",0,1,1,0);
5833
  char *curr_host= thd->security_ctx->priv_host_name();
5834 5835 5836 5837 5838 5839 5840 5841 5842
  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= "";
5843 5844

    if (no_global_access &&
5845
        (strcmp(thd->security_ctx->priv_user, user) ||
5846 5847 5848 5849
         my_strcasecmp(system_charset_info, curr_host,
                       grant_table->host.hostname)))
      continue;

5850
    ulong table_access= grant_table->privs;
5851
    if (table_access)
5852 5853
    {
      ulong test_access= table_access & ~GRANT_ACL;
unknown's avatar
unknown committed
5854 5855 5856 5857
      /*
        We should skip 'usage' privilege on table if
        we have any privileges on column(s) of this table
      */
5858 5859
      if (!test_access && grant_table->cols)
        continue;
5860 5861 5862
      if (!(table_access & GRANT_ACL))
        is_grantable= "NO";

5863
      strxmov(buff,"'",user,"'@'",grant_table->host.hostname,"'",NullS);
5864 5865
      if (!test_access)
        update_schema_privilege(table, buff, grant_table->db, grant_table->tname,
5866
                                0, 0, STRING_WITH_LEN("USAGE"), is_grantable);
5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881
      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);
5882 5883 5884
#else
  return (0);
#endif
5885 5886 5887 5888 5889 5890 5891 5892 5893
}


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;
5894
  bool no_global_access= check_access(thd, SELECT_ACL, "mysql",0,1,1,0);
5895
  char *curr_host= thd->security_ctx->priv_host_name();
5896 5897 5898 5899 5900 5901 5902 5903 5904
  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= "";
5905 5906

    if (no_global_access &&
5907
        (strcmp(thd->security_ctx->priv_user, user) ||
5908 5909 5910 5911
         my_strcasecmp(system_charset_info, curr_host,
                       grant_table->host.hostname)))
      continue;

5912 5913 5914
    ulong table_access= grant_table->cols;
    if (table_access != 0)
    {
unknown's avatar
unknown committed
5915
      if (!(grant_table->privs & GRANT_ACL))
5916 5917
        is_grantable= "NO";

unknown's avatar
unknown committed
5918
      ulong test_access= table_access & ~GRANT_ACL;
5919
      strxmov(buff,"'",user,"'@'",grant_table->host.hostname,"'",NullS);
5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949
      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);
5950 5951 5952
#else
  return (0);
#endif
5953 5954 5955
}


unknown's avatar
VIEW  
unknown committed
5956 5957 5958 5959 5960
#ifndef NO_EMBEDDED_ACCESS_CHECKS
/*
  fill effective privileges for table

  SYNOPSIS
5961 5962
    fill_effective_table_privileges()
    thd     thread handler
unknown's avatar
VIEW  
unknown committed
5963 5964 5965 5966 5967 5968 5969 5970
    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)
{
5971
  Security_context *sctx= thd->security_ctx;
5972 5973 5974 5975 5976
  DBUG_ENTER("fill_effective_table_privileges");
  DBUG_PRINT("enter", ("Host: '%s', Ip: '%s', User: '%s', table: `%s`.`%s`",
                       sctx->priv_host, (sctx->ip ? sctx->ip : "(NULL)"),
                       (sctx->priv_user ? sctx->priv_user : "(NULL)"),
                       db, table));
5977 5978 5979
  /* --skip-grants */
  if (!initialized)
  {
5980
    DBUG_PRINT("info", ("skip grants"));
5981
    grant->privilege= ~NO_ACCESS;             // everything is allowed
5982 5983
    DBUG_PRINT("info", ("privilege 0x%lx", grant->privilege));
    DBUG_VOID_RETURN;
5984 5985
  }

unknown's avatar
VIEW  
unknown committed
5986
  /* global privileges */
5987
  grant->privilege= sctx->master_access;
5988

5989
  if (!sctx->priv_user)
5990 5991 5992 5993
  {
    DBUG_PRINT("info", ("privilege 0x%lx", grant->privilege));
    DBUG_VOID_RETURN;                         // it is slave
  }
5994

5995
  /* db privileges */
5996
  grant->privilege|= acl_get(sctx->host, sctx->ip, sctx->priv_user, db, 0);
5997

5998
  if (!grant_option)
5999 6000 6001 6002
  {
    DBUG_PRINT("info", ("privilege 0x%lx", grant->privilege));
    DBUG_VOID_RETURN;
  }
6003

unknown's avatar
VIEW  
unknown committed
6004 6005 6006
  /* table privileges */
  if (grant->version != grant_version)
  {
6007
    rw_rdlock(&LOCK_grant);
unknown's avatar
VIEW  
unknown committed
6008
    grant->grant_table=
6009 6010
      table_hash_search(sctx->host, sctx->ip, db,
			sctx->priv_user,
unknown's avatar
VIEW  
unknown committed
6011 6012
			table, 0);              /* purecov: inspected */
    grant->version= grant_version;              /* purecov: inspected */
6013
    rw_unlock(&LOCK_grant);
unknown's avatar
VIEW  
unknown committed
6014 6015 6016 6017 6018
  }
  if (grant->grant_table != 0)
  {
    grant->privilege|= grant->grant_table->privs;
  }
6019 6020
  DBUG_PRINT("info", ("privilege 0x%lx", grant->privilege));
  DBUG_VOID_RETURN;
unknown's avatar
VIEW  
unknown committed
6021
}
6022 6023 6024 6025 6026 6027 6028

#else /* NO_EMBEDDED_ACCESS_CHECKS */

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

unknown's avatar
unknown committed
6029 6030
bool check_routine_level_acl(THD *thd, const char *db, const char *name,
                             bool is_proc)
6031 6032 6033 6034
{
  return FALSE;
}

unknown's avatar
VIEW  
unknown committed
6035
#endif