sql_acl.cc 173 KB
Newer Older
1
/* Copyright (C) 2000-2003 MySQL AB
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2

bk@work.mysql.com's avatar
bk@work.mysql.com 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.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
7

bk@work.mysql.com's avatar
bk@work.mysql.com 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.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
12

bk@work.mysql.com's avatar
bk@work.mysql.com 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.
bk@work.mysql.com's avatar
bk@work.mysql.com 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
bk@work.mysql.com's avatar
bk@work.mysql.com committed
33 34
#include <m_ctype.h>
#include <stdarg.h>
35 36
#include "sp_head.h"
#include "sp.h"
bk@work.mysql.com's avatar
bk@work.mysql.com committed
37

hf@deer.(none)'s avatar
hf@deer.(none) committed
38
#ifndef NO_EMBEDDED_ACCESS_CHECKS
39

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

48

bk@work.mysql.com's avatar
bk@work.mysql.com 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;
}

serg@serg.mylan's avatar
serg@serg.mylan 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)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
58 59 60 61 62

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

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

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

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

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

124

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

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

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

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

143
my_bool acl_init(bool dont_read_acl_tables)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
144
{
145
  THD  *thd;
146
  my_bool return_val;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
147 148
  DBUG_ENTER("acl_init");

149 150 151
  acl_cache= new hash_filo(ACL_CACHE_SIZE, 0, 0,
                           (hash_get_key) acl_entry_get_key,
                           (hash_free_key) free, system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
152
  if (dont_read_acl_tables)
153
  {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
154
    DBUG_RETURN(0); /* purecov: tested */
peter@mysql.com's avatar
peter@mysql.com committed
155 156
  }

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


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

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

  RETURN VALUES
    FALSE  Success
    TRUE   Error
*/

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

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
205 206
  acl_cache->clear(1);				// Clear locked hostname cache

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

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

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

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

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

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

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

357 358 359
      user.sort= get_sort(2,user.host.hostname,user.user);
      user.hostname_length= (user.host.hostname ?
                             (uint) strlen(user.host.hostname) : 0);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
360

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

374 375 376
        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++]);
377

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

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

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

481 482 483 484 485
  initialized=1;
  return_val=0;

end:
  DBUG_RETURN(return_val);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
486 487 488 489 490
}


void acl_free(bool end)
{
491
  free_root(&mem,MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
492 493 494 495 496 497 498 499 500 501 502 503 504 505
  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;
  }
}

506 507

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

  SYNOPSIS
    acl_reload()
513 514 515 516 517 518 519 520 521 522 523
      thd  Current thread

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

  RETURN VALUE
    FALSE  Success
    TRUE   Failure
524
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
525

526
my_bool acl_reload(THD *thd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
527
{
528
  TABLE_LIST tables[3];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
529 530 531
  DYNAMIC_ARRAY old_acl_hosts,old_acl_users,old_acl_dbs;
  MEM_ROOT old_mem;
  bool old_initialized;
532
  my_bool return_val= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
533 534
  DBUG_ENTER("acl_reload");

535
  if (thd->locked_tables)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
536
  {					// Can't have locked tables here
537 538 539
    thd->lock=thd->locked_tables;
    thd->locked_tables=0;
    close_thread_tables(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
540
  }
541 542 543 544 545 546

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

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
562 563 564 565 566 567 568 569 570 571
  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);

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


597 598
/*
  Get all access bits from table after fieldnr
599 600

  IMPLEMENTATION
601 602
  We know that the access privileges ends when there is no more fields
  or the field is not an enum with two elements.
603 604 605 606 607 608 609 610 611 612 613

  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
614
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
615

616
static ulong get_access(TABLE *form, uint fieldnr, uint *next_field)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
617
{
618
  ulong access_bits=0,bit;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
619
  char buff[2];
620
  String res(buff,sizeof(buff),&my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
621 622
  Field **pos;

623 624 625
  for (pos=form->field+fieldnr, bit=1;
       *pos && (*pos)->real_type() == FIELD_TYPE_ENUM &&
	 ((Field_enum*) (*pos))->typelib->count == 2 ;
626
       pos++, fieldnr++, bit<<=1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
627
  {
628
    (*pos)->val_str(&res);
629
    if (my_toupper(&my_charset_latin1, res[0]) == 'Y')
630
      access_bits|= bit;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
631
  }
632 633
  if (next_field)
    *next_field=fieldnr;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
634 635 636 637 638
  return access_bits;
}


/*
639 640 641 642 643
  Return a number which, if sorted 'desc', puts strings in this order:
    no wildcards
    wildcards
    empty string
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
644 645 646 647 648 649 650

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

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
654 655
  while (count--)
  {
656 657 658
    char *start, *str= va_arg(args,char*);
    uint chars= 0;
    uint wild_pos= 0;           /* first wildcard position */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
659

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

688

689
/*
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
690 691
  Seek ACL entry for a user, check password, SSL cypher, and if
  everything is OK, update THD user data and USER_RESOURCES struct.
692

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
693 694 695 696
  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.
peter@mysql.com's avatar
peter@mysql.com committed
697

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

721 722
int acl_getroot(THD *thd, USER_RESOURCES  *mqh,
                const char *passwd, uint passwd_len)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
723
{
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
724 725 726
  ulong user_access= NO_ACCESS;
  int res= 1;
  ACL_USER *acl_user= 0;
727
  Security_context *sctx= thd->security_ctx;
728
  DBUG_ENTER("acl_getroot");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
729 730

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
740
  VOID(pthread_mutex_lock(&acl_cache->lock));
peter@mysql.com's avatar
peter@mysql.com committed
741

bk@work.mysql.com's avatar
bk@work.mysql.com committed
742
  /*
743 744 745
    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
bk@work.mysql.com's avatar
bk@work.mysql.com committed
746
  */
peter@mysql.com's avatar
peter@mysql.com committed
747

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

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

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

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

904
    if (acl_user->host.hostname)
905
      strmake(sctx->priv_host, acl_user->host.hostname, MAX_HOSTNAME);
906
    else
907
      *sctx->priv_host= 0;
908
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
909
  VOID(pthread_mutex_unlock(&acl_cache->lock));
910
  DBUG_RETURN(res);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
911 912 913
}


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

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

  RETURN
    FALSE  OK
    TRUE   Error
*/

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

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

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

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

958 959
  sctx->master_access= 0;
  sctx->db_access= 0;
960

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

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

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1011 1012 1013 1014 1015 1016 1017
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;
}

1018

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


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

  set_user_salt(&acl_user, password, password_len);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1091 1092 1093 1094

  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])
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
1095
    allow_all_hosts=1;		// Anyone can connect /* purecov: tested */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1096 1097 1098
  qsort((gptr) dynamic_element(&acl_users,0,ACL_USER*),acl_users.elements,
	sizeof(ACL_USER),(qsort_cmp) acl_compare);

1099 1100
  /* Rebuild 'acl_check_hosts' since 'acl_users' has been modified */
  rebuild_check_host();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1101 1102 1103 1104
}


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


1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
/*
  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
*/

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1146
static void acl_insert_db(const char *user, const char *host, const char *db,
1147
			  ulong privileges)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1148 1149
{
  ACL_DB acl_db;
1150
  safe_mutex_assert_owner(&acl_cache->lock);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
  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);
}


1162 1163 1164

/*
  Get privilege for a host, user and db combination
1165 1166 1167

  as db_is_pattern changes the semantics of comparison,
  acl_cache is not used if db_is_pattern is set.
1168
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1169

1170
ulong acl_get(const char *host, const char *ip,
1171
              const char *user, const char *db, my_bool db_is_pattern)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1172
{
1173
  ulong host_access= ~(ulong)0, db_access= 0;
1174
  uint i,key_length;
1175
  char key[ACL_KEY_LENGTH],*tmp_db,*end;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1176
  acl_entry *entry;
monty@mysql.com's avatar
monty@mysql.com committed
1177
  DBUG_ENTER("acl_get");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1178 1179

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

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

1249 1250 1251 1252 1253 1254 1255
/*
  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
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1256 1257 1258 1259

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


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

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


bk@work.mysql.com's avatar
bk@work.mysql.com committed
1318 1319 1320 1321 1322 1323 1324 1325
/* 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));

1326 1327
  if (host && hash_search(&acl_check_hosts,(byte*) host,(uint) strlen(host)) ||
      ip && hash_search(&acl_check_hosts,(byte*) ip,(uint) strlen(ip)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
  {
    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
}


1346 1347 1348 1349 1350 1351 1352 1353
/*
  Check if the user is allowed to change password

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

  NOTE:
    new_password cannot be NULL
monty@hundin.mysql.fi's avatar
merge  
monty@hundin.mysql.fi committed
1358

1359
    RETURN VALUE
1360 1361
      0		OK
      1		ERROR  ; In this case the error is sent to the client.
1362 1363
*/

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


1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
/*
  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.
peter@mysql.com's avatar
peter@mysql.com committed
1410
*/
1411

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

1427
  if (check_change_password(thd, host, user, new_password, new_password_len))
1428 1429
    DBUG_RETURN(1);

1430
  bzero((char*) &tables, sizeof(tables));
1431
  tables.alias= tables.table_name= (char*) "user";
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
  tables.db= (char*) "mysql";

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

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1455 1456
  VOID(pthread_mutex_lock(&acl_cache->lock));
  ACL_USER *acl_user;
1457
  if (!(acl_user= find_acl_user(host, user, TRUE)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1458 1459
  {
    VOID(pthread_mutex_unlock(&acl_cache->lock));
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1460
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH), MYF(0));
1461
    goto end;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1462
  }
1463 1464 1465
  /* update loaded acl entry: */
  set_user_salt(acl_user, new_password, new_password_len);

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1475 1476
  acl_cache->clear(1);				// Clear locked hostname cache
  VOID(pthread_mutex_unlock(&acl_cache->lock));
1477 1478 1479
  result= 0;
  if (mysql_bin_log.is_open())
  {
1480 1481 1482 1483 1484 1485
    query_length=
      my_sprintf(buff,
                 (buff,"SET PASSWORD FOR \"%-.120s\"@\"%-.120s\"=\"%-.120s\"",
                  acl_user->user ? acl_user->user : "",
                  acl_user->host.hostname ? acl_user->host.hostname : "",
                  new_password));
1486 1487 1488 1489 1490 1491 1492
    thd->clear_error();
    Query_log_event qinfo(thd, buff, query_length, 0, FALSE);
    mysql_bin_log.write(&qinfo);
  }
end:
  close_thread_tables(thd);
  DBUG_RETURN(result);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1493 1494 1495
}


1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
/*
  Find user in ACL

  SYNOPSIS
    is_acl_user()
    host                 host name
    user                 user name

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

bool is_acl_user(const char *host, const char *user)
{
  bool res;
1512 1513 1514 1515 1516

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

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


bk@work.mysql.com's avatar
bk@work.mysql.com committed
1524 1525 1526 1527 1528
/*
  Find first entry that matches the current user
*/

static ACL_USER *
1529
find_acl_user(const char *host, const char *user, my_bool exact)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1530
{
1531
  DBUG_ENTER("find_acl_user");
1532
  DBUG_PRINT("enter",("host: '%s'  user: '%s'",host,user));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1533 1534 1535
  for (uint i=0 ; i < acl_users.elements ; i++)
  {
    ACL_USER *acl_user=dynamic_element(&acl_users,i,ACL_USER*);
1536
    DBUG_PRINT("info",("strcmp('%s','%s'), compare_hostname('%s','%s'),",
1537 1538 1539 1540 1541
		       user,
		       acl_user->user ? acl_user->user : "",
		       host,
		       acl_user->host.hostname ? acl_user->host.hostname :
		       ""));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1542 1543 1544
    if (!acl_user->user && !user[0] ||
	acl_user->user && !strcmp(user,acl_user->user))
    {
1545
      if (exact ? !my_strcasecmp(&my_charset_latin1, host,
1546 1547
                                 acl_user->host.hostname ?
				 acl_user->host.hostname : "") :
1548
          compare_hostname(&acl_user->host,host,host))
1549 1550 1551
      {
	DBUG_RETURN(acl_user);
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1552 1553
    }
  }
1554
  DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1555 1556 1557
}


1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
/*
  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.
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591

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


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 ||
1610
	  (hostname && !wild_case_compare(system_charset_info,
1611
                                          hostname,host->hostname)) ||
1612
	  (ip && !wild_compare(ip,host->hostname,0)));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1613 1614
}

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

1635

1636
/*
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646
  Update record for user in mysql.user privilege table with new password.

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

1649 1650
static bool update_user_table(THD *thd, TABLE *table,
                              const char *host, const char *user,
1651
			      const char *new_password, uint new_password_len)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1652
{
1653
  char user_key[MAX_KEY_LENGTH];
1654
  int error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1655 1656 1657
  DBUG_ENTER("update_user_table");
  DBUG_PRINT("enter",("user: %s  host: %s",user,host));

1658 1659
  table->field[0]->store(host,(uint) strlen(host), system_charset_info);
  table->field[1]->store(user,(uint) strlen(user), system_charset_info);
1660
  key_copy((byte *) user_key, table->record[0], table->key_info,
1661
           table->key_info->key_length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1662

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

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1682

1683 1684 1685 1686 1687 1688
/*
  Return 1 if we are allowed to create new users
  the logic here is: INSERT_ACL is sufficient.
  It's also a requirement in opt_safe_user_create,
  otherwise CREATE_USER_ACL is enough.
*/
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1689 1690 1691

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

1705 1706
    db_access=acl_get(sctx->host, sctx->ip,
		      sctx->priv_user, tl.db, 0);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1707 1708
    if (!(db_access & INSERT_ACL))
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1709
      if (check_grant(thd, INSERT_ACL, &tl, 0, UINT_MAX, 1))
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1710 1711 1712 1713 1714 1715 1716
	create_new_users=0;
    }
  }
  return create_new_users;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
1717
/****************************************************************************
1718
  Handle GRANT commands
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1719 1720
****************************************************************************/

1721
static int replace_user_table(THD *thd, TABLE *table, const LEX_USER &combo,
1722
			      ulong rights, bool revoke_grant,
serg@serg.mylan's avatar
serg@serg.mylan committed
1723
			      bool can_create_user, bool no_auto_create)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1724 1725
{
  int error = -1;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1726
  bool old_row_exists=0;
1727
  const char *password= "";
1728
  uint password_len= 0;
1729
  char what= (revoke_grant) ? 'N' : 'Y';
1730
  byte user_key[MAX_KEY_LENGTH];
1731
  LEX *lex= thd->lex;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1732
  DBUG_ENTER("replace_user_table");
1733

1734
  safe_mutex_assert_owner(&acl_cache->lock);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1735 1736

  if (combo.password.str && combo.password.str[0])
1737
  {
1738 1739
    if (combo.password.length != SCRAMBLED_PASSWORD_CHAR_LENGTH &&
        combo.password.length != SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
1740
    {
1741
      my_error(ER_PASSWD_LENGTH, MYF(0), SCRAMBLED_PASSWORD_CHAR_LENGTH);
1742
      DBUG_RETURN(-1);
1743
    }
1744
    password_len= combo.password.length;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1745
    password=combo.password.str;
1746
  }
peter@mysql.com's avatar
peter@mysql.com committed
1747

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

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

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

1811 1812 1813 1814
  /* Update table columns with new privileges */

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

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

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


/*
1937
  change grants in the mysql.db table
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1938 1939 1940 1941
*/

static int replace_db_table(TABLE *table, const char *db,
			    const LEX_USER &combo,
1942
			    ulong rights, bool revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1943
{
1944 1945
  uint i;
  ulong priv,store_rights;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1946
  bool old_row_exists=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1947
  int error;
1948
  char what= (revoke_grant) ? 'N' : 'Y';
1949
  byte user_key[MAX_KEY_LENGTH];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1950 1951
  DBUG_ENTER("replace_db_table");

1952 1953
  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
1954
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
1955 1956 1957
    DBUG_RETURN(-1);
  }

1958
  /* Check if there is such a user in user table in memory? */
1959
  if (!find_acl_user(combo.host.str,combo.user.str, FALSE))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1960
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1961
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH), MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1962 1963 1964
    DBUG_RETURN(-1);
  }

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

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

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

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2002
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2003
  {
2004
    /* update old existing row */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2005 2006
    if (rights)
    {
2007
      table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2008 2009 2010 2011 2012 2013 2014 2015 2016
      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 */
    }
  }
2017
  else if (rights && (error=table->file->write_row(table->record[0])))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2018 2019 2020 2021 2022 2023
  {
    if (error && error != HA_ERR_FOUND_DUPP_KEY) /* purecov: inspected */
      goto table_error; /* purecov: deadcode */
  }

  acl_cache->clear(1);				// Clear privilege cache
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2024
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2025 2026
    acl_update_db(combo.user.str,combo.host.str,db,rights);
  else
2027
  if (rights)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2028 2029 2030 2031
    acl_insert_db(combo.user.str,combo.host.str,db,rights);
  DBUG_RETURN(0);

  /* This could only happen if the grant tables got corrupted */
2032
table_error:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2033 2034
  table->file->print_error(error,MYF(0));	/* purecov: deadcode */

2035
abort:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2036 2037 2038 2039 2040 2041 2042 2043
  DBUG_RETURN(-1);
}


class GRANT_COLUMN :public Sql_alloc
{
public:
  char *column;
2044 2045 2046
  ulong rights;
  uint key_length;
  GRANT_COLUMN(String &c,  ulong y) :rights (y)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2047
  {
2048
    column= memdup_root(&memex,c.ptr(), key_length=c.length());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2049 2050 2051
  }
};

2052

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2053 2054 2055 2056 2057 2058 2059
static byte* get_key_column(GRANT_COLUMN *buff,uint *length,
			    my_bool not_used __attribute__((unused)))
{
  *length=buff->key_length;
  return (byte*) buff->column;
}

2060

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

  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);
2086
  ~GRANT_TABLE();
2087 2088
  bool ok() { return privs != 0 || cols != 0; }
};
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2089

2090

monty@mysql.com's avatar
monty@mysql.com committed
2091

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


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)
{
2117
  (void) hash_init(&hash_columns,system_charset_info,
monty@mysql.com's avatar
monty@mysql.com committed
2118
                   0,0,0, (hash_get_key) get_key_column,0,0);
2119
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2120

2121

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


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();
2164 2165
  cols =  fix_rights_for_column(cols);

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

    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);
monty@mysql.com's avatar
monty@mysql.com committed
2184
    col_privs->field[4]->store("",0, &my_charset_latin1);
2185

2186 2187
    col_privs->file->ha_index_init(0);
    if (col_privs->file->index_read(col_privs->record[0],
2188 2189
                                    (byte*) key,
                                    key_prefix_len, HA_READ_KEY_EXACT))
2190
    {
2191
      cols = 0; /* purecov: deadcode */
2192
      col_privs->file->ha_index_end();
2193
      return;
2194
    }
2195
    do
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2196
    {
2197 2198 2199
      String *res,column_name;
      GRANT_COLUMN *mem_check;
      /* As column name is a string, we don't have to supply a buffer */
monty@mysql.com's avatar
monty@mysql.com committed
2200
      res=col_privs->field[4]->val_str(&column_name);
2201 2202 2203
      ulong priv= (ulong) col_privs->field[6]->val_int();
      if (!(mem_check = new GRANT_COLUMN(*res,
                                         fix_rights_for_column(priv))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2204
      {
2205 2206 2207
        /* Don't use this entry */
        privs = cols = 0;			/* purecov: deadcode */
        return;				/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2208
      }
monty@mysql.com's avatar
monty@mysql.com committed
2209
      my_hash_insert(&hash_columns, (byte *) mem_check);
2210
    } while (!col_privs->file->index_next(col_privs->record[0]) &&
2211
             !key_cmp_if_same(col_privs,key,0,key_prefix_len));
2212
    col_privs->file->ha_index_end();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2213
  }
2214
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2215

2216

2217 2218 2219 2220 2221 2222
GRANT_TABLE::~GRANT_TABLE()
{
  hash_free(&hash_columns);
}


2223
static byte* get_grant_table(GRANT_NAME *buff,uint *length,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2224 2225 2226 2227 2228 2229
			     my_bool not_used __attribute__((unused)))
{
  *length=buff->key_length;
  return (byte*) buff->hash_key;
}

2230

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2231 2232 2233 2234 2235
void free_grant_table(GRANT_TABLE *grant_table)
{
  hash_free(&grant_table->hash_columns);
}

2236

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2237 2238
/* Search after a matching grant. Prefer exact grants before not exact ones */

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

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


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


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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2291

2292
inline GRANT_COLUMN *
2293
column_hash_search(GRANT_TABLE *t, const char *cname, uint length)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2294 2295 2296 2297 2298 2299 2300 2301 2302
{
  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,
2303
				ulong rights, bool revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2304 2305 2306
{
  int error=0,result=0;
  byte key[MAX_KEY_LENGTH];
2307 2308
  uint key_prefix_length;
  KEY_PART_INFO *key_part= table->key_info->key_part;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2309 2310
  DBUG_ENTER("replace_column_table");

2311 2312 2313 2314 2315 2316 2317 2318
  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);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2319

2320 2321 2322 2323
  /* 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);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2324

2325
  rights&= COL_ACLS;				// Only ACL for columns
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2326 2327 2328 2329

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

  List_iterator <LEX_COLUMN> iter(columns);
2330
  class LEX_COLUMN *column;
2331
  table->file->ha_index_init(0);
2332
  while ((column= iter++))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2333
  {
2334
    ulong privileges= column->rights;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2335
    bool old_row_exists=0;
2336 2337 2338 2339
    byte user_key[MAX_KEY_LENGTH];

    key_restore(table->record[0],key,table->key_info,
                key_prefix_length);
2340
    table->field[4]->store(column->column.ptr(), column->column.length(),
2341
                           system_charset_info);
2342 2343 2344
    /* Get key for the first 4 columns */
    key_copy(user_key, table->record[0], table->key_info,
             table->key_info->key_length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2345

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

      if (revoke_grant)
	privileges = tmp & ~(privileges | rights);
      else
	privileges |= tmp;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2375
      old_row_exists = 1;
2376
      store_record(table,record[1]);			// copy original row
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2377 2378
    }

2379
    table->field[6]->store((longlong) get_rights_for_column(privileges), TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2380

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2381
    if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2382
    {
2383
      GRANT_COLUMN *grant_column;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2384 2385 2386 2387 2388 2389 2390 2391 2392 2393
      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 */
      }
2394 2395
      grant_column= column_hash_search(g_t, column->column.ptr(),
                                       column->column.length());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2396
      if (grant_column)				// Should always be true
2397
	grant_column->rights= privileges;	// Update hash
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2398 2399 2400
    }
    else					// new grant
    {
2401
      GRANT_COLUMN *grant_column;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2402 2403 2404 2405 2406 2407
      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 */
      }
2408
      grant_column= new GRANT_COLUMN(column->column,privileges);
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2409
      my_hash_insert(&g_t->hash_columns,(byte*) grant_column);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2410 2411 2412 2413 2414 2415 2416 2417 2418 2419
    }
  }

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

  if (revoke_grant)
  {
2420 2421
    byte user_key[MAX_KEY_LENGTH];
    key_copy(user_key, table->record[0], table->key_info,
2422 2423
             key_prefix_length);

2424
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
2425
    if (table->file->index_read(table->record[0], user_key,
2426
				key_prefix_length,
2427
                                HA_READ_KEY_EXACT))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2428 2429
      goto end;

2430
    /* Scan through all rows with the same host,db,user and table */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2431 2432
    do
    {
2433
      ulong privileges = (ulong) table->field[6]->val_int();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2434
      privileges=fix_rights_for_column(privileges);
2435
      store_record(table,record[1]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2436 2437 2438 2439 2440

      if (privileges & rights)	// is in this record the priv to be revoked ??
      {
	GRANT_COLUMN *grant_column = NULL;
	char  colum_name_buf[HOSTNAME_LENGTH+1];
2441
	String column_name(colum_name_buf,sizeof(colum_name_buf),
2442
                           system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2443 2444 2445

	privileges&= ~rights;
	table->field[6]->store((longlong)
2446
			       get_rights_for_column(privileges), TRUE);
2447
	table->field[4]->val_str(&column_name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2448 2449 2450 2451 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
	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]) &&
2478
	     !key_cmp_if_same(table, key, 0, key_prefix_length));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2479 2480
  }

2481
end:
2482
  table->file->ha_index_end();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2483 2484 2485 2486 2487 2488 2489
  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,
2490 2491
			       ulong rights, ulong col_rights,
			       bool revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2492
{
2493
  char grantor[HOSTNAME_LENGTH+USERNAME_LENGTH+2];
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2494
  int old_row_exists = 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2495
  int error=0;
2496
  ulong store_table_rights, store_col_rights;
2497
  byte user_key[MAX_KEY_LENGTH];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2498 2499
  DBUG_ENTER("replace_table_table");

2500 2501
  strxmov(grantor, thd->security_ctx->user, "@",
          thd->security_ctx->host_or_ip, NullS);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2502

2503 2504 2505 2506
  /*
    The following should always succeed as new users are created before
    this function is called!
  */
2507
  if (!find_acl_user(combo.host.str,combo.user.str, FALSE))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2508
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2509 2510
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH),
               MYF(0));	/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2511 2512 2513
    DBUG_RETURN(-1);				/* purecov: deadcode */
  }

2514
  restore_record(table, s->default_values);     // Get empty record
2515 2516 2517 2518
  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);
2519
  store_record(table,record[1]);			// store at pos 1
2520 2521
  key_copy(user_key, table->record[0], table->key_info,
           table->key_info->key_length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2522

2523
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
2524 2525
  if (table->file->index_read_idx(table->record[0], 0,
                                  user_key, table->key_info->key_length,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2526 2527 2528 2529 2530 2531 2532 2533 2534
				  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
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2535 2536
      my_error(ER_NONEXISTING_TABLE_GRANT, MYF(0),
               combo.user.str, combo.host.str,
2537
               table_name);		        /* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2538 2539
      DBUG_RETURN(-1);				/* purecov: deadcode */
    }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2540
    old_row_exists = 0;
2541
    restore_record(table,record[1]);			// Get saved record
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2542 2543
  }

2544 2545
  store_table_rights= get_rights_for_table(rights);
  store_col_rights=   get_rights_for_column(col_rights);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2546
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2547
  {
2548
    ulong j,k;
2549
    store_record(table,record[1]);
2550 2551
    j = (ulong) table->field[6]->val_int();
    k = (ulong) table->field[7]->val_int();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2552 2553 2554

    if (revoke_grant)
    {
2555
      /* column rights are already fixed in mysql_table_grant */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2556 2557 2558 2559
      store_table_rights=j & ~store_table_rights;
    }
    else
    {
2560 2561
      store_table_rights|= j;
      store_col_rights|=   k;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2562 2563 2564
    }
  }

2565
  table->field[4]->store(grantor,(uint) strlen(grantor), system_charset_info);
2566 2567
  table->field[6]->store((longlong) store_table_rights, TRUE);
  table->field[7]->store((longlong) store_col_rights, TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2568
  rights=fix_rights_for_table(store_table_rights);
2569
  col_rights=fix_rights_for_column(store_col_rights);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2570

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2571
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587
  {
    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 */
  }

2588
  if (rights | col_rights)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2589
  {
2590
    grant_table->privs= rights;
2591
    grant_table->cols=	col_rights;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2592 2593 2594
  }
  else
  {
2595
    hash_delete(&column_priv_hash,(byte*) grant_table);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2596 2597 2598
  }
  DBUG_RETURN(0);

2599 2600
  /* This should never happen */
table_error:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2601 2602 2603 2604 2605
  table->file->print_error(error,MYF(0)); /* purecov: deadcode */
  DBUG_RETURN(-1); /* purecov: deadcode */
}


2606
static int replace_routine_table(THD *thd, GRANT_NAME *grant_name,
2607
			      TABLE *table, const LEX_USER &combo,
2608 2609
			      const char *db, const char *routine_name,
			      bool is_proc, ulong rights, bool revoke_grant)
2610 2611 2612 2613 2614
{
  char grantor[HOSTNAME_LENGTH+USERNAME_LENGTH+2];
  int old_row_exists= 1;
  int error=0;
  ulong store_proc_rights;
2615
  DBUG_ENTER("replace_routine_table");
2616 2617 2618 2619 2620 2621 2622

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

2623 2624
  strxmov(grantor, thd->security_ctx->user, "@",
          thd->security_ctx->host_or_ip, NullS);
2625 2626 2627 2628 2629

  /*
    The following should always succeed as new users are created before
    this function is called!
  */
monty@mishka.local's avatar
monty@mishka.local committed
2630
  if (!find_acl_user(combo.host.str, combo.user.str, FALSE))
2631 2632 2633 2634 2635
  {
    my_error(ER_PASSWORD_NO_MATCH,MYF(0));
    DBUG_RETURN(-1);
  }

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

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

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


2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734
/*
  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
2735 2736
    FALSE ok
    TRUE  error
2737 2738
*/

2739
bool mysql_table_grant(THD *thd, TABLE_LIST *table_list,
2740 2741 2742
		      List <LEX_USER> &user_list,
		      List <LEX_COLUMN> &columns, ulong rights,
		      bool revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2743
{
2744
  ulong column_priv= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2745 2746 2747
  List_iterator <LEX_USER> str_list (user_list);
  LEX_USER *Str;
  TABLE_LIST tables[3];
2748
  bool create_new_users=0;
2749
  char *db_name, *table_name;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2750 2751 2752 2753
  DBUG_ENTER("mysql_table_grant");

  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2754 2755
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0),
             "--skip-grant-tables");	/* purecov: inspected */
2756
    DBUG_RETURN(TRUE);				/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2757 2758 2759
  }
  if (rights & ~TABLE_ACLS)
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2760 2761
    my_message(ER_ILLEGAL_GRANT_FOR_TABLE, ER(ER_ILLEGAL_GRANT_FOR_TABLE),
               MYF(0));
2762
    DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2763 2764
  }

2765
  if (!revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2766
  {
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
2767
    if (columns.elements)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2768
    {
2769 2770
      class LEX_COLUMN *column;
      List_iterator <LEX_COLUMN> column_iter(columns);
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
2771 2772 2773

      if (open_and_lock_tables(thd, table_list))
        DBUG_RETURN(TRUE);
2774 2775

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

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

  bzero((char*) &tables,sizeof(tables));
2826 2827 2828
  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";
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2829
  tables[0].next_local= tables[0].next_global= tables+1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2830
  /* Don't open column table if we don't need it ! */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2831 2832 2833 2834 2835
  tables[1].next_local=
    tables[1].next_global= ((column_priv ||
			     (revoke_grant &&
			      ((rights & COL_ACLS) || columns.elements)))
			    ? tables+2 : 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2836 2837 2838
  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";

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

2856
  if (simple_open_n_lock_tables(thd,tables))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2857 2858
  {						// Should never happen
    close_thread_tables(thd);			/* purecov: deadcode */
2859
    DBUG_RETURN(TRUE);				/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2860 2861
  }

2862 2863
  if (!revoke_grant)
    create_new_users= test_if_create_new_users(thd);
2864
  bool result= FALSE;
2865
  rw_wrlock(&LOCK_grant);
2866 2867
  MEM_ROOT *old_root= thd->mem_root;
  thd->mem_root= &memex;
2868
  grant_version++;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2869 2870 2871

  while ((Str = str_list++))
  {
2872
    int error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2873 2874 2875 2876
    GRANT_TABLE *grant_table;
    if (Str->host.length > HOSTNAME_LENGTH ||
	Str->user.length > USERNAME_LENGTH)
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2877 2878
      my_message(ER_GRANT_WRONG_HOST_OR_USER, ER(ER_GRANT_WRONG_HOST_OR_USER),
                 MYF(0));
2879
      result= TRUE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2880 2881 2882
      continue;
    }
    /* Create user if needed */
2883
    pthread_mutex_lock(&acl_cache->lock);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2884
    error=replace_user_table(thd, tables[0].table, *Str,
serg@serg.mylan's avatar
serg@serg.mylan committed
2885
			     0, revoke_grant, create_new_users,
monty@mysql.com's avatar
monty@mysql.com committed
2886 2887
                             test(thd->variables.sql_mode &
                                  MODE_NO_AUTO_CREATE_USER));
2888 2889
    pthread_mutex_unlock(&acl_cache->lock);
    if (error)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2890
    {
2891
      result= TRUE;				// Remember error
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2892 2893 2894
      continue;					// Add next user
    }

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2895 2896 2897
    db_name= (table_list->view_db.length ?
	      table_list->view_db.str :
	      table_list->db);
2898
    table_name= (table_list->view_name.length ?
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2899
		table_list->view_name.str :
2900
		table_list->table_name);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2901

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2902
    /* Find/create cached table grant */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2903
    grant_table= table_hash_search(Str->host.str, NullS, db_name,
2904
				   Str->user.str, table_name, 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2905 2906 2907 2908
    if (!grant_table)
    {
      if (revoke_grant)
      {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2909
	my_error(ER_NONEXISTING_TABLE_GRANT, MYF(0),
2910
                 Str->user.str, Str->host.str, table_list->table_name);
2911
	result= TRUE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2912 2913
	continue;
      }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2914
      grant_table = new GRANT_TABLE (Str->host.str, db_name,
2915
				     Str->user.str, table_name,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2916 2917 2918 2919
				     rights,
				     column_priv);
      if (!grant_table)				// end of memory
      {
2920
	result= TRUE;				/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2921 2922
	continue;				/* purecov: deadcode */
      }
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2923
      my_hash_insert(&column_priv_hash,(byte*) grant_table);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2924 2925 2926 2927 2928
    }

    /* If revoke_grant, calculate the new column privilege for tables_priv */
    if (revoke_grant)
    {
2929 2930
      class LEX_COLUMN *column;
      List_iterator <LEX_COLUMN> column_iter(columns);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2931 2932 2933
      GRANT_COLUMN *grant_column;

      /* Fix old grants */
2934
      while ((column = column_iter++))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2935 2936
      {
	grant_column = column_hash_search(grant_table,
2937 2938
					  column->column.ptr(),
					  column->column.length());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2939
	if (grant_column)
2940
	  grant_column->rights&= ~(column->rights | rights);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2941 2942
      }
      /* scan trough all columns to get new column grant */
2943
      column_priv= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959
      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 */

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2960
    if (replace_table_table(thd, grant_table, tables[1].table, *Str,
2961
			    db_name, table_name,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2962
			    rights, column_priv, revoke_grant))
2963 2964
    {
      /* Should only happen if table is crashed */
2965
      result= TRUE;			       /* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2966 2967 2968
    }
    else if (tables[2].table)
    {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2969
      if ((replace_column_table(grant_table, tables[2].table, *Str,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2970
				columns,
2971
				db_name, table_name,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2972 2973
				rights, revoke_grant)))
      {
2974
	result= TRUE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2975 2976 2977 2978
      }
    }
  }
  grant_option=TRUE;
2979
  thd->mem_root= old_root;
2980
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2981
  if (!result)
2982
    send_ok(thd);
2983
  /* Tables are automatically closed */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2984 2985 2986 2987
  DBUG_RETURN(result);
}


2988
/*
2989
  Store routine level grants in the privilege tables
2990 2991

  SYNOPSIS
2992
    mysql_routine_grant()
2993
    thd			Thread handle
2994 2995
    table_list		List of routines to give grant
    is_proc             true indicates routine list are procedures
2996 2997 2998 2999 3000 3001 3002 3003 3004
    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
*/

3005 3006 3007
bool mysql_routine_grant(THD *thd, TABLE_LIST *table_list, bool is_proc,
			 List <LEX_USER> &user_list, ulong rights,
			 bool revoke_grant, bool no_error)
3008 3009 3010 3011 3012
{
  List_iterator <LEX_USER> str_list (user_list);
  LEX_USER *Str;
  TABLE_LIST tables[2];
  bool create_new_users=0, result=0;
3013
  char *db_name, *table_name;
3014
  DBUG_ENTER("mysql_routine_grant");
3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032

  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)
  {
3033
    if (sp_exists_routine(thd, table_list, is_proc, no_error)<0)
3034 3035 3036 3037 3038 3039
      DBUG_RETURN(TRUE);
  }

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

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

    db_name= table_list->db;
3104
    table_name= table_list->table_name;
3105

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

3129 3130
    if (replace_routine_table(thd, grant_name, tables[1].table, *Str,
			   db_name, table_name, is_proc, rights, revoke_grant))
3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145
    {
      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);
}


3146 3147
bool mysql_grant(THD *thd, const char *db, List <LEX_USER> &list,
                 ulong rights, bool revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3148 3149 3150
{
  List_iterator <LEX_USER> str_list (list);
  LEX_USER *Str;
3151
  char tmp_db[NAME_LEN+1];
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
3152
  bool create_new_users=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3153 3154 3155 3156
  TABLE_LIST tables[2];
  DBUG_ENTER("mysql_grant");
  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3157 3158
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0),
             "--skip-grant-tables");	/* purecov: tested */
3159
    DBUG_RETURN(TRUE);				/* purecov: tested */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3160 3161
  }

3162 3163 3164
  if (lower_case_table_names && db)
  {
    strmov(tmp_db,db);
3165
    my_casedn_str(files_charset_info, tmp_db);
3166 3167
    db=tmp_db;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3168 3169

  /* open the mysql.user and mysql.db tables */
3170
  bzero((char*) &tables,sizeof(tables));
3171 3172
  tables[0].alias=tables[0].table_name=(char*) "user";
  tables[1].alias=tables[1].table_name=(char*) "db";
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3173
  tables[0].next_local= tables[0].next_global= tables+1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3174 3175
  tables[0].lock_type=tables[1].lock_type=TL_WRITE;
  tables[0].db=tables[1].db=(char*) "mysql";
3176 3177 3178 3179 3180 3181

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

3194
  if (simple_open_n_lock_tables(thd,tables))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3195 3196
  {						// This should never happen
    close_thread_tables(thd);			/* purecov: deadcode */
3197
    DBUG_RETURN(TRUE);				/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3198 3199
  }

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
3200 3201
  if (!revoke_grant)
    create_new_users= test_if_create_new_users(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3202

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

  if (!result)
3245
    send_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3246 3247 3248
  DBUG_RETURN(result);
}

3249 3250

/* Free grant array if possible */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3251 3252 3253 3254 3255

void  grant_free(void)
{
  DBUG_ENTER("grant_free");
  grant_option = FALSE;
3256
  hash_free(&column_priv_hash);
3257
  hash_free(&proc_priv_hash);
monty@mysql.com's avatar
monty@mysql.com committed
3258
  hash_free(&func_priv_hash);
3259
  free_root(&memex,MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3260 3261 3262 3263
  DBUG_VOID_RETURN;
}


3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274
/*
  Initialize structures responsible for table/column-level privilege checking
  and load information for them from tables in the 'mysql' database.

  SYNOPSIS
    grant_init()

  RETURN VALUES
    0	ok
    1	Could not initialize grant's
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3275

3276
my_bool grant_init()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3277
{
3278
  THD  *thd;
3279 3280 3281 3282 3283
  my_bool return_val;
  DBUG_ENTER("grant_init");

  if (!(thd= new THD))
    DBUG_RETURN(1);				/* purecov: deadcode */
3284
  thd->thread_stack= (char*) &thd;
3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310
  thd->store_globals();
  return_val=  grant_reload(thd);
  delete thd;
  /* Remember that we don't have a THD */
  my_pthread_setspecific_ptr(THR_THD,  0);
  DBUG_RETURN(return_val);
}


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

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

  RETURN VALUES
    FALSE - success
    TRUE  - error
*/

static my_bool grant_load(TABLE_LIST *tables)
{
3311
  MEM_ROOT *memex_ptr;
3312
  my_bool return_val= 1;
3313
  TABLE *t_table, *c_table, *p_table;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
3314
  bool check_no_resolve= specialflag & SPECIAL_NO_RESOLVE;
3315 3316 3317
  MEM_ROOT **save_mem_root_ptr= my_pthread_getspecific_ptr(MEM_ROOT**,
                                                           THR_MALLOC);
  DBUG_ENTER("grant_load");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3318 3319

  grant_option = FALSE;
3320
  (void) hash_init(&column_priv_hash,system_charset_info,
3321
		   0,0,0, (hash_get_key) get_grant_table,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3322
		   (hash_free_key) free_grant_table,0);
3323 3324 3325
  (void) hash_init(&proc_priv_hash,system_charset_info,
		   0,0,0, (hash_get_key) get_grant_table,
		   0,0);
3326 3327 3328
  (void) hash_init(&func_priv_hash,system_charset_info,
		   0,0,0, (hash_get_key) get_grant_table,
		   0,0);
3329
  init_sql_alloc(&memex, ACL_ALLOC_BLOCK_SIZE, 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3330 3331

  t_table = tables[0].table; c_table = tables[1].table;
3332
  p_table= tables[2].table;
3333
  t_table->file->ha_index_init(0);
3334 3335
  p_table->file->ha_index_init(0);
  if (!t_table->file->index_first(t_table->record[0]))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3336
  {
3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347
    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;
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3348

3349 3350
      if (check_no_resolve)
      {
3351
	if (hostname_requires_resolving(mem_check->host.hostname))
3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372
	{
          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]))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3373
  {
3374 3375 3376
    memex_ptr= &memex;
    my_pthread_setspecific_ptr(THR_MALLOC, &memex_ptr);
    do
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3377
    {
3378
      GRANT_NAME *mem_check;
3379
      HASH *hash;
3380 3381 3382 3383 3384 3385
      if (!(mem_check=new GRANT_NAME(p_table)))
      {
	/* This could only happen if we are out memory */
	grant_option= FALSE;
	goto end_unlock;
      }
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
3386

3387
      if (check_no_resolve)
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
3388
      {
jimw@mysql.com's avatar
jimw@mysql.com committed
3389
	if (hostname_requires_resolving(mem_check->host.hostname))
3390 3391 3392 3393
	{
          sql_print_warning("'procs_priv' entry '%s %s@%s' "
                            "ignored in --skip-name-resolve mode.",
                            mem_check->tname, mem_check->user,
acurtis@xiphis.org's avatar
Merge  
acurtis@xiphis.org committed
3394
                            mem_check->host);
3395 3396
	  continue;
	}
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
3397
      }
3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413
      if (p_table->field[4]->val_int() == TYPE_ENUM_PROCEDURE)
      {
        hash= &proc_priv_hash;
      }
      else
      if (p_table->field[4]->val_int() == TYPE_ENUM_FUNCTION)
      {
        hash= &func_priv_hash;
      }
      else
      {
        sql_print_warning("'procs_priv' entry '%s' "
                          "ignored, bad routine type",
                          mem_check->tname);
	continue;
      }
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
3414

3415 3416 3417
      mem_check->privs= fix_rights_for_procedure(mem_check->privs);
      if (! mem_check->ok())
	delete mem_check;
3418
      else if (my_hash_insert(hash, (byte*) mem_check))
3419 3420 3421 3422 3423
      {
	delete mem_check;
	grant_option= FALSE;
	goto end_unlock;
      }
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
3424
    }
3425
    while (!p_table->file->index_next(p_table->record[0]));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3426
  }
3427
  grant_option= TRUE;
3428 3429 3430
  return_val=0;					// Return ok

end_unlock:
3431
  t_table->file->ha_index_end();
3432
  p_table->file->ha_index_end();
3433
  my_pthread_setspecific_ptr(THR_MALLOC, save_mem_root_ptr);
3434
  DBUG_RETURN(return_val);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3435 3436 3437
}


3438
/*
3439
  Reload information about table and column level privileges if possible.
3440 3441 3442

  SYNOPSIS
    grant_reload()
3443
      thd  Current thread
3444 3445

  NOTES
3446 3447 3448 3449 3450 3451 3452 3453
    Locked tables are checked by acl_reload() and doesn't have to be checked
    in this call.
    This function is also used for initialization of structures responsible
    for table/column-level privilege checking.

  RETURN VALUE
    FALSE Success
    TRUE  Error
3454
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3455

3456
my_bool grant_reload(THD *thd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3457
{
3458
  TABLE_LIST tables[3];
3459
  HASH old_column_priv_hash, old_proc_priv_hash, old_func_priv_hash;
3460
  bool old_grant_option;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3461
  MEM_ROOT old_mem;
3462
  my_bool return_val= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3463 3464
  DBUG_ENTER("grant_reload");

3465 3466 3467 3468 3469
  /* Don't do anything if running with --skip-grant-tables */
  if (!initialized)
    DBUG_RETURN(0);

  bzero((char*) tables, sizeof(tables));
3470 3471 3472 3473 3474 3475 3476
  tables[0].alias= tables[0].table_name= (char*) "tables_priv";
  tables[1].alias= tables[1].table_name= (char*) "columns_priv";
  tables[2].alias= tables[2].table_name= (char*) "procs_priv";
  tables[0].db= tables[1].db= tables[2].db= (char *) "mysql";
  tables[0].next_local= tables[0].next_global= tables+1;
  tables[1].next_local= tables[1].next_global= tables+2;
  tables[0].lock_type= tables[1].lock_type= tables[2].lock_type= TL_READ;
3477 3478 3479 3480 3481 3482 3483 3484

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

3485
  rw_wrlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3486
  grant_version++;
3487
  old_column_priv_hash= column_priv_hash;
3488
  old_proc_priv_hash= proc_priv_hash;
3489
  old_func_priv_hash= func_priv_hash;
3490
  old_grant_option= grant_option;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3491
  old_mem= memex;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3492

3493
  if ((return_val= grant_load(tables)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3494
  {						// Error. Revert to old hash
3495
    DBUG_PRINT("error",("Reverting to old privileges"));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3496
    grant_free();				/* purecov: deadcode */
3497
    column_priv_hash= old_column_priv_hash;	/* purecov: deadcode */
3498
    proc_priv_hash= old_proc_priv_hash;
3499
    func_priv_hash= old_func_priv_hash;
3500
    grant_option= old_grant_option;		/* purecov: deadcode */
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3501
    memex= old_mem;				/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3502 3503 3504
  }
  else
  {
3505
    hash_free(&old_column_priv_hash);
3506
    hash_free(&old_proc_priv_hash);
3507
    hash_free(&old_func_priv_hash);
3508
    free_root(&old_mem,MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3509
  }
3510
  rw_unlock(&LOCK_grant);
3511 3512 3513
end:
  close_thread_tables(thd);
  DBUG_RETURN(return_val);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3514 3515 3516 3517
}


/****************************************************************************
3518
  Check table level grants
3519

3520
  SYNOPSIS
3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533
   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
3534
     1  Error: User did not have the requested privileges
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3535 3536
****************************************************************************/

3537
bool check_grant(THD *thd, ulong want_access, TABLE_LIST *tables,
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3538
		 uint show_table, uint number, bool no_errors)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3539
{
3540
  TABLE_LIST *table, *first_not_own_table= thd->lex->first_not_own_table();
3541
  Security_context *sctx= thd->security_ctx;
3542
  uint i;
3543 3544
  DBUG_ENTER("check_grant");
  DBUG_ASSERT(number > 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3545

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

3564
  want_access&= ~sctx->master_access;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3565
  if (!want_access)
3566
    DBUG_RETURN(0);                             // ok
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3567

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

    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
    }
  }
3617
  rw_unlock(&LOCK_grant);
3618
  DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3619

3620
err:
3621
  rw_unlock(&LOCK_grant);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
3622
  if (!no_errors)				// Not a silent skip of table
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3623
  {
3624 3625
    char command[128];
    get_privilege_desc(command, sizeof(command), want_access);
3626 3627
    my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0),
             command,
3628 3629
             sctx->priv_user,
             sctx->host_or_ip,
3630
             table ? table->table_name : "unknown");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3631
  }
3632
  DBUG_RETURN(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3633 3634 3635
}


3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653
/*
  Check column rights in given security context

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

  RETURN
    FALSE OK
    TRUE  access denied
*/

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3654
bool check_grant_column(THD *thd, GRANT_INFO *grant,
3655
			const char *db_name, const char *table_name,
3656
			const char *name, uint length,  Security_context *sctx)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3657 3658 3659
{
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3660
  ulong want_access= grant->want_privilege & ~grant->privilege;
monty@mysql.com's avatar
monty@mysql.com committed
3661 3662 3663
  DBUG_ENTER("check_grant_column");
  DBUG_PRINT("enter", ("table: %s  want_access: %u", table_name, want_access));

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3664
  if (!want_access)
monty@mysql.com's avatar
monty@mysql.com committed
3665
    DBUG_RETURN(0);				// Already checked
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3666

3667
  rw_rdlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3668

3669
  /* reload table if someone has modified any grants */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3670

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3671
  if (grant->version != grant_version)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3672
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3673
    grant->grant_table=
3674 3675
      table_hash_search(sctx->host, sctx->ip, db_name,
			sctx->priv_user,
monty@mysql.com's avatar
monty@mysql.com committed
3676
			table_name, 0);         /* purecov: inspected */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3677
    grant->version= grant_version;		/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3678
  }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3679
  if (!(grant_table= grant->grant_table))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3680 3681 3682 3683 3684
    goto err;					/* purecov: deadcode */

  grant_column=column_hash_search(grant_table, name, length);
  if (grant_column && !(~grant_column->rights & want_access))
  {
3685
    rw_unlock(&LOCK_grant);
monty@mysql.com's avatar
monty@mysql.com committed
3686
    DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3687 3688
  }

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


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

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

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

  RETURN
    FALSE OK
    TRUE  access denied
*/

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

  if (table_ref->view || table_ref->field_translation)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3735
  {
3736 3737 3738 3739
    /* View or derived information schema table. */
    grant= &(table_ref->grant);
    db_name= table_ref->view_db.str;
    table_name= table_ref->view_name.str;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3740
  }
3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755
  else
  {
    /* Normal or temporary table. */
    TABLE *table= table_ref->table;
    grant= &(table->grant);
    db_name= table->s->db;
    table_name= table->s->table_name;
  }

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3756 3757 3758
}


bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3759
bool check_grant_all_columns(THD *thd, ulong want_access, GRANT_INFO *grant,
3760
                             const char* db_name, const char *table_name,
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3761
                             Field_iterator *fields)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3762
{
3763
  Security_context *sctx= thd->security_ctx;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3764 3765 3766
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3767
  want_access &= ~grant->privilege;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3768
  if (!want_access)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3769
    return 0;				// Already checked
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3770 3771
  if (!grant_option)
    goto err2;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3772

3773
  rw_rdlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3774

3775
  /* reload table if someone has modified any grants */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3776

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3777
  if (grant->version != grant_version)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3778
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3779
    grant->grant_table=
3780 3781
      table_hash_search(sctx->host, sctx->ip, db_name,
			sctx->priv_user,
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3782 3783
			table_name, 0);	/* purecov: inspected */
    grant->version= grant_version;		/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3784
  }
3785
  /* The following should always be true */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3786
  if (!(grant_table= grant->grant_table))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3787 3788
    goto err;					/* purecov: inspected */

3789
  for (; !fields->end_of_fields(); fields->next())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3790
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3791 3792 3793
    const char *field_name= fields->name();
    grant_column= column_hash_search(grant_table, field_name,
				    (uint) strlen(field_name));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3794 3795 3796
    if (!grant_column || (~grant_column->rights & want_access))
      goto err;
  }
3797
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3798 3799
  return 0;

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3800
err:
3801
  rw_unlock(&LOCK_grant);
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3802
err2:
3803 3804
  char command[128];
  get_privilege_desc(command, sizeof(command), want_access);
3805 3806
  my_error(ER_COLUMNACCESS_DENIED_ERROR, MYF(0),
           command,
3807 3808
           sctx->priv_user,
           sctx->host_or_ip,
3809 3810
           fields->name(),
           table_name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3811 3812 3813 3814
  return 1;
}


3815
/*
3816
  Check if a user has the right to access a database
3817
  Access is accepted if he has a grant for any table/routine in the database
3818
  Return 1 if access is denied
3819
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3820 3821 3822

bool check_grant_db(THD *thd,const char *db)
{
3823
  Security_context *sctx= thd->security_ctx;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3824 3825
  char helping [NAME_LEN+USERNAME_LENGTH+2];
  uint len;
3826
  bool error= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3827

3828
  len= (uint) (strmov(strmov(helping, sctx->priv_user) + 1, db) - helping) + 1;
3829
  rw_rdlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3830

3831
  for (uint idx=0 ; idx < column_priv_hash.records ; idx++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3832
  {
3833 3834
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  idx);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3835 3836
    if (len < grant_table->key_length &&
	!memcmp(grant_table->hash_key,helping,len) &&
3837
        compare_hostname(&grant_table->host, sctx->host, sctx->ip))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3838 3839 3840 3841 3842
    {
      error=0;					// Found match
      break;
    }
  }
3843
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3844 3845 3846
  return error;
}

3847 3848

/****************************************************************************
3849
  Check routine level grants
3850 3851

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

3865
bool check_grant_routine(THD *thd, ulong want_access,
3866
			 TABLE_LIST *procs, bool is_proc, bool no_errors)
3867 3868
{
  TABLE_LIST *table;
3869
  Security_context *sctx= thd->security_ctx;
3870 3871
  char *user= sctx->priv_user;
  char *host= sctx->priv_host;
3872
  DBUG_ENTER("check_grant_routine");
3873

3874
  want_access&= ~sctx->master_access;
3875 3876 3877 3878 3879 3880 3881
  if (!want_access)
    DBUG_RETURN(0);                             // ok

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


3915 3916
/*
  Check if routine has any of the 
3917
  routine level grants
3918 3919 3920 3921 3922 3923 3924 3925 3926
  
  SYNPOSIS
   bool    check_routine_level_acl()
   thd	        Thread handler
   db           Database name
   name         Routine name

  RETURN
   0            Ok 
3927
   1            error
3928 3929
*/

acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
3930 3931
bool check_routine_level_acl(THD *thd, const char *db, const char *name, 
                             bool is_proc)
3932 3933 3934 3935 3936
{
  bool no_routine_acl= 1;
  if (grant_option)
  {
    GRANT_NAME *grant_proc;
3937
    Security_context *sctx= thd->security_ctx;
3938
    rw_rdlock(&LOCK_grant);
3939 3940 3941
    if ((grant_proc= routine_hash_search(sctx->priv_host,
                                         sctx->ip, db,
                                         sctx->priv_user,
3942
                                         name, is_proc, 0)))
3943 3944 3945 3946 3947 3948 3949
      no_routine_acl= !(grant_proc->privs & SHOW_PROC_ACLS);
    rw_unlock(&LOCK_grant);
  }
  return no_routine_acl;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
3950
/*****************************************************************************
3951
  Functions to retrieve the grant for a table/column  (for SHOW functions)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3952 3953
*****************************************************************************/

3954
ulong get_table_grant(THD *thd, TABLE_LIST *table)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3955
{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3956
  ulong privilege;
3957
  Security_context *sctx= thd->security_ctx;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3958 3959 3960
  const char *db = table->db ? table->db : thd->db;
  GRANT_TABLE *grant_table;

3961
  rw_rdlock(&LOCK_grant);
3962 3963 3964
#ifdef EMBEDDED_LIBRARY
  grant_table= NULL;
#else
3965
  grant_table= table_hash_search(sctx->host, sctx->ip, db, sctx->priv_user,
3966
				 table->table_name, 0);
3967
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3968 3969 3970 3971
  table->grant.grant_table=grant_table; // Remember for column test
  table->grant.version=grant_version;
  if (grant_table)
    table->grant.privilege|= grant_table->privs;
3972
  privilege= table->grant.privilege;
3973
  rw_unlock(&LOCK_grant);
3974
  return privilege;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3975 3976 3977
}


3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995
/*
  Determine the access priviliges for a field.

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

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

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

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3996 3997 3998
ulong get_column_grant(THD *thd, GRANT_INFO *grant,
                       const char *db_name, const char *table_name,
                       const char *field_name)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3999 4000 4001
{
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;
4002
  ulong priv;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4003

4004
  rw_rdlock(&LOCK_grant);
4005
  /* reload table if someone has modified any grants */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4006
  if (grant->version != grant_version)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4007
  {
4008
    Security_context *sctx= thd->security_ctx;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4009
    grant->grant_table=
4010 4011
      table_hash_search(sctx->host, sctx->ip,
                        db_name, sctx->priv_user,
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4012 4013
			table_name, 0);	        /* purecov: inspected */
    grant->version= grant_version;              /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4014 4015
  }

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4016 4017
  if (!(grant_table= grant->grant_table))
    priv= grant->privilege;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4018 4019
  else
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4020 4021
    grant_column= column_hash_search(grant_table, field_name,
                                     (uint) strlen(field_name));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4022
    if (!grant_column)
4023
      priv= (grant->privilege | grant_table->privs);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4024
    else
4025
      priv= (grant->privilege | grant_table->privs | grant_column->rights);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4026
  }
4027
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4028 4029 4030
  return priv;
}

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4031

4032
/* Help function for mysql_show_grants */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4033

4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045
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);
  }
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4046 4047

static const char *command_array[]=
4048
{
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4049 4050 4051 4052
  "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",
4053
  "CREATE VIEW", "SHOW VIEW", "CREATE ROUTINE", "ALTER ROUTINE",
4054
  "CREATE USER"
4055
};
4056

4057 4058
static uint command_lengths[]=
{
4059 4060
  6, 6, 6, 6, 6, 4, 6, 8, 7, 4, 5, 10, 5, 5, 14, 5, 23, 11, 7, 17, 18, 11, 9,
  14, 13, 11
4061 4062
};

bk@work.mysql.com's avatar
bk@work.mysql.com committed
4063

4064 4065 4066 4067 4068
static int show_routine_grants(THD *thd, LEX_USER *lex_user, HASH *hash,
                               const char *type, int typelen,
                               char *buff, int buffsize);


4069 4070 4071 4072 4073 4074 4075
/*
  SHOW GRANTS;  Send grants for a user to the client

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

4076
bool mysql_show_grants(THD *thd,LEX_USER *lex_user)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4077
{
4078 4079
  ulong want_access;
  uint counter,index;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4080
  int  error = 0;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4081 4082
  ACL_USER *acl_user;
  ACL_DB *acl_db;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4083
  char buff[1024];
4084
  Protocol *protocol= thd->protocol;
tonu@x153.internalnet's avatar
tonu@x153.internalnet committed
4085
  DBUG_ENTER("mysql_show_grants");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4086 4087 4088 4089

  LINT_INIT(acl_user);
  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
4090
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
4091
    DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4092
  }
monty@mysql.com's avatar
monty@mysql.com committed
4093 4094 4095 4096 4097 4098

  if (!lex_user->host.str)
  {
    lex_user->host.str= (char*) "%";
    lex_user->host.length=1;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4099 4100 4101
  if (lex_user->host.length > HOSTNAME_LENGTH ||
      lex_user->user.length > USERNAME_LENGTH)
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4102 4103
    my_message(ER_GRANT_WRONG_HOST_OR_USER, ER(ER_GRANT_WRONG_HOST_OR_USER),
               MYF(0));
4104
    DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4105 4106 4107 4108 4109 4110 4111
  }

  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))
monty@mysql.com's avatar
monty@mysql.com committed
4112
      user= "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4113
    if (!(host=acl_user->host.hostname))
monty@mysql.com's avatar
monty@mysql.com committed
4114
      host= "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4115
    if (!strcmp(lex_user->user.str,user) &&
4116
	!my_strcasecmp(system_charset_info, lex_user->host.str, host))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4117 4118
      break;
  }
peter@mysql.com's avatar
peter@mysql.com committed
4119
  if (counter == acl_users.elements)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4120
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
4121 4122
    my_error(ER_NONEXISTING_GRANT, MYF(0),
             lex_user->user.str, lex_user->host.str);
4123
    DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4124 4125
  }

4126
  Item_string *field=new Item_string("",0,&my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4127 4128 4129 4130 4131 4132
  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);
4133 4134
  if (protocol->send_fields(&field_list,
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
4135
    DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4136

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4137
  rw_wrlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4138 4139 4140 4141
  VOID(pthread_mutex_lock(&acl_cache->lock));

  /* Add first global access grants */
  {
4142
    String global(buff,sizeof(buff),system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4143
    global.length(0);
4144
    global.append(STRING_WITH_LEN("GRANT "));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4145

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

  /* Add database access */
  for (counter=0 ; counter < acl_dbs.elements ; counter++)
  {
monty@mysql.com's avatar
monty@mysql.com committed
4249
    const char *user, *host;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4250 4251 4252

    acl_db=dynamic_element(&acl_dbs,counter,ACL_DB*);
    if (!(user=acl_db->user))
monty@mysql.com's avatar
monty@mysql.com committed
4253
      user= "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4254
    if (!(host=acl_db->host.hostname))
monty@mysql.com's avatar
monty@mysql.com committed
4255
      host= "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4256 4257

    if (!strcmp(lex_user->user.str,user) &&
4258
	!my_strcasecmp(system_charset_info, lex_user->host.str, host))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4259 4260
    {
      want_access=acl_db->access;
peter@mysql.com's avatar
peter@mysql.com committed
4261
      if (want_access)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4262
      {
4263
	String db(buff,sizeof(buff),system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4264
	db.length(0);
4265
	db.append(STRING_WITH_LEN("GRANT "));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4266 4267

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

4308
  /* Add table & column access */
4309
  for (index=0 ; index < column_priv_hash.records ; index++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4310
  {
monty@mysql.com's avatar
monty@mysql.com committed
4311
    const char *user;
4312 4313
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  index);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4314 4315

    if (!(user=grant_table->user))
4316
      user= "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4317 4318

    if (!strcmp(lex_user->user.str,user) &&
4319
	!my_strcasecmp(system_charset_info, lex_user->host.str,
4320
                       grant_table->host.hostname))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4321
    {
4322 4323
      ulong table_access= grant_table->privs;
      if ((table_access | grant_table->cols) != 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4324
      {
4325
	String global(buff, sizeof(buff), system_charset_info);
4326 4327
	ulong test_access= (table_access | grant_table->cols) & ~GRANT_ACL;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
4328
	global.length(0);
4329
	global.append(STRING_WITH_LEN("GRANT "));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4330

4331
	if (test_all_bits(table_access, (TABLE_ACLS & ~GRANT_ACL)))
4332
	  global.append(STRING_WITH_LEN("ALL PRIVILEGES"));
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4333
	else if (!test_access)
4334
	  global.append(STRING_WITH_LEN("USAGE"));
peter@mysql.com's avatar
peter@mysql.com committed
4335
	else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4336
	{
4337
          /* Add specific column access */
4338
	  int found= 0;
4339
	  ulong j;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4340

4341
	  for (counter= 0, j= SELECT_ACL; j <= TABLE_ACLS; counter++, j<<= 1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4342
	  {
peter@mysql.com's avatar
peter@mysql.com committed
4343
	    if (test_access & j)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4344 4345
	    {
	      if (found)
4346
		global.append(STRING_WITH_LEN(", "));
4347
	      found= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4348 4349
	      global.append(command_array[counter],command_lengths[counter]);

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

4415
  if (show_routine_grants(thd, lex_user, &proc_priv_hash, 
4416
                          STRING_WITH_LEN("PROCEDURE"), buff, sizeof(buff)))
4417 4418 4419 4420 4421 4422
  {
    error= -1;
    goto end;
  }

  if (show_routine_grants(thd, lex_user, &func_priv_hash,
4423
                          STRING_WITH_LEN("FUNCTION"), buff, sizeof(buff)))
4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445
  {
    error= -1;
    goto end;
  }

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

  send_eof(thd);
  DBUG_RETURN(error);
}

static int show_routine_grants(THD* thd, LEX_USER *lex_user, HASH *hash,
                               const char *type, int typelen,
                               char *buff, int buffsize)
{
  uint counter, index;
  int error= 0;
  Protocol *protocol= thd->protocol;
  /* Add routine access */
  for (index=0 ; index < hash->records ; index++)
4446 4447
  {
    const char *user;
4448
    GRANT_NAME *grant_proc= (GRANT_NAME*) hash_element(hash, index);
4449 4450 4451 4452 4453 4454

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

    if (!strcmp(lex_user->user.str,user) &&
	!my_strcasecmp(system_charset_info, lex_user->host.str,
4455
                       grant_proc->host.hostname))
4456 4457 4458 4459
    {
      ulong proc_access= grant_proc->privs;
      if (proc_access != 0)
      {
4460
	String global(buff, buffsize, system_charset_info);
4461 4462 4463
	ulong test_access= proc_access & ~GRANT_ACL;

	global.length(0);
4464
	global.append(STRING_WITH_LEN("GRANT "));
4465 4466

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

4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542
/*
  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;
}


4543
void get_mqh(const char *user, const char *host, USER_CONN *uc)
4544 4545
{
  ACL_USER *acl_user;
4546
  if (initialized && (acl_user= find_acl_user(host,user, FALSE)))
4547 4548 4549
    uc->user_resources= acl_user->user_resource;
  else
    bzero((char*) &uc->user_resources, sizeof(uc->user_resources));
4550 4551
}

4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572
/*
  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.
*/

4573
#define GRANT_TABLES 5
4574 4575 4576 4577 4578 4579
int open_grant_tables(THD *thd, TABLE_LIST *tables)
{
  DBUG_ENTER("open_grant_tables");

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

4584
  bzero((char*) tables, GRANT_TABLES*sizeof(*tables));
4585 4586 4587 4588 4589
  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";
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4590 4591 4592
  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;
4593
  (tables+3)->next_local= (tables+3)->next_global= tables+4;
4594
  tables->lock_type= (tables+1)->lock_type=
4595 4596 4597 4598
    (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";
4599 4600 4601 4602 4603 4604

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

4620
  if (simple_open_n_lock_tables(thd, tables))
4621 4622 4623 4624 4625 4626 4627 4628 4629
  {						// This should never happen
    close_thread_tables(thd);
    DBUG_RETURN(-1);
  }

  DBUG_RETURN(0);
}

ACL_USER *check_acl_user(LEX_USER *user_name,
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
4630
			 uint *acl_acl_userdx)
4631 4632 4633 4634 4635 4636 4637 4638 4639
{
  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))
monty@mysql.com's avatar
monty@mysql.com committed
4640
      user= "";
4641
    if (!(host=acl_user->host.hostname))
4642
      host= "";
4643 4644 4645 4646 4647 4648 4649
    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;

monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
4650
  *acl_acl_userdx= counter;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4651
  return acl_user;
4652 4653
}

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4654

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

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

4699 4700
  DBUG_RETURN(error);
}
4701 4702


4703 4704 4705 4706 4707 4708
/*
  Handle a privilege table.

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

  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;
4747
  byte user_key[MAX_KEY_LENGTH];
4748
  uint key_prefix_length;
4749 4750
  DBUG_ENTER("handle_grant_table");

4751
  if (! table_no) // mysql.user table
4752
  {
4753 4754 4755 4756 4757 4758 4759 4760 4761 4762
    /*
      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'",
4763
                       table->s->table_name, user_str, host_str));
4764 4765
    host_field->store(host_str, user_from->host.length, system_charset_info);
    user_field->store(user_str, user_from->user.length, system_charset_info);
4766 4767 4768 4769 4770

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

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

  RETURN
    > 0         At least one element matched.
    0           OK, but no element matched.
4876
    -1		Wrong arguments to function
4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888
*/

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;
4889
  GRANT_NAME *grant_name;
4890
  DBUG_ENTER("handle_grant_struct");
monty@mishka.local's avatar
monty@mishka.local committed
4891 4892 4893
  DBUG_PRINT("info",("scan struct: %u  search: '%s'@'%s'",
                     struct_no, user_from->user.str, user_from->host.str));

4894 4895
  LINT_INIT(acl_user);
  LINT_INIT(acl_db);
4896
  LINT_INIT(grant_name);
4897 4898

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

#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.
    */
4927
    switch (struct_no) {
4928 4929 4930 4931 4932 4933 4934 4935 4936 4937
    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;
4938 4939
      if (!(host= acl_db->host.hostname))
        host= "%";
4940 4941
      break;

4942 4943 4944
    case 2:
      grant_name= (GRANT_NAME*) hash_element(&column_priv_hash, idx);
      user= grant_name->user;
4945 4946
      if (!(host= grant_name->host.hostname))
        host= "%";
4947 4948 4949 4950 4951
      break;

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

    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;

4981 4982 4983 4984 4985 4986 4987
      case 2:
        hash_delete(&column_priv_hash, (byte*) grant_name);
	break;

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

5000 5001 5002 5003 5004
      case 1:
        acl_db->user= strdup_root(&mem, user_to->user.str);
        acl_db->host.hostname= strdup_root(&mem, user_to->host.str);
        break;

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

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

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

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

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

5149

5150 5151 5152 5153 5154 5155
static void append_user(String *str, LEX_USER *user)
{
  if (str->length())
    str->append(',');
  str->append('\'');
  str->append(user->user.str);
5156
  str->append(STRING_WITH_LEN("'@'"));
5157 5158 5159
  str->append(user->host.str);
  str->append('\'');
}
5160

5161

5162 5163 5164 5165 5166 5167 5168
/*
  Create a list of users.

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

5170 5171 5172 5173 5174 5175 5176 5177
  RETURN
    FALSE       OK.
    TRUE        Error.
*/

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

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

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

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

5260 5261 5262
  /* Rebuild 'acl_check_hosts' since 'acl_users' has been modified */
  rebuild_check_host();

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

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

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

5319 5320 5321
  /* Rebuild 'acl_check_hosts' since 'acl_users' has been modified */
  rebuild_check_host();

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

5330

5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344
/*
  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.
*/

5345
bool mysql_revoke_all(THD *thd,  List <LEX_USER> &list)
5346
{
5347
  uint counter, revoked, is_proc;
5348
  int result;
5349
  ACL_DB *acl_db;
5350
  TABLE_LIST tables[GRANT_TABLES];
5351 5352 5353
  DBUG_ENTER("mysql_revoke_all");

  if ((result= open_grant_tables(thd, tables)))
5354
    DBUG_RETURN(result != 1);
5355 5356 5357 5358 5359 5360 5361 5362

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

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

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

dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5390 5391 5392 5393 5394
	acl_db=dynamic_element(&acl_dbs,counter,ACL_DB*);
	if (!(user=acl_db->user))
	  user= "";
	if (!(host=acl_db->host.hostname))
	  host= "";
5395

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

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

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

    /* Remove procedure access */
5462 5463 5464
    for (is_proc=0; is_proc<2; is_proc++) do {
      HASH *hash= is_proc ? &proc_priv_hash : &func_priv_hash;
      for (counter= 0, revoked= 0 ; counter < hash->records ; )
5465 5466
      {
	const char *user,*host;
5467
	GRANT_NAME *grant_proc= (GRANT_NAME*) hash_element(hash, counter);
5468 5469
	if (!(user=grant_proc->user))
	  user= "";
5470
	if (!(host=grant_proc->host.hostname))
5471 5472 5473 5474 5475
	  host= "";

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

5492 5493 5494
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
5495

5496
  if (result)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5497
    my_message(ER_REVOKE_GRANTS, ER(ER_REVOKE_GRANTS), MYF(0));
5498

5499 5500
  DBUG_RETURN(result);
}
5501

5502

5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516
/*
  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.
*/

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

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

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

5597
  combo->user.str= sctx->user;
5598
  
5599 5600 5601
  if (!find_acl_user(combo->host.str=(char*)sctx->host_or_ip, combo->user.str,
                     FALSE) &&
      !find_acl_user(combo->host.str=(char*)sctx->host, combo->user.str,
monty@mishka.local's avatar
monty@mishka.local committed
5602
                     FALSE) &&
5603
      !find_acl_user(combo->host.str=(char*)sctx->ip, combo->user.str,
monty@mishka.local's avatar
monty@mishka.local committed
5604 5605
                     FALSE) &&
      !find_acl_user(combo->host.str=(char*)"%", combo->user.str, FALSE))
5606 5607 5608 5609 5610 5611
    DBUG_RETURN(TRUE);

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

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

5627
  result= mysql_routine_grant(thd, tables, is_proc, user_list,
5628 5629 5630 5631 5632
  				DEFAULT_CREATE_PROC_ACLS, 0, 1);
  DBUG_RETURN(result);
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
5633
/*****************************************************************************
5634
  Instantiate used templates
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5635 5636
*****************************************************************************/

5637
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5638 5639 5640 5641 5642
template class List_iterator<LEX_COLUMN>;
template class List_iterator<LEX_USER>;
template class List<LEX_COLUMN>;
template class List<LEX_USER>;
#endif
hf@deer.(none)'s avatar
hf@deer.(none) committed
5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689

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

5690 5691 5692 5693 5694 5695 5696 5697

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

5724 5725 5726 5727 5728 5729 5730 5731
  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= "";
5732 5733

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

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


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

5788
    if (no_global_access &&
5789
        (strcmp(thd->security_ctx->priv_user, user) ||
5790 5791 5792
         my_strcasecmp(system_charset_info, curr_host, host)))
      continue;

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


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

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

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

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


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

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

5909 5910 5911
    ulong table_access= grant_table->cols;
    if (table_access != 0)
    {
5912
      if (!(grant_table->privs & GRANT_ACL))
5913 5914
        is_grantable= "NO";

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


bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
5953 5954 5955 5956 5957
#ifndef NO_EMBEDDED_ACCESS_CHECKS
/*
  fill effective privileges for table

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

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
5983
  /* global privileges */
5984
  grant->privilege= sctx->master_access;
5985

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

5992
  /* db privileges */
5993
  grant->privilege|= acl_get(sctx->host, sctx->ip, sctx->priv_user, db, 0);
5994

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

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

#else /* NO_EMBEDDED_ACCESS_CHECKS */

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

acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
6026 6027
bool check_routine_level_acl(THD *thd, const char *db, const char *name,
                             bool is_proc)
6028 6029 6030 6031
{
  return FALSE;
}

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
6032
#endif