sql_acl.cc 157 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
SCRUM:  
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;
unknown's avatar
unknown committed
64 65 66
static DYNAMIC_ARRAY acl_wild_hosts;
static hash_filo *acl_cache;
static uint grant_version=0;
unknown's avatar
unknown committed
67
static uint priv_version=0; /* Version of priv tables. incremented by acl_init */
unknown's avatar
unknown committed
68
static ulong get_access(TABLE *form,uint fieldnr, uint *next_field=0);
unknown's avatar
unknown committed
69 70 71 72 73
static int acl_compare(ACL_ACCESS *a,ACL_ACCESS *b);
static ulong get_sort(uint count,...);
static void init_check_host(void);
static ACL_USER *find_acl_user(const char *host, const char *user);
static bool update_user_table(THD *thd, const char *host, const char *user,
74
			      const char *new_password, uint new_password_len);
unknown's avatar
unknown committed
75
static void update_hostname(acl_host_and_ip *host, const char *hostname);
76
static bool compare_hostname(const acl_host_and_ip *host,const char *hostname,
unknown's avatar
unknown committed
77 78
			     const char *ip);

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

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
/*
  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;
}

120

121 122 123 124 125
/*
  Read grant privileges from the privilege tables in the 'mysql' database.

  SYNOPSIS
    acl_init()
unknown's avatar
unknown committed
126
    thd				Thread handler
127 128 129 130 131 132 133 134
    dont_read_acl_tables	Set to 1 if run with --skip-grant

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


unknown's avatar
unknown committed
135
my_bool acl_init(THD *org_thd, bool dont_read_acl_tables)
unknown's avatar
unknown committed
136
{
unknown's avatar
unknown committed
137
  THD  *thd;
unknown's avatar
unknown committed
138 139 140
  TABLE_LIST tables[3];
  TABLE *table;
  READ_RECORD read_record_info;
141
  my_bool return_val=1;
unknown's avatar
SCRUM  
unknown committed
142
  bool check_no_resolve= specialflag & SPECIAL_NO_RESOLVE;
143
  char tmp_name[NAME_LEN+1];
unknown's avatar
SCRUM  
unknown committed
144

unknown's avatar
unknown committed
145 146 147 148 149
  DBUG_ENTER("acl_init");

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

156
  priv_version++; /* Privileges updated */
157
  mysql_proc_table_exists= 1;			// Assume mysql.proc exists
unknown's avatar
unknown committed
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 165
  thd->store_globals();

unknown's avatar
unknown committed
166
  acl_cache->clear(1);				// Clear locked hostname cache
unknown's avatar
unknown committed
167 168
  thd->db= my_strdup("mysql",MYF(0));
  thd->db_length=5;				// Safety
unknown's avatar
unknown committed
169
  bzero((char*) &tables,sizeof(tables));
170 171 172
  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";
unknown's avatar
VIEW  
unknown committed
173 174
  tables[0].next_local= tables[0].next_global= tables+1;
  tables[1].next_local= tables[1].next_global= tables+2;
unknown's avatar
unknown committed
175 176 177
  tables[0].lock_type=tables[1].lock_type=tables[2].lock_type=TL_READ;
  tables[0].db=tables[1].db=tables[2].db=thd->db;

178
  if (simple_open_n_lock_tables(thd, tables))
unknown's avatar
unknown committed
179
  {
180
    sql_print_error("Fatal error: Can't open and lock privilege tables: %s",
unknown's avatar
unknown committed
181
		    thd->net.last_error);
182
    goto end;
unknown's avatar
unknown committed
183
  }
184
  init_sql_alloc(&mem, ACL_ALLOC_BLOCK_SIZE, 0);
unknown's avatar
unknown committed
185
  init_read_record(&read_record_info,thd,table= tables[0].table,NULL,1,0);
186
  VOID(my_init_dynamic_array(&acl_hosts,sizeof(ACL_HOST),20,50));
unknown's avatar
unknown committed
187 188 189
  while (!(read_record_info.read_record(&read_record_info)))
  {
    ACL_HOST host;
190 191
    update_hostname(&host.host,get_field(&mem, table->field[0]));
    host.db=	 get_field(&mem, table->field[1]);
192 193 194
    if (lower_case_table_names)
    {
      /*
195 196
        convert db to lower case and give a warning if the db wasn't
        already in lower case
197
      */
198 199
      (void) strmov(tmp_name, host.db);
      my_casedn_str(files_charset_info, host.db);
200 201 202
      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 "
203 204
                          "lower_case_table_names is set. It will not be "
                          "possible to remove this privilege using REVOKE.",
205 206
                          host.host.hostname, host.db);
    }
unknown's avatar
unknown committed
207 208
    host.access= get_access(table,2);
    host.access= fix_rights_for_db(host.access);
209
    host.sort=	 get_sort(2,host.host.hostname,host.db);
unknown's avatar
SCRUM  
unknown committed
210 211
    if (check_no_resolve && hostname_requires_resolving(host.host.hostname))
    {
unknown's avatar
unknown committed
212
      sql_print_warning("'host' entry '%s|%s' "
unknown's avatar
SCRUM  
unknown committed
213
		      "ignored in --skip-name-resolve mode.",
unknown's avatar
SCRUM  
unknown committed
214 215 216
		      host.host.hostname, host.db, host.host.hostname);
      continue;
    }
unknown's avatar
unknown committed
217
#ifndef TO_BE_REMOVED
218
    if (table->s->fields == 8)
unknown's avatar
unknown committed
219 220
    {						// Without grant
      if (host.access & CREATE_ACL)
221
	host.access|=REFERENCES_ACL | INDEX_ACL | ALTER_ACL | CREATE_TMP_ACL;
unknown's avatar
unknown committed
222 223 224 225 226 227 228 229 230 231
    }
#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);
232
  VOID(my_init_dynamic_array(&acl_users,sizeof(ACL_USER),50,100));
233
  if (table->field[2]->field_length < SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
unknown's avatar
unknown committed
234
  {
235 236 237
    sql_print_error("Fatal error: mysql.user table is damaged or in "
                    "unsupported 3.20 format.");
    goto end;
unknown's avatar
unknown committed
238 239
  }

240
  DBUG_PRINT("info",("user table fields: %d, password length: %d",
241
		     table->s->fields, table->field[2]->field_length));
242 243 244
  
  pthread_mutex_lock(&LOCK_global_system_variables);
  if (table->field[2]->field_length < SCRAMBLED_PASSWORD_CHAR_LENGTH)
245
  {
246 247 248 249 250 251 252 253 254 255 256 257 258 259
    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);
260 261 262
      sql_print_warning("mysql.user table is not updated to new password format; "
                        "Disabling new password usage until "
                        "mysql_fix_privilege_tables is run");
263 264 265 266
    }
    thd->variables.old_passwords= 1;
  }
  else
267
  {
268 269
    sys_old_passwords.after_update= 0;
    pthread_mutex_unlock(&LOCK_global_system_variables);
270 271
  }

unknown's avatar
unknown committed
272 273 274 275
  allow_all_hosts=0;
  while (!(read_record_info.read_record(&read_record_info)))
  {
    ACL_USER user;
276 277
    update_hostname(&user.host, get_field(&mem, table->field[0]));
    user.user= get_field(&mem, table->field[1]);
unknown's avatar
SCRUM  
unknown committed
278 279
    if (check_no_resolve && hostname_requires_resolving(user.host.hostname))
    {
unknown's avatar
unknown committed
280 281
      sql_print_warning("'user' entry '%s@%s' "
                        "ignored in --skip-name-resolve mode.",
unknown's avatar
SCRUM  
unknown committed
282 283 284 285
		      user.user, user.host.hostname, user.host.hostname);
      continue;
    }

286 287 288 289
    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
290
    {
291 292
      switch (password_len) {
      case 45: /* 4.1: to be removed */
unknown's avatar
unknown committed
293 294 295 296 297
        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 : "");
298 299
        break;
      default:
unknown's avatar
unknown committed
300 301 302
        sql_print_warning("Found invalid password for user: '%s@%s'; "
                          "Ignoring user", user.user ? user.user : "",
                           user.host.hostname ? user.host.hostname : "");
303 304
        break;
      }
unknown's avatar
unknown committed
305
    }
306
    else                                        // password is correct
unknown's avatar
unknown committed
307
    {
unknown's avatar
unknown committed
308 309
      uint next_field;
      user.access= get_access(table,3,&next_field) & GLOBAL_ACLS;
310 311 312 313
      /*
        if it is pre 5.0.1 privilege table then map CREATE privilege on
        CREATE VIEW & SHOW VIEW privileges
      */
314
      if (table->s->fields <= 31 && (user.access & CREATE_ACL))
315
        user.access|= (CREATE_VIEW_ACL | SHOW_VIEW_ACL);
316 317 318 319 320

      /*
        if it is pre 5.0.2 privilege table then map CREATE/ALTER privilege on
        CREATE PROCEDURE & ALTER PROCEDURE privileges
      */
321
      if (table->s->fields <= 33 && (user.access & CREATE_ACL))
322
        user.access|= CREATE_PROC_ACL;
323
      if (table->s->fields <= 33 && (user.access & ALTER_ACL))
324 325
        user.access|= ALTER_PROC_ACL;

326 327 328
      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
329

330 331
      /* Starting from 4.0.2 we have more fields */
      if (table->s->fields >= 31)
332
      {
unknown's avatar
unknown committed
333
        char *ssl_type=get_field(&mem, table->field[next_field++]);
334 335 336 337 338 339 340 341 342
        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
343 344 345
        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++]);
346

unknown's avatar
unknown committed
347 348 349 350 351
        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++]);
352
        user.user_resource.conn_per_hour= ptr ? atoi(ptr) : 0;
353
        if (user.user_resource.questions || user.user_resource.updates ||
354
            user.user_resource.conn_per_hour)
355
          mqh_used=1;
356

357
        if (table->s->fields >= 36)
358 359 360 361 362 363 364
        {
          /* 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;
365
      }
366 367 368
      else
      {
        user.ssl_type=SSL_TYPE_NONE;
369
        bzero((char *)&(user.user_resource),sizeof(user.user_resource));
unknown's avatar
unknown committed
370
#ifndef TO_BE_REMOVED
371
        if (table->s->fields <= 13)
372 373 374 375 376 377 378 379 380 381
        {						// 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
382
#endif
383 384 385 386 387
      }
      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
388
    }
unknown's avatar
unknown committed
389 390 391 392 393
  }
  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
394

unknown's avatar
unknown committed
395
  init_read_record(&read_record_info,thd,table=tables[2].table,NULL,1,0);
396
  VOID(my_init_dynamic_array(&acl_dbs,sizeof(ACL_DB),50,100));
unknown's avatar
unknown committed
397 398 399
  while (!(read_record_info.read_record(&read_record_info)))
  {
    ACL_DB db;
400 401
    update_hostname(&db.host,get_field(&mem, table->field[0]));
    db.db=get_field(&mem, table->field[1]);
402 403
    if (!db.db)
    {
unknown's avatar
unknown committed
404
      sql_print_warning("Found an entry in the 'db' table with empty database name; Skipped");
405
      continue;
406
    }
407
    db.user=get_field(&mem, table->field[2]);
unknown's avatar
SCRUM  
unknown committed
408 409
    if (check_no_resolve && hostname_requires_resolving(db.host.hostname))
    {
unknown's avatar
unknown committed
410 411 412
      sql_print_warning("'db' entry '%s %s@%s' "
		        "ignored in --skip-name-resolve mode.",
		        db.db, db.user, db.host.hostname, db.host.hostname);
unknown's avatar
SCRUM  
unknown committed
413 414
      continue;
    }
unknown's avatar
unknown committed
415 416
    db.access=get_access(table,3);
    db.access=fix_rights_for_db(db.access);
417 418 419
    if (lower_case_table_names)
    {
      /*
420 421
        convert db to lower case and give a warning if the db wasn't
        already in lower case
422 423
      */
      (void)strmov(tmp_name, db.db);
424
      my_casedn_str(files_charset_info, db.db);
425 426 427 428
      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 "
429 430
                          "lower_case_table_names is set. It will not be "
                          "possible to remove this privilege using REVOKE.",
431 432 433
		          db.db, db.user, db.host.hostname, db.host.hostname);
      }
    }
unknown's avatar
unknown committed
434 435
    db.sort=get_sort(3,db.host.hostname,db.db,db.user);
#ifndef TO_BE_REMOVED
436
    if (table->s->fields <=  9)
unknown's avatar
unknown committed
437 438 439 440 441 442 443 444 445 446 447 448 449
    {						// 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();

450
  initialized=1;
unknown's avatar
unknown committed
451
  thd->version--;				// Force close to free memory
452 453 454
  return_val=0;

end:
unknown's avatar
unknown committed
455 456
  close_thread_tables(thd);
  delete thd;
457 458
  if (org_thd)
    org_thd->store_globals();			/* purecov: inspected */
unknown's avatar
unknown committed
459 460 461 462 463
  else
  {
    /* Remember that we don't have a THD */
    my_pthread_setspecific_ptr(THR_THD,  0);
  }
464
  DBUG_RETURN(return_val);
unknown's avatar
unknown committed
465 466 467 468 469
}


void acl_free(bool end)
{
470
  free_root(&mem,MYF(0));
unknown's avatar
unknown committed
471 472 473 474 475 476 477 478 479 480 481 482 483 484
  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;
  }
}

485 486 487 488 489 490

/*
  Forget current privileges and read new privileges from the privilege tables

  SYNOPSIS
    acl_reload()
unknown's avatar
unknown committed
491 492
    thd			Thread handle. Note that this may be NULL if we refresh
			because we got a signal    
493
*/
unknown's avatar
unknown committed
494

495
void acl_reload(THD *thd)
unknown's avatar
unknown committed
496 497 498 499 500 501
{
  DYNAMIC_ARRAY old_acl_hosts,old_acl_users,old_acl_dbs;
  MEM_ROOT old_mem;
  bool old_initialized;
  DBUG_ENTER("acl_reload");

502
  if (thd && thd->locked_tables)
unknown's avatar
unknown committed
503
  {					// Can't have locked tables here
504 505 506
    thd->lock=thd->locked_tables;
    thd->locked_tables=0;
    close_thread_tables(thd);
unknown's avatar
unknown committed
507 508 509 510 511 512 513 514 515 516 517
  }
  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);

unknown's avatar
unknown committed
518
  if (acl_init(thd, 0))
unknown's avatar
unknown committed
519
  {					// Error. Revert to old list
520
    DBUG_PRINT("error",("Reverting to old privileges"));
521
    acl_free();				/* purecov: inspected */
unknown's avatar
unknown committed
522 523 524 525 526 527 528 529
    acl_hosts=old_acl_hosts;
    acl_users=old_acl_users;
    acl_dbs=old_acl_dbs;
    mem=old_mem;
    init_check_host();
  }
  else
  {
530
    free_root(&old_mem,MYF(0));
unknown's avatar
unknown committed
531 532 533 534 535 536 537 538 539 540
    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));
  DBUG_VOID_RETURN;
}


unknown's avatar
unknown committed
541 542
/*
  Get all access bits from table after fieldnr
unknown's avatar
unknown committed
543 544

  IMPLEMENTATION
unknown's avatar
unknown committed
545 546
  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
547 548 549 550 551 552 553 554 555 556 557

  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
558
*/
unknown's avatar
unknown committed
559

unknown's avatar
unknown committed
560
static ulong get_access(TABLE *form, uint fieldnr, uint *next_field)
unknown's avatar
unknown committed
561
{
unknown's avatar
unknown committed
562
  ulong access_bits=0,bit;
unknown's avatar
unknown committed
563
  char buff[2];
unknown's avatar
unknown committed
564
  String res(buff,sizeof(buff),&my_charset_latin1);
unknown's avatar
unknown committed
565 566
  Field **pos;

unknown's avatar
unknown committed
567 568 569
  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
570
       pos++, fieldnr++, bit<<=1)
unknown's avatar
unknown committed
571
  {
572
    (*pos)->val_str(&res);
unknown's avatar
unknown committed
573
    if (my_toupper(&my_charset_latin1, res[0]) == 'Y')
unknown's avatar
unknown committed
574
      access_bits|= bit;
unknown's avatar
unknown committed
575
  }
unknown's avatar
unknown committed
576 577
  if (next_field)
    *next_field=fieldnr;
unknown's avatar
unknown committed
578 579 580 581 582
  return access_bits;
}


/*
unknown's avatar
unknown committed
583 584 585 586 587
  Return a number which, if sorted 'desc', puts strings in this order:
    no wildcards
    wildcards
    empty string
*/
unknown's avatar
unknown committed
588 589 590 591 592 593 594

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

595 596 597
  /* Should not use this function with more than 4 arguments for compare. */
  DBUG_ASSERT(count <= 4);

unknown's avatar
unknown committed
598 599
  while (count--)
  {
600 601 602
    char *start, *str= va_arg(args,char*);
    uint chars= 0;
    uint wild_pos= 0;           /* first wildcard position */
unknown's avatar
unknown committed
603

unknown's avatar
unknown committed
604
    if ((start= str))
unknown's avatar
unknown committed
605 606 607 608
    {
      for (; *str ; str++)
      {
	if (*str == wild_many || *str == wild_one || *str == wild_prefix)
609
        {
unknown's avatar
unknown committed
610
          wild_pos= (uint) (str - start) + 1;
611 612
          break;
        }
unknown's avatar
unknown committed
613
        chars= 128;                             // Marker that chars existed
unknown's avatar
unknown committed
614 615
      }
    }
unknown's avatar
unknown committed
616
    sort= (sort << 8) + (wild_pos ? min(wild_pos, 127) : chars);
unknown's avatar
unknown committed
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
  }
  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;
}

632

633
/*
unknown's avatar
unknown committed
634 635
  Seek ACL entry for a user, check password, SSL cypher, and if
  everything is OK, update THD user data and USER_RESOURCES struct.
636

unknown's avatar
unknown committed
637 638 639 640
  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
641

642
  SYNOPSIS
643 644 645 646 647 648
    acl_getroot()
    thd         thread handle. If all checks are OK,
                thd->priv_user, thd->master_access are updated.
                thd->host, thd->ip, thd->user are used for checks.
    mqh         user resources; on success mqh is reset, else
                unchanged
649
    passwd      scrambled & crypted password, received from client
650 651 652 653 654 655 656
                (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
657
  RETURN VALUE
658 659
    0  success: thd->priv_user, thd->priv_host, thd->master_access, mqh are
       updated
660
    1  user not found or authentication failure
unknown's avatar
unknown committed
661
    2  user found, has long (4.1.1) salt, but passwd is in old (3.23) format.
662
   -1  user found, has short (3.23) salt, but passwd is in new (4.1.1) format.
unknown's avatar
unknown committed
663 664
*/

665 666
int acl_getroot(THD *thd, USER_RESOURCES  *mqh,
                const char *passwd, uint passwd_len)
unknown's avatar
unknown committed
667
{
unknown's avatar
merge  
unknown committed
668 669 670
  ulong user_access= NO_ACCESS;
  int res= 1;
  ACL_USER *acl_user= 0;
671
  DBUG_ENTER("acl_getroot");
unknown's avatar
unknown committed
672 673

  if (!initialized)
674
  {
675 676 677 678 679 680
    /* 
      here if mysqld's been started with --skip-grant-tables option.
    */
    thd->priv_user= (char *) "";                // privileges for
    *thd->priv_host= '\0';                      // the user are unknown
    thd->master_access= ~NO_ACCESS;             // everything is allowed
unknown's avatar
merge  
unknown committed
681
    bzero((char*) mqh, sizeof(*mqh));
682
    DBUG_RETURN(0);
683
  }
684

unknown's avatar
unknown committed
685
  VOID(pthread_mutex_lock(&acl_cache->lock));
unknown's avatar
unknown committed
686

unknown's avatar
unknown committed
687
  /*
688 689 690
    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
691
  */
unknown's avatar
unknown committed
692

693
  for (uint i=0 ; i < acl_users.elements ; i++)
694
  {
unknown's avatar
unknown committed
695 696
    ACL_USER *acl_user_tmp= dynamic_element(&acl_users,i,ACL_USER*);
    if (!acl_user_tmp->user || !strcmp(thd->user, acl_user_tmp->user))
unknown's avatar
unknown committed
697
    {
unknown's avatar
unknown committed
698
      if (compare_hostname(&acl_user_tmp->host, thd->host, thd->ip))
unknown's avatar
unknown committed
699
      {
700
        /* check password: it should be empty or valid */
unknown's avatar
unknown committed
701
        if (passwd_len == acl_user_tmp->salt_len)
unknown's avatar
unknown committed
702
        {
unknown's avatar
unknown committed
703
          if (acl_user_tmp->salt_len == 0 ||
unknown's avatar
cleanup  
unknown committed
704 705
              (acl_user_tmp->salt_len == SCRAMBLE_LENGTH ?
              check_scramble(passwd, thd->scramble, acl_user_tmp->salt) :
706
              check_scramble_323(passwd, thd->scramble,
unknown's avatar
cleanup  
unknown committed
707
                                 (ulong *) acl_user_tmp->salt)) == 0)
708
          {
unknown's avatar
unknown committed
709
            acl_user= acl_user_tmp;
710 711
            res= 0;
          }
unknown's avatar
unknown committed
712
        }
713
        else if (passwd_len == SCRAMBLE_LENGTH &&
unknown's avatar
unknown committed
714
                 acl_user_tmp->salt_len == SCRAMBLE_LENGTH_323)
715
          res= -1;
unknown's avatar
unknown committed
716
        else if (passwd_len == SCRAMBLE_LENGTH_323 &&
unknown's avatar
unknown committed
717
                 acl_user_tmp->salt_len == SCRAMBLE_LENGTH)
unknown's avatar
unknown committed
718
          res= 2;
719 720
        /* linear search complete: */
        break;
unknown's avatar
unknown committed
721
      }
unknown's avatar
unknown committed
722
    }
723
  }
724 725 726 727
  /*
    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
728 729 730

  if (acl_user)
  {
731
    /* OK. User found and password checked continue validation */
732
#ifdef HAVE_OPENSSL
unknown's avatar
unknown committed
733
    Vio *vio=thd->net.vio;
unknown's avatar
unknown committed
734
    SSL *ssl= (SSL*) vio->ssl_arg;
735
#endif
unknown's avatar
merge  
unknown committed
736

737
    /*
unknown's avatar
unknown committed
738
      At this point we know that user is allowed to connect
739 740 741 742 743 744
      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
745 746
    case SSL_TYPE_NONE:				// SSL is not required
      user_access= acl_user->access;
747
      break;
748
#ifdef HAVE_OPENSSL
unknown's avatar
merge  
unknown committed
749
    case SSL_TYPE_ANY:				// Any kind of SSL is ok
750
      if (vio_type(vio) == VIO_TYPE_SSL)
unknown's avatar
merge  
unknown committed
751
	user_access= acl_user->access;
752 753 754 755 756
      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
757

unknown's avatar
unknown committed
758 759
	We need to check for absence of SSL because without SSL
	we should reject connection.
760
      */
unknown's avatar
unknown committed
761
      if (vio_type(vio) == VIO_TYPE_SSL &&
unknown's avatar
unknown committed
762 763
	  SSL_get_verify_result(ssl) == X509_V_OK &&
	  SSL_get_peer_certificate(ssl))
unknown's avatar
merge  
unknown committed
764
	user_access= acl_user->access;
765 766 767 768 769 770 771 772
      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
773
      X509 *cert;
unknown's avatar
unknown committed
774
      if (vio_type(vio) != VIO_TYPE_SSL ||
unknown's avatar
unknown committed
775
	  SSL_get_verify_result(ssl) != X509_V_OK)
unknown's avatar
unknown committed
776
	break;
777
      if (acl_user->ssl_cipher)
unknown's avatar
unknown committed
778
      {
779
	DBUG_PRINT("info",("comparing ciphers: '%s' and '%s'",
unknown's avatar
unknown committed
780 781
			   acl_user->ssl_cipher,SSL_get_cipher(ssl)));
	if (!strcmp(acl_user->ssl_cipher,SSL_get_cipher(ssl)))
unknown's avatar
merge  
unknown committed
782
	  user_access= acl_user->access;
783 784
	else
	{
unknown's avatar
unknown committed
785
	  if (global_system_variables.log_warnings)
unknown's avatar
unknown committed
786 787 788
	    sql_print_information("X509 ciphers mismatch: should be '%s' but is '%s'",
			      acl_user->ssl_cipher,
			      SSL_get_cipher(ssl));
789 790
	  break;
	}
unknown's avatar
unknown committed
791
      }
792 793
      /* Prepare certificate (if exists) */
      DBUG_PRINT("info",("checkpoint 1"));
unknown's avatar
unknown committed
794 795 796 797 798
      if (!(cert= SSL_get_peer_certificate(ssl)))
      {
	user_access=NO_ACCESS;
	break;
      }
799
      DBUG_PRINT("info",("checkpoint 2"));
800
      /* If X509 issuer is specified, we check it... */
801
      if (acl_user->x509_issuer)
unknown's avatar
unknown committed
802
      {
unknown's avatar
unknown committed
803
        DBUG_PRINT("info",("checkpoint 3"));
804 805 806
	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
807
        if (strcmp(acl_user->x509_issuer, ptr))
808
        {
unknown's avatar
unknown committed
809
          if (global_system_variables.log_warnings)
unknown's avatar
unknown committed
810 811
            sql_print_information("X509 issuer mismatch: should be '%s' "
			      "but is '%s'", acl_user->x509_issuer, ptr);
812
          free(ptr);
unknown's avatar
unknown committed
813
          break;
814
        }
unknown's avatar
merge  
unknown committed
815
        user_access= acl_user->access;
unknown's avatar
unknown committed
816
        free(ptr);
unknown's avatar
unknown committed
817
      }
818 819 820 821
      DBUG_PRINT("info",("checkpoint 4"));
      /* X509 subject is specified, we check it .. */
      if (acl_user->x509_subject)
      {
unknown's avatar
unknown committed
822 823 824 825
        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))
826
        {
unknown's avatar
unknown committed
827
          if (global_system_variables.log_warnings)
unknown's avatar
unknown committed
828
            sql_print_information("X509 subject mismatch: '%s' vs '%s'",
unknown's avatar
unknown committed
829
                            acl_user->x509_subject, ptr);
830
        }
unknown's avatar
unknown committed
831
        else
unknown's avatar
merge  
unknown committed
832
          user_access= acl_user->access;
unknown's avatar
unknown committed
833
        free(ptr);
834 835
      }
      break;
unknown's avatar
unknown committed
836
#else  /* HAVE_OPENSSL */
unknown's avatar
unknown committed
837
    default:
838
      /*
unknown's avatar
unknown committed
839 840 841
        If we don't have SSL but SSL is required for this user the 
        authentication should fail.
      */
842 843
      break;
#endif /* HAVE_OPENSSL */
unknown's avatar
unknown committed
844
    }
unknown's avatar
merge  
unknown committed
845
    thd->master_access= user_access;
846 847
    thd->priv_user= acl_user->user ? thd->user : (char *) "";
    *mqh= acl_user->user_resource;
848

849 850 851 852 853
    if (acl_user->host.hostname)
      strmake(thd->priv_host, acl_user->host.hostname, MAX_HOSTNAME);
    else
      *thd->priv_host= 0;
  }
unknown's avatar
unknown committed
854
  VOID(pthread_mutex_unlock(&acl_cache->lock));
855
  DBUG_RETURN(res);
unknown's avatar
unknown committed
856 857 858
}


859 860 861
/*
 * This is like acl_getroot() above, but it doesn't check password,
 * and we don't care about the user resources.
862
 * Used to get access rights for SQL SECURITY DEFINER invocation of
863 864 865 866 867
 * stored procedures.
 */
int acl_getroot_no_password(THD *thd)
{
  int res= 1;
868
  uint i;
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
  ACL_USER *acl_user= 0;
  DBUG_ENTER("acl_getroot_no_password");

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

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

885 886 887
  thd->master_access= 0;
  thd->db_access= 0;

888 889 890 891 892 893
  /*
     Find acl entry in user database.
     This is specially tailored to suit the check we do for CALL of
     a stored procedure; thd->user is set to what is actually a
     priv_user, which can be ''.
  */
894
  for (i=0 ; i < acl_users.elements ; i++)
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
  {
    acl_user= dynamic_element(&acl_users,i,ACL_USER*);
    if ((!acl_user->user && (!thd->user || !thd->user[0])) ||
	(acl_user->user && strcmp(thd->user, acl_user->user) == 0))
    {
      if (compare_hostname(&acl_user->host, thd->host, thd->ip))
      {
	res= 0;
	break;
      }
    }
  }

  if (acl_user)
  {
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
    for (i=0 ; i < acl_dbs.elements ; i++)
    {
      ACL_DB *acl_db= dynamic_element(&acl_dbs, i, ACL_DB*);
      if (!acl_db->user ||
	  (thd->user && thd->user[0] && !strcmp(thd->user, acl_db->user)))
      {
	if (compare_hostname(&acl_db->host, thd->host, thd->ip))
	{
	  if (!acl_db->db || (thd->db && !strcmp(acl_db->db, thd->db)))
	  {
	    thd->db_access= acl_db->access;
	    break;
	  }
	}
      }
    }
926 927 928 929 930 931 932 933 934 935 936 937
    thd->master_access= acl_user->access;
    thd->priv_user= acl_user->user ? thd->user : (char *) "";

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

unknown's avatar
unknown committed
938 939 940 941 942 943 944
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;
}

945

unknown's avatar
unknown committed
946
static void acl_update_user(const char *user, const char *host,
947
			    const char *password, uint password_len,
948 949 950 951
			    enum SSL_type ssl_type,
			    const char *ssl_cipher,
			    const char *x509_issuer,
			    const char *x509_subject,
unknown's avatar
unknown committed
952
			    USER_RESOURCES  *mqh,
unknown's avatar
unknown committed
953
			    ulong privileges)
unknown's avatar
unknown committed
954 955 956 957 958 959 960 961 962
{
  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
963
	  acl_user->host.hostname &&
964
	  !my_strcasecmp(system_charset_info, host, acl_user->host.hostname))
unknown's avatar
unknown committed
965 966
      {
	acl_user->access=privileges;
967
	if (mqh->specified_limits & USER_RESOURCES::QUERIES_PER_HOUR)
968
	  acl_user->user_resource.questions=mqh->questions;
969
	if (mqh->specified_limits & USER_RESOURCES::UPDATES_PER_HOUR)
970
	  acl_user->user_resource.updates=mqh->updates;
971 972 973 974
	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;
975 976 977 978 979 980 981 982 983 984
	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
985 986
	if (password)
	  set_user_salt(acl_user, password, password_len);
987
        /* search complete: */
unknown's avatar
unknown committed
988 989 990 991 992 993 994 995
	break;
      }
    }
  }
}


static void acl_insert_user(const char *user, const char *host,
996
			    const char *password, uint password_len,
997 998 999 1000
			    enum SSL_type ssl_type,
			    const char *ssl_cipher,
			    const char *x509_issuer,
			    const char *x509_subject,
1001
			    USER_RESOURCES *mqh,
unknown's avatar
unknown committed
1002
			    ulong privileges)
unknown's avatar
unknown committed
1003 1004
{
  ACL_USER acl_user;
1005
  acl_user.user=*user ? strdup_root(&mem,user) : 0;
unknown's avatar
unknown committed
1006
  update_hostname(&acl_user.host, *host ? strdup_root(&mem, host): 0);
unknown's avatar
unknown committed
1007
  acl_user.access=privileges;
1008
  acl_user.user_resource = *mqh;
unknown's avatar
unknown committed
1009
  acl_user.sort=get_sort(2,acl_user.host.hostname,acl_user.user);
1010
  acl_user.hostname_length=(uint) strlen(host);
1011 1012 1013 1014 1015
  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;
1016 1017

  set_user_salt(&acl_user, password, password_len);
unknown's avatar
unknown committed
1018 1019 1020 1021

  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
1022
    allow_all_hosts=1;		// Anyone can connect /* purecov: tested */
unknown's avatar
unknown committed
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
  qsort((gptr) dynamic_element(&acl_users,0,ACL_USER*),acl_users.elements,
	sizeof(ACL_USER),(qsort_cmp) acl_compare);

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


static void acl_update_db(const char *user, const char *host, const char *db,
unknown's avatar
unknown committed
1034
			  ulong privileges)
unknown's avatar
unknown committed
1035 1036 1037 1038 1039 1040 1041 1042 1043
{
  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] ||
1044
	  acl_db->host.hostname &&
1045
	  !my_strcasecmp(system_charset_info, host, acl_db->host.hostname))
unknown's avatar
unknown committed
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
      {
	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);
	}
      }
    }
  }
}


1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
/*
  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
1075
static void acl_insert_db(const char *user, const char *host, const char *db,
unknown's avatar
unknown committed
1076
			  ulong privileges)
unknown's avatar
unknown committed
1077 1078
{
  ACL_DB acl_db;
1079
  safe_mutex_assert_owner(&acl_cache->lock);
unknown's avatar
unknown committed
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
  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);
}


1091 1092 1093 1094

/*
  Get privilege for a host, user and db combination
*/
unknown's avatar
unknown committed
1095

1096
ulong acl_get(const char *host, const char *ip,
1097
              const char *user, const char *db, my_bool db_is_pattern)
unknown's avatar
unknown committed
1098
{
1099
  ulong host_access= ~0, db_access= 0;
unknown's avatar
unknown committed
1100
  uint i,key_length;
unknown's avatar
unknown committed
1101
  char key[ACL_KEY_LENGTH],*tmp_db,*end;
unknown's avatar
unknown committed
1102
  acl_entry *entry;
unknown's avatar
unknown committed
1103
  DBUG_ENTER("acl_get");
unknown's avatar
unknown committed
1104 1105

  VOID(pthread_mutex_lock(&acl_cache->lock));
1106
  end=strmov((tmp_db=strmov(strmov(key, ip ? ip : "")+1,user)+1),db);
unknown's avatar
unknown committed
1107 1108
  if (lower_case_table_names)
  {
1109
    my_casedn_str(files_charset_info, tmp_db);
unknown's avatar
unknown committed
1110 1111
    db=tmp_db;
  }
unknown's avatar
unknown committed
1112 1113 1114 1115 1116
  key_length=(uint) (end-key);
  if ((entry=(acl_entry*) acl_cache->search(key,key_length)))
  {
    db_access=entry->access;
    VOID(pthread_mutex_unlock(&acl_cache->lock));
unknown's avatar
unknown committed
1117 1118
    DBUG_PRINT("exit", ("access: 0x%lx", db_access));
    DBUG_RETURN(db_access);
unknown's avatar
unknown committed
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
  }

  /*
    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))
      {
1131
	if (!acl_db->db || !wild_compare(db,acl_db->db,db_is_pattern))
unknown's avatar
unknown committed
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
	{
	  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))
    {
1153
      if (!acl_host->db || !wild_compare(db,acl_host->db,db_is_pattern))
unknown's avatar
unknown committed
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
      {
	host_access=acl_host->access;		// Fully specified. Take it
	break;
      }
    }
  }
exit:
  /* Save entry in cache for quick retrieval */
  if ((entry= (acl_entry*) malloc(sizeof(acl_entry)+key_length)))
  {
    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
1170 1171
  DBUG_PRINT("exit", ("access: 0x%lx", db_access & host_access));
  DBUG_RETURN(db_access & host_access);
unknown's avatar
unknown committed
1172 1173
}

1174 1175 1176 1177 1178 1179 1180
/*
  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
1181 1182 1183 1184

static void init_check_host(void)
{
  DBUG_ENTER("init_check_host");
1185
  VOID(my_init_dynamic_array(&acl_wild_hosts,sizeof(struct acl_host_and_ip),
unknown's avatar
unknown committed
1186
			  acl_users.elements,1));
1187
  VOID(hash_init(&acl_check_hosts,system_charset_info,acl_users.elements,0,0,
unknown's avatar
unknown committed
1188
		 (hash_get_key) check_get_key,0,0));
unknown's avatar
unknown committed
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
  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 *);
1203
	  if (!my_strcasecmp(system_charset_info,
1204
                             acl_user->host.hostname, acl->hostname))
unknown's avatar
unknown committed
1205 1206 1207 1208 1209 1210
	    break;				// already stored
	}
	if (j == acl_wild_hosts.elements)	// If new
	  (void) push_dynamic(&acl_wild_hosts,(char*) &acl_user->host);
      }
      else if (!hash_search(&acl_check_hosts,(byte*) &acl_user->host,
unknown's avatar
unknown committed
1211
			    (uint) strlen(acl_user->host.hostname)))
unknown's avatar
unknown committed
1212
      {
unknown's avatar
SCRUM  
unknown committed
1213
	if (my_hash_insert(&acl_check_hosts,(byte*) acl_user))
unknown's avatar
unknown committed
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
	{					// End of memory
	  allow_all_hosts=1;			// Should never happen
	  DBUG_VOID_RETURN;
	}
      }
    }
  }
  freeze_size(&acl_wild_hosts);
  freeze_size(&acl_check_hosts.array);
  DBUG_VOID_RETURN;
}


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

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

unknown's avatar
unknown committed
1235 1236
  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
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
  {
    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
1255 1256 1257 1258 1259 1260 1261 1262
/*
  Check if the user is allowed to change password

  SYNOPSIS:
    check_change_password()
    thd		THD
    host	hostname for the user
    user	user name
1263 1264 1265 1266
    new_password new password

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

unknown's avatar
unknown committed
1268
    RETURN VALUE
1269 1270
      0		OK
      1		ERROR  ; In this case the error is sent to the client.
unknown's avatar
unknown committed
1271 1272
*/

1273
bool check_change_password(THD *thd, const char *host, const char *user,
1274
                           char *new_password, uint new_password_len)
unknown's avatar
unknown committed
1275
{
unknown's avatar
unknown committed
1276 1277
  if (!initialized)
  {
unknown's avatar
unknown committed
1278
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
1279
    return(1);
unknown's avatar
unknown committed
1280
  }
unknown's avatar
unknown committed
1281 1282
  if (!thd->slave_thread &&
      (strcmp(thd->user,user) ||
1283
       my_strcasecmp(system_charset_info, host, thd->host_or_ip)))
unknown's avatar
unknown committed
1284
  {
unknown's avatar
SCRUM:  
unknown committed
1285
    if (check_access(thd, UPDATE_ACL, "mysql",0,1,0))
unknown's avatar
unknown committed
1286
      return(1);
unknown's avatar
unknown committed
1287
  }
unknown's avatar
unknown committed
1288 1289
  if (!thd->slave_thread && !thd->user[0])
  {
unknown's avatar
unknown committed
1290 1291
    my_message(ER_PASSWORD_ANONYMOUS_USER, ER(ER_PASSWORD_ANONYMOUS_USER),
               MYF(0));
unknown's avatar
unknown committed
1292
    return(1);
unknown's avatar
unknown committed
1293
  }
1294
  uint len=strlen(new_password);
unknown's avatar
unknown committed
1295
  if (len && len != SCRAMBLED_PASSWORD_CHAR_LENGTH &&
1296 1297
      len != SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
  {
unknown's avatar
unknown committed
1298
    my_error(ER_PASSWD_LENGTH, MYF(0), SCRAMBLED_PASSWORD_CHAR_LENGTH);
1299 1300
    return -1;
  }
unknown's avatar
unknown committed
1301 1302 1303 1304
  return(0);
}


1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
/*
  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
1318
*/
1319

unknown's avatar
unknown committed
1320 1321 1322
bool change_password(THD *thd, const char *host, const char *user,
		     char *new_password)
{
1323
  uint new_password_len= strlen(new_password);
unknown's avatar
unknown committed
1324 1325 1326 1327 1328
  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

1329
  if (check_change_password(thd, host, user, new_password, new_password_len))
unknown's avatar
unknown committed
1330 1331
    DBUG_RETURN(1);

unknown's avatar
unknown committed
1332 1333
  VOID(pthread_mutex_lock(&acl_cache->lock));
  ACL_USER *acl_user;
1334
  if (!(acl_user= find_acl_user(host, user)))
unknown's avatar
unknown committed
1335 1336
  {
    VOID(pthread_mutex_unlock(&acl_cache->lock));
unknown's avatar
unknown committed
1337
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH), MYF(0));
unknown's avatar
unknown committed
1338
    DBUG_RETURN(1);
unknown's avatar
unknown committed
1339
  }
1340 1341 1342
  /* update loaded acl entry: */
  set_user_salt(acl_user, new_password, new_password_len);

unknown's avatar
unknown committed
1343 1344
  if (update_user_table(thd,
			acl_user->host.hostname ? acl_user->host.hostname : "",
unknown's avatar
unknown committed
1345
			acl_user->user ? acl_user->user : "",
1346
			new_password, new_password_len))
unknown's avatar
unknown committed
1347 1348
  {
    VOID(pthread_mutex_unlock(&acl_cache->lock)); /* purecov: deadcode */
unknown's avatar
unknown committed
1349
    DBUG_RETURN(1); /* purecov: deadcode */
unknown's avatar
unknown committed
1350
  }
unknown's avatar
unknown committed
1351

unknown's avatar
unknown committed
1352 1353 1354
  acl_cache->clear(1);				// Clear locked hostname cache
  VOID(pthread_mutex_unlock(&acl_cache->lock));

1355
  char buff[512]; /* Extend with extended password length*/
1356
  ulong query_length=
unknown's avatar
unknown committed
1357 1358
    my_sprintf(buff,
	       (buff,"SET PASSWORD FOR \"%-.120s\"@\"%-.120s\"=\"%-.120s\"",
unknown's avatar
unknown committed
1359
		acl_user->user ? acl_user->user : "",
unknown's avatar
unknown committed
1360 1361
		acl_user->host.hostname ? acl_user->host.hostname : "",
		new_password));
unknown's avatar
unknown committed
1362
  thd->clear_error();
1363
  Query_log_event qinfo(thd, buff, query_length, 0, FALSE);
unknown's avatar
unknown committed
1364
  mysql_bin_log.write(&qinfo);
unknown's avatar
unknown committed
1365
  DBUG_RETURN(0);
unknown's avatar
unknown committed
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
}


/*
  Find first entry that matches the current user
*/

static ACL_USER *
find_acl_user(const char *host, const char *user)
{
unknown's avatar
unknown committed
1376
  DBUG_ENTER("find_acl_user");
1377
  DBUG_PRINT("enter",("host: '%s'  user: '%s'",host,user));
unknown's avatar
unknown committed
1378 1379 1380
  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
1381
    DBUG_PRINT("info",("strcmp('%s','%s'), compare_hostname('%s','%s'),",
1382 1383 1384 1385 1386
		       user,
		       acl_user->user ? acl_user->user : "",
		       host,
		       acl_user->host.hostname ? acl_user->host.hostname :
		       ""));
unknown's avatar
unknown committed
1387 1388 1389
    if (!acl_user->user && !user[0] ||
	acl_user->user && !strcmp(user,acl_user->user))
    {
1390
      if (compare_hostname(&acl_user->host,host,host))
unknown's avatar
unknown committed
1391 1392 1393
      {
	DBUG_RETURN(acl_user);
      }
unknown's avatar
unknown committed
1394 1395
    }
  }
unknown's avatar
unknown committed
1396
  DBUG_RETURN(0);
unknown's avatar
unknown committed
1397 1398 1399
}


1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
/*
  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
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433

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!
1434
  if (!hostname ||
unknown's avatar
unknown committed
1435 1436 1437
      (!(hostname=calc_ip(hostname,&host->ip,'/')) ||
       !(hostname=calc_ip(hostname+1,&host->ip_mask,'\0'))))
  {
1438
    host->ip= host->ip_mask=0;			// Not a masked ip
unknown's avatar
unknown committed
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
  }
}


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 ||
1452
	  (hostname && !wild_case_compare(system_charset_info,
1453
                                          hostname,host->hostname)) ||
1454
	  (ip && !wild_compare(ip,host->hostname,0)));
unknown's avatar
unknown committed
1455 1456
}

unknown's avatar
SCRUM  
unknown committed
1457 1458 1459 1460
bool hostname_requires_resolving(const char *hostname)
{
  char cur;
  if (!hostname)
unknown's avatar
unknown committed
1461
    return FALSE;
unknown's avatar
SCRUM  
unknown committed
1462 1463 1464
  int namelen= strlen(hostname);
  int lhlen= strlen(my_localhost);
  if ((namelen == lhlen) &&
1465
      !my_strnncoll(system_charset_info, (const uchar *)hostname,  namelen,
unknown's avatar
SCRUM  
unknown committed
1466
		    (const uchar *)my_localhost, strlen(my_localhost)))
unknown's avatar
unknown committed
1467
    return FALSE;
unknown's avatar
SCRUM  
unknown committed
1468 1469
  for (; (cur=*hostname); hostname++)
  {
1470
    if ((cur != '%') && (cur != '_') && (cur != '.') && (cur != '/') &&
unknown's avatar
SCRUM  
unknown committed
1471
	((cur < '0') || (cur > '9')))
unknown's avatar
unknown committed
1472
      return TRUE;
unknown's avatar
SCRUM  
unknown committed
1473
  }
unknown's avatar
unknown committed
1474
  return FALSE;
unknown's avatar
SCRUM  
unknown committed
1475
}
unknown's avatar
unknown committed
1476

1477 1478 1479
/*
  Update grants in the user and database privilege tables
*/
unknown's avatar
unknown committed
1480 1481

static bool update_user_table(THD *thd, const char *host, const char *user,
1482
			      const char *new_password, uint new_password_len)
unknown's avatar
unknown committed
1483 1484 1485 1486
{
  TABLE_LIST tables;
  TABLE *table;
  bool error=1;
1487
  char user_key[MAX_KEY_LENGTH];
unknown's avatar
unknown committed
1488 1489 1490 1491
  DBUG_ENTER("update_user_table");
  DBUG_PRINT("enter",("user: %s  host: %s",user,host));

  bzero((char*) &tables,sizeof(tables));
1492
  tables.alias=tables.table_name=(char*) "user";
unknown's avatar
unknown committed
1493
  tables.db=(char*) "mysql";
unknown's avatar
unknown committed
1494

1495 1496 1497 1498 1499 1500 1501
#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)
  {
unknown's avatar
unknown committed
1502 1503 1504
    /*
      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.
1505
    */
1506
    tables.updating= 1;
1507 1508 1509 1510 1511 1512
    /* Thanks to bzero, tables.next==0 */
    if (!tables_ok(0, &tables))
      DBUG_RETURN(0);
  }
#endif

unknown's avatar
unknown committed
1513 1514
  if (!(table=open_ltable(thd,&tables,TL_WRITE)))
    DBUG_RETURN(1); /* purecov: deadcode */
1515 1516
  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
1517
  key_copy((byte *) user_key, table->record[0], table->key_info,
1518
           table->key_info->key_length);
unknown's avatar
unknown committed
1519

unknown's avatar
unknown committed
1520
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
1521
  if (table->file->index_read_idx(table->record[0], 0,
unknown's avatar
unknown committed
1522
				  (byte *) user_key, table->key_info->key_length,
unknown's avatar
unknown committed
1523 1524
				  HA_READ_KEY_EXACT))
  {
unknown's avatar
unknown committed
1525 1526
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH),
               MYF(0));	/* purecov: deadcode */
unknown's avatar
unknown committed
1527 1528
    DBUG_RETURN(1);				/* purecov: deadcode */
  }
unknown's avatar
unknown committed
1529
  store_record(table,record[1]);
1530
  table->field[2]->store(new_password, new_password_len, system_charset_info);
unknown's avatar
unknown committed
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
  if ((error=table->file->update_row(table->record[1],table->record[0])))
  {
    table->file->print_error(error,MYF(0));	/* purecov: deadcode */
    goto end;					/* purecov: deadcode */
  }
  error=0;					// Record updated

end:
  close_thread_tables(thd);
  DBUG_RETURN(error);
}

unknown's avatar
unknown committed
1543 1544 1545 1546 1547 1548 1549 1550 1551

/* Return 1 if we are allowed to create new users */

static bool test_if_create_new_users(THD *thd)
{
  bool create_new_users=1;    // Assume that we are allowed to create new users
  if (opt_safe_user_create && !(thd->master_access & INSERT_ACL))
  {
    TABLE_LIST tl;
unknown's avatar
unknown committed
1552
    ulong db_access;
unknown's avatar
unknown committed
1553 1554
    bzero((char*) &tl,sizeof(tl));
    tl.db=	   (char*) "mysql";
1555
    tl.table_name=  (char*) "user";
unknown's avatar
unknown committed
1556

1557
    db_access=acl_get(thd->host, thd->ip,
1558
		      thd->priv_user, tl.db, 0);
unknown's avatar
unknown committed
1559 1560
    if (!(db_access & INSERT_ACL))
    {
unknown's avatar
unknown committed
1561
      if (check_grant(thd, INSERT_ACL, &tl, 0, UINT_MAX, 1))
unknown's avatar
unknown committed
1562 1563 1564 1565 1566 1567 1568
	create_new_users=0;
    }
  }
  return create_new_users;
}


unknown's avatar
unknown committed
1569
/****************************************************************************
1570
  Handle GRANT commands
unknown's avatar
unknown committed
1571 1572
****************************************************************************/

1573
static int replace_user_table(THD *thd, TABLE *table, const LEX_USER &combo,
unknown's avatar
unknown committed
1574 1575
			      ulong rights, bool revoke_grant,
			      bool create_user)
unknown's avatar
unknown committed
1576 1577
{
  int error = -1;
unknown's avatar
unknown committed
1578
  bool old_row_exists=0;
1579
  const char *password= "";
1580
  uint password_len= 0;
unknown's avatar
unknown committed
1581
  char what= (revoke_grant) ? 'N' : 'Y';
1582
  byte user_key[MAX_KEY_LENGTH];
1583
  LEX *lex= thd->lex;
unknown's avatar
unknown committed
1584
  DBUG_ENTER("replace_user_table");
unknown's avatar
unknown committed
1585

1586
  safe_mutex_assert_owner(&acl_cache->lock);
unknown's avatar
unknown committed
1587 1588

  if (combo.password.str && combo.password.str[0])
1589
  {
1590 1591
    if (combo.password.length != SCRAMBLED_PASSWORD_CHAR_LENGTH &&
        combo.password.length != SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
1592
    {
1593
      my_error(ER_PASSWD_LENGTH, MYF(0), SCRAMBLED_PASSWORD_CHAR_LENGTH);
unknown's avatar
unknown committed
1594
      DBUG_RETURN(-1);
1595
    }
1596
    password_len= combo.password.length;
unknown's avatar
unknown committed
1597
    password=combo.password.str;
1598
  }
unknown's avatar
unknown committed
1599

1600 1601
  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);
1602 1603 1604
  key_copy(user_key, table->record[0], table->key_info,
           table->key_info->key_length);

unknown's avatar
unknown committed
1605
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
unknown's avatar
unknown committed
1606
  if (table->file->index_read_idx(table->record[0], 0,
1607 1608
                                  user_key, table->key_info->key_length,
                                  HA_READ_KEY_EXACT))
unknown's avatar
unknown committed
1609
  {
1610 1611
    /* what == 'N' means revoke */
    if (what == 'N')
unknown's avatar
unknown committed
1612
    {
1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
      my_error(ER_NONEXISTING_GRANT, MYF(0), combo.user.str, combo.host.str);
      goto end;
    }
    /*
      There are four options which affect the process of creation of 
      a new user(mysqld option --safe-create-user, 'insert' privilege
      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
    */
    else if (((thd->variables.sql_mode & MODE_NO_AUTO_CREATE_USER) &&
              !password_len) || !create_user)
    {
      my_error(ER_NO_PERMISSION_TO_CREATE_USER, MYF(0),
               thd->user, thd->host_or_ip);
unknown's avatar
unknown committed
1632 1633
      goto end;
    }
unknown's avatar
unknown committed
1634
    old_row_exists = 0;
1635
    restore_record(table,s->default_values);
1636
    table->field[0]->store(combo.host.str,combo.host.length,
1637
                           system_charset_info);
1638
    table->field[1]->store(combo.user.str,combo.user.length,
1639
                           system_charset_info);
1640
    table->field[2]->store(password, password_len,
1641
                           system_charset_info);
unknown's avatar
unknown committed
1642 1643 1644
  }
  else
  {
1645 1646 1647 1648
    /*
      Check that the user isn't trying to change a password for another
      user if he doesn't have UPDATE privilege to the MySQL database
    */
1649
    DBUG_ASSERT(combo.host.str != 0);
1650 1651
    if (thd->user && combo.password.str &&
        (strcmp(thd->user,combo.user.str) ||
1652
         my_strcasecmp(system_charset_info,
1653 1654 1655
                       combo.host.str, thd->host_or_ip)) &&
        check_access(thd, UPDATE_ACL, "mysql",0,1,0))
      goto end;
unknown's avatar
unknown committed
1656
    old_row_exists = 1;
unknown's avatar
unknown committed
1657
    store_record(table,record[1]);			// Save copy for update
unknown's avatar
unknown committed
1658
    if (combo.password.str)			// If password given
1659
      table->field[2]->store(password, password_len, system_charset_info);
1660
    else if (!rights && !revoke_grant &&
1661 1662
             lex->ssl_type == SSL_TYPE_NOT_SPECIFIED &&
             !lex->mqh.specified_limits)
unknown's avatar
unknown committed
1663 1664 1665
    {
      DBUG_RETURN(0);
    }
unknown's avatar
unknown committed
1666 1667
  }

unknown's avatar
unknown committed
1668 1669 1670 1671
  /* Update table columns with new privileges */

  Field **tmp_field;
  ulong priv;
1672
  uint next_field;
unknown's avatar
unknown committed
1673 1674 1675 1676
  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
1677
  {
unknown's avatar
unknown committed
1678
    if (priv & rights)				 // set requested privileges
unknown's avatar
unknown committed
1679
      (*tmp_field)->store(&what, 1, &my_charset_latin1);
unknown's avatar
unknown committed
1680
  }
1681
  rights= get_access(table, 3, &next_field);
1682 1683
  DBUG_PRINT("info",("table fields: %d",table->s->fields));
  if (table->s->fields >= 31)		/* From 4.0.0 we have more fields */
1684
  {
unknown's avatar
unknown committed
1685
    /* We write down SSL related ACL stuff */
1686
    switch (lex->ssl_type) {
unknown's avatar
unknown committed
1687
    case SSL_TYPE_ANY:
1688 1689 1690 1691
      table->field[next_field]->store("ANY", 3, &my_charset_latin1);
      table->field[next_field+1]->store("", 0, &my_charset_latin1);
      table->field[next_field+2]->store("", 0, &my_charset_latin1);
      table->field[next_field+3]->store("", 0, &my_charset_latin1);
unknown's avatar
unknown committed
1692 1693
      break;
    case SSL_TYPE_X509:
1694 1695 1696 1697
      table->field[next_field]->store("X509", 4, &my_charset_latin1);
      table->field[next_field+1]->store("", 0, &my_charset_latin1);
      table->field[next_field+2]->store("", 0, &my_charset_latin1);
      table->field[next_field+3]->store("", 0, &my_charset_latin1);
unknown's avatar
unknown committed
1698 1699
      break;
    case SSL_TYPE_SPECIFIED:
1700 1701 1702 1703
      table->field[next_field]->store("SPECIFIED", 9, &my_charset_latin1);
      table->field[next_field+1]->store("", 0, &my_charset_latin1);
      table->field[next_field+2]->store("", 0, &my_charset_latin1);
      table->field[next_field+3]->store("", 0, &my_charset_latin1);
1704
      if (lex->ssl_cipher)
unknown's avatar
unknown committed
1705 1706
        table->field[next_field+1]->store(lex->ssl_cipher,
                                strlen(lex->ssl_cipher), system_charset_info);
1707
      if (lex->x509_issuer)
unknown's avatar
unknown committed
1708 1709
        table->field[next_field+2]->store(lex->x509_issuer,
                                strlen(lex->x509_issuer), system_charset_info);
1710
      if (lex->x509_subject)
unknown's avatar
unknown committed
1711 1712
        table->field[next_field+3]->store(lex->x509_subject,
                                strlen(lex->x509_subject), system_charset_info);
unknown's avatar
unknown committed
1713
      break;
unknown's avatar
unknown committed
1714
    case SSL_TYPE_NOT_SPECIFIED:
unknown's avatar
unknown committed
1715 1716
      break;
    case SSL_TYPE_NONE:
1717 1718 1719 1720
      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
1721
      break;
1722
    }
unknown's avatar
unknown committed
1723
    next_field+=4;
unknown's avatar
unknown committed
1724

1725
    USER_RESOURCES mqh= lex->mqh;
1726
    if (mqh.specified_limits & USER_RESOURCES::QUERIES_PER_HOUR)
1727
      table->field[next_field]->store((longlong) mqh.questions);
1728
    if (mqh.specified_limits & USER_RESOURCES::UPDATES_PER_HOUR)
1729
      table->field[next_field+1]->store((longlong) mqh.updates);
1730
    if (mqh.specified_limits & USER_RESOURCES::CONNECTIONS_PER_HOUR)
unknown's avatar
unknown committed
1731
      table->field[next_field+2]->store((longlong) mqh.conn_per_hour);
1732
    if (table->s->fields >= 36 &&
1733
        (mqh.specified_limits & USER_RESOURCES::USER_CONNECTIONS))
unknown's avatar
unknown committed
1734
      table->field[next_field+3]->store((longlong) mqh.user_conn);
1735
    mqh_used= mqh_used || mqh.questions || mqh.updates || mqh.conn_per_hour;
unknown's avatar
unknown committed
1736
  }
unknown's avatar
unknown committed
1737
  if (old_row_exists)
unknown's avatar
unknown committed
1738 1739 1740 1741 1742
  {
    /*
      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!
    */
unknown's avatar
unknown committed
1743
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
unknown's avatar
unknown committed
1744
    if (cmp_record(table,record[1]) &&
unknown's avatar
unknown committed
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763
	(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

unknown's avatar
unknown committed
1764
end:
unknown's avatar
unknown committed
1765 1766 1767
  if (!error)
  {
    acl_cache->clear(1);			// Clear privilege cache
unknown's avatar
unknown committed
1768
    if (old_row_exists)
1769 1770
      acl_update_user(combo.user.str, combo.host.str,
                      combo.password.str, password_len,
1771 1772 1773 1774 1775
		      lex->ssl_type,
		      lex->ssl_cipher,
		      lex->x509_issuer,
		      lex->x509_subject,
		      &lex->mqh,
unknown's avatar
unknown committed
1776
		      rights);
unknown's avatar
unknown committed
1777
    else
1778
      acl_insert_user(combo.user.str, combo.host.str, password, password_len,
1779 1780 1781 1782 1783
		      lex->ssl_type,
		      lex->ssl_cipher,
		      lex->x509_issuer,
		      lex->x509_subject,
		      &lex->mqh,
unknown's avatar
unknown committed
1784
		      rights);
unknown's avatar
unknown committed
1785 1786 1787 1788 1789 1790
  }
  DBUG_RETURN(error);
}


/*
unknown's avatar
unknown committed
1791
  change grants in the mysql.db table
unknown's avatar
unknown committed
1792 1793 1794 1795
*/

static int replace_db_table(TABLE *table, const char *db,
			    const LEX_USER &combo,
unknown's avatar
unknown committed
1796
			    ulong rights, bool revoke_grant)
unknown's avatar
unknown committed
1797
{
unknown's avatar
unknown committed
1798 1799
  uint i;
  ulong priv,store_rights;
unknown's avatar
unknown committed
1800
  bool old_row_exists=0;
unknown's avatar
unknown committed
1801
  int error;
unknown's avatar
unknown committed
1802
  char what= (revoke_grant) ? 'N' : 'Y';
1803
  byte user_key[MAX_KEY_LENGTH];
unknown's avatar
unknown committed
1804 1805
  DBUG_ENTER("replace_db_table");

1806 1807
  if (!initialized)
  {
unknown's avatar
unknown committed
1808
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
1809 1810 1811
    DBUG_RETURN(-1);
  }

1812
  /* Check if there is such a user in user table in memory? */
1813
  if (!find_acl_user(combo.host.str,combo.user.str))
unknown's avatar
unknown committed
1814
  {
unknown's avatar
unknown committed
1815
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH), MYF(0));
unknown's avatar
unknown committed
1816 1817 1818
    DBUG_RETURN(-1);
  }

1819 1820 1821
  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);
1822 1823 1824
  key_copy(user_key, table->record[0], table->key_info,
           table->key_info->key_length);

unknown's avatar
unknown committed
1825 1826
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
  if (table->file->index_read_idx(table->record[0],0,
1827 1828
                                  user_key, table->key_info->key_length,
                                  HA_READ_KEY_EXACT))
unknown's avatar
unknown committed
1829 1830 1831
  {
    if (what == 'N')
    { // no row, no revoke
unknown's avatar
unknown committed
1832
      my_error(ER_NONEXISTING_GRANT, MYF(0), combo.user.str, combo.host.str);
unknown's avatar
unknown committed
1833 1834
      goto abort;
    }
unknown's avatar
unknown committed
1835
    old_row_exists = 0;
1836
    restore_record(table, s->default_values);
1837 1838 1839
    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
1840 1841 1842
  }
  else
  {
unknown's avatar
unknown committed
1843
    old_row_exists = 1;
unknown's avatar
unknown committed
1844
    store_record(table,record[1]);
unknown's avatar
unknown committed
1845 1846 1847
  }

  store_rights=get_rights_for_db(rights);
1848
  for (i= 3, priv= 1; i < table->s->fields; i++, priv <<= 1)
unknown's avatar
unknown committed
1849
  {
unknown's avatar
unknown committed
1850
    if (priv & store_rights)			// do it if priv is chosen
unknown's avatar
unknown committed
1851
      table->field [i]->store(&what,1, &my_charset_latin1);// set requested privileges
unknown's avatar
unknown committed
1852 1853 1854 1855
  }
  rights=get_access(table,3);
  rights=fix_rights_for_db(rights);

unknown's avatar
unknown committed
1856
  if (old_row_exists)
unknown's avatar
unknown committed
1857
  {
1858
    /* update old existing row */
unknown's avatar
unknown committed
1859 1860
    if (rights)
    {
unknown's avatar
unknown committed
1861
      table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
unknown's avatar
unknown committed
1862 1863 1864 1865 1866 1867 1868 1869 1870
      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 */
    }
  }
1871
  else if (rights && (error=table->file->write_row(table->record[0])))
unknown's avatar
unknown committed
1872 1873 1874 1875 1876 1877
  {
    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
1878
  if (old_row_exists)
unknown's avatar
unknown committed
1879 1880
    acl_update_db(combo.user.str,combo.host.str,db,rights);
  else
1881
  if (rights)
unknown's avatar
unknown committed
1882 1883 1884 1885
    acl_insert_db(combo.user.str,combo.host.str,db,rights);
  DBUG_RETURN(0);

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

1889
abort:
unknown's avatar
unknown committed
1890 1891 1892 1893 1894 1895 1896 1897
  DBUG_RETURN(-1);
}


class GRANT_COLUMN :public Sql_alloc
{
public:
  char *column;
unknown's avatar
unknown committed
1898 1899 1900
  ulong rights;
  uint key_length;
  GRANT_COLUMN(String &c,  ulong y) :rights (y)
unknown's avatar
unknown committed
1901
  {
unknown's avatar
unknown committed
1902
    column= memdup_root(&memex,c.ptr(), key_length=c.length());
unknown's avatar
unknown committed
1903 1904 1905
  }
};

unknown's avatar
unknown committed
1906

unknown's avatar
unknown committed
1907 1908 1909 1910 1911 1912 1913
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
1914

1915
class GRANT_NAME :public Sql_alloc
unknown's avatar
unknown committed
1916 1917
{
public:
1918 1919
  acl_host_and_ip host;
  char *db, *user, *tname, *hash_key;
1920
  ulong privs;
1921
  ulong sort;
unknown's avatar
unknown committed
1922
  uint key_length;
1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934
  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
1935
  HASH hash_columns;
unknown's avatar
unknown committed
1936 1937 1938 1939

  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);
1940
  ~GRANT_TABLE();
1941 1942
  bool ok() { return privs != 0 || cols != 0; }
};
unknown's avatar
unknown committed
1943

1944

unknown's avatar
unknown committed
1945

1946 1947 1948
GRANT_NAME::GRANT_NAME(const char *h, const char *d,const char *u,
                       const char *t, ulong p)
  :privs(p)
1949 1950
{
  /* Host given by user */
1951
  update_hostname(&host, strdup_root(&memex, h));
1952 1953
  db =   strdup_root(&memex,d);
  user = strdup_root(&memex,u);
1954
  sort=  get_sort(3,host.hostname,db,user);
1955 1956
  tname= strdup_root(&memex,t);
  if (lower_case_table_names)
unknown's avatar
unknown committed
1957
  {
1958 1959
    my_casedn_str(files_charset_info, db);
    my_casedn_str(files_charset_info, tname);
1960 1961 1962 1963
  }
  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);
1964 1965 1966 1967 1968 1969 1970
}


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)
{
1971
  (void) hash_init(&hash_columns,system_charset_info,
unknown's avatar
unknown committed
1972
                   0,0,0, (hash_get_key) get_key_column,0,0);
1973
}
unknown's avatar
unknown committed
1974

1975

1976
GRANT_NAME::GRANT_NAME(TABLE *form)
1977
{
1978
  update_hostname(&host, get_field(&memex, form->field[0]));
unknown's avatar
unknown committed
1979 1980
  db=    get_field(&memex,form->field[1]);
  user=  get_field(&memex,form->field[2]);
1981 1982
  if (!user)
    user= (char*) "";
1983
  sort=  get_sort(3, host.hostname, db, user);
unknown's avatar
unknown committed
1984
  tname= get_field(&memex,form->field[3]);
1985 1986 1987
  if (!db || !tname)
  {
    /* Wrong table row; Ignore it */
1988
    privs= 0;
1989 1990 1991 1992
    return;					/* purecov: inspected */
  }
  if (lower_case_table_names)
  {
1993 1994
    my_casedn_str(files_charset_info, db);
    my_casedn_str(files_charset_info, tname);
1995 1996 1997 1998 1999 2000 2001
  }
  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);
2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017
}


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();
2018 2019
  cols =  fix_rights_for_column(cols);

2020
  (void) hash_init(&hash_columns,system_charset_info,
unknown's avatar
unknown committed
2021
                   0,0,0, (hash_get_key) get_key_column,0,0);
2022 2023
  if (cols)
  {
2024 2025
    uint key_prefix_len;
    KEY_PART_INFO *key_part= col_privs->key_info->key_part;
2026
    col_privs->field[0]->store(host.hostname,(uint) strlen(host.hostname),
2027 2028 2029 2030
                               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);
2031 2032 2033 2034 2035 2036

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

unknown's avatar
unknown committed
2039 2040
    col_privs->file->ha_index_init(0);
    if (col_privs->file->index_read(col_privs->record[0],
2041 2042
                                    (byte*) key,
                                    key_prefix_len, HA_READ_KEY_EXACT))
unknown's avatar
unknown committed
2043
    {
2044
      cols = 0; /* purecov: deadcode */
unknown's avatar
unknown committed
2045
      col_privs->file->ha_index_end();
2046
      return;
unknown's avatar
unknown committed
2047
    }
2048
    do
unknown's avatar
unknown committed
2049
    {
2050 2051 2052
      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
2053
      res=col_privs->field[4]->val_str(&column_name);
2054 2055 2056
      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
2057
      {
2058 2059 2060
        /* Don't use this entry */
        privs = cols = 0;			/* purecov: deadcode */
        return;				/* purecov: deadcode */
unknown's avatar
unknown committed
2061
      }
unknown's avatar
unknown committed
2062
      my_hash_insert(&hash_columns, (byte *) mem_check);
2063
    } while (!col_privs->file->index_next(col_privs->record[0]) &&
2064
             !key_cmp_if_same(col_privs,key,0,key_prefix_len));
unknown's avatar
unknown committed
2065
    col_privs->file->ha_index_end();
unknown's avatar
unknown committed
2066
  }
2067
}
unknown's avatar
unknown committed
2068

unknown's avatar
unknown committed
2069

2070 2071 2072 2073 2074 2075
GRANT_TABLE::~GRANT_TABLE()
{
  hash_free(&hash_columns);
}


2076
static byte* get_grant_table(GRANT_NAME *buff,uint *length,
unknown's avatar
unknown committed
2077 2078 2079 2080 2081 2082
			     my_bool not_used __attribute__((unused)))
{
  *length=buff->key_length;
  return (byte*) buff->hash_key;
}

unknown's avatar
unknown committed
2083

unknown's avatar
unknown committed
2084 2085 2086 2087 2088
void free_grant_table(GRANT_TABLE *grant_table)
{
  hash_free(&grant_table->hash_columns);
}

unknown's avatar
unknown committed
2089

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

2092 2093
static GRANT_NAME *name_hash_search(HASH *name_hash,
				      const char *host,const char* ip,
unknown's avatar
unknown committed
2094 2095 2096 2097 2098 2099
				      const char *db,
				      const char *user, const char *tname,
				      bool exact)
{
  char helping [NAME_LEN*2+USERNAME_LENGTH+3];
  uint len;
2100
  GRANT_NAME *grant_name,*found=0;
unknown's avatar
unknown committed
2101 2102

  len  = (uint) (strmov(strmov(strmov(helping,user)+1,db)+1,tname)-helping)+ 1;
2103
  for (grant_name=(GRANT_NAME*) hash_search(name_hash,
2104
					      (byte*) helping,
unknown's avatar
unknown committed
2105
					      len) ;
2106 2107
       grant_name ;
       grant_name= (GRANT_NAME*) hash_next(name_hash,(byte*) helping,
2108
					     len))
unknown's avatar
unknown committed
2109 2110 2111
  {
    if (exact)
    {
unknown's avatar
unknown committed
2112
      if (compare_hostname(&grant_name->host, host, ip))
2113
	return grant_name;
unknown's avatar
unknown committed
2114 2115 2116
    }
    else
    {
unknown's avatar
unknown committed
2117
      if (compare_hostname(&grant_name->host, host, ip) &&
2118 2119
          (!found || found->sort < grant_name->sort))
	found=grant_name;					// Host ok
unknown's avatar
unknown committed
2120 2121 2122 2123 2124 2125
    }
  }
  return found;
}


2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142
inline GRANT_NAME *
proc_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(&proc_priv_hash, host, ip, db,
					 user, tname, exact);
}


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
2143

unknown's avatar
unknown committed
2144
inline GRANT_COLUMN *
unknown's avatar
unknown committed
2145
column_hash_search(GRANT_TABLE *t, const char *cname, uint length)
unknown's avatar
unknown committed
2146 2147 2148 2149 2150 2151 2152 2153 2154
{
  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
2155
				ulong rights, bool revoke_grant)
unknown's avatar
unknown committed
2156 2157 2158
{
  int error=0,result=0;
  byte key[MAX_KEY_LENGTH];
2159 2160
  uint key_prefix_length;
  KEY_PART_INFO *key_part= table->key_info->key_part;
unknown's avatar
unknown committed
2161 2162
  DBUG_ENTER("replace_column_table");

2163 2164 2165 2166
  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
2167

2168 2169 2170 2171
  /* 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
2172

2173
  rights&= COL_ACLS;				// Only ACL for columns
unknown's avatar
unknown committed
2174 2175 2176 2177 2178

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

  List_iterator <LEX_COLUMN> iter(columns);
  class LEX_COLUMN *xx;
unknown's avatar
unknown committed
2179
  table->file->ha_index_init(0);
unknown's avatar
unknown committed
2180 2181
  while ((xx=iter++))
  {
unknown's avatar
unknown committed
2182
    ulong privileges = xx->rights;
unknown's avatar
unknown committed
2183
    bool old_row_exists=0;
2184 2185 2186 2187
    byte user_key[MAX_KEY_LENGTH];

    key_restore(table->record[0],key,table->key_info,
                key_prefix_length);
2188
    table->field[4]->store(xx->column.ptr(),xx->column.length(),
2189
                           system_charset_info);
2190 2191 2192
    /* 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
2193

unknown's avatar
unknown committed
2194
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
2195 2196 2197
    if (table->file->index_read(table->record[0], user_key,
				table->key_info->key_length,
                                HA_READ_KEY_EXACT))
unknown's avatar
unknown committed
2198 2199 2200
    {
      if (revoke_grant)
      {
unknown's avatar
unknown committed
2201
	my_error(ER_NONEXISTING_TABLE_GRANT, MYF(0),
2202 2203
                 combo.user.str, combo.host.str,
                 table_name); /* purecov: inspected */
unknown's avatar
unknown committed
2204 2205 2206
	result= -1; /* purecov: inspected */
	continue; /* purecov: inspected */
      }
unknown's avatar
unknown committed
2207
      old_row_exists = 0;
2208
      restore_record(table, s->default_values);		// Get empty record
2209 2210
      key_restore(table->record[0],key,table->key_info,
                  key_prefix_length);
2211
      table->field[4]->store(xx->column.ptr(),xx->column.length(),
2212
                             system_charset_info);
unknown's avatar
unknown committed
2213 2214 2215
    }
    else
    {
unknown's avatar
unknown committed
2216
      ulong tmp= (ulong) table->field[6]->val_int();
unknown's avatar
unknown committed
2217 2218 2219 2220 2221 2222
      tmp=fix_rights_for_column(tmp);

      if (revoke_grant)
	privileges = tmp & ~(privileges | rights);
      else
	privileges |= tmp;
unknown's avatar
unknown committed
2223
      old_row_exists = 1;
unknown's avatar
unknown committed
2224
      store_record(table,record[1]);			// copy original row
unknown's avatar
unknown committed
2225 2226 2227 2228
    }

    table->field[6]->store((longlong) get_rights_for_column(privileges));

unknown's avatar
unknown committed
2229
    if (old_row_exists)
unknown's avatar
unknown committed
2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255
    {
      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 */
      }
      GRANT_COLUMN *grant_column = column_hash_search(g_t,
						      xx->column.ptr(),
						      xx->column.length());
      if (grant_column)				// Should always be true
	grant_column->rights = privileges;	// Update hash
    }
    else					// new grant
    {
      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 */
      }
      GRANT_COLUMN *grant_column = new GRANT_COLUMN(xx->column,privileges);
unknown's avatar
SCRUM  
unknown committed
2256
      my_hash_insert(&g_t->hash_columns,(byte*) grant_column);
unknown's avatar
unknown committed
2257 2258 2259 2260 2261 2262 2263 2264 2265 2266
    }
  }

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

  if (revoke_grant)
  {
2267 2268
    byte user_key[MAX_KEY_LENGTH];
    key_copy(user_key, table->record[0], table->key_info,
unknown's avatar
unknown committed
2269 2270
             key_prefix_length);

unknown's avatar
unknown committed
2271
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
2272
    if (table->file->index_read(table->record[0], user_key,
unknown's avatar
unknown committed
2273
				key_prefix_length,
2274
                                HA_READ_KEY_EXACT))
unknown's avatar
unknown committed
2275 2276
      goto end;

2277
    /* Scan through all rows with the same host,db,user and table */
unknown's avatar
unknown committed
2278 2279
    do
    {
unknown's avatar
unknown committed
2280
      ulong privileges = (ulong) table->field[6]->val_int();
unknown's avatar
unknown committed
2281
      privileges=fix_rights_for_column(privileges);
unknown's avatar
unknown committed
2282
      store_record(table,record[1]);
unknown's avatar
unknown committed
2283 2284 2285 2286 2287

      if (privileges & rights)	// is in this record the priv to be revoked ??
      {
	GRANT_COLUMN *grant_column = NULL;
	char  colum_name_buf[HOSTNAME_LENGTH+1];
2288
	String column_name(colum_name_buf,sizeof(colum_name_buf),
unknown's avatar
unknown committed
2289
                           system_charset_info);
unknown's avatar
unknown committed
2290 2291 2292 2293

	privileges&= ~rights;
	table->field[6]->store((longlong)
			       get_rights_for_column(privileges));
2294
	table->field[4]->val_str(&column_name);
unknown's avatar
unknown committed
2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324
	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]) &&
2325
	     !key_cmp_if_same(table, key, 0, key_prefix_length));
unknown's avatar
unknown committed
2326 2327
  }

2328
end:
unknown's avatar
unknown committed
2329
  table->file->ha_index_end();
unknown's avatar
unknown committed
2330 2331 2332 2333 2334 2335 2336
  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
2337 2338
			       ulong rights, ulong col_rights,
			       bool revoke_grant)
unknown's avatar
unknown committed
2339
{
2340
  char grantor[HOSTNAME_LENGTH+USERNAME_LENGTH+2];
unknown's avatar
unknown committed
2341
  int old_row_exists = 1;
unknown's avatar
unknown committed
2342
  int error=0;
unknown's avatar
unknown committed
2343
  ulong store_table_rights, store_col_rights;
2344
  byte user_key[MAX_KEY_LENGTH];
unknown's avatar
unknown committed
2345 2346
  DBUG_ENTER("replace_table_table");

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

unknown's avatar
unknown committed
2349 2350 2351 2352
  /*
    The following should always succeed as new users are created before
    this function is called!
  */
unknown's avatar
unknown committed
2353 2354
  if (!find_acl_user(combo.host.str,combo.user.str))
  {
unknown's avatar
unknown committed
2355 2356
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH),
               MYF(0));	/* purecov: deadcode */
unknown's avatar
unknown committed
2357 2358 2359
    DBUG_RETURN(-1);				/* purecov: deadcode */
  }

2360
  restore_record(table, s->default_values);     // Get empty record
2361 2362 2363 2364
  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
2365
  store_record(table,record[1]);			// store at pos 1
2366 2367
  key_copy(user_key, table->record[0], table->key_info,
           table->key_info->key_length);
unknown's avatar
unknown committed
2368

unknown's avatar
unknown committed
2369
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
2370 2371
  if (table->file->index_read_idx(table->record[0], 0,
                                  user_key, table->key_info->key_length,
unknown's avatar
unknown committed
2372 2373 2374 2375 2376 2377 2378 2379 2380
				  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
2381 2382
      my_error(ER_NONEXISTING_TABLE_GRANT, MYF(0),
               combo.user.str, combo.host.str,
2383
               table_name);		        /* purecov: deadcode */
unknown's avatar
unknown committed
2384 2385
      DBUG_RETURN(-1);				/* purecov: deadcode */
    }
unknown's avatar
unknown committed
2386
    old_row_exists = 0;
unknown's avatar
unknown committed
2387
    restore_record(table,record[1]);			// Get saved record
unknown's avatar
unknown committed
2388 2389
  }

unknown's avatar
unknown committed
2390 2391
  store_table_rights= get_rights_for_table(rights);
  store_col_rights=   get_rights_for_column(col_rights);
unknown's avatar
unknown committed
2392
  if (old_row_exists)
unknown's avatar
unknown committed
2393
  {
unknown's avatar
unknown committed
2394
    ulong j,k;
unknown's avatar
unknown committed
2395
    store_record(table,record[1]);
unknown's avatar
unknown committed
2396 2397
    j = (ulong) table->field[6]->val_int();
    k = (ulong) table->field[7]->val_int();
unknown's avatar
unknown committed
2398 2399 2400

    if (revoke_grant)
    {
2401
      /* column rights are already fixed in mysql_table_grant */
unknown's avatar
unknown committed
2402 2403 2404 2405
      store_table_rights=j & ~store_table_rights;
    }
    else
    {
unknown's avatar
unknown committed
2406 2407
      store_table_rights|= j;
      store_col_rights|=   k;
unknown's avatar
unknown committed
2408 2409 2410
    }
  }

2411
  table->field[4]->store(grantor,(uint) strlen(grantor), system_charset_info);
unknown's avatar
unknown committed
2412 2413 2414
  table->field[6]->store((longlong) store_table_rights);
  table->field[7]->store((longlong) store_col_rights);
  rights=fix_rights_for_table(store_table_rights);
unknown's avatar
unknown committed
2415
  col_rights=fix_rights_for_column(store_col_rights);
unknown's avatar
unknown committed
2416

unknown's avatar
unknown committed
2417
  if (old_row_exists)
unknown's avatar
unknown committed
2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433
  {
    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
2434
  if (rights | col_rights)
unknown's avatar
unknown committed
2435
  {
unknown's avatar
unknown committed
2436
    grant_table->privs= rights;
2437
    grant_table->cols=	col_rights;
unknown's avatar
unknown committed
2438 2439 2440
  }
  else
  {
2441
    hash_delete(&column_priv_hash,(byte*) grant_table);
unknown's avatar
unknown committed
2442 2443 2444
  }
  DBUG_RETURN(0);

2445 2446
  /* This should never happen */
table_error:
unknown's avatar
unknown committed
2447 2448 2449 2450 2451
  table->file->print_error(error,MYF(0)); /* purecov: deadcode */
  DBUG_RETURN(-1); /* purecov: deadcode */
}


2452 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
static int replace_proc_table(THD *thd, GRANT_NAME *grant_name,
			      TABLE *table, const LEX_USER &combo,
			      const char *db, const char *proc_name,
			      ulong rights, bool revoke_grant)
{
  char grantor[HOSTNAME_LENGTH+USERNAME_LENGTH+2];
  int old_row_exists= 1;
  int error=0;
  ulong store_proc_rights;
  DBUG_ENTER("replace_proc_table");

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

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

  /*
    The following should always succeed as new users are created before
    this function is called!
  */
  if (!find_acl_user(combo.host.str,combo.user.str))
  {
    my_error(ER_PASSWORD_NO_MATCH,MYF(0));
    DBUG_RETURN(-1);
  }

2481
  restore_record(table, s->default_values);		// Get empty record
2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562
  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);
  table->field[3]->store(proc_name,(uint) strlen(proc_name), &my_charset_latin1);
  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),
               combo.user.str, combo.host.str, proc_name);
      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;
    }
  }

  table->field[4]->store(grantor,(uint) strlen(grantor), &my_charset_latin1);
  table->field[6]->store((longlong) store_proc_rights);
  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
  {
    hash_delete(&proc_priv_hash,(byte*) grant_name);
  }
  DBUG_RETURN(0);

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


2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575
/*
  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
2576 2577
    FALSE ok
    TRUE  error
2578 2579
*/

unknown's avatar
unknown committed
2580
bool mysql_table_grant(THD *thd, TABLE_LIST *table_list,
unknown's avatar
unknown committed
2581 2582 2583
		      List <LEX_USER> &user_list,
		      List <LEX_COLUMN> &columns, ulong rights,
		      bool revoke_grant)
unknown's avatar
unknown committed
2584
{
2585
  ulong column_priv= 0;
unknown's avatar
unknown committed
2586 2587 2588
  List_iterator <LEX_USER> str_list (user_list);
  LEX_USER *Str;
  TABLE_LIST tables[3];
unknown's avatar
unknown committed
2589
  bool create_new_users=0;
2590
  char *db_name, *table_name;
unknown's avatar
unknown committed
2591 2592 2593 2594
  DBUG_ENTER("mysql_table_grant");

  if (!initialized)
  {
unknown's avatar
unknown committed
2595 2596
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0),
             "--skip-grant-tables");	/* purecov: inspected */
unknown's avatar
unknown committed
2597
    DBUG_RETURN(TRUE);				/* purecov: inspected */
unknown's avatar
unknown committed
2598 2599 2600
  }
  if (rights & ~TABLE_ACLS)
  {
unknown's avatar
unknown committed
2601 2602
    my_message(ER_ILLEGAL_GRANT_FOR_TABLE, ER(ER_ILLEGAL_GRANT_FOR_TABLE),
               MYF(0));
unknown's avatar
unknown committed
2603
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
2604 2605
  }

2606
  if (!revoke_grant)
unknown's avatar
unknown committed
2607
  {
unknown's avatar
unknown committed
2608
    if (columns.elements)
unknown's avatar
unknown committed
2609
    {
2610 2611
      class LEX_COLUMN *column;
      List_iterator <LEX_COLUMN> column_iter(columns);
unknown's avatar
unknown committed
2612 2613 2614

      if (open_and_lock_tables(thd, table_list))
        DBUG_RETURN(TRUE);
2615 2616

      while ((column = column_iter++))
unknown's avatar
unknown committed
2617
      {
unknown's avatar
merged  
unknown committed
2618
        uint unused_field_idx= NO_CACHED_FIELD_INDEX;
unknown's avatar
unknown committed
2619 2620
        Field *f=find_field_in_table(thd, table_list, column->column.ptr(),
                                     column->column.ptr(),
unknown's avatar
unknown committed
2621
                                     column->column.length(), 0, 1, 1, 0,
unknown's avatar
unknown committed
2622 2623
                                     &unused_field_idx, FALSE);
        if (f == (Field*)0)
2624
        {
unknown's avatar
merged  
unknown committed
2625 2626
          my_error(ER_BAD_FIELD_ERROR, MYF(0),
                   column->column.c_ptr(), table_list->alias);
unknown's avatar
unknown committed
2627
          DBUG_RETURN(TRUE);
2628
        }
unknown's avatar
unknown committed
2629 2630
        if (f == (Field *)-1)
          DBUG_RETURN(TRUE);
2631
        column_priv|= column->rights;
unknown's avatar
unknown committed
2632
      }
2633
      close_thread_tables(thd);
unknown's avatar
unknown committed
2634
    }
2635
    else
unknown's avatar
unknown committed
2636
    {
2637 2638 2639 2640
      if (!(rights & CREATE_ACL))
      {
        char buf[FN_REFLEN];
        sprintf(buf,"%s/%s/%s.frm",mysql_data_home, table_list->db,
2641
                table_list->table_name);
2642 2643 2644
        fn_format(buf,buf,"","",4+16+32);
        if (access(buf,F_OK))
        {
unknown's avatar
merged  
unknown committed
2645
          my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->alias);
unknown's avatar
unknown committed
2646
          DBUG_RETURN(TRUE);
2647 2648 2649 2650 2651 2652 2653 2654
        }
      }
      if (table_list->grant.want_privilege)
      {
        char command[128];
        get_privilege_desc(command, sizeof(command),
                           table_list->grant.want_privilege);
        my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0),
unknown's avatar
unknown committed
2655
                 command, thd->priv_user, thd->host_or_ip, table_list->alias);
2656 2657
        DBUG_RETURN(-1);
      }
unknown's avatar
unknown committed
2658 2659 2660 2661 2662 2663
    }
  }

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

  bzero((char*) &tables,sizeof(tables));
2664 2665 2666
  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
2667
  tables[0].next_local= tables[0].next_global= tables+1;
unknown's avatar
unknown committed
2668
  /* Don't open column table if we don't need it ! */
unknown's avatar
VIEW  
unknown committed
2669 2670 2671 2672 2673
  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
2674 2675 2676
  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";

2677 2678 2679 2680 2681
#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
2682 2683
  if (thd->slave_thread && table_rules_on)
  {
unknown's avatar
unknown committed
2684 2685 2686
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
2687
    */
2688
    tables[0].updating= tables[1].updating= tables[2].updating= 1;
2689
    if (!tables_ok(0, tables))
unknown's avatar
unknown committed
2690
      DBUG_RETURN(FALSE);
2691
  }
2692 2693
#endif

2694
  if (simple_open_n_lock_tables(thd,tables))
unknown's avatar
unknown committed
2695 2696
  {						// Should never happen
    close_thread_tables(thd);			/* purecov: deadcode */
unknown's avatar
unknown committed
2697
    DBUG_RETURN(TRUE);				/* purecov: deadcode */
unknown's avatar
unknown committed
2698 2699
  }

unknown's avatar
unknown committed
2700 2701
  if (!revoke_grant)
    create_new_users= test_if_create_new_users(thd);
unknown's avatar
unknown committed
2702
  bool result= FALSE;
2703
  rw_wrlock(&LOCK_grant);
unknown's avatar
unknown committed
2704 2705
  MEM_ROOT *old_root= thd->mem_root;
  thd->mem_root= &memex;
unknown's avatar
unknown committed
2706 2707 2708

  while ((Str = str_list++))
  {
unknown's avatar
unknown committed
2709
    int error;
unknown's avatar
unknown committed
2710 2711 2712 2713
    GRANT_TABLE *grant_table;
    if (Str->host.length > HOSTNAME_LENGTH ||
	Str->user.length > USERNAME_LENGTH)
    {
unknown's avatar
unknown committed
2714 2715
      my_message(ER_GRANT_WRONG_HOST_OR_USER, ER(ER_GRANT_WRONG_HOST_OR_USER),
                 MYF(0));
unknown's avatar
unknown committed
2716
      result= TRUE;
unknown's avatar
unknown committed
2717 2718 2719
      continue;
    }
    /* Create user if needed */
unknown's avatar
unknown committed
2720
    pthread_mutex_lock(&acl_cache->lock);
unknown's avatar
unknown committed
2721 2722
    error=replace_user_table(thd, tables[0].table, *Str,
			     0, revoke_grant, create_new_users);
unknown's avatar
unknown committed
2723 2724
    pthread_mutex_unlock(&acl_cache->lock);
    if (error)
unknown's avatar
unknown committed
2725
    {
unknown's avatar
unknown committed
2726
      result= TRUE;				// Remember error
unknown's avatar
unknown committed
2727 2728 2729
      continue;					// Add next user
    }

unknown's avatar
VIEW  
unknown committed
2730 2731 2732
    db_name= (table_list->view_db.length ?
	      table_list->view_db.str :
	      table_list->db);
2733
    table_name= (table_list->view_name.length ?
unknown's avatar
VIEW  
unknown committed
2734
		table_list->view_name.str :
2735
		table_list->table_name);
unknown's avatar
VIEW  
unknown committed
2736

unknown's avatar
unknown committed
2737
    /* Find/create cached table grant */
unknown's avatar
VIEW  
unknown committed
2738
    grant_table= table_hash_search(Str->host.str, NullS, db_name,
2739
				   Str->user.str, table_name, 1);
unknown's avatar
unknown committed
2740 2741 2742 2743
    if (!grant_table)
    {
      if (revoke_grant)
      {
unknown's avatar
unknown committed
2744
	my_error(ER_NONEXISTING_TABLE_GRANT, MYF(0),
2745
                 Str->user.str, Str->host.str, table_list->table_name);
unknown's avatar
unknown committed
2746
	result= TRUE;
unknown's avatar
unknown committed
2747 2748
	continue;
      }
unknown's avatar
VIEW  
unknown committed
2749
      grant_table = new GRANT_TABLE (Str->host.str, db_name,
2750
				     Str->user.str, table_name,
unknown's avatar
unknown committed
2751 2752 2753 2754
				     rights,
				     column_priv);
      if (!grant_table)				// end of memory
      {
unknown's avatar
unknown committed
2755
	result= TRUE;				/* purecov: deadcode */
unknown's avatar
unknown committed
2756 2757
	continue;				/* purecov: deadcode */
      }
unknown's avatar
SCRUM  
unknown committed
2758
      my_hash_insert(&column_priv_hash,(byte*) grant_table);
unknown's avatar
unknown committed
2759 2760 2761 2762 2763
    }

    /* If revoke_grant, calculate the new column privilege for tables_priv */
    if (revoke_grant)
    {
2764 2765
      class LEX_COLUMN *column;
      List_iterator <LEX_COLUMN> column_iter(columns);
unknown's avatar
unknown committed
2766 2767 2768
      GRANT_COLUMN *grant_column;

      /* Fix old grants */
2769
      while ((column = column_iter++))
unknown's avatar
unknown committed
2770 2771
      {
	grant_column = column_hash_search(grant_table,
2772 2773
					  column->column.ptr(),
					  column->column.length());
unknown's avatar
unknown committed
2774
	if (grant_column)
2775
	  grant_column->rights&= ~(column->rights | rights);
unknown's avatar
unknown committed
2776 2777
      }
      /* scan trough all columns to get new column grant */
2778
      column_priv= 0;
unknown's avatar
unknown committed
2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794
      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
2795
    if (replace_table_table(thd, grant_table, tables[1].table, *Str,
2796
			    db_name, table_name,
unknown's avatar
unknown committed
2797
			    rights, column_priv, revoke_grant))
2798 2799
    {
      /* Should only happen if table is crashed */
unknown's avatar
unknown committed
2800
      result= TRUE;			       /* purecov: deadcode */
unknown's avatar
unknown committed
2801 2802 2803
    }
    else if (tables[2].table)
    {
unknown's avatar
VIEW  
unknown committed
2804
      if ((replace_column_table(grant_table, tables[2].table, *Str,
unknown's avatar
unknown committed
2805
				columns,
2806
				db_name, table_name,
unknown's avatar
unknown committed
2807 2808
				rights, revoke_grant)))
      {
unknown's avatar
unknown committed
2809
	result= TRUE;
unknown's avatar
unknown committed
2810 2811 2812 2813
      }
    }
  }
  grant_option=TRUE;
unknown's avatar
unknown committed
2814
  thd->mem_root= old_root;
2815
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
2816
  if (!result)
2817
    send_ok(thd);
2818
  /* Tables are automatically closed */
unknown's avatar
unknown committed
2819 2820 2821 2822
  DBUG_RETURN(result);
}


2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846
/*
  Store procedure level grants in the privilege tables

  SYNOPSIS
    mysql_procedure_grant()
    thd			Thread handle
    table_list		List of procedures to give grant
    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
*/

bool mysql_procedure_grant(THD *thd, TABLE_LIST *table_list,
			   List <LEX_USER> &user_list, ulong rights,
			   bool revoke_grant, bool no_error)
{
  List_iterator <LEX_USER> str_list (user_list);
  LEX_USER *Str;
  TABLE_LIST tables[2];
  bool create_new_users=0, result=0;
2847
  char *db_name, *table_name;
2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873
  DBUG_ENTER("mysql_procedure_grant");

  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)
  {
    if (sp_exists_routine(thd, table_list, 0, no_error)<0)
      DBUG_RETURN(TRUE);
  }

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

  bzero((char*) &tables,sizeof(tables));
2874 2875
  tables[0].alias=tables[0].table_name= (char*) "user";
  tables[1].alias=tables[1].table_name= (char*) "procs_priv";
2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935
  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;
    if (!tables_ok(0, tables))
      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,
			     0, revoke_grant, create_new_users);
    pthread_mutex_unlock(&acl_cache->lock);
    if (error)
    {
      result= TRUE;				// Remember error
      continue;					// Add next user
    }

    db_name= table_list->db;
2936
    table_name= table_list->table_name;
2937 2938

    grant_name= proc_hash_search(Str->host.str, NullS, db_name,
2939
    				 Str->user.str, table_name, 1);
2940 2941 2942 2943 2944 2945
    if (!grant_name)
    {
      if (revoke_grant)
      {
        if (!no_error)
          my_error(ER_NONEXISTING_PROC_GRANT, MYF(0),
2946
		   Str->user.str, Str->host.str, table_name);
2947 2948 2949 2950
	result= TRUE;
	continue;
      }
      grant_name= new GRANT_NAME(Str->host.str, db_name,
2951
				 Str->user.str, table_name,
2952 2953 2954 2955 2956 2957 2958 2959 2960 2961
				 rights);
      if (!grant_name)
      {
        result= TRUE;
	continue;
      }
      my_hash_insert(&proc_priv_hash,(byte*) grant_name);
    }
    
    if (replace_proc_table(thd, grant_name, tables[1].table, *Str,
2962
			   db_name, table_name, rights, revoke_grant))
2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977
    {
      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
2978 2979
bool mysql_grant(THD *thd, const char *db, List <LEX_USER> &list,
                 ulong rights, bool revoke_grant)
unknown's avatar
unknown committed
2980 2981 2982
{
  List_iterator <LEX_USER> str_list (list);
  LEX_USER *Str;
unknown's avatar
unknown committed
2983
  char tmp_db[NAME_LEN+1];
unknown's avatar
unknown committed
2984
  bool create_new_users=0;
unknown's avatar
unknown committed
2985 2986 2987 2988
  TABLE_LIST tables[2];
  DBUG_ENTER("mysql_grant");
  if (!initialized)
  {
unknown's avatar
unknown committed
2989 2990
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0),
             "--skip-grant-tables");	/* purecov: tested */
unknown's avatar
unknown committed
2991
    DBUG_RETURN(TRUE);				/* purecov: tested */
unknown's avatar
unknown committed
2992 2993
  }

unknown's avatar
unknown committed
2994 2995 2996
  if (lower_case_table_names && db)
  {
    strmov(tmp_db,db);
2997
    my_casedn_str(files_charset_info, tmp_db);
unknown's avatar
unknown committed
2998 2999
    db=tmp_db;
  }
unknown's avatar
unknown committed
3000 3001

  /* open the mysql.user and mysql.db tables */
3002
  bzero((char*) &tables,sizeof(tables));
3003 3004
  tables[0].alias=tables[0].table_name=(char*) "user";
  tables[1].alias=tables[1].table_name=(char*) "db";
unknown's avatar
VIEW  
unknown committed
3005
  tables[0].next_local= tables[0].next_global= tables+1;
unknown's avatar
unknown committed
3006 3007
  tables[0].lock_type=tables[1].lock_type=TL_WRITE;
  tables[0].db=tables[1].db=(char*) "mysql";
3008 3009 3010 3011 3012 3013

#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
3014 3015
  if (thd->slave_thread && table_rules_on)
  {
unknown's avatar
unknown committed
3016 3017 3018
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
3019
    */
3020
    tables[0].updating= tables[1].updating= 1;
3021
    if (!tables_ok(0, tables))
unknown's avatar
unknown committed
3022
      DBUG_RETURN(FALSE);
3023
  }
3024 3025
#endif

3026
  if (simple_open_n_lock_tables(thd,tables))
unknown's avatar
unknown committed
3027 3028
  {						// This should never happen
    close_thread_tables(thd);			/* purecov: deadcode */
unknown's avatar
unknown committed
3029
    DBUG_RETURN(TRUE);				/* purecov: deadcode */
unknown's avatar
unknown committed
3030 3031
  }

unknown's avatar
unknown committed
3032 3033
  if (!revoke_grant)
    create_new_users= test_if_create_new_users(thd);
unknown's avatar
unknown committed
3034

3035
  /* go through users in user_list */
3036
  rw_wrlock(&LOCK_grant);
unknown's avatar
unknown committed
3037 3038 3039 3040 3041 3042 3043 3044 3045
  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
3046 3047
      my_message(ER_GRANT_WRONG_HOST_OR_USER, ER(ER_GRANT_WRONG_HOST_OR_USER),
                 MYF(0));
unknown's avatar
unknown committed
3048 3049 3050
      result= -1;
      continue;
    }
3051
    if ((replace_user_table(thd,
3052
			    tables[0].table,
unknown's avatar
unknown committed
3053
			    *Str,
unknown's avatar
unknown committed
3054 3055
			    (!db ? rights : 0), revoke_grant,
			    create_new_users)))
unknown's avatar
unknown committed
3056
      result= -1;
unknown's avatar
unknown committed
3057
    else if (db)
unknown's avatar
unknown committed
3058
    {
unknown's avatar
unknown committed
3059 3060 3061 3062 3063 3064 3065 3066 3067
      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
3068
	my_error(ER_WRONG_USAGE, MYF(0), "DB GRANT", "GLOBAL PRIVILEGES");
unknown's avatar
unknown committed
3069
	result= -1;
unknown's avatar
unknown committed
3070
      }
unknown's avatar
unknown committed
3071
    }
unknown's avatar
unknown committed
3072 3073
  }
  VOID(pthread_mutex_unlock(&acl_cache->lock));
3074
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
3075 3076 3077
  close_thread_tables(thd);

  if (!result)
3078
    send_ok(thd);
unknown's avatar
unknown committed
3079 3080 3081
  DBUG_RETURN(result);
}

unknown's avatar
unknown committed
3082 3083

/* Free grant array if possible */
unknown's avatar
unknown committed
3084 3085 3086 3087 3088

void  grant_free(void)
{
  DBUG_ENTER("grant_free");
  grant_option = FALSE;
3089
  hash_free(&column_priv_hash);
3090
  hash_free(&proc_priv_hash);
3091
  free_root(&memex,MYF(0));
unknown's avatar
unknown committed
3092 3093 3094 3095 3096 3097
  DBUG_VOID_RETURN;
}


/* Init grant array if possible */

unknown's avatar
unknown committed
3098
my_bool grant_init(THD *org_thd)
unknown's avatar
unknown committed
3099
{
unknown's avatar
unknown committed
3100
  THD  *thd;
3101
  TABLE_LIST tables[3];
unknown's avatar
unknown committed
3102
  MEM_ROOT *memex_ptr;
3103
  my_bool return_val= 1;
3104
  TABLE *t_table, *c_table, *p_table;
unknown's avatar
SCRUM  
unknown committed
3105
  bool check_no_resolve= specialflag & SPECIAL_NO_RESOLVE;
unknown's avatar
unknown committed
3106 3107 3108
  DBUG_ENTER("grant_init");

  grant_option = FALSE;
3109
  (void) hash_init(&column_priv_hash,system_charset_info,
unknown's avatar
unknown committed
3110
		   0,0,0, (hash_get_key) get_grant_table,
unknown's avatar
unknown committed
3111
		   (hash_free_key) free_grant_table,0);
3112 3113 3114
  (void) hash_init(&proc_priv_hash,system_charset_info,
		   0,0,0, (hash_get_key) get_grant_table,
		   0,0);
3115
  init_sql_alloc(&memex, ACL_ALLOC_BLOCK_SIZE, 0);
unknown's avatar
unknown committed
3116

3117
  /* Don't do anything if running with --skip-grant */
unknown's avatar
unknown committed
3118 3119
  if (!initialized)
    DBUG_RETURN(0);				/* purecov: tested */
3120

unknown's avatar
unknown committed
3121 3122
  if (!(thd=new THD))
    DBUG_RETURN(1);				/* purecov: deadcode */
3123
  thd->store_globals();
unknown's avatar
unknown committed
3124 3125
  thd->db= my_strdup("mysql",MYF(0));
  thd->db_length=5;				// Safety
3126
  bzero((char*) &tables, sizeof(tables));
3127 3128 3129
  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";
unknown's avatar
VIEW  
unknown committed
3130
  tables[0].next_local= tables[0].next_global= tables+1;
3131 3132 3133
  tables[1].next_local= tables[1].next_global= tables+2;
  tables[0].lock_type=tables[1].lock_type=tables[2].lock_type=TL_READ;
  tables[0].db=tables[1].db=tables[2].db=thd->db;
unknown's avatar
unknown committed
3134

3135
  if (simple_open_n_lock_tables(thd, tables))
3136
    goto end;
unknown's avatar
unknown committed
3137 3138

  t_table = tables[0].table; c_table = tables[1].table;
3139
  p_table= tables[2].table;
unknown's avatar
unknown committed
3140
  t_table->file->ha_index_init(0);
3141 3142
  p_table->file->ha_index_init(0);
  if (!t_table->file->index_first(t_table->record[0]))
unknown's avatar
unknown committed
3143
  {
3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155
    /* Will be restored by org_thd->store_globals() */
    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
3156

3157 3158
      if (check_no_resolve)
      {
unknown's avatar
unknown committed
3159
	if (hostname_requires_resolving(mem_check->host.hostname))
3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180
	{
          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
3181
  {
3182 3183 3184 3185
    /* Will be restored by org_thd->store_globals() */
    memex_ptr= &memex;
    my_pthread_setspecific_ptr(THR_MALLOC, &memex_ptr);
    do
unknown's avatar
unknown committed
3186
    {
3187 3188 3189 3190 3191 3192 3193
      GRANT_NAME *mem_check;
      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
3194

3195
      if (check_no_resolve)
unknown's avatar
SCRUM  
unknown committed
3196
      {
unknown's avatar
unknown committed
3197
	if (hostname_requires_resolving(mem_check->host.hostname))
3198 3199 3200 3201 3202 3203 3204
	{
          sql_print_warning("'procs_priv' entry '%s %s@%s' "
                            "ignored in --skip-name-resolve mode.",
                            mem_check->tname, mem_check->user,
                            mem_check->host, mem_check->host);
	  continue;
	}
unknown's avatar
SCRUM  
unknown committed
3205 3206
      }

3207 3208 3209 3210 3211 3212 3213 3214 3215
      mem_check->privs= fix_rights_for_procedure(mem_check->privs);
      if (! mem_check->ok())
	delete mem_check;
      else if (my_hash_insert(&proc_priv_hash,(byte*) mem_check))
      {
	delete mem_check;
	grant_option= FALSE;
	goto end_unlock;
      }
unknown's avatar
SCRUM  
unknown committed
3216
    }
3217
    while (!p_table->file->index_next(p_table->record[0]));
unknown's avatar
unknown committed
3218
  }
3219
  grant_option= TRUE;
3220 3221 3222
  return_val=0;					// Return ok

end_unlock:
unknown's avatar
unknown committed
3223
  t_table->file->ha_index_end();
3224
  p_table->file->ha_index_end();
unknown's avatar
unknown committed
3225
  thd->version--;				// Force close to free memory
3226 3227

end:
unknown's avatar
unknown committed
3228 3229
  close_thread_tables(thd);
  delete thd;
3230 3231
  if (org_thd)
    org_thd->store_globals();
unknown's avatar
unknown committed
3232 3233 3234 3235 3236
  else
  {
    /* Remember that we don't have a THD */
    my_pthread_setspecific_ptr(THR_THD,  0);
  }
3237
  DBUG_RETURN(return_val);
unknown's avatar
unknown committed
3238 3239 3240
}


3241
/*
unknown's avatar
unknown committed
3242
 Reload grant array (table and column privileges) if possible
3243 3244 3245

  SYNOPSIS
    grant_reload()
3246
    thd			Thread handler (can be NULL)
3247 3248 3249 3250

  NOTES
    Locked tables are checked by acl_init and doesn't have to be checked here
*/
unknown's avatar
unknown committed
3251

unknown's avatar
unknown committed
3252
void grant_reload(THD *thd)
unknown's avatar
unknown committed
3253
{
3254
  HASH old_column_priv_hash, old_proc_priv_hash;
3255
  bool old_grant_option;
unknown's avatar
unknown committed
3256 3257 3258
  MEM_ROOT old_mem;
  DBUG_ENTER("grant_reload");

3259
  rw_wrlock(&LOCK_grant);
unknown's avatar
unknown committed
3260
  grant_version++;
3261
  old_column_priv_hash= column_priv_hash;
3262
  old_proc_priv_hash= proc_priv_hash;
unknown's avatar
unknown committed
3263
  old_grant_option= grant_option;
unknown's avatar
unknown committed
3264
  old_mem= memex;
unknown's avatar
unknown committed
3265

unknown's avatar
unknown committed
3266
  if (grant_init(thd))
unknown's avatar
unknown committed
3267
  {						// Error. Revert to old hash
3268
    DBUG_PRINT("error",("Reverting to old privileges"));
unknown's avatar
unknown committed
3269
    grant_free();				/* purecov: deadcode */
3270
    column_priv_hash= old_column_priv_hash;	/* purecov: deadcode */
3271
    proc_priv_hash= old_proc_priv_hash;
unknown's avatar
unknown committed
3272
    grant_option= old_grant_option;		/* purecov: deadcode */
unknown's avatar
unknown committed
3273
    memex= old_mem;				/* purecov: deadcode */
unknown's avatar
unknown committed
3274 3275 3276
  }
  else
  {
3277
    hash_free(&old_column_priv_hash);
3278
    hash_free(&old_proc_priv_hash);
3279
    free_root(&old_mem,MYF(0));
unknown's avatar
unknown committed
3280
  }
3281
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
3282 3283 3284 3285 3286
  DBUG_VOID_RETURN;
}


/****************************************************************************
3287
  Check table level grants
3288

3289
  SYNOPSIS
3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302
   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
3303
     1  Error: User did not have the requested privileges
unknown's avatar
unknown committed
3304 3305
****************************************************************************/

unknown's avatar
unknown committed
3306
bool check_grant(THD *thd, ulong want_access, TABLE_LIST *tables,
unknown's avatar
unknown committed
3307
		 uint show_table, uint number, bool no_errors)
unknown's avatar
unknown committed
3308 3309 3310
{
  TABLE_LIST *table;
  char *user = thd->priv_user;
3311 3312
  DBUG_ENTER("check_grant");
  DBUG_ASSERT(number > 0);
unknown's avatar
unknown committed
3313

3314
  want_access&= ~thd->master_access;
unknown's avatar
unknown committed
3315
  if (!want_access)
3316
    DBUG_RETURN(0);                             // ok
unknown's avatar
unknown committed
3317

3318
  rw_rdlock(&LOCK_grant);
unknown's avatar
VIEW  
unknown committed
3319
  for (table= tables; table && number--; table= table->next_global)
unknown's avatar
unknown committed
3320
  {
3321
    GRANT_TABLE *grant_table;
3322
    if (!(~table->grant.privilege & want_access) || 
3323
        table->derived || table->schema_table || table->belong_to_view)
unknown's avatar
unknown committed
3324
    {
unknown's avatar
VIEW  
unknown committed
3325 3326 3327 3328 3329
      /*
        It is subquery in the FROM clause. VIEW set table->derived after
        table opening, but this function always called before table opening.
      */
      table->grant.want_privilege= 0;
unknown's avatar
unknown committed
3330 3331
      continue;					// Already checked
    }
3332
    if (!(grant_table= table_hash_search(thd->host,thd->ip,
3333
                                         table->db,user, table->table_name,0)))
unknown's avatar
unknown committed
3334 3335 3336 3337
    {
      want_access &= ~table->grant.privilege;
      goto err;					// No grants
    }
unknown's avatar
unknown committed
3338 3339
    if (show_table)
      continue;					// We have some priv on this
unknown's avatar
unknown committed
3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355

    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
    }
  }
3356
  rw_unlock(&LOCK_grant);
3357
  DBUG_RETURN(0);
unknown's avatar
unknown committed
3358

3359
err:
3360
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
3361
  if (!no_errors)				// Not a silent skip of table
unknown's avatar
unknown committed
3362
  {
3363 3364
    char command[128];
    get_privilege_desc(command, sizeof(command), want_access);
3365 3366 3367 3368
    my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0),
             command,
             thd->priv_user,
             thd->host_or_ip,
3369
             table ? table->table_name : "unknown");
unknown's avatar
unknown committed
3370
  }
3371
  DBUG_RETURN(1);
unknown's avatar
unknown committed
3372 3373 3374
}


unknown's avatar
VIEW  
unknown committed
3375
bool check_grant_column(THD *thd, GRANT_INFO *grant,
3376
			const char *db_name, const char *table_name,
unknown's avatar
VIEW  
unknown committed
3377
			const char *name, uint length, uint show_tables)
unknown's avatar
unknown committed
3378 3379 3380
{
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;
unknown's avatar
VIEW  
unknown committed
3381
  ulong want_access= grant->want_privilege & ~grant->privilege;
unknown's avatar
unknown committed
3382 3383 3384
  DBUG_ENTER("check_grant_column");
  DBUG_PRINT("enter", ("table: %s  want_access: %u", table_name, want_access));

unknown's avatar
unknown committed
3385
  if (!want_access)
unknown's avatar
unknown committed
3386
    DBUG_RETURN(0);				// Already checked
unknown's avatar
unknown committed
3387

3388
  rw_rdlock(&LOCK_grant);
unknown's avatar
unknown committed
3389

3390
  /* reload table if someone has modified any grants */
unknown's avatar
unknown committed
3391

unknown's avatar
VIEW  
unknown committed
3392
  if (grant->version != grant_version)
unknown's avatar
unknown committed
3393
  {
unknown's avatar
VIEW  
unknown committed
3394 3395
    grant->grant_table=
      table_hash_search(thd->host, thd->ip, db_name,
unknown's avatar
unknown committed
3396
			thd->priv_user,
unknown's avatar
unknown committed
3397
			table_name, 0);         /* purecov: inspected */
unknown's avatar
VIEW  
unknown committed
3398
    grant->version= grant_version;		/* purecov: inspected */
unknown's avatar
unknown committed
3399
  }
unknown's avatar
VIEW  
unknown committed
3400
  if (!(grant_table= grant->grant_table))
unknown's avatar
unknown committed
3401 3402 3403 3404 3405
    goto err;					/* purecov: deadcode */

  grant_column=column_hash_search(grant_table, name, length);
  if (grant_column && !(~grant_column->rights & want_access))
  {
3406
    rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
3407
    DBUG_RETURN(0);
unknown's avatar
unknown committed
3408 3409
  }
#ifdef NOT_USED
unknown's avatar
VIEW  
unknown committed
3410
  if (show_tables && (grant_column || grant->privilege & COL_ACLS))
unknown's avatar
unknown committed
3411
  {
3412
    rw_unlock(&LOCK_grant);			/* purecov: deadcode */
unknown's avatar
unknown committed
3413
    DBUG_RETURN(0);				/* purecov: deadcode */
unknown's avatar
unknown committed
3414 3415 3416
  }
#endif

3417
err:
3418
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
3419 3420
  if (!show_tables)
  {
unknown's avatar
unknown committed
3421 3422
    char command[128];
    get_privilege_desc(command, sizeof(command), want_access);
3423 3424 3425 3426 3427 3428
    my_error(ER_COLUMNACCESS_DENIED_ERROR, MYF(0),
             command,
             thd->priv_user,
             thd->host_or_ip,
             name,
             table_name);
unknown's avatar
unknown committed
3429
  }
unknown's avatar
unknown committed
3430
  DBUG_RETURN(1);
unknown's avatar
unknown committed
3431 3432 3433
}


unknown's avatar
VIEW  
unknown committed
3434
bool check_grant_all_columns(THD *thd, ulong want_access, GRANT_INFO *grant,
3435
                             const char* db_name, const char *table_name,
unknown's avatar
VIEW  
unknown committed
3436
                             Field_iterator *fields)
unknown's avatar
unknown committed
3437 3438 3439 3440
{
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;

unknown's avatar
VIEW  
unknown committed
3441
  want_access &= ~grant->privilege;
unknown's avatar
unknown committed
3442
  if (!want_access)
unknown's avatar
unknown committed
3443
    return 0;				// Already checked
unknown's avatar
unknown committed
3444 3445
  if (!grant_option)
    goto err2;
unknown's avatar
unknown committed
3446

3447
  rw_rdlock(&LOCK_grant);
unknown's avatar
unknown committed
3448

3449
  /* reload table if someone has modified any grants */
unknown's avatar
unknown committed
3450

unknown's avatar
VIEW  
unknown committed
3451
  if (grant->version != grant_version)
unknown's avatar
unknown committed
3452
  {
unknown's avatar
VIEW  
unknown committed
3453 3454
    grant->grant_table=
      table_hash_search(thd->host, thd->ip, db_name,
unknown's avatar
unknown committed
3455
			thd->priv_user,
unknown's avatar
VIEW  
unknown committed
3456 3457
			table_name, 0);	/* purecov: inspected */
    grant->version= grant_version;		/* purecov: inspected */
unknown's avatar
unknown committed
3458
  }
3459
  /* The following should always be true */
unknown's avatar
VIEW  
unknown committed
3460
  if (!(grant_table= grant->grant_table))
unknown's avatar
unknown committed
3461 3462
    goto err;					/* purecov: inspected */

3463
  for (; !fields->end_of_fields(); fields->next())
unknown's avatar
unknown committed
3464
  {
unknown's avatar
VIEW  
unknown committed
3465 3466 3467
    const char *field_name= fields->name();
    grant_column= column_hash_search(grant_table, field_name,
				    (uint) strlen(field_name));
unknown's avatar
unknown committed
3468 3469 3470
    if (!grant_column || (~grant_column->rights & want_access))
      goto err;
  }
3471
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
3472 3473
  return 0;

unknown's avatar
unknown committed
3474
err:
3475
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
3476
err2:
3477 3478
  char command[128];
  get_privilege_desc(command, sizeof(command), want_access);
3479 3480 3481 3482 3483 3484
  my_error(ER_COLUMNACCESS_DENIED_ERROR, MYF(0),
           command,
           thd->priv_user,
           thd->host_or_ip,
           fields->name(),
           table_name);
unknown's avatar
unknown committed
3485 3486 3487 3488
  return 1;
}


3489
/*
unknown's avatar
unknown committed
3490
  Check if a user has the right to access a database
3491
  Access is accepted if he has a grant for any table/routine in the database
unknown's avatar
unknown committed
3492
  Return 1 if access is denied
3493
*/
unknown's avatar
unknown committed
3494 3495 3496 3497 3498 3499 3500 3501

bool check_grant_db(THD *thd,const char *db)
{
  char helping [NAME_LEN+USERNAME_LENGTH+2];
  uint len;
  bool error=1;

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

3504
  for (uint idx=0 ; idx < column_priv_hash.records ; idx++)
unknown's avatar
unknown committed
3505
  {
3506 3507
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  idx);
unknown's avatar
unknown committed
3508 3509
    if (len < grant_table->key_length &&
	!memcmp(grant_table->hash_key,helping,len) &&
3510
        compare_hostname(&grant_table->host, thd->host, thd->ip))
unknown's avatar
unknown committed
3511 3512 3513 3514 3515
    {
      error=0;					// Found match
      break;
    }
  }
3516
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
3517 3518 3519
  return error;
}

3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553

/****************************************************************************
  Check procedure level grants

  SYNPOSIS
   bool check_grant_procedure()
   thd		Thread handler
   want_access  Bits of privileges user needs to have
   procs	List of procedures to check. The user should have 'want_access'
   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
****************************************************************************/

bool check_grant_procedure(THD *thd, ulong want_access, 
			   TABLE_LIST *procs, bool no_errors)
{
  TABLE_LIST *table;
  char *user= thd->priv_user;
  char *host= thd->priv_host;
  DBUG_ENTER("check_grant_procedure");

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

  rw_rdlock(&LOCK_grant);
  for (table= procs; table; table= table->next_global)
  {
    GRANT_NAME *grant_proc;
    if ((grant_proc= proc_hash_search(host,thd->ip, 
3554
				      table->db, user, table->table_name, 0)))
3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571
      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)
3572
      strxmov(buff, table->db, ".", table->table_name, NullS);
3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585
    if (want_access & EXECUTE_ACL)
      command= "execute";
    else if (want_access & ALTER_PROC_ACL)
      command= "alter procedure";
    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);
}


unknown's avatar
unknown committed
3586
/*****************************************************************************
unknown's avatar
unknown committed
3587
  Functions to retrieve the grant for a table/column  (for SHOW functions)
unknown's avatar
unknown committed
3588 3589
*****************************************************************************/

unknown's avatar
unknown committed
3590
ulong get_table_grant(THD *thd, TABLE_LIST *table)
unknown's avatar
unknown committed
3591
{
unknown's avatar
unknown committed
3592
  ulong privilege;
unknown's avatar
unknown committed
3593 3594 3595 3596
  char *user = thd->priv_user;
  const char *db = table->db ? table->db : thd->db;
  GRANT_TABLE *grant_table;

3597
  rw_rdlock(&LOCK_grant);
3598 3599 3600
#ifdef EMBEDDED_LIBRARY
  grant_table= NULL;
#else
unknown's avatar
unknown committed
3601
  grant_table= table_hash_search(thd->host, thd->ip, db, user,
3602
				 table->table_name, 0);
3603
#endif
unknown's avatar
unknown committed
3604 3605 3606 3607
  table->grant.grant_table=grant_table; // Remember for column test
  table->grant.version=grant_version;
  if (grant_table)
    table->grant.privilege|= grant_table->privs;
unknown's avatar
unknown committed
3608
  privilege= table->grant.privilege;
3609
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
3610
  return privilege;
unknown's avatar
unknown committed
3611 3612 3613
}


unknown's avatar
VIEW  
unknown committed
3614 3615 3616
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
3617 3618 3619
{
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;
unknown's avatar
unknown committed
3620
  ulong priv;
unknown's avatar
unknown committed
3621

3622
  rw_rdlock(&LOCK_grant);
3623
  /* reload table if someone has modified any grants */
unknown's avatar
VIEW  
unknown committed
3624
  if (grant->version != grant_version)
unknown's avatar
unknown committed
3625
  {
unknown's avatar
VIEW  
unknown committed
3626 3627
    grant->grant_table=
      table_hash_search(thd->host, thd->ip, db_name,
unknown's avatar
unknown committed
3628
			thd->priv_user,
unknown's avatar
VIEW  
unknown committed
3629 3630
			table_name, 0);	        /* purecov: inspected */
    grant->version= grant_version;              /* purecov: inspected */
unknown's avatar
unknown committed
3631 3632
  }

unknown's avatar
VIEW  
unknown committed
3633 3634
  if (!(grant_table= grant->grant_table))
    priv= grant->privilege;
unknown's avatar
unknown committed
3635 3636
  else
  {
unknown's avatar
VIEW  
unknown committed
3637 3638
    grant_column= column_hash_search(grant_table, field_name,
                                     (uint) strlen(field_name));
unknown's avatar
unknown committed
3639
    if (!grant_column)
unknown's avatar
VIEW  
unknown committed
3640
      priv= grant->privilege;
unknown's avatar
unknown committed
3641
    else
unknown's avatar
VIEW  
unknown committed
3642
      priv= grant->privilege | grant_column->rights;
unknown's avatar
unknown committed
3643
  }
3644
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
3645 3646 3647
  return priv;
}

unknown's avatar
VIEW  
unknown committed
3648

3649
/* Help function for mysql_show_grants */
unknown's avatar
unknown committed
3650

3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662
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
3663 3664

static const char *command_array[]=
unknown's avatar
unknown committed
3665
{
unknown's avatar
VIEW  
unknown committed
3666 3667 3668 3669
  "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",
3670
  "CREATE VIEW", "SHOW VIEW", "CREATE ROUTINE", "ALTER ROUTINE",
unknown's avatar
unknown committed
3671
};
3672

unknown's avatar
unknown committed
3673 3674
static uint command_lengths[]=
{
3675
  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
unknown's avatar
unknown committed
3676 3677
};

unknown's avatar
unknown committed
3678

3679 3680 3681 3682 3683 3684 3685
/*
  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
3686
bool mysql_show_grants(THD *thd,LEX_USER *lex_user)
unknown's avatar
unknown committed
3687
{
unknown's avatar
unknown committed
3688 3689
  ulong want_access;
  uint counter,index;
unknown's avatar
unknown committed
3690
  int  error = 0;
unknown's avatar
unknown committed
3691 3692
  ACL_USER *acl_user;
  ACL_DB *acl_db;
unknown's avatar
unknown committed
3693
  char buff[1024];
unknown's avatar
unknown committed
3694
  Protocol *protocol= thd->protocol;
unknown's avatar
unknown committed
3695
  DBUG_ENTER("mysql_show_grants");
unknown's avatar
unknown committed
3696 3697 3698 3699

  LINT_INIT(acl_user);
  if (!initialized)
  {
unknown's avatar
unknown committed
3700
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
unknown's avatar
unknown committed
3701
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
3702
  }
unknown's avatar
unknown committed
3703 3704 3705 3706 3707 3708

  if (!lex_user->host.str)
  {
    lex_user->host.str= (char*) "%";
    lex_user->host.length=1;
  }
unknown's avatar
unknown committed
3709 3710 3711
  if (lex_user->host.length > HOSTNAME_LENGTH ||
      lex_user->user.length > USERNAME_LENGTH)
  {
unknown's avatar
unknown committed
3712 3713
    my_message(ER_GRANT_WRONG_HOST_OR_USER, ER(ER_GRANT_WRONG_HOST_OR_USER),
               MYF(0));
unknown's avatar
unknown committed
3714
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
3715 3716 3717 3718 3719 3720 3721
  }

  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
3722
      user= "";
unknown's avatar
unknown committed
3723
    if (!(host=acl_user->host.hostname))
unknown's avatar
unknown committed
3724
      host= "";
unknown's avatar
unknown committed
3725
    if (!strcmp(lex_user->user.str,user) &&
3726
	!my_strcasecmp(system_charset_info, lex_user->host.str, host))
unknown's avatar
unknown committed
3727 3728
      break;
  }
unknown's avatar
unknown committed
3729
  if (counter == acl_users.elements)
unknown's avatar
unknown committed
3730
  {
unknown's avatar
unknown committed
3731 3732
    my_error(ER_NONEXISTING_GRANT, MYF(0),
             lex_user->user.str, lex_user->host.str);
unknown's avatar
unknown committed
3733
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
3734 3735
  }

unknown's avatar
unknown committed
3736
  Item_string *field=new Item_string("",0,&my_charset_latin1);
unknown's avatar
unknown committed
3737 3738 3739 3740 3741 3742
  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);
3743 3744
  if (protocol->send_fields(&field_list,
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
unknown's avatar
unknown committed
3745
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
3746

unknown's avatar
unknown committed
3747
  rw_wrlock(&LOCK_grant);
unknown's avatar
unknown committed
3748 3749 3750 3751
  VOID(pthread_mutex_lock(&acl_cache->lock));

  /* Add first global access grants */
  {
3752
    String global(buff,sizeof(buff),system_charset_info);
unknown's avatar
unknown committed
3753 3754 3755
    global.length(0);
    global.append("GRANT ",6);

unknown's avatar
unknown committed
3756
    want_access= acl_user->access;
unknown's avatar
unknown committed
3757 3758 3759 3760
    if (test_all_bits(want_access, (GLOBAL_ACLS & ~ GRANT_ACL)))
      global.append("ALL PRIVILEGES",14);
    else if (!(want_access & ~GRANT_ACL))
      global.append("USAGE",5);
unknown's avatar
unknown committed
3761
    else
unknown's avatar
unknown committed
3762 3763
    {
      bool found=0;
unknown's avatar
unknown committed
3764
      ulong j,test_access= want_access & ~GRANT_ACL;
unknown's avatar
unknown committed
3765 3766
      for (counter=0, j = SELECT_ACL;j <= GLOBAL_ACLS;counter++,j <<= 1)
      {
unknown's avatar
unknown committed
3767
	if (test_access & j)
unknown's avatar
unknown committed
3768 3769 3770 3771 3772 3773 3774 3775 3776
	{
	  if (found)
	    global.append(", ",2);
	  found=1;
	  global.append(command_array[counter],command_lengths[counter]);
	}
      }
    }
    global.append (" ON *.* TO '",12);
3777 3778
    global.append(lex_user->user.str, lex_user->user.length,
		  system_charset_info);
unknown's avatar
unknown committed
3779
    global.append ("'@'",3);
3780 3781
    global.append(lex_user->host.str,lex_user->host.length,
		  system_charset_info);
unknown's avatar
unknown committed
3782
    global.append ('\'');
3783
    if (acl_user->salt_len)
unknown's avatar
unknown committed
3784
    {
3785 3786 3787 3788 3789
      char passwd_buff[SCRAMBLED_PASSWORD_CHAR_LENGTH+1];
      if (acl_user->salt_len == SCRAMBLE_LENGTH)
        make_password_from_salt(passwd_buff, acl_user->salt);
      else
        make_password_from_salt_323(passwd_buff, (ulong *) acl_user->salt);
unknown's avatar
unknown committed
3790
      global.append(" IDENTIFIED BY PASSWORD '",25);
3791
      global.append(passwd_buff);
unknown's avatar
unknown committed
3792 3793
      global.append('\'');
    }
unknown's avatar
unknown committed
3794 3795
    /* "show grants" SSL related stuff */
    if (acl_user->ssl_type == SSL_TYPE_ANY)
3796
      global.append(" REQUIRE SSL",12);
3797
    else if (acl_user->ssl_type == SSL_TYPE_X509)
3798
      global.append(" REQUIRE X509",13);
3799
    else if (acl_user->ssl_type == SSL_TYPE_SPECIFIED)
3800
    {
3801
      int ssl_options = 0;
3802
      global.append(" REQUIRE ",9);
unknown's avatar
unknown committed
3803 3804
      if (acl_user->x509_issuer)
      {
3805 3806 3807
	ssl_options++;
	global.append("ISSUER \'",8);
	global.append(acl_user->x509_issuer,strlen(acl_user->x509_issuer));
3808
	global.append('\'');
3809
      }
unknown's avatar
unknown committed
3810 3811
      if (acl_user->x509_subject)
      {
3812 3813 3814
	if (ssl_options++)
	  global.append(' ');
	global.append("SUBJECT \'",9);
3815 3816
	global.append(acl_user->x509_subject,strlen(acl_user->x509_subject),
                      system_charset_info);
3817
	global.append('\'');
unknown's avatar
unknown committed
3818
      }
unknown's avatar
unknown committed
3819 3820
      if (acl_user->ssl_cipher)
      {
3821 3822 3823
	if (ssl_options++)
	  global.append(' ');
	global.append("CIPHER '",8);
3824 3825
	global.append(acl_user->ssl_cipher,strlen(acl_user->ssl_cipher),
                      system_charset_info);
3826
	global.append('\'');
3827 3828
      }
    }
unknown's avatar
unknown committed
3829
    if ((want_access & GRANT_ACL) ||
3830 3831 3832 3833
	(acl_user->user_resource.questions ||
         acl_user->user_resource.updates ||
         acl_user->user_resource.conn_per_hour ||
         acl_user->user_resource.user_conn))
3834
    {
unknown's avatar
unknown committed
3835
      global.append(" WITH",5);
unknown's avatar
unknown committed
3836
      if (want_access & GRANT_ACL)
unknown's avatar
unknown committed
3837
	global.append(" GRANT OPTION",13);
3838 3839 3840 3841
      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");
3842
      add_user_option(&global, acl_user->user_resource.conn_per_hour,
3843
		      "MAX_CONNECTIONS_PER_HOUR");
3844 3845
      add_user_option(&global, acl_user->user_resource.user_conn,
		      "MAX_USER_CONNECTIONS");
unknown's avatar
unknown committed
3846
    }
unknown's avatar
unknown committed
3847
    protocol->prepare_for_resend();
3848
    protocol->store(global.ptr(),global.length(),global.charset());
unknown's avatar
unknown committed
3849
    if (protocol->write())
unknown's avatar
unknown committed
3850
    {
unknown's avatar
unknown committed
3851
      error= -1;
unknown's avatar
unknown committed
3852
      goto end;
unknown's avatar
unknown committed
3853 3854 3855 3856 3857 3858
    }
  }

  /* Add database access */
  for (counter=0 ; counter < acl_dbs.elements ; counter++)
  {
unknown's avatar
unknown committed
3859
    const char *user, *host;
unknown's avatar
unknown committed
3860 3861 3862

    acl_db=dynamic_element(&acl_dbs,counter,ACL_DB*);
    if (!(user=acl_db->user))
unknown's avatar
unknown committed
3863
      user= "";
unknown's avatar
unknown committed
3864
    if (!(host=acl_db->host.hostname))
unknown's avatar
unknown committed
3865
      host= "";
unknown's avatar
unknown committed
3866 3867

    if (!strcmp(lex_user->user.str,user) &&
3868
	!my_strcasecmp(system_charset_info, lex_user->host.str, host))
unknown's avatar
unknown committed
3869 3870
    {
      want_access=acl_db->access;
unknown's avatar
unknown committed
3871
      if (want_access)
unknown's avatar
unknown committed
3872
      {
3873
	String db(buff,sizeof(buff),system_charset_info);
unknown's avatar
unknown committed
3874 3875 3876 3877 3878
	db.length(0);
	db.append("GRANT ",6);

	if (test_all_bits(want_access,(DB_ACLS & ~GRANT_ACL)))
	  db.append("ALL PRIVILEGES",14);
unknown's avatar
unknown committed
3879
	else if (!(want_access & ~GRANT_ACL))
3880
	  db.append("USAGE",5);
unknown's avatar
unknown committed
3881 3882 3883
	else
	{
	  int found=0, cnt;
unknown's avatar
unknown committed
3884
	  ulong j,test_access= want_access & ~GRANT_ACL;
unknown's avatar
unknown committed
3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895
	  for (cnt=0, j = SELECT_ACL; j <= DB_ACLS; cnt++,j <<= 1)
	  {
	    if (test_access & j)
	    {
	      if (found)
		db.append(", ",2);
	      found = 1;
	      db.append(command_array[cnt],command_lengths[cnt]);
	    }
	  }
	}
3896 3897 3898
	db.append (" ON ",4);
	append_identifier(thd, &db, acl_db->db, strlen(acl_db->db));
	db.append (".* TO '",7);
3899 3900
	db.append(lex_user->user.str, lex_user->user.length,
		  system_charset_info);
unknown's avatar
unknown committed
3901
	db.append ("'@'",3);
3902 3903
	db.append(lex_user->host.str, lex_user->host.length,
                  system_charset_info);
unknown's avatar
unknown committed
3904
	db.append ('\'');
unknown's avatar
unknown committed
3905
	if (want_access & GRANT_ACL)
unknown's avatar
unknown committed
3906
	  db.append(" WITH GRANT OPTION",18);
unknown's avatar
unknown committed
3907
	protocol->prepare_for_resend();
3908
	protocol->store(db.ptr(),db.length(),db.charset());
unknown's avatar
unknown committed
3909
	if (protocol->write())
unknown's avatar
unknown committed
3910
	{
unknown's avatar
unknown committed
3911
	  error= -1;
unknown's avatar
unknown committed
3912 3913 3914 3915 3916 3917
	  goto end;
	}
      }
    }
  }

3918
  /* Add table & column access */
3919
  for (index=0 ; index < column_priv_hash.records ; index++)
unknown's avatar
unknown committed
3920
  {
unknown's avatar
unknown committed
3921
    const char *user;
3922 3923
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  index);
unknown's avatar
unknown committed
3924 3925

    if (!(user=grant_table->user))
3926
      user= "";
unknown's avatar
unknown committed
3927 3928

    if (!strcmp(lex_user->user.str,user) &&
3929
	!my_strcasecmp(system_charset_info, lex_user->host.str,
3930
                       grant_table->host.hostname))
unknown's avatar
unknown committed
3931
    {
3932 3933
      ulong table_access= grant_table->privs;
      if ((table_access | grant_table->cols) != 0)
unknown's avatar
unknown committed
3934
      {
3935
	String global(buff, sizeof(buff), system_charset_info);
unknown's avatar
unknown committed
3936 3937
	ulong test_access= (table_access | grant_table->cols) & ~GRANT_ACL;

unknown's avatar
unknown committed
3938 3939 3940
	global.length(0);
	global.append("GRANT ",6);

3941
	if (test_all_bits(table_access, (TABLE_ACLS & ~GRANT_ACL)))
unknown's avatar
unknown committed
3942
	  global.append("ALL PRIVILEGES",14);
unknown's avatar
unknown committed
3943
	else if (!test_access)
3944
 	  global.append("USAGE",5);
unknown's avatar
unknown committed
3945
	else
unknown's avatar
unknown committed
3946
	{
3947
          /* Add specific column access */
3948
	  int found= 0;
unknown's avatar
unknown committed
3949
	  ulong j;
unknown's avatar
unknown committed
3950

3951
	  for (counter= 0, j= SELECT_ACL; j <= TABLE_ACLS; counter++, j<<= 1)
unknown's avatar
unknown committed
3952
	  {
unknown's avatar
unknown committed
3953
	    if (test_access & j)
unknown's avatar
unknown committed
3954 3955 3956
	    {
	      if (found)
		global.append(", ",2);
3957
	      found= 1;
unknown's avatar
unknown committed
3958 3959
	      global.append(command_array[counter],command_lengths[counter]);

unknown's avatar
unknown committed
3960
	      if (grant_table->cols)
unknown's avatar
unknown committed
3961
	      {
3962
		uint found_col= 0;
unknown's avatar
unknown committed
3963 3964 3965 3966 3967 3968
		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
3969
		  if (grant_column->rights & j)
unknown's avatar
unknown committed
3970
		  {
unknown's avatar
unknown committed
3971
		    if (!found_col)
unknown's avatar
unknown committed
3972
		    {
3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983
		      found_col= 1;
		      /*
			If we have a duplicated table level privilege, we
			must write the access privilege name again.
		      */
		      if (table_access & j)
		      {
			global.append(", ", 2);
			global.append(command_array[counter],
				      command_lengths[counter]);
		      }
unknown's avatar
unknown committed
3984 3985 3986 3987 3988
		      global.append(" (",2);
		    }
		    else
		      global.append(", ",2);
		    global.append(grant_column->column,
3989 3990
				  grant_column->key_length,
				  system_charset_info);
unknown's avatar
unknown committed
3991 3992 3993 3994 3995 3996 3997 3998
		  }
		}
		if (found_col)
		  global.append(')');
	      }
	    }
	  }
	}
3999 4000 4001 4002 4003 4004 4005
	global.append(" ON ",4);
	append_identifier(thd, &global, grant_table->db,
			  strlen(grant_table->db));
	global.append('.');
	append_identifier(thd, &global, grant_table->tname,
			  strlen(grant_table->tname));
	global.append(" TO '",5);
4006 4007
	global.append(lex_user->user.str, lex_user->user.length,
		      system_charset_info);
unknown's avatar
unknown committed
4008
	global.append("'@'",3);
4009 4010
	global.append(lex_user->host.str,lex_user->host.length,
		      system_charset_info);
unknown's avatar
unknown committed
4011
	global.append('\'');
4012
	if (table_access & GRANT_ACL)
unknown's avatar
unknown committed
4013
	  global.append(" WITH GRANT OPTION",18);
unknown's avatar
unknown committed
4014
	protocol->prepare_for_resend();
4015
	protocol->store(global.ptr(),global.length(),global.charset());
unknown's avatar
unknown committed
4016
	if (protocol->write())
unknown's avatar
unknown committed
4017
	{
unknown's avatar
unknown committed
4018
	  error= -1;
unknown's avatar
unknown committed
4019
	  break;
unknown's avatar
unknown committed
4020 4021 4022 4023
	}
      }
    }
  }
4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036

  /* Add procedure access */
  for (index=0 ; index < proc_priv_hash.records ; index++)
  {
    const char *user;
    GRANT_NAME *grant_proc= (GRANT_NAME*) hash_element(&proc_priv_hash,
						       index);

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

    if (!strcmp(lex_user->user.str,user) &&
	!my_strcasecmp(system_charset_info, lex_user->host.str,
unknown's avatar
unknown committed
4037
                       grant_proc->host.hostname))
4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091
    {
      ulong proc_access= grant_proc->privs;
      if (proc_access != 0)
      {
	String global(buff, sizeof(buff), system_charset_info);
	ulong test_access= proc_access & ~GRANT_ACL;

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

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

	  for (counter= 0, j= SELECT_ACL; j <= PROC_ACLS; counter++, j<<= 1)
	  {
	    if (test_access & j)
	    {
	      if (found)
		global.append(", ",2);
	      found= 1;
	      global.append(command_array[counter],command_lengths[counter]);
	    }
	  }
	}
	global.append(" ON ",4);
	append_identifier(thd, &global, grant_proc->db,
			  strlen(grant_proc->db));
	global.append('.');
	append_identifier(thd, &global, grant_proc->tname,
			  strlen(grant_proc->tname));
	global.append(" TO '",5);
	global.append(lex_user->user.str, lex_user->user.length,
		      system_charset_info);
	global.append("'@'",3);
	global.append(lex_user->host.str,lex_user->host.length,
		      system_charset_info);
	global.append('\'');
	if (proc_access & GRANT_ACL)
	  global.append(" WITH GRANT OPTION",18);
	protocol->prepare_for_resend();
	protocol->store(global.ptr(),global.length(),global.charset());
	if (protocol->write())
	{
	  error= -1;
	  break;
	}
      }
    }
  }
4092
end:
unknown's avatar
unknown committed
4093
  VOID(pthread_mutex_unlock(&acl_cache->lock));
unknown's avatar
unknown committed
4094
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
4095

4096
  send_eof(thd);
unknown's avatar
unknown committed
4097 4098 4099 4100
  DBUG_RETURN(error);
}


unknown's avatar
unknown committed
4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128
/*
  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;
}


4129
void get_mqh(const char *user, const char *host, USER_CONN *uc)
unknown's avatar
unknown committed
4130 4131
{
  ACL_USER *acl_user;
4132 4133 4134 4135
  if (initialized && (acl_user= find_acl_user(host,user)))
    uc->user_resources= acl_user->user_resource;
  else
    bzero((char*) &uc->user_resources, sizeof(uc->user_resources));
unknown's avatar
unknown committed
4136 4137
}

4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158
/*
  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.
*/

4159
#define GRANT_TABLES 5
4160 4161 4162 4163 4164 4165
int open_grant_tables(THD *thd, TABLE_LIST *tables)
{
  DBUG_ENTER("open_grant_tables");

  if (!initialized)
  {
unknown's avatar
unknown committed
4166
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
4167 4168 4169
    DBUG_RETURN(-1);
  }

4170
  bzero((char*) tables, GRANT_TABLES*sizeof(*tables));
4171 4172 4173 4174 4175
  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
4176 4177 4178
  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;
4179
  (tables+3)->next_local= (tables+3)->next_global= tables+4;
4180
  tables->lock_type= (tables+1)->lock_type=
4181 4182 4183 4184
    (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";
4185 4186 4187 4188 4189 4190

#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
4191 4192
  if (thd->slave_thread && table_rules_on)
  {
unknown's avatar
unknown committed
4193 4194 4195
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
4196
    */
4197 4198
    tables[0].updating=tables[1].updating=tables[2].updating=
      tables[3].updating=tables[4].updating=1;
4199 4200
    if (!tables_ok(0, tables))
      DBUG_RETURN(1);
4201 4202
    tables[0].updating=tables[1].updating=tables[2].updating=
      tables[3].updating=tables[4].updating=0;;
4203
  }
4204 4205
#endif

4206
  if (simple_open_n_lock_tables(thd, tables))
4207 4208 4209 4210 4211 4212 4213 4214 4215
  {						// 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
4216
			 uint *acl_acl_userdx)
4217 4218 4219 4220 4221 4222 4223 4224 4225
{
  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
4226
      user= "";
4227
    if (!(host=acl_user->host.hostname))
unknown's avatar
unknown committed
4228
      host= "%";
4229 4230 4231 4232 4233 4234 4235
    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
4236
  *acl_acl_userdx= counter;
unknown's avatar
unknown committed
4237
  return acl_user;
4238 4239
}

unknown's avatar
unknown committed
4240

4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262
/*
  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)
4263
{
4264 4265
  int error;
  DBUG_ENTER("modify_grant_table");
4266

4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283
  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));
  }
4284

4285 4286
  DBUG_RETURN(error);
}
4287 4288


4289 4290 4291 4292 4293 4294
/*
  Handle a privilege table.

  SYNOPSIS
    handle_grant_table()
    tables                      The array with the four open tables.
4295
    table_no                    The number of the table to handle (0..4).
4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312
    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
4313
    4 procs_priv
4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332

  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;
4333
  byte user_key[MAX_KEY_LENGTH];
unknown's avatar
unknown committed
4334
  uint key_prefix_length;
4335 4336
  DBUG_ENTER("handle_grant_table");

unknown's avatar
unknown committed
4337
  if (! table_no) // mysql.user table
4338
  {
4339 4340 4341 4342 4343 4344 4345 4346 4347 4348
    /*
      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'",
4349
                       table->s->table_name, user_str, host_str));
4350 4351
    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
4352 4353 4354 4355 4356

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

4357
    if ((error= table->file->index_read_idx(table->record[0], 0,
unknown's avatar
unknown committed
4358
                                            user_key, key_prefix_length,
4359
                                            HA_READ_KEY_EXACT)))
4360
    {
4361 4362 4363 4364 4365
      if (error != HA_ERR_KEY_NOT_FOUND)
      {
        table->file->print_error(error, MYF(0));
        result= -1;
      }
4366
    }
4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383
    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)))
4384
    {
4385
      table->file->print_error(error, MYF(0));
4386
      result= -1;
4387 4388 4389 4390 4391
    }
    else
    {
#ifdef EXTRA_DEBUG
      DBUG_PRINT("info",("scan table: '%s'  search: '%s'@'%s'",
4392
                         table->s->table_name, user_str, host_str));
4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440
#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()
4441
    struct_no                   The number of the structure to handle (0..3).
4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456
    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
4457
    3 procs_priv_hash
4458 4459 4460 4461

  RETURN
    > 0         At least one element matched.
    0           OK, but no element matched.
4462
    -1		Wrong arguments to function
4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474
*/

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;
4475
  GRANT_NAME *grant_name;
4476 4477 4478
  DBUG_ENTER("handle_grant_struct");
  LINT_INIT(acl_user);
  LINT_INIT(acl_db);
4479
  LINT_INIT(grant_name);
4480 4481 4482 4483
  DBUG_PRINT("info",("scan struct: %u  search: '%s'@'%s'",
                     struct_no, user_from->user.str, user_from->host.str));

  /* Get the number of elements in the in-memory structure. */
4484
  switch (struct_no) {
4485 4486 4487 4488 4489 4490
  case 0:
    elements= acl_users.elements;
    break;
  case 1:
    elements= acl_dbs.elements;
    break;
4491
  case 2:
4492
    elements= column_priv_hash.records;
4493 4494 4495 4496 4497 4498
    break;
  case 3:
    elements= proc_priv_hash.records;
    break;
  default:
    return -1;
4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511
  }

#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.
    */
4512
    switch (struct_no) {
4513 4514 4515 4516 4517 4518 4519 4520 4521 4522
    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;
unknown's avatar
unknown committed
4523 4524
      if (!(host= acl_db->host.hostname))
        host= "%";
4525 4526
      break;

4527 4528 4529
    case 2:
      grant_name= (GRANT_NAME*) hash_element(&column_priv_hash, idx);
      user= grant_name->user;
unknown's avatar
unknown committed
4530 4531
      if (!(host= grant_name->host.hostname))
        host= "%";
4532 4533 4534 4535 4536
      break;

    case 3:
      grant_name= (GRANT_NAME*) hash_element(&proc_priv_hash, idx);
      user= grant_name->user;
unknown's avatar
unknown committed
4537 4538
      if (!(host= grant_name->host.hostname))
        host= "%";
4539
      break;
4540 4541
    }
    if (! user)
4542
      user= "";
4543
    if (! host)
4544
      host= "";
4545 4546 4547 4548 4549 4550
#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))
4551
      continue;
4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565

    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;

4566 4567 4568 4569 4570 4571 4572
      case 2:
        hash_delete(&column_priv_hash, (byte*) grant_name);
	break;

      case 3:
        hash_delete(&proc_priv_hash, (byte*) grant_name);
	break;
4573 4574 4575
      }
      elements--;
      idx--;
4576
    }
4577 4578
    else if ( user_to )
    {
4579
      switch ( struct_no ) {
4580 4581 4582 4583
      case 0:
        acl_user->user= strdup_root(&mem, user_to->user.str);
        acl_user->host.hostname= strdup_root(&mem, user_to->host.str);
        break;
4584

4585 4586 4587 4588 4589
      case 1:
        acl_db->user= strdup_root(&mem, user_to->user.str);
        acl_db->host.hostname= strdup_root(&mem, user_to->host.str);
        break;

4590 4591 4592
      case 2:
      case 3:
        grant_name->user= strdup_root(&mem, user_to->user.str);
unknown's avatar
unknown committed
4593 4594
        update_hostname(&grant_name->host,
                        strdup_root(&mem, user_to->host.str));
4595
	break;
4596 4597 4598
      }
    }
    else
4599
    {
4600 4601 4602 4603 4604 4605 4606
      /* 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
4607

4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651
  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
4652 4653
    if ((handle_grant_struct(0, drop, user_from, user_to) && ! result) ||
        found)
4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680
    {
      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;
    }
  }

4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699
  /* 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;
    }
  }

4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713
  /* 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;
4714
    }
4715 4716 4717

    /* Handle columns table. */
    if ((found= handle_grant_table(tables, 3, drop, user_from, user_to)) < 0)
4718
    {
4719
      /* Handle of table failed, don't touch the in-memory array. */
4720 4721
      result= -1;
    }
4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733
    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
4734

unknown's avatar
unknown committed
4735 4736 4737 4738 4739 4740 4741 4742 4743 4744
static void append_user(String *str, LEX_USER *user)
{
  if (str->length())
    str->append(',');
  str->append('\'');
  str->append(user->user.str);
  str->append("'@'");
  str->append(user->host.str);
  str->append('\'');
}
4745

unknown's avatar
unknown committed
4746

4747 4748 4749 4750 4751 4752 4753
/*
  Create a list of users.

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

4755 4756 4757 4758 4759 4760 4761 4762
  RETURN
    FALSE       OK.
    TRUE        Error.
*/

bool mysql_create_user(THD *thd, List <LEX_USER> &list)
{
  int result;
unknown's avatar
unknown committed
4763
  String wrong_users;
4764 4765 4766
  ulong sql_mode;
  LEX_USER *user_name;
  List_iterator <LEX_USER> user_list(list);
4767
  TABLE_LIST tables[GRANT_TABLES];
4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782
  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.
    */
4783
    if (handle_grant_data(tables, 0, user_name, NULL))
4784
    {
unknown's avatar
unknown committed
4785
      append_user(&wrong_users, user_name);
4786
      result= TRUE;
unknown's avatar
unknown committed
4787
      continue;
4788
    }
4789

4790 4791 4792 4793
    sql_mode= thd->variables.sql_mode;
    thd->variables.sql_mode&= ~MODE_NO_AUTO_CREATE_USER;
    if (replace_user_table(thd, tables[0].table, *user_name, 0, 0, 1))
    {
unknown's avatar
unknown committed
4794
      append_user(&wrong_users, user_name);
4795 4796 4797 4798 4799 4800 4801 4802 4803
      result= TRUE;
    }
    thd->variables.sql_mode= sql_mode;
  }

  VOID(pthread_mutex_unlock(&acl_cache->lock));
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
  if (result)
4804
    my_error(ER_CANNOT_USER, MYF(0), "CREATE USER", wrong_users.c_ptr_safe());
4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824
  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
4825
  String wrong_users;
4826 4827
  LEX_USER *user_name;
  List_iterator <LEX_USER> user_list(list);
4828
  TABLE_LIST tables[GRANT_TABLES];
4829 4830
  DBUG_ENTER("mysql_drop_user");

unknown's avatar
unknown committed
4831
  /* DROP USER may be skipped on replication client. */
4832 4833 4834 4835 4836 4837 4838 4839
  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++))
  {
4840
    if (handle_grant_data(tables, 1, user_name, NULL) <= 0)
4841
    {
unknown's avatar
unknown committed
4842
      append_user(&wrong_users, user_name);
4843
      result= TRUE;
4844
    }
4845
  }
4846

4847 4848 4849 4850
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
  if (result)
unknown's avatar
unknown committed
4851
    my_error(ER_CANNOT_USER, MYF(0), "DROP USER", wrong_users.c_ptr_safe());
4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871
  DBUG_RETURN(result);
}


/*
  Rename a user.

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

  RETURN
    FALSE       OK.
    TRUE        Error.
*/

bool mysql_rename_user(THD *thd, List <LEX_USER> &list)
{
  int result= 0;
unknown's avatar
unknown committed
4872
  String wrong_users;
4873 4874 4875
  LEX_USER *user_from;
  LEX_USER *user_to;
  List_iterator <LEX_USER> user_list(list);
4876
  TABLE_LIST tables[GRANT_TABLES];
4877 4878
  DBUG_ENTER("mysql_rename_user");

unknown's avatar
unknown committed
4879
  /* RENAME USER may be skipped on replication client. */
4880 4881 4882 4883 4884 4885 4886 4887 4888
  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++;
4889
    DBUG_ASSERT(user_to != 0); /* Syntax enforces pairs of users. */
4890 4891 4892 4893 4894

    /*
      Search all in-memory structures and grant tables
      for a mention of the new user name.
    */
unknown's avatar
unknown committed
4895 4896
    if (handle_grant_data(tables, 0, user_to, NULL) ||
        handle_grant_data(tables, 0, user_from, user_to) <= 0)
4897
    {
unknown's avatar
unknown committed
4898
      append_user(&wrong_users, user_from);
4899 4900
      result= TRUE;
    }
4901
  }
unknown's avatar
unknown committed
4902

4903 4904 4905 4906
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
  if (result)
4907
    my_error(ER_CANNOT_USER, MYF(0), "RENAME USER", wrong_users.c_ptr_safe());
4908 4909 4910
  DBUG_RETURN(result);
}

4911

4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925
/*
  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
4926
bool mysql_revoke_all(THD *thd,  List <LEX_USER> &list)
4927
{
unknown's avatar
unknown committed
4928
  uint counter, revoked;
4929
  int result;
unknown's avatar
unknown committed
4930
  ACL_DB *acl_db;
4931
  TABLE_LIST tables[GRANT_TABLES];
4932 4933 4934
  DBUG_ENTER("mysql_revoke_all");

  if ((result= open_grant_tables(thd, tables)))
unknown's avatar
unknown committed
4935
    DBUG_RETURN(result != 1);
4936 4937 4938 4939 4940 4941 4942 4943

  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
4944
    if (!check_acl_user(lex_user, &counter))
4945
    {
unknown's avatar
unknown committed
4946 4947
      sql_print_error("REVOKE ALL PRIVILEGES, GRANT: User '%s'@'%s' does not "
                      "exists", lex_user->user.str, lex_user->host.str);
4948 4949 4950
      result= -1;
      continue;
    }
unknown's avatar
unknown committed
4951

4952 4953 4954 4955 4956 4957 4958 4959
    if (replace_user_table(thd, tables[0].table,
			   *lex_user, ~0, 1, 0))
    {
      result= -1;
      continue;
    }

    /* Remove db access privileges */
unknown's avatar
unknown committed
4960 4961 4962 4963 4964
    /*
      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
4965
    do
4966
    {
unknown's avatar
unknown committed
4967
      for (counter= 0, revoked= 0 ; counter < acl_dbs.elements ; )
4968
      {
unknown's avatar
unknown committed
4969
	const char *user,*host;
unknown's avatar
unknown committed
4970

unknown's avatar
unknown committed
4971 4972 4973 4974 4975
	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
4976

unknown's avatar
unknown committed
4977 4978 4979
	if (!strcmp(lex_user->user.str,user) &&
	    !my_strcasecmp(system_charset_info, lex_user->host.str, host))
	{
unknown's avatar
unknown committed
4980
	  if (!replace_db_table(tables[1].table, acl_db->db, *lex_user, ~0, 1))
unknown's avatar
unknown committed
4981
	  {
unknown's avatar
unknown committed
4982 4983 4984 4985 4986
	    /*
	      Don't increment counter as replace_db_table deleted the
	      current element in acl_dbs.
	     */
	    revoked= 1;
unknown's avatar
unknown committed
4987 4988
	    continue;
	  }
unknown's avatar
unknown committed
4989
	  result= -1; // Something went wrong
unknown's avatar
unknown committed
4990
	}
unknown's avatar
unknown committed
4991
	counter++;
4992
      }
unknown's avatar
unknown committed
4993
    } while (revoked);
4994 4995

    /* Remove column access */
unknown's avatar
unknown committed
4996
    do
4997
    {
unknown's avatar
unknown committed
4998
      for (counter= 0, revoked= 0 ; counter < column_priv_hash.records ; )
4999
      {
unknown's avatar
unknown committed
5000 5001 5002 5003 5004
	const char *user,*host;
	GRANT_TABLE *grant_table= (GRANT_TABLE*)hash_element(&column_priv_hash,
							     counter);
	if (!(user=grant_table->user))
	  user= "";
5005
	if (!(host=grant_table->host.hostname))
unknown's avatar
unknown committed
5006
	  host= "";
unknown's avatar
unknown committed
5007

unknown's avatar
unknown committed
5008 5009
	if (!strcmp(lex_user->user.str,user) &&
	    !my_strcasecmp(system_charset_info, lex_user->host.str, host))
5010
	{
unknown's avatar
unknown committed
5011 5012 5013 5014
	  if (replace_table_table(thd,grant_table,tables[2].table,*lex_user,
				  grant_table->db,
				  grant_table->tname,
				  ~0, 0, 1))
unknown's avatar
unknown committed
5015
	  {
unknown's avatar
unknown committed
5016
	    result= -1;
unknown's avatar
unknown committed
5017
	  }
unknown's avatar
unknown committed
5018
	  else
unknown's avatar
unknown committed
5019
	  {
unknown's avatar
unknown committed
5020
	    if (!grant_table->cols)
unknown's avatar
unknown committed
5021
	    {
unknown's avatar
unknown committed
5022 5023
	      revoked= 1;
	      continue;
unknown's avatar
unknown committed
5024
	    }
unknown's avatar
unknown committed
5025 5026
	    List<LEX_COLUMN> columns;
	    if (!replace_column_table(grant_table,tables[3].table, *lex_user,
unknown's avatar
unknown committed
5027 5028 5029 5030
				      columns,
				      grant_table->db,
				      grant_table->tname,
				      ~0, 1))
unknown's avatar
unknown committed
5031
	    {
unknown's avatar
unknown committed
5032
	      revoked= 1;
5033
	      continue;
unknown's avatar
unknown committed
5034
	    }
5035
	    result= -1;
unknown's avatar
unknown committed
5036
	  }
5037
	}
unknown's avatar
unknown committed
5038
	counter++;
5039
      }
unknown's avatar
unknown committed
5040
    } while (revoked);
5041 5042 5043 5044 5045 5046 5047 5048 5049 5050

    /* Remove procedure access */
    do {
      for (counter= 0, revoked= 0 ; counter < proc_priv_hash.records ; )
      {
	const char *user,*host;
	GRANT_NAME *grant_proc= (GRANT_NAME*) hash_element(&proc_priv_hash,
							   counter);
	if (!(user=grant_proc->user))
	  user= "";
unknown's avatar
unknown committed
5051
	if (!(host=grant_proc->host.hostname))
5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069
	  host= "";

	if (!strcmp(lex_user->user.str,user) &&
	    !my_strcasecmp(system_charset_info, lex_user->host.str, host))
	{
	  if (!replace_proc_table(thd,grant_proc,tables[4].table,*lex_user,
				  grant_proc->db,
				  grant_proc->tname,
				  ~0, 1))
	  {
	    revoked= 1;
	    continue;
	  }
	  result= -1;	// Something went wrong
	}
	counter++;
      }
    } while (revoked);
5070
  }
unknown's avatar
unknown committed
5071

5072 5073 5074
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
unknown's avatar
unknown committed
5075

5076
  if (result)
unknown's avatar
unknown committed
5077
    my_message(ER_REVOKE_GRANTS, ER(ER_REVOKE_GRANTS), MYF(0));
unknown's avatar
unknown committed
5078

5079 5080
  DBUG_RETURN(result);
}
unknown's avatar
unknown committed
5081

5082

5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110
/*
  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.
*/

bool sp_revoke_privileges(THD *thd, const char *sp_db, const char *sp_name)
{
  uint counter, revoked;
  int result;
  TABLE_LIST tables[GRANT_TABLES];
  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 */
5111 5112
  do
  {
5113 5114 5115 5116 5117 5118 5119 5120 5121 5122
    for (counter= 0, revoked= 0 ; counter < proc_priv_hash.records ; )
    {
      GRANT_NAME *grant_proc= (GRANT_NAME*) hash_element(&proc_priv_hash,
							 counter);
      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);
unknown's avatar
unknown committed
5123 5124
	lex_user.host.str= grant_proc->host.hostname;
	lex_user.host.length= strlen(grant_proc->host.hostname);
5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184
	if (!replace_proc_table(thd,grant_proc,tables[4].table,lex_user,
				grant_proc->db, grant_proc->tname, ~0, 1))
	{
	  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.
*/

bool sp_grant_privileges(THD *thd, const char *sp_db, const char *sp_name)
{
  LEX_USER *combo;
  TABLE_LIST tables[1];
  List<LEX_USER> user_list;
  bool result;
  DBUG_ENTER("sp_grant_privileges");  

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

  combo->user.str= thd->user;
  
  if (!find_acl_user(combo->host.str=(char*)thd->host_or_ip, combo->user.str) &&
      !find_acl_user(combo->host.str=(char*)thd->host, combo->user.str) &&
      !find_acl_user(combo->host.str=(char*)thd->ip, combo->user.str) &&
      !find_acl_user(combo->host.str=(char*)"%", combo->user.str))
    DBUG_RETURN(TRUE);

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

  tables->db= (char*)sp_db;
5185
  tables->table_name= tables->alias= (char*)sp_name;
5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197
  
  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;
5198
  bzero((char*) &thd->lex->mqh, sizeof(thd->lex->mqh));
5199 5200 5201 5202 5203 5204 5205

  result= mysql_procedure_grant(thd, tables, user_list,
  				DEFAULT_CREATE_PROC_ACLS, 0, 1);
  DBUG_RETURN(result);
}


unknown's avatar
unknown committed
5206
/*****************************************************************************
unknown's avatar
unknown committed
5207
  Instantiate used templates
unknown's avatar
unknown committed
5208 5209 5210 5211 5212 5213 5214 5215
*****************************************************************************/

#ifdef __GNUC__
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
SCRUM:  
unknown committed
5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262

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

5263 5264 5265 5266 5267 5268 5269 5270

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;
5271
  restore_record(table, s->default_values);
5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323
  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;
  DBUG_ENTER("fill_schema_user_privileges");
  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= "";
    want_access= acl_user->access;
    if (!(want_access & GRANT_ACL))
      is_grantable= "NO";

    strxmov(buff,"'",user,"'@'",host,"'",NullS);
    if (!(want_access & ~GRANT_ACL))
      update_schema_privilege(table, buff, 0, 0, 0, 0, "USAGE", 5, is_grantable);
    else
    {
      uint priv_id;
      ulong j,test_access= want_access & ~GRANT_ACL;
      for (priv_id=0, j = SELECT_ACL;j <= GLOBAL_ACLS; priv_id++,j <<= 1)
      {
	if (test_access & j)
          update_schema_privilege(table, buff, 0, 0, 0, 0, 
                                  command_array[priv_id],
                                  command_lengths[priv_id], is_grantable);
      }
    }
  }
  DBUG_RETURN(0);
5324 5325 5326
#else
  return(0);
#endif
5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373
}


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;
  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= "";

    want_access=acl_db->access;
    if (want_access)
    {
      if (!(want_access & GRANT_ACL))
      {
        is_grantable= "NO";
      }
      strxmov(buff,"'",user,"'@'",host,"'",NullS);
      if (!(want_access & ~GRANT_ACL))
        update_schema_privilege(table, buff, acl_db->db, 0, 0,
                                0, "USAGE", 5, is_grantable);
      else
      {
        int cnt;
        ulong j,test_access= want_access & ~GRANT_ACL;
        for (cnt=0, j = SELECT_ACL; j <= DB_ACLS; cnt++,j <<= 1)
          if (test_access & j)
            update_schema_privilege(table, buff, acl_db->db, 0, 0, 0,
                                    command_array[cnt], command_lengths[cnt],
                                    is_grantable);
      }
    }
  }
  DBUG_RETURN(0);
5374 5375 5376
#else
  return (0);
#endif
5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395
}


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;
  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= "";
    ulong table_access= grant_table->privs;
5396
    if (table_access)
5397 5398
    {
      ulong test_access= table_access & ~GRANT_ACL;
unknown's avatar
unknown committed
5399 5400 5401 5402
      /*
        We should skip 'usage' privilege on table if
        we have any privileges on column(s) of this table
      */
5403 5404
      if (!test_access && grant_table->cols)
        continue;
5405 5406 5407
      if (!(table_access & GRANT_ACL))
        is_grantable= "NO";

unknown's avatar
unknown committed
5408
      strxmov(buff,"'",user,"'@'",grant_table->host.hostname,"'",NullS);
5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426
      if (!test_access)
        update_schema_privilege(table, buff, grant_table->db, grant_table->tname,
                                0, 0, "USAGE", 5, is_grantable);
      else
      {
        ulong j;
        int cnt;
        for (cnt= 0, j= SELECT_ACL; j <= TABLE_ACLS; cnt++, j<<= 1)
        {
          if (test_access & j)
            update_schema_privilege(table, buff, grant_table->db, 
                                    grant_table->tname, 0, 0, command_array[cnt],
                                    command_lengths[cnt], is_grantable);
        }
      }
    }
  }
  DBUG_RETURN(0);
5427 5428 5429
#else
  return (0);
#endif
5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450
}


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;
  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= "";
    ulong table_access= grant_table->cols;
    if (table_access != 0)
    {
unknown's avatar
unknown committed
5451
      if (!(grant_table->privs & GRANT_ACL))
5452 5453
        is_grantable= "NO";

unknown's avatar
unknown committed
5454
      ulong test_access= table_access & ~GRANT_ACL;
unknown's avatar
unknown committed
5455
      strxmov(buff,"'",user,"'@'",grant_table->host.hostname,"'",NullS);
5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485
      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);
5486 5487 5488
#else
  return (0);
#endif
5489 5490 5491
}


unknown's avatar
VIEW  
unknown committed
5492 5493 5494 5495 5496
#ifndef NO_EMBEDDED_ACCESS_CHECKS
/*
  fill effective privileges for table

  SYNOPSIS
5497 5498
    fill_effective_table_privileges()
    thd     thread handler
unknown's avatar
VIEW  
unknown committed
5499 5500 5501 5502 5503 5504 5505 5506
    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)
{
5507 5508 5509 5510 5511 5512 5513
  /* --skip-grants */
  if (!initialized)
  {
    grant->privilege= ~NO_ACCESS;             // everything is allowed
    return;
  }

unknown's avatar
VIEW  
unknown committed
5514 5515
  /* global privileges */
  grant->privilege= thd->master_access;
5516

5517 5518 5519
  if (!thd->priv_user)
    return;                                   // it is slave

5520 5521 5522
  /* db privileges */
  grant->privilege|= acl_get(thd->host, thd->ip, thd->priv_user, db, 0);

5523 5524 5525
  if (!grant_option)
    return;

unknown's avatar
VIEW  
unknown committed
5526 5527 5528
  /* table privileges */
  if (grant->version != grant_version)
  {
5529
    rw_rdlock(&LOCK_grant);
unknown's avatar
VIEW  
unknown committed
5530 5531 5532 5533 5534
    grant->grant_table=
      table_hash_search(thd->host, thd->ip, db,
			thd->priv_user,
			table, 0);              /* purecov: inspected */
    grant->version= grant_version;              /* purecov: inspected */
5535
    rw_unlock(&LOCK_grant);
unknown's avatar
VIEW  
unknown committed
5536 5537 5538 5539 5540 5541 5542
  }
  if (grant->grant_table != 0)
  {
    grant->privilege|= grant->grant_table->privs;
  }
}
#endif