sql_acl.cc 177 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
   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
5
   the Free Software Foundation; version 2 of the License.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
6

bk@work.mysql.com's avatar
bk@work.mysql.com committed
7 8 9 10
   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
11

bk@work.mysql.com's avatar
bk@work.mysql.com committed
12 13 14 15 16 17 18
   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:
19 20
  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
21 22 23 24 25 26 27 28
  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"
29 30 31
#ifdef HAVE_REPLICATION
#include "sql_repl.h" //for tables_ok()
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
32 33
#include <m_ctype.h>
#include <stdarg.h>
34 35
#include "sp_head.h"
#include "sp.h"
bk@work.mysql.com's avatar
bk@work.mysql.com committed
36

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

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

47

bk@work.mysql.com's avatar
bk@work.mysql.com committed
48 49 50 51 52 53 54
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
55
#define IP_ADDR_STRLEN (3+1+3+1+3+1+3)
gluh@mysql.com/gluh.(none)'s avatar
gluh@mysql.com/gluh.(none) committed
56
#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
57 58 59 60 61

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

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

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

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

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

123

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

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

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

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

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

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

158 159 160
  /*
    To be able to run this from boot, we allocate a temporary THD
  */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
161 162
  if (!(thd=new THD))
    DBUG_RETURN(1); /* purecov: inspected */
163
  thd->thread_stack= (char*) &thd;
164
  thd->store_globals();
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;
gluh@mysql.com/gluh.(none)'s avatar
gluh@mysql.com/gluh.(none) committed
199
  char tmp_name[NAME_LEN+1];
200
  int password_length;
201 202
  DBUG_ENTER("acl_load");

203
  grant_version++; /* Privileges updated */
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.host.hostname : "",
                          host.db ? host.db : "");
230
    }
231 232
    host.access= get_access(table,2);
    host.access= fix_rights_for_db(host.access);
233
    host.sort=	 get_sort(2,host.host.hostname,host.db);
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
234 235
    if (check_no_resolve && hostname_requires_resolving(host.host.hostname))
    {
serg@serg.mylan's avatar
serg@serg.mylan committed
236
      sql_print_warning("'host' entry '%s|%s' "
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
237
		      "ignored in --skip-name-resolve mode.",
238 239
			host.host.hostname ? host.host.hostname : "",
			host.db ? host.db : "");
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
240 241
      continue;
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
242
#ifndef TO_BE_REMOVED
243
    if (table->s->fields == 8)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
244 245
    {						// Without grant
      if (host.access & CREATE_ACL)
246
	host.access|=REFERENCES_ACL | INDEX_ACL | ALTER_ACL | CREATE_TMP_ACL;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
247 248 249 250 251 252 253 254 255 256
    }
#endif
    VOID(push_dynamic(&acl_hosts,(gptr) &host));
  }
  qsort((gptr) dynamic_element(&acl_hosts,0,ACL_HOST*),acl_hosts.elements,
	sizeof(ACL_HOST),(qsort_cmp) acl_compare);
  end_read_record(&read_record_info);
  freeze_size(&acl_hosts);

  init_read_record(&read_record_info,thd,table=tables[1].table,NULL,1,0);
257
  VOID(my_init_dynamic_array(&acl_users,sizeof(ACL_USER),50,100));
258 259 260
  password_length= table->field[2]->field_length /
    table->field[2]->charset()->mbmaxlen;
  if (password_length < SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
261
  {
262 263 264
    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
265 266
  }

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

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

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

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

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

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

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

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

377 378 379
        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++]);
380

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

391
        if (table->s->fields >= 36)
392 393 394 395 396 397 398
        {
          /* 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;
399
      }
400 401 402
      else
      {
        user.ssl_type=SSL_TYPE_NONE;
403
        bzero((char *)&(user.user_resource),sizeof(user.user_resource));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
404
#ifndef TO_BE_REMOVED
405
        if (table->s->fields <= 13)
406 407 408 409 410 411 412 413 414 415
        {						// 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
416
#endif
417 418
      }
      VOID(push_dynamic(&acl_users,(gptr) &user));
419 420
      if (!user.host.hostname ||
	  (user.host.hostname[0] == wild_many && !user.host.hostname[1]))
421
        allow_all_hosts=1;			// Anyone can connect
422
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
423 424 425 426 427
  }
  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
428

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

488 489 490 491 492
  initialized=1;
  return_val=0;

end:
  DBUG_RETURN(return_val);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
493 494 495 496 497
}


void acl_free(bool end)
{
498
  free_root(&mem,MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
499 500 501 502 503 504 505 506 507 508 509 510 511 512
  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;
  }
}

513 514

/*
515 516
  Forget current user/db-level privileges and read new privileges
  from the privilege tables.
517 518 519

  SYNOPSIS
    acl_reload()
520 521 522 523 524 525 526 527 528 529 530
      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
531
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
532

533
my_bool acl_reload(THD *thd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
534
{
535
  TABLE_LIST tables[3];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
536 537 538
  DYNAMIC_ARRAY old_acl_hosts,old_acl_users,old_acl_dbs;
  MEM_ROOT old_mem;
  bool old_initialized;
539
  my_bool return_val= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
540 541
  DBUG_ENTER("acl_reload");

542
  if (thd->locked_tables)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
543
  {					// Can't have locked tables here
544 545 546
    thd->lock=thd->locked_tables;
    thd->locked_tables=0;
    close_thread_tables(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
547
  }
548 549 550 551 552 553

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

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


604 605
/*
  Get all access bits from table after fieldnr
606 607

  IMPLEMENTATION
608 609
  We know that the access privileges ends when there is no more fields
  or the field is not an enum with two elements.
610 611 612 613 614 615 616 617 618 619 620

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

623
static ulong get_access(TABLE *form, uint fieldnr, uint *next_field)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
624
{
625
  ulong access_bits=0,bit;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
626
  char buff[2];
627
  String res(buff,sizeof(buff),&my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
628 629
  Field **pos;

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


/*
646 647 648 649 650
  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
651 652 653 654 655 656 657

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

658 659 660
  /* 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
661 662
  while (count--)
  {
663 664 665
    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
666

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

695

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

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
700 701 702 703
  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
704

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

728 729
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
730
{
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
731 732 733
  ulong user_access= NO_ACCESS;
  int res= 1;
  ACL_USER *acl_user= 0;
734
  Security_context *sctx= thd->security_ctx;
735
  DBUG_ENTER("acl_getroot");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
736 737

  if (!initialized)
738
  {
739 740 741
    /* 
      here if mysqld's been started with --skip-grant-tables option.
    */
742
    sctx->skip_grants();
743
    bzero((char*) mqh, sizeof(*mqh));
744
    DBUG_RETURN(0);
745
  }
746

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
749
  /*
750 751 752
    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
753
  */
peter@mysql.com's avatar
peter@mysql.com committed
754

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

  if (acl_user)
  {
793
    /* OK. User found and password checked continue validation */
794
#ifdef HAVE_OPENSSL
795
    Vio *vio=thd->net.vio;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
796
    SSL *ssl= (SSL*) vio->ssl_arg;
797
#endif
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
798

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

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

914
    if (acl_user->host.hostname)
915
      strmake(sctx->priv_host, acl_user->host.hostname, MAX_HOSTNAME);
916
    else
917
      *sctx->priv_host= 0;
918
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
919
  VOID(pthread_mutex_unlock(&acl_cache->lock));
920
  DBUG_RETURN(res);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
921 922 923
}


924
/*
925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
  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)
943 944
{
  int res= 1;
945
  uint i;
946 947 948
  ACL_USER *acl_user= 0;
  DBUG_ENTER("acl_getroot_no_password");

949 950
  DBUG_PRINT("enter", ("Host: '%s', Ip: '%s', User: '%s', db: '%s'",
                       (host ? host : "(NULL)"), (ip ? ip : "(NULL)"),
951
                       user, (db ? db : "(NULL)")));
952 953 954 955 956
  sctx->user= user;
  sctx->host= host;
  sctx->ip= ip;
  sctx->host_or_ip= host ? host : (ip ? ip : "");

957 958
  if (!initialized)
  {
959
    /*
960 961
      here if mysqld's been started with --skip-grant-tables option.
    */
962
    sctx->skip_grants();
963
    DBUG_RETURN(FALSE);
964 965 966 967
  }

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

968 969
  sctx->master_access= 0;
  sctx->db_access= 0;
970 971
  sctx->priv_user= (char *) "";
  *sctx->priv_host= 0;
972

973 974 975
  /*
     Find acl entry in user database.
     This is specially tailored to suit the check we do for CALL of
976
     a stored procedure; user is set to what is actually a
977 978
     priv_user, which can be ''.
  */
979
  for (i=0 ; i < acl_users.elements ; i++)
980 981
  {
    acl_user= dynamic_element(&acl_users,i,ACL_USER*);
982
    if ((!acl_user->user && !user[0]) ||
983
	(acl_user->user && strcmp(user, acl_user->user) == 0))
984
    {
985
      if (compare_hostname(&acl_user->host, host, ip))
986 987 988 989 990 991 992 993 994
      {
	res= 0;
	break;
      }
    }
  }

  if (acl_user)
  {
995 996 997 998
    for (i=0 ; i < acl_dbs.elements ; i++)
    {
      ACL_DB *acl_db= dynamic_element(&acl_dbs, i, ACL_DB*);
      if (!acl_db->user ||
999
	  (user && user[0] && !strcmp(user, acl_db->user)))
1000
      {
1001
	if (compare_hostname(&acl_db->host, host, ip))
1002
	{
1003
	  if (!acl_db->db || (db && !wild_compare(db, acl_db->db, 0)))
1004
	  {
1005
	    sctx->db_access= acl_db->access;
1006 1007 1008 1009 1010
	    break;
	  }
	}
      }
    }
1011 1012
    sctx->master_access= acl_user->access;
    sctx->priv_user= acl_user->user ? user : (char *) "";
1013 1014

    if (acl_user->host.hostname)
1015
      strmake(sctx->priv_host, acl_user->host.hostname, MAX_HOSTNAME);
1016
    else
1017
      *sctx->priv_host= 0;
1018 1019 1020 1021 1022
  }
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  DBUG_RETURN(res);
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1023 1024 1025 1026 1027 1028 1029
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;
}

1030

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1031
static void acl_update_user(const char *user, const char *host,
1032
			    const char *password, uint password_len,
1033 1034 1035 1036
			    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
1037
			    USER_RESOURCES  *mqh,
1038
			    ulong privileges)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1039
{
1040 1041
  safe_mutex_assert_owner(&acl_cache->lock);

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1042 1043 1044 1045
  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] ||
1046
	acl_user->user && !strcmp(user,acl_user->user))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1047 1048
    {
      if (!acl_user->host.hostname && !host[0] ||
1049
	  acl_user->host.hostname &&
1050
	  !my_strcasecmp(system_charset_info, host, acl_user->host.hostname))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1051 1052
      {
	acl_user->access=privileges;
1053
	if (mqh->specified_limits & USER_RESOURCES::QUERIES_PER_HOUR)
1054
	  acl_user->user_resource.questions=mqh->questions;
1055
	if (mqh->specified_limits & USER_RESOURCES::UPDATES_PER_HOUR)
1056
	  acl_user->user_resource.updates=mqh->updates;
1057 1058 1059 1060
	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;
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
	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);
	}
1071 1072
	if (password)
	  set_user_salt(acl_user, password, password_len);
1073
        /* search complete: */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1074 1075 1076 1077 1078 1079 1080 1081
	break;
      }
    }
  }
}


static void acl_insert_user(const char *user, const char *host,
1082
			    const char *password, uint password_len,
1083 1084 1085 1086
			    enum SSL_type ssl_type,
			    const char *ssl_cipher,
			    const char *x509_issuer,
			    const char *x509_subject,
1087
			    USER_RESOURCES *mqh,
1088
			    ulong privileges)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1089 1090
{
  ACL_USER acl_user;
1091 1092 1093

  safe_mutex_assert_owner(&acl_cache->lock);

1094
  acl_user.user=*user ? strdup_root(&mem,user) : 0;
monty@mysql.com's avatar
monty@mysql.com committed
1095
  update_hostname(&acl_user.host, *host ? strdup_root(&mem, host): 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1096
  acl_user.access=privileges;
1097
  acl_user.user_resource = *mqh;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1098
  acl_user.sort=get_sort(2,acl_user.host.hostname,acl_user.user);
1099
  acl_user.hostname_length=(uint) strlen(host);
1100 1101 1102 1103 1104
  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;
1105 1106

  set_user_salt(&acl_user, password, password_len);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1107 1108

  VOID(push_dynamic(&acl_users,(gptr) &acl_user));
1109 1110
  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
1111
    allow_all_hosts=1;		// Anyone can connect /* purecov: tested */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1112 1113 1114
  qsort((gptr) dynamic_element(&acl_users,0,ACL_USER*),acl_users.elements,
	sizeof(ACL_USER),(qsort_cmp) acl_compare);

1115 1116
  /* Rebuild 'acl_check_hosts' since 'acl_users' has been modified */
  rebuild_check_host();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1117 1118 1119 1120
}


static void acl_update_db(const char *user, const char *host, const char *db,
1121
			  ulong privileges)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1122
{
1123 1124
  safe_mutex_assert_owner(&acl_cache->lock);

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1125 1126 1127 1128 1129 1130 1131 1132
  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] ||
1133
	  acl_db->host.hostname &&
1134
	  !my_strcasecmp(system_charset_info, host, acl_db->host.hostname))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
      {
	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);
	}
      }
    }
  }
}


1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
/*
  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
1164
static void acl_insert_db(const char *user, const char *host, const char *db,
1165
			  ulong privileges)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1166 1167
{
  ACL_DB acl_db;
1168
  safe_mutex_assert_owner(&acl_cache->lock);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1169
  acl_db.user=strdup_root(&mem,user);
1170
  update_hostname(&acl_db.host, *host ? strdup_root(&mem,host) : 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1171 1172 1173 1174 1175 1176 1177 1178 1179
  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);
}


1180 1181 1182

/*
  Get privilege for a host, user and db combination
1183 1184 1185

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

1188
ulong acl_get(const char *host, const char *ip,
1189
              const char *user, const char *db, my_bool db_is_pattern)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1190
{
1191
  ulong host_access= ~(ulong)0, db_access= 0;
1192
  uint i,key_length;
1193
  char key[ACL_KEY_LENGTH],*tmp_db,*end;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1194
  acl_entry *entry;
monty@mysql.com's avatar
monty@mysql.com committed
1195
  DBUG_ENTER("acl_get");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1196 1197

  VOID(pthread_mutex_lock(&acl_cache->lock));
1198
  end=strmov((tmp_db=strmov(strmov(key, ip ? ip : "")+1,user)+1),db);
1199 1200
  if (lower_case_table_names)
  {
1201
    my_casedn_str(files_charset_info, tmp_db);
1202 1203
    db=tmp_db;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1204
  key_length=(uint) (end-key);
1205
  if (!db_is_pattern && (entry=(acl_entry*) acl_cache->search(key,key_length)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1206 1207 1208
  {
    db_access=entry->access;
    VOID(pthread_mutex_unlock(&acl_cache->lock));
monty@mysql.com's avatar
monty@mysql.com committed
1209 1210
    DBUG_PRINT("exit", ("access: 0x%lx", db_access));
    DBUG_RETURN(db_access);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
  }

  /*
    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))
      {
1223
	if (!acl_db->db || !wild_compare(db,acl_db->db,db_is_pattern))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
	{
	  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))
    {
1245
      if (!acl_host->db || !wild_compare(db,acl_host->db,db_is_pattern))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1246 1247 1248 1249 1250 1251 1252 1253
      {
	host_access=acl_host->access;		// Fully specified. Take it
	break;
      }
    }
  }
exit:
  /* Save entry in cache for quick retrieval */
1254 1255
  if (!db_is_pattern &&
      (entry= (acl_entry*) malloc(sizeof(acl_entry)+key_length)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1256 1257 1258 1259 1260 1261 1262
  {
    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
1263 1264
  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
1265 1266
}

1267 1268 1269 1270 1271 1272 1273
/*
  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
1274 1275 1276 1277

static void init_check_host(void)
{
  DBUG_ENTER("init_check_host");
1278
  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
1279
			  acl_users.elements,1));
1280
  VOID(hash_init(&acl_check_hosts,system_charset_info,acl_users.elements,0,0,
1281
		 (hash_get_key) check_get_key,0,0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
  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 *);
1296
	  if (!my_strcasecmp(system_charset_info,
1297
                             acl_user->host.hostname, acl->hostname))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1298 1299 1300 1301 1302
	    break;				// already stored
	}
	if (j == acl_wild_hosts.elements)	// If new
	  (void) push_dynamic(&acl_wild_hosts,(char*) &acl_user->host);
      }
1303
      else if (!hash_search(&acl_check_hosts,(byte*) acl_user->host.hostname,
1304
			    (uint) strlen(acl_user->host.hostname)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1305
      {
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1306
	if (my_hash_insert(&acl_check_hosts,(byte*) acl_user))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
	{					// 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;
}


1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
/*
  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
1336 1337 1338 1339 1340 1341 1342 1343
/* 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));

1344 1345
  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
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
  {
    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
}


1364 1365 1366 1367 1368 1369 1370 1371
/*
  Check if the user is allowed to change password

  SYNOPSIS:
    check_change_password()
    thd		THD
    host	hostname for the user
    user	user name
1372 1373 1374 1375
    new_password new password

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

1377
    RETURN VALUE
1378 1379
      0		OK
      1		ERROR  ; In this case the error is sent to the client.
1380 1381
*/

1382
bool check_change_password(THD *thd, const char *host, const char *user,
1383
                           char *new_password, uint new_password_len)
1384
{
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1385 1386
  if (!initialized)
  {
1387
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
1388
    return(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1389
  }
1390
  if (!thd->slave_thread &&
1391 1392 1393
      (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
1394
  {
1395
    if (check_access(thd, UPDATE_ACL, "mysql",0,1,0,0))
1396
      return(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1397
  }
1398
  if (!thd->slave_thread && !thd->security_ctx->user[0])
1399
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1400 1401
    my_message(ER_PASSWORD_ANONYMOUS_USER, ER(ER_PASSWORD_ANONYMOUS_USER),
               MYF(0));
1402
    return(1);
1403
  }
1404
  uint len=strlen(new_password);
1405
  if (len && len != SCRAMBLED_PASSWORD_CHAR_LENGTH &&
1406 1407
      len != SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
  {
1408
    my_error(ER_PASSWD_LENGTH, MYF(0), SCRAMBLED_PASSWORD_CHAR_LENGTH);
1409 1410
    return -1;
  }
1411 1412 1413 1414
  return(0);
}


1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
/*
  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
1428
*/
1429

1430 1431 1432
bool change_password(THD *thd, const char *host, const char *user,
		     char *new_password)
{
1433 1434 1435 1436 1437
  TABLE_LIST tables;
  TABLE *table;
  /* Buffer should be extended when password length is extended. */
  char buff[512];
  ulong query_length;
1438
  uint new_password_len= strlen(new_password);
1439
  bool result= 1;
1440 1441 1442 1443 1444
  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

1445
  if (check_change_password(thd, host, user, new_password, new_password_len))
1446 1447
    DBUG_RETURN(1);

1448
  bzero((char*) &tables, sizeof(tables));
1449
  tables.alias= tables.table_name= (char*) "user";
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
  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 */
1465
    if (!tables_ok(thd, &tables))
1466 1467 1468 1469 1470 1471 1472
      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
1473 1474
  VOID(pthread_mutex_lock(&acl_cache->lock));
  ACL_USER *acl_user;
1475
  if (!(acl_user= find_acl_user(host, user, TRUE)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1476 1477
  {
    VOID(pthread_mutex_unlock(&acl_cache->lock));
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1478
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH), MYF(0));
1479
    goto end;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1480
  }
1481 1482 1483
  /* update loaded acl entry: */
  set_user_salt(acl_user, new_password, new_password_len);

1484
  if (update_user_table(thd, table,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1485
			acl_user->host.hostname ? acl_user->host.hostname : "",
1486
			acl_user->user ? acl_user->user : "",
1487
			new_password, new_password_len))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1488 1489
  {
    VOID(pthread_mutex_unlock(&acl_cache->lock)); /* purecov: deadcode */
1490
    goto end;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1491
  }
peter@mysql.com's avatar
peter@mysql.com committed
1492

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1493 1494
  acl_cache->clear(1);				// Clear locked hostname cache
  VOID(pthread_mutex_unlock(&acl_cache->lock));
1495 1496 1497
  result= 0;
  if (mysql_bin_log.is_open())
  {
1498 1499
    query_length=
      my_sprintf(buff,
1500
                 (buff,"SET PASSWORD FOR '%-.120s'@'%-.120s'='%-.120s'",
1501 1502 1503
                  acl_user->user ? acl_user->user : "",
                  acl_user->host.hostname ? acl_user->host.hostname : "",
                  new_password));
1504 1505 1506 1507 1508 1509 1510
    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
1511 1512 1513
}


1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
/*
  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;
1530 1531 1532 1533 1534

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

1535
  VOID(pthread_mutex_lock(&acl_cache->lock));
1536
  res= find_acl_user(host, user, TRUE) != NULL;
1537 1538 1539 1540 1541
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  return res;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
1542 1543 1544 1545 1546
/*
  Find first entry that matches the current user
*/

static ACL_USER *
1547
find_acl_user(const char *host, const char *user, my_bool exact)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1548
{
1549
  DBUG_ENTER("find_acl_user");
1550
  DBUG_PRINT("enter",("host: '%s'  user: '%s'",host,user));
1551 1552 1553

  safe_mutex_assert_owner(&acl_cache->lock);

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1554 1555 1556
  for (uint i=0 ; i < acl_users.elements ; i++)
  {
    ACL_USER *acl_user=dynamic_element(&acl_users,i,ACL_USER*);
1557
    DBUG_PRINT("info",("strcmp('%s','%s'), compare_hostname('%s','%s'),",
1558 1559 1560 1561
                       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
1562 1563 1564
    if (!acl_user->user && !user[0] ||
	acl_user->user && !strcmp(user,acl_user->user))
    {
1565
      if (exact ? !my_strcasecmp(system_charset_info, host,
1566 1567
                                 acl_user->host.hostname ?
				 acl_user->host.hostname : "") :
1568
          compare_hostname(&acl_user->host,host,host))
1569 1570 1571
      {
	DBUG_RETURN(acl_user);
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1572 1573
    }
  }
1574
  DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1575 1576 1577
}


1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
/*
  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
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610

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)
{
1611
  host->hostname=(char*) hostname;             // This will not be modified!
1612
  if (!hostname ||
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1613 1614 1615
      (!(hostname=calc_ip(hostname,&host->ip,'/')) ||
       !(hostname=calc_ip(hostname+1,&host->ip_mask,'\0'))))
  {
1616
    host->ip= host->ip_mask=0;			// Not a masked ip
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
  }
}


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 ||
1630
	  (hostname && !wild_case_compare(system_charset_info,
1631 1632
                                          hostname, host->hostname)) ||
	  (ip && !wild_compare(ip, host->hostname, 0)));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1633 1634
}

hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1635 1636 1637 1638
bool hostname_requires_resolving(const char *hostname)
{
  char cur;
  if (!hostname)
monty@mysql.com's avatar
monty@mysql.com committed
1639
    return FALSE;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1640 1641 1642
  int namelen= strlen(hostname);
  int lhlen= strlen(my_localhost);
  if ((namelen == lhlen) &&
1643
      !my_strnncoll(system_charset_info, (const uchar *)hostname,  namelen,
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1644
		    (const uchar *)my_localhost, strlen(my_localhost)))
monty@mysql.com's avatar
monty@mysql.com committed
1645
    return FALSE;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1646 1647
  for (; (cur=*hostname); hostname++)
  {
1648
    if ((cur != '%') && (cur != '_') && (cur != '.') && (cur != '/') &&
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1649
	((cur < '0') || (cur > '9')))
monty@mysql.com's avatar
monty@mysql.com committed
1650
      return TRUE;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1651
  }
monty@mysql.com's avatar
monty@mysql.com committed
1652
  return FALSE;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1653
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1654

1655

1656
/*
1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
  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
1667
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1668

1669 1670
static bool update_user_table(THD *thd, TABLE *table,
                              const char *host, const char *user,
1671
			      const char *new_password, uint new_password_len)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1672
{
1673
  char user_key[MAX_KEY_LENGTH];
1674
  int error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1675 1676 1677
  DBUG_ENTER("update_user_table");
  DBUG_PRINT("enter",("user: %s  host: %s",user,host));

1678 1679
  table->field[0]->store(host,(uint) strlen(host), system_charset_info);
  table->field[1]->store(user,(uint) strlen(user), system_charset_info);
1680
  key_copy((byte *) user_key, table->record[0], table->key_info,
1681
           table->key_info->key_length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1682

1683
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
1684
  if (table->file->index_read_idx(table->record[0], 0,
1685
				  (byte *) user_key, table->key_info->key_length,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1686 1687
				  HA_READ_KEY_EXACT))
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1688 1689
    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
1690 1691
    DBUG_RETURN(1);				/* purecov: deadcode */
  }
1692
  store_record(table,record[1]);
1693
  table->field[2]->store(new_password, new_password_len, system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1694 1695 1696
  if ((error=table->file->update_row(table->record[1],table->record[0])))
  {
    table->file->print_error(error,MYF(0));	/* purecov: deadcode */
1697
    DBUG_RETURN(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1698
  }
1699
  DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1700 1701
}

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

1703 1704 1705 1706 1707 1708
/*
  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
1709 1710 1711

static bool test_if_create_new_users(THD *thd)
{
1712
  Security_context *sctx= thd->security_ctx;
1713
  bool create_new_users= test(sctx->master_access & INSERT_ACL) ||
1714
                         (!opt_safe_user_create &&
1715
                          test(sctx->master_access & CREATE_USER_ACL));
1716
  if (!create_new_users)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1717 1718
  {
    TABLE_LIST tl;
1719
    ulong db_access;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1720 1721
    bzero((char*) &tl,sizeof(tl));
    tl.db=	   (char*) "mysql";
1722
    tl.table_name=  (char*) "user";
1723
    create_new_users= 1;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1724

1725 1726
    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
1727 1728
    if (!(db_access & INSERT_ACL))
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1729
      if (check_grant(thd, INSERT_ACL, &tl, 0, UINT_MAX, 1))
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1730 1731 1732 1733 1734 1735 1736
	create_new_users=0;
    }
  }
  return create_new_users;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
1737
/****************************************************************************
1738
  Handle GRANT commands
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1739 1740
****************************************************************************/

1741
static int replace_user_table(THD *thd, TABLE *table, const LEX_USER &combo,
1742
			      ulong rights, bool revoke_grant,
serg@serg.mylan's avatar
serg@serg.mylan committed
1743
			      bool can_create_user, bool no_auto_create)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1744 1745
{
  int error = -1;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1746
  bool old_row_exists=0;
1747
  const char *password= "";
1748
  uint password_len= 0;
1749
  char what= (revoke_grant) ? 'N' : 'Y';
1750
  byte user_key[MAX_KEY_LENGTH];
1751
  LEX *lex= thd->lex;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1752
  DBUG_ENTER("replace_user_table");
1753

1754
  safe_mutex_assert_owner(&acl_cache->lock);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1755 1756

  if (combo.password.str && combo.password.str[0])
1757
  {
1758 1759
    if (combo.password.length != SCRAMBLED_PASSWORD_CHAR_LENGTH &&
        combo.password.length != SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
1760
    {
1761
      my_error(ER_PASSWD_LENGTH, MYF(0), SCRAMBLED_PASSWORD_CHAR_LENGTH);
1762
      DBUG_RETURN(-1);
1763
    }
1764
    password_len= combo.password.length;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1765
    password=combo.password.str;
1766
  }
peter@mysql.com's avatar
peter@mysql.com committed
1767

1768 1769
  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);
1770 1771 1772
  key_copy(user_key, table->record[0], table->key_info,
           table->key_info->key_length);

1773
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
1774
  if (table->file->index_read_idx(table->record[0], 0,
1775 1776
                                  user_key, table->key_info->key_length,
                                  HA_READ_KEY_EXACT))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1777
  {
1778 1779
    /* what == 'N' means revoke */
    if (what == 'N')
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1780
    {
1781 1782 1783 1784
      my_error(ER_NONEXISTING_GRANT, MYF(0), combo.user.str, combo.host.str);
      goto end;
    }
    /*
1785 1786
      There are four options which affect the process of creation of
      a new user (mysqld option --safe-create-user, 'insert' privilege
1787 1788 1789 1790 1791 1792 1793
      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
1794 1795

      see also test_if_create_new_users()
1796
    */
serg@serg.mylan's avatar
serg@serg.mylan committed
1797 1798 1799 1800 1801 1802
    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)
1803
    {
1804
      my_error(ER_CANT_CREATE_USER_WITH_GRANT, MYF(0),
1805
               thd->security_ctx->user, thd->security_ctx->host_or_ip);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1806 1807
      goto end;
    }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1808
    old_row_exists = 0;
1809
    restore_record(table,s->default_values);
1810
    table->field[0]->store(combo.host.str,combo.host.length,
1811
                           system_charset_info);
1812
    table->field[1]->store(combo.user.str,combo.user.length,
1813
                           system_charset_info);
1814
    table->field[2]->store(password, password_len,
1815
                           system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1816 1817 1818
  }
  else
  {
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1819
    old_row_exists = 1;
1820
    store_record(table,record[1]);			// Save copy for update
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1821
    if (combo.password.str)			// If password given
1822
      table->field[2]->store(password, password_len, system_charset_info);
1823
    else if (!rights && !revoke_grant &&
1824 1825
             lex->ssl_type == SSL_TYPE_NOT_SPECIFIED &&
             !lex->mqh.specified_limits)
1826 1827 1828
    {
      DBUG_RETURN(0);
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1829 1830
  }

1831 1832 1833 1834
  /* Update table columns with new privileges */

  Field **tmp_field;
  ulong priv;
1835
  uint next_field;
1836 1837 1838 1839
  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
1840
  {
1841
    if (priv & rights)				 // set requested privileges
1842
      (*tmp_field)->store(&what, 1, &my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1843
  }
1844
  rights= get_access(table, 3, &next_field);
1845 1846
  DBUG_PRINT("info",("table fields: %d",table->s->fields));
  if (table->s->fields >= 31)		/* From 4.0.0 we have more fields */
1847
  {
1848
    /* We write down SSL related ACL stuff */
1849
    switch (lex->ssl_type) {
1850
    case SSL_TYPE_ANY:
1851 1852
      table->field[next_field]->store(STRING_WITH_LEN("ANY"),
                                      &my_charset_latin1);
1853 1854 1855
      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);
1856 1857
      break;
    case SSL_TYPE_X509:
1858 1859
      table->field[next_field]->store(STRING_WITH_LEN("X509"),
                                      &my_charset_latin1);
1860 1861 1862
      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);
1863 1864
      break;
    case SSL_TYPE_SPECIFIED:
1865 1866
      table->field[next_field]->store(STRING_WITH_LEN("SPECIFIED"),
                                      &my_charset_latin1);
1867 1868 1869
      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);
1870
      if (lex->ssl_cipher)
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
1871 1872
        table->field[next_field+1]->store(lex->ssl_cipher,
                                strlen(lex->ssl_cipher), system_charset_info);
1873
      if (lex->x509_issuer)
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
1874 1875
        table->field[next_field+2]->store(lex->x509_issuer,
                                strlen(lex->x509_issuer), system_charset_info);
1876
      if (lex->x509_subject)
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
1877 1878
        table->field[next_field+3]->store(lex->x509_subject,
                                strlen(lex->x509_subject), system_charset_info);
1879
      break;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1880
    case SSL_TYPE_NOT_SPECIFIED:
gluh@gluh.(none)'s avatar
gluh@gluh.(none) committed
1881 1882
      break;
    case SSL_TYPE_NONE:
1883 1884 1885 1886
      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
1887
      break;
1888
    }
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
1889
    next_field+=4;
1890

1891
    USER_RESOURCES mqh= lex->mqh;
1892
    if (mqh.specified_limits & USER_RESOURCES::QUERIES_PER_HOUR)
1893
      table->field[next_field]->store((longlong) mqh.questions, TRUE);
1894
    if (mqh.specified_limits & USER_RESOURCES::UPDATES_PER_HOUR)
1895
      table->field[next_field+1]->store((longlong) mqh.updates, TRUE);
1896
    if (mqh.specified_limits & USER_RESOURCES::CONNECTIONS_PER_HOUR)
1897
      table->field[next_field+2]->store((longlong) mqh.conn_per_hour, TRUE);
1898
    if (table->s->fields >= 36 &&
1899
        (mqh.specified_limits & USER_RESOURCES::USER_CONNECTIONS))
1900
      table->field[next_field+3]->store((longlong) mqh.user_conn, TRUE);
1901
    mqh_used= mqh_used || mqh.questions || mqh.updates || mqh.conn_per_hour;
1902
  }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1903
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1904 1905 1906 1907 1908
  {
    /*
      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!
    */
1909
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
1910
    if (cmp_record(table,record[1]) &&
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
	(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

1930
end:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1931 1932 1933
  if (!error)
  {
    acl_cache->clear(1);			// Clear privilege cache
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1934
    if (old_row_exists)
1935 1936
      acl_update_user(combo.user.str, combo.host.str,
                      combo.password.str, password_len,
1937 1938 1939 1940 1941
		      lex->ssl_type,
		      lex->ssl_cipher,
		      lex->x509_issuer,
		      lex->x509_subject,
		      &lex->mqh,
1942
		      rights);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1943
    else
1944
      acl_insert_user(combo.user.str, combo.host.str, password, password_len,
1945 1946 1947 1948 1949
		      lex->ssl_type,
		      lex->ssl_cipher,
		      lex->x509_issuer,
		      lex->x509_subject,
		      &lex->mqh,
1950
		      rights);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1951 1952 1953 1954 1955 1956
  }
  DBUG_RETURN(error);
}


/*
1957
  change grants in the mysql.db table
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1958 1959 1960 1961
*/

static int replace_db_table(TABLE *table, const char *db,
			    const LEX_USER &combo,
1962
			    ulong rights, bool revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1963
{
1964 1965
  uint i;
  ulong priv,store_rights;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1966
  bool old_row_exists=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1967
  int error;
1968
  char what= (revoke_grant) ? 'N' : 'Y';
1969
  byte user_key[MAX_KEY_LENGTH];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1970 1971
  DBUG_ENTER("replace_db_table");

1972 1973
  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
1974
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
1975 1976 1977
    DBUG_RETURN(-1);
  }

1978
  /* Check if there is such a user in user table in memory? */
1979
  if (!find_acl_user(combo.host.str,combo.user.str, FALSE))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1980
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1981
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH), MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1982 1983 1984
    DBUG_RETURN(-1);
  }

1985 1986 1987
  table->field[0]->store(combo.host.str,combo.host.length, system_charset_info);
  table->field[1]->store(db,(uint) strlen(db), system_charset_info);
  table->field[2]->store(combo.user.str,combo.user.length, system_charset_info);
1988 1989 1990
  key_copy(user_key, table->record[0], table->key_info,
           table->key_info->key_length);

1991 1992
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
  if (table->file->index_read_idx(table->record[0],0,
1993 1994
                                  user_key, table->key_info->key_length,
                                  HA_READ_KEY_EXACT))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1995 1996 1997
  {
    if (what == 'N')
    { // no row, no revoke
guilhem@mysql.com's avatar
guilhem@mysql.com committed
1998
      my_error(ER_NONEXISTING_GRANT, MYF(0), combo.user.str, combo.host.str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1999 2000
      goto abort;
    }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2001
    old_row_exists = 0;
2002
    restore_record(table, s->default_values);
2003 2004 2005
    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
2006 2007 2008
  }
  else
  {
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2009
    old_row_exists = 1;
2010
    store_record(table,record[1]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2011 2012 2013
  }

  store_rights=get_rights_for_db(rights);
2014
  for (i= 3, priv= 1; i < table->s->fields; i++, priv <<= 1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2015
  {
2016
    if (priv & store_rights)			// do it if priv is chosen
2017
      table->field [i]->store(&what,1, &my_charset_latin1);// set requested privileges
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2018 2019 2020 2021
  }
  rights=get_access(table,3);
  rights=fix_rights_for_db(rights);

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2022
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2023
  {
2024
    /* update old existing row */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2025 2026
    if (rights)
    {
2027
      table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2028 2029 2030 2031 2032 2033 2034 2035 2036
      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 */
    }
  }
2037
  else if (rights && (error=table->file->write_row(table->record[0])))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2038 2039 2040 2041 2042 2043
  {
    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
2044
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2045 2046
    acl_update_db(combo.user.str,combo.host.str,db,rights);
  else
2047
  if (rights)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2048 2049 2050 2051
    acl_insert_db(combo.user.str,combo.host.str,db,rights);
  DBUG_RETURN(0);

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

2055
abort:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2056 2057 2058 2059 2060 2061 2062 2063
  DBUG_RETURN(-1);
}


class GRANT_COLUMN :public Sql_alloc
{
public:
  char *column;
2064 2065 2066
  ulong rights;
  uint key_length;
  GRANT_COLUMN(String &c,  ulong y) :rights (y)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2067
  {
2068
    column= memdup_root(&memex,c.ptr(), key_length=c.length());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2069 2070 2071
  }
};

2072

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2073 2074 2075 2076 2077 2078 2079
static byte* get_key_column(GRANT_COLUMN *buff,uint *length,
			    my_bool not_used __attribute__((unused)))
{
  *length=buff->key_length;
  return (byte*) buff->column;
}

2080

2081
class GRANT_NAME :public Sql_alloc
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2082 2083
{
public:
2084 2085
  acl_host_and_ip host;
  char *db, *user, *tname, *hash_key;
2086
  ulong privs;
2087
  ulong sort;
2088
  uint key_length;
2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100
  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
2101
  HASH hash_columns;
monty@mysql.com's avatar
monty@mysql.com committed
2102 2103 2104 2105

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

2110

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

2112 2113 2114
GRANT_NAME::GRANT_NAME(const char *h, const char *d,const char *u,
                       const char *t, ulong p)
  :privs(p)
2115 2116
{
  /* Host given by user */
2117
  update_hostname(&host, strdup_root(&memex, h));
2118 2119
  db =   strdup_root(&memex,d);
  user = strdup_root(&memex,u);
2120
  sort=  get_sort(3,host.hostname,db,user);
2121 2122
  tname= strdup_root(&memex,t);
  if (lower_case_table_names)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2123
  {
2124 2125
    my_casedn_str(files_charset_info, db);
    my_casedn_str(files_charset_info, tname);
2126 2127 2128 2129
  }
  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);
2130 2131 2132 2133 2134 2135 2136
}


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

2141

2142
GRANT_NAME::GRANT_NAME(TABLE *form)
2143
{
2144
  update_hostname(&host, get_field(&memex, form->field[0]));
monty@mysql.com's avatar
monty@mysql.com committed
2145 2146
  db=    get_field(&memex,form->field[1]);
  user=  get_field(&memex,form->field[2]);
2147 2148
  if (!user)
    user= (char*) "";
2149
  sort=  get_sort(3, host.hostname, db, user);
monty@mysql.com's avatar
monty@mysql.com committed
2150
  tname= get_field(&memex,form->field[3]);
2151 2152 2153
  if (!db || !tname)
  {
    /* Wrong table row; Ignore it */
2154
    privs= 0;
2155 2156 2157 2158
    return;					/* purecov: inspected */
  }
  if (lower_case_table_names)
  {
2159 2160
    my_casedn_str(files_charset_info, db);
    my_casedn_str(files_charset_info, tname);
2161 2162 2163 2164 2165 2166 2167
  }
  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);
2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
}


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();
2184 2185
  cols =  fix_rights_for_column(cols);

2186
  (void) hash_init(&hash_columns,system_charset_info,
monty@mysql.com's avatar
monty@mysql.com committed
2187
                   0,0,0, (hash_get_key) get_key_column,0,0);
2188 2189
  if (cols)
  {
2190 2191
    uint key_prefix_len;
    KEY_PART_INFO *key_part= col_privs->key_info->key_part;
2192 2193
    col_privs->field[0]->store(host.hostname,
                               host.hostname ? (uint) strlen(host.hostname) : 0,
2194 2195 2196 2197
                               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);
2198 2199 2200 2201 2202 2203

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

2206 2207
    col_privs->file->ha_index_init(0);
    if (col_privs->file->index_read(col_privs->record[0],
2208 2209
                                    (byte*) key,
                                    key_prefix_len, HA_READ_KEY_EXACT))
2210
    {
2211
      cols = 0; /* purecov: deadcode */
2212
      col_privs->file->ha_index_end();
2213
      return;
2214
    }
2215
    do
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2216
    {
2217 2218 2219
      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
2220
      res=col_privs->field[4]->val_str(&column_name);
2221 2222 2223
      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
2224
      {
2225 2226 2227
        /* Don't use this entry */
        privs = cols = 0;			/* purecov: deadcode */
        return;				/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2228
      }
monty@mysql.com's avatar
monty@mysql.com committed
2229
      my_hash_insert(&hash_columns, (byte *) mem_check);
2230
    } while (!col_privs->file->index_next(col_privs->record[0]) &&
2231
             !key_cmp_if_same(col_privs,key,0,key_prefix_len));
2232
    col_privs->file->ha_index_end();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2233
  }
2234
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2235

2236

2237 2238 2239 2240 2241 2242
GRANT_TABLE::~GRANT_TABLE()
{
  hash_free(&hash_columns);
}


2243
static byte* get_grant_table(GRANT_NAME *buff,uint *length,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2244 2245 2246 2247 2248 2249
			     my_bool not_used __attribute__((unused)))
{
  *length=buff->key_length;
  return (byte*) buff->hash_key;
}

2250

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2251 2252 2253 2254 2255
void free_grant_table(GRANT_TABLE *grant_table)
{
  hash_free(&grant_table->hash_columns);
}

2256

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

2259 2260
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
2261 2262 2263 2264
				      const char *db,
				      const char *user, const char *tname,
				      bool exact)
{
gluh@mysql.com/gluh.(none)'s avatar
gluh@mysql.com/gluh.(none) committed
2265
  char helping [NAME_LEN*2+USERNAME_LENGTH+3];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2266
  uint len;
2267
  GRANT_NAME *grant_name,*found=0;
2268
  HASH_SEARCH_STATE state;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2269 2270

  len  = (uint) (strmov(strmov(strmov(helping,user)+1,db)+1,tname)-helping)+ 1;
2271 2272
  for (grant_name= (GRANT_NAME*) hash_first(name_hash, (byte*) helping,
                                            len, &state);
2273 2274
       grant_name ;
       grant_name= (GRANT_NAME*) hash_next(name_hash,(byte*) helping,
2275
                                           len, &state))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2276 2277 2278
  {
    if (exact)
    {
2279 2280
      if (!grant_name->host.hostname ||
          (host &&
2281
	   !my_strcasecmp(system_charset_info, host,
gluh@mysql.com's avatar
gluh@mysql.com committed
2282 2283
                          grant_name->host.hostname)) ||
	  (ip && !strcmp(ip, grant_name->host.hostname)))
2284
	return grant_name;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2285 2286 2287
    }
    else
    {
2288
      if (compare_hostname(&grant_name->host, host, ip) &&
2289 2290
          (!found || found->sort < grant_name->sort))
	found=grant_name;					// Host ok
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2291 2292 2293 2294 2295 2296
    }
  }
  return found;
}


2297
inline GRANT_NAME *
2298 2299
routine_hash_search(const char *host, const char *ip, const char *db,
                 const char *user, const char *tname, bool proc, bool exact)
2300
{
2301 2302 2303
  return (GRANT_TABLE*)
    name_hash_search(proc ? &proc_priv_hash : &func_priv_hash,
		     host, ip, db, user, tname, exact);
2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314
}


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
2315

2316
inline GRANT_COLUMN *
2317
column_hash_search(GRANT_TABLE *t, const char *cname, uint length)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2318 2319 2320 2321 2322 2323 2324 2325 2326
{
  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,
2327
				ulong rights, bool revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2328 2329 2330
{
  int error=0,result=0;
  byte key[MAX_KEY_LENGTH];
2331 2332
  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
2333 2334
  DBUG_ENTER("replace_column_table");

2335 2336 2337 2338 2339 2340 2341 2342
  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
2343

2344 2345 2346 2347
  /* 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
2348

2349
  rights&= COL_ACLS;				// Only ACL for columns
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2350 2351 2352 2353

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

  List_iterator <LEX_COLUMN> iter(columns);
2354
  class LEX_COLUMN *column;
2355
  table->file->ha_index_init(0);
2356
  while ((column= iter++))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2357
  {
2358
    ulong privileges= column->rights;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2359
    bool old_row_exists=0;
2360 2361 2362 2363
    byte user_key[MAX_KEY_LENGTH];

    key_restore(table->record[0],key,table->key_info,
                key_prefix_length);
2364
    table->field[4]->store(column->column.ptr(), column->column.length(),
2365
                           system_charset_info);
2366 2367 2368
    /* 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
2369

2370
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
2371 2372 2373
    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
2374 2375 2376
    {
      if (revoke_grant)
      {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2377
	my_error(ER_NONEXISTING_TABLE_GRANT, MYF(0),
2378
                 combo.user.str, combo.host.str,
2379 2380 2381
                 table_name);                   /* purecov: inspected */
	result= -1;                             /* purecov: inspected */
	continue;                               /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2382
      }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2383
      old_row_exists = 0;
2384
      restore_record(table, s->default_values);		// Get empty record
2385 2386
      key_restore(table->record[0],key,table->key_info,
                  key_prefix_length);
2387
      table->field[4]->store(column->column.ptr(),column->column.length(),
2388
                             system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2389 2390 2391
    }
    else
    {
2392
      ulong tmp= (ulong) table->field[6]->val_int();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2393 2394 2395 2396 2397 2398
      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
2399
      old_row_exists = 1;
2400
      store_record(table,record[1]);			// copy original row
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2401 2402
    }

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

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2405
    if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2406
    {
2407
      GRANT_COLUMN *grant_column;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2408 2409 2410 2411 2412 2413 2414 2415 2416 2417
      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 */
      }
2418 2419
      grant_column= column_hash_search(g_t, column->column.ptr(),
                                       column->column.length());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2420
      if (grant_column)				// Should always be true
2421
	grant_column->rights= privileges;	// Update hash
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2422 2423 2424
    }
    else					// new grant
    {
2425
      GRANT_COLUMN *grant_column;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2426 2427 2428 2429 2430 2431
      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 */
      }
2432
      grant_column= new GRANT_COLUMN(column->column,privileges);
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2433
      my_hash_insert(&g_t->hash_columns,(byte*) grant_column);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2434 2435 2436 2437 2438 2439 2440 2441 2442 2443
    }
  }

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

  if (revoke_grant)
  {
2444 2445
    byte user_key[MAX_KEY_LENGTH];
    key_copy(user_key, table->record[0], table->key_info,
2446 2447
             key_prefix_length);

2448
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
2449
    if (table->file->index_read(table->record[0], user_key,
2450
				key_prefix_length,
2451
                                HA_READ_KEY_EXACT))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2452 2453
      goto end;

2454
    /* Scan through all rows with the same host,db,user and table */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2455 2456
    do
    {
2457
      ulong privileges = (ulong) table->field[6]->val_int();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2458
      privileges=fix_rights_for_column(privileges);
2459
      store_record(table,record[1]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2460 2461 2462 2463 2464

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

	privileges&= ~rights;
	table->field[6]->store((longlong)
2470
			       get_rights_for_column(privileges), TRUE);
2471
	table->field[4]->val_str(&column_name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501
	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]) &&
2502
	     !key_cmp_if_same(table, key, 0, key_prefix_length));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2503 2504
  }

2505
end:
2506
  table->file->ha_index_end();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2507 2508 2509 2510 2511 2512 2513
  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,
2514 2515
			       ulong rights, ulong col_rights,
			       bool revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2516
{
2517
  char grantor[USER_HOST_BUFF_SIZE];
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2518
  int old_row_exists = 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2519
  int error=0;
2520
  ulong store_table_rights, store_col_rights;
2521
  byte user_key[MAX_KEY_LENGTH];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2522 2523
  DBUG_ENTER("replace_table_table");

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

2527 2528 2529 2530
  /*
    The following should always succeed as new users are created before
    this function is called!
  */
2531
  if (!find_acl_user(combo.host.str,combo.user.str, FALSE))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2532
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2533 2534
    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
2535 2536 2537
    DBUG_RETURN(-1);				/* purecov: deadcode */
  }

2538
  restore_record(table, s->default_values);     // Get empty record
2539 2540 2541 2542
  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);
2543
  store_record(table,record[1]);			// store at pos 1
2544 2545
  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
2546

2547
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
2548 2549
  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
2550 2551 2552 2553 2554 2555 2556 2557 2558
				  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
2559 2560
      my_error(ER_NONEXISTING_TABLE_GRANT, MYF(0),
               combo.user.str, combo.host.str,
2561
               table_name);		        /* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2562 2563
      DBUG_RETURN(-1);				/* purecov: deadcode */
    }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2564
    old_row_exists = 0;
2565
    restore_record(table,record[1]);			// Get saved record
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2566 2567
  }

2568 2569
  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
2570
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2571
  {
2572
    ulong j,k;
2573
    store_record(table,record[1]);
2574 2575
    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
2576 2577 2578

    if (revoke_grant)
    {
2579
      /* column rights are already fixed in mysql_table_grant */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2580 2581 2582 2583
      store_table_rights=j & ~store_table_rights;
    }
    else
    {
2584 2585
      store_table_rights|= j;
      store_col_rights|=   k;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2586 2587 2588
    }
  }

2589
  table->field[4]->store(grantor,(uint) strlen(grantor), system_charset_info);
2590 2591
  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
2592
  rights=fix_rights_for_table(store_table_rights);
2593
  col_rights=fix_rights_for_column(store_col_rights);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2594

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2595
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611
  {
    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 */
  }

2612
  if (rights | col_rights)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2613
  {
2614
    grant_table->privs= rights;
2615
    grant_table->cols=	col_rights;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2616 2617 2618
  }
  else
  {
2619
    hash_delete(&column_priv_hash,(byte*) grant_table);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2620 2621 2622
  }
  DBUG_RETURN(0);

2623 2624
  /* This should never happen */
table_error:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2625 2626 2627 2628 2629
  table->file->print_error(error,MYF(0)); /* purecov: deadcode */
  DBUG_RETURN(-1); /* purecov: deadcode */
}


2630
static int replace_routine_table(THD *thd, GRANT_NAME *grant_name,
2631
			      TABLE *table, const LEX_USER &combo,
2632 2633
			      const char *db, const char *routine_name,
			      bool is_proc, ulong rights, bool revoke_grant)
2634
{
2635
  char grantor[USER_HOST_BUFF_SIZE];
2636 2637 2638
  int old_row_exists= 1;
  int error=0;
  ulong store_proc_rights;
2639
  DBUG_ENTER("replace_routine_table");
2640 2641 2642 2643 2644 2645 2646

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

2647 2648
  strxmov(grantor, thd->security_ctx->user, "@",
          thd->security_ctx->host_or_ip, NullS);
2649 2650 2651 2652 2653

  /*
    The following should always succeed as new users are created before
    this function is called!
  */
monty@mishka.local's avatar
monty@mishka.local committed
2654
  if (!find_acl_user(combo.host.str, combo.user.str, FALSE))
2655 2656 2657 2658 2659
  {
    my_error(ER_PASSWORD_NO_MATCH,MYF(0));
    DBUG_RETURN(-1);
  }

2660
  restore_record(table, s->default_values);		// Get empty record
2661 2662 2663
  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);
2664 2665 2666
  table->field[3]->store(routine_name,(uint) strlen(routine_name),
                         &my_charset_latin1);
  table->field[4]->store((longlong)(is_proc ? 
2667 2668
                                    TYPE_ENUM_PROCEDURE : TYPE_ENUM_FUNCTION),
                         TRUE);
2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682
  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),
2683
               combo.user.str, combo.host.str, routine_name);
2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707
      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;
    }
  }

2708
  table->field[5]->store(grantor,(uint) strlen(grantor), &my_charset_latin1);
2709
  table->field[6]->store((longlong) store_proc_rights, TRUE);
2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734
  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
  {
2735
    hash_delete(is_proc ? &proc_priv_hash : &func_priv_hash,(byte*) grant_name);
2736 2737 2738 2739 2740 2741 2742 2743 2744 2745
  }
  DBUG_RETURN(0);

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


2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758
/*
  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
2759 2760
    FALSE ok
    TRUE  error
2761 2762
*/

2763
bool mysql_table_grant(THD *thd, TABLE_LIST *table_list,
2764 2765 2766
		      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
2767
{
2768
  ulong column_priv= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2769
  List_iterator <LEX_USER> str_list (user_list);
2770
  LEX_USER *Str, *tmp_Str;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2771
  TABLE_LIST tables[3];
2772
  bool create_new_users=0;
2773
  char *db_name, *table_name;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2774 2775 2776 2777
  DBUG_ENTER("mysql_table_grant");

  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2778 2779
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0),
             "--skip-grant-tables");	/* purecov: inspected */
2780
    DBUG_RETURN(TRUE);				/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2781 2782 2783
  }
  if (rights & ~TABLE_ACLS)
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2784 2785
    my_message(ER_ILLEGAL_GRANT_FOR_TABLE, ER(ER_ILLEGAL_GRANT_FOR_TABLE),
               MYF(0));
2786
    DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2787 2788
  }

2789
  if (!revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2790
  {
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
2791
    if (columns.elements)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2792
    {
2793 2794
      class LEX_COLUMN *column;
      List_iterator <LEX_COLUMN> column_iter(columns);
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
2795 2796 2797

      if (open_and_lock_tables(thd, table_list))
        DBUG_RETURN(TRUE);
2798 2799

      while ((column = column_iter++))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2800
      {
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
2801
        uint unused_field_idx= NO_CACHED_FIELD_INDEX;
2802 2803
        TABLE_LIST *dummy;
        Field *f=find_field_in_table_ref(thd, table_list, column->column.ptr(),
2804
                                         column->column.length(),
2805
                                         column->column.ptr(), NULL, NULL,
2806
                                         NULL, TRUE, FALSE,
2807
                                         &unused_field_idx, FALSE, &dummy);
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
2808
        if (f == (Field*)0)
2809
        {
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
2810 2811
          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
2812
          DBUG_RETURN(TRUE);
2813
        }
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
2814 2815
        if (f == (Field *)-1)
          DBUG_RETURN(TRUE);
2816
        column_priv|= column->rights;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2817
      }
2818
      close_thread_tables(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2819
    }
2820
    else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2821
    {
2822 2823 2824 2825
      if (!(rights & CREATE_ACL))
      {
        char buf[FN_REFLEN];
        sprintf(buf,"%s/%s/%s.frm",mysql_data_home, table_list->db,
2826
                table_list->table_name);
2827 2828 2829
        fn_format(buf,buf,"","",4+16+32);
        if (access(buf,F_OK))
        {
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
2830
          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
2831
          DBUG_RETURN(TRUE);
2832 2833 2834 2835 2836 2837 2838 2839
        }
      }
      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),
2840 2841
                 command, thd->security_ctx->priv_user,
                 thd->security_ctx->host_or_ip, table_list->alias);
2842 2843
        DBUG_RETURN(-1);
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2844 2845 2846 2847 2848 2849
    }
  }

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

  bzero((char*) &tables,sizeof(tables));
2850 2851 2852
  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
2853
  tables[0].next_local= tables[0].next_global= tables+1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2854
  /* 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
2855 2856 2857 2858 2859
  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
2860 2861 2862
  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";

2863 2864 2865 2866 2867
#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
2868 2869
  if (thd->slave_thread && table_rules_on)
  {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2870 2871 2872
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
2873
    */
2874
    tables[0].updating= tables[1].updating= tables[2].updating= 1;
2875
    if (!tables_ok(thd, tables))
2876
      DBUG_RETURN(FALSE);
2877
  }
2878 2879
#endif

2880
  if (simple_open_n_lock_tables(thd,tables))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2881 2882
  {						// Should never happen
    close_thread_tables(thd);			/* purecov: deadcode */
2883
    DBUG_RETURN(TRUE);				/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2884 2885
  }

2886 2887
  if (!revoke_grant)
    create_new_users= test_if_create_new_users(thd);
2888
  bool result= FALSE;
2889
  rw_wrlock(&LOCK_grant);
2890
  pthread_mutex_lock(&acl_cache->lock);
2891 2892
  MEM_ROOT *old_root= thd->mem_root;
  thd->mem_root= &memex;
2893
  grant_version++;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2894

2895
  while ((tmp_Str = str_list++))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2896
  {
2897
    int error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2898
    GRANT_TABLE *grant_table;
2899 2900 2901 2902 2903
    if (!(Str= get_current_user(thd, tmp_Str)))
    {
      result= TRUE;
      continue;
    }  
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2904
    /* Create user if needed */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2905
    error=replace_user_table(thd, tables[0].table, *Str,
serg@serg.mylan's avatar
serg@serg.mylan committed
2906
			     0, revoke_grant, create_new_users,
monty@mysql.com's avatar
monty@mysql.com committed
2907 2908
                             test(thd->variables.sql_mode &
                                  MODE_NO_AUTO_CREATE_USER));
2909
    if (error)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2910
    {
2911
      result= TRUE;				// Remember error
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2912 2913 2914
      continue;					// Add next user
    }

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2915 2916 2917
    db_name= (table_list->view_db.length ?
	      table_list->view_db.str :
	      table_list->db);
2918
    table_name= (table_list->view_name.length ?
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2919
		table_list->view_name.str :
2920
		table_list->table_name);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2921

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2922
    /* Find/create cached table grant */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2923
    grant_table= table_hash_search(Str->host.str, NullS, db_name,
2924
				   Str->user.str, table_name, 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2925 2926 2927 2928
    if (!grant_table)
    {
      if (revoke_grant)
      {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2929
	my_error(ER_NONEXISTING_TABLE_GRANT, MYF(0),
2930
                 Str->user.str, Str->host.str, table_list->table_name);
2931
	result= TRUE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2932 2933
	continue;
      }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2934
      grant_table = new GRANT_TABLE (Str->host.str, db_name,
2935
				     Str->user.str, table_name,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2936 2937 2938 2939
				     rights,
				     column_priv);
      if (!grant_table)				// end of memory
      {
2940
	result= TRUE;				/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2941 2942
	continue;				/* purecov: deadcode */
      }
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2943
      my_hash_insert(&column_priv_hash,(byte*) grant_table);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2944 2945 2946 2947 2948
    }

    /* If revoke_grant, calculate the new column privilege for tables_priv */
    if (revoke_grant)
    {
2949 2950
      class LEX_COLUMN *column;
      List_iterator <LEX_COLUMN> column_iter(columns);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2951 2952 2953
      GRANT_COLUMN *grant_column;

      /* Fix old grants */
2954
      while ((column = column_iter++))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2955 2956
      {
	grant_column = column_hash_search(grant_table,
2957 2958
					  column->column.ptr(),
					  column->column.length());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2959
	if (grant_column)
2960
	  grant_column->rights&= ~(column->rights | rights);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2961 2962
      }
      /* scan trough all columns to get new column grant */
2963
      column_priv= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979
      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
2980
    if (replace_table_table(thd, grant_table, tables[1].table, *Str,
2981
			    db_name, table_name,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2982
			    rights, column_priv, revoke_grant))
2983 2984
    {
      /* Should only happen if table is crashed */
2985
      result= TRUE;			       /* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2986 2987 2988
    }
    else if (tables[2].table)
    {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2989
      if ((replace_column_table(grant_table, tables[2].table, *Str,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2990
				columns,
2991
				db_name, table_name,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2992 2993
				rights, revoke_grant)))
      {
2994
	result= TRUE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2995 2996 2997 2998
      }
    }
  }
  grant_option=TRUE;
2999
  thd->mem_root= old_root;
3000
  pthread_mutex_unlock(&acl_cache->lock);
3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011

  if (!result) /* success */
  {
    if (mysql_bin_log.is_open())
    {
      thd->clear_error();
      Query_log_event qinfo(thd, thd->query, thd->query_length, 0, FALSE);
      mysql_bin_log.write(&qinfo);
    }
  }

3012
  rw_unlock(&LOCK_grant);
3013 3014

  if (!result) /* success */
3015
    send_ok(thd);
3016

3017
  /* Tables are automatically closed */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3018 3019 3020 3021
  DBUG_RETURN(result);
}


3022
/*
3023
  Store routine level grants in the privilege tables
3024 3025

  SYNOPSIS
3026
    mysql_routine_grant()
3027
    thd			Thread handle
3028 3029
    table_list		List of routines to give grant
    is_proc             true indicates routine list are procedures
3030 3031 3032 3033 3034 3035 3036 3037 3038
    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
*/

3039 3040 3041
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)
3042 3043
{
  List_iterator <LEX_USER> str_list (user_list);
3044
  LEX_USER *Str, *tmp_Str;
3045 3046
  TABLE_LIST tables[2];
  bool create_new_users=0, result=0;
3047
  char *db_name, *table_name;
3048
  DBUG_ENTER("mysql_routine_grant");
3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066

  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)
  {
3067
    if (sp_exist_routines(thd, table_list, is_proc, no_error)<0)
3068 3069 3070 3071 3072 3073
      DBUG_RETURN(TRUE);
  }

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

  bzero((char*) &tables,sizeof(tables));
3074 3075
  tables[0].alias=tables[0].table_name= (char*) "user";
  tables[1].alias=tables[1].table_name= (char*) "procs_priv";
3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091
  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;
3092
    if (!tables_ok(thd, tables))
3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105
      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);
3106
  pthread_mutex_lock(&acl_cache->lock);
3107 3108 3109 3110 3111
  MEM_ROOT *old_root= thd->mem_root;
  thd->mem_root= &memex;

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

3112
  while ((tmp_Str= str_list++))
3113 3114 3115
  {
    int error;
    GRANT_NAME *grant_name;
3116 3117 3118 3119 3120
    if (!(Str= get_current_user(thd, tmp_Str)))
    {
      result= TRUE;
      continue;
    }  
3121 3122
    /* Create user if needed */
    error=replace_user_table(thd, tables[0].table, *Str,
serg@serg.mylan's avatar
serg@serg.mylan committed
3123
			     0, revoke_grant, create_new_users,
monty@mysql.com's avatar
monty@mysql.com committed
3124 3125
                             test(thd->variables.sql_mode &
                                  MODE_NO_AUTO_CREATE_USER));
3126 3127 3128 3129 3130 3131 3132
    if (error)
    {
      result= TRUE;				// Remember error
      continue;					// Add next user
    }

    db_name= table_list->db;
3133
    table_name= table_list->table_name;
3134

3135 3136
    grant_name= routine_hash_search(Str->host.str, NullS, db_name,
                                    Str->user.str, table_name, is_proc, 1);
3137 3138 3139 3140 3141 3142
    if (!grant_name)
    {
      if (revoke_grant)
      {
        if (!no_error)
          my_error(ER_NONEXISTING_PROC_GRANT, MYF(0),
3143
		   Str->user.str, Str->host.str, table_name);
3144 3145 3146 3147
	result= TRUE;
	continue;
      }
      grant_name= new GRANT_NAME(Str->host.str, db_name,
3148
				 Str->user.str, table_name,
3149 3150 3151 3152 3153 3154
				 rights);
      if (!grant_name)
      {
        result= TRUE;
	continue;
      }
3155
      my_hash_insert(is_proc ? &proc_priv_hash : &func_priv_hash,(byte*) grant_name);
3156
    }
3157

3158 3159
    if (replace_routine_table(thd, grant_name, tables[1].table, *Str,
			   db_name, table_name, is_proc, rights, revoke_grant))
3160 3161 3162 3163 3164 3165 3166
    {
      result= TRUE;
      continue;
    }
  }
  grant_option=TRUE;
  thd->mem_root= old_root;
3167
  pthread_mutex_unlock(&acl_cache->lock);
3168 3169 3170 3171 3172 3173 3174 3175 3176 3177
  if (!result && !no_error)
  {
    if (mysql_bin_log.is_open())
    {
      thd->clear_error();
      Query_log_event qinfo(thd, thd->query, thd->query_length, 0, FALSE);
      mysql_bin_log.write(&qinfo);
    }
  }

3178
  rw_unlock(&LOCK_grant);
3179

3180 3181
  if (!result && !no_error)
    send_ok(thd);
3182

3183 3184 3185 3186 3187
  /* Tables are automatically closed */
  DBUG_RETURN(result);
}


3188 3189
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
3190 3191
{
  List_iterator <LEX_USER> str_list (list);
3192
  LEX_USER *Str, *tmp_Str;
gluh@mysql.com/gluh.(none)'s avatar
gluh@mysql.com/gluh.(none) committed
3193
  char tmp_db[NAME_LEN+1];
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
3194
  bool create_new_users=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3195 3196 3197 3198
  TABLE_LIST tables[2];
  DBUG_ENTER("mysql_grant");
  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3199 3200
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0),
             "--skip-grant-tables");	/* purecov: tested */
3201
    DBUG_RETURN(TRUE);				/* purecov: tested */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3202 3203
  }

3204 3205 3206
  if (lower_case_table_names && db)
  {
    strmov(tmp_db,db);
3207
    my_casedn_str(files_charset_info, tmp_db);
3208 3209
    db=tmp_db;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3210 3211

  /* open the mysql.user and mysql.db tables */
3212
  bzero((char*) &tables,sizeof(tables));
3213 3214
  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
3215
  tables[0].next_local= tables[0].next_global= tables+1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3216 3217
  tables[0].lock_type=tables[1].lock_type=TL_WRITE;
  tables[0].db=tables[1].db=(char*) "mysql";
3218 3219 3220 3221 3222 3223

#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
3224 3225
  if (thd->slave_thread && table_rules_on)
  {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3226 3227 3228
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
3229
    */
3230
    tables[0].updating= tables[1].updating= 1;
3231
    if (!tables_ok(thd, tables))
3232
      DBUG_RETURN(FALSE);
3233
  }
3234 3235
#endif

3236
  if (simple_open_n_lock_tables(thd,tables))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3237 3238
  {						// This should never happen
    close_thread_tables(thd);			/* purecov: deadcode */
3239
    DBUG_RETURN(TRUE);				/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3240 3241
  }

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
3242 3243
  if (!revoke_grant)
    create_new_users= test_if_create_new_users(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3244

3245
  /* go through users in user_list */
3246
  rw_wrlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3247 3248 3249 3250
  VOID(pthread_mutex_lock(&acl_cache->lock));
  grant_version++;

  int result=0;
3251
  while ((tmp_Str = str_list++))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3252
  {
3253 3254 3255 3256
    if (!(Str= get_current_user(thd, tmp_Str)))
    {
      result= TRUE;
      continue;
gluh@mysql.com/gluh.(none)'s avatar
gluh@mysql.com/gluh.(none) committed
3257
    }
serg@serg.mylan's avatar
serg@serg.mylan committed
3258 3259
    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
3260 3261
                           test(thd->variables.sql_mode &
                                MODE_NO_AUTO_CREATE_USER)))
3262
      result= -1;
3263
    else if (db)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
3264
    {
3265 3266 3267 3268 3269 3270 3271 3272 3273
      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
3274
	my_error(ER_WRONG_USAGE, MYF(0), "DB GRANT", "GLOBAL PRIVILEGES");
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3275
	result= -1;
3276
      }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
3277
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3278 3279
  }
  VOID(pthread_mutex_unlock(&acl_cache->lock));
3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290

  if (!result)
  {
    if (mysql_bin_log.is_open())
    {
      thd->clear_error();
      Query_log_event qinfo(thd, thd->query, thd->query_length, 0, FALSE);
      mysql_bin_log.write(&qinfo);
    }
  }

3291
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3292 3293 3294
  close_thread_tables(thd);

  if (!result)
3295
    send_ok(thd);
3296

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3297 3298 3299
  DBUG_RETURN(result);
}

3300 3301

/* Free grant array if possible */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3302 3303 3304 3305 3306

void  grant_free(void)
{
  DBUG_ENTER("grant_free");
  grant_option = FALSE;
3307
  hash_free(&column_priv_hash);
3308
  hash_free(&proc_priv_hash);
monty@mysql.com's avatar
monty@mysql.com committed
3309
  hash_free(&func_priv_hash);
3310
  free_root(&memex,MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3311 3312 3313 3314
  DBUG_VOID_RETURN;
}


3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325
/*
  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
3326

3327
my_bool grant_init()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3328
{
3329
  THD  *thd;
3330 3331 3332 3333 3334
  my_bool return_val;
  DBUG_ENTER("grant_init");

  if (!(thd= new THD))
    DBUG_RETURN(1);				/* purecov: deadcode */
3335
  thd->thread_stack= (char*) &thd;
3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361
  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)
{
3362
  MEM_ROOT *memex_ptr;
3363
  my_bool return_val= 1;
3364
  TABLE *t_table, *c_table, *p_table;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
3365
  bool check_no_resolve= specialflag & SPECIAL_NO_RESOLVE;
3366 3367 3368
  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
3369 3370

  grant_option = FALSE;
3371
  (void) hash_init(&column_priv_hash,system_charset_info,
3372
		   0,0,0, (hash_get_key) get_grant_table,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3373
		   (hash_free_key) free_grant_table,0);
3374 3375 3376
  (void) hash_init(&proc_priv_hash,system_charset_info,
		   0,0,0, (hash_get_key) get_grant_table,
		   0,0);
3377 3378 3379
  (void) hash_init(&func_priv_hash,system_charset_info,
		   0,0,0, (hash_get_key) get_grant_table,
		   0,0);
3380
  init_sql_alloc(&memex, ACL_ALLOC_BLOCK_SIZE, 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3381 3382

  t_table = tables[0].table; c_table = tables[1].table;
3383
  p_table= tables[2].table;
3384
  t_table->file->ha_index_init(0);
3385 3386
  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
3387
  {
3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398
    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
3399

3400 3401
      if (check_no_resolve)
      {
3402
	if (hostname_requires_resolving(mem_check->host.hostname))
3403 3404 3405
	{
          sql_print_warning("'tables_priv' entry '%s %s@%s' "
                            "ignored in --skip-name-resolve mode.",
3406 3407 3408 3409
                            mem_check->tname,
                            mem_check->user ? mem_check->user : "",
                            mem_check->host.hostname ?
                            mem_check->host.hostname : "");
3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425
	  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
3426
  {
3427 3428 3429
    memex_ptr= &memex;
    my_pthread_setspecific_ptr(THR_MALLOC, &memex_ptr);
    do
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3430
    {
3431
      GRANT_NAME *mem_check;
3432
      HASH *hash;
3433 3434 3435 3436 3437 3438
      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
3439

3440
      if (check_no_resolve)
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
3441
      {
jimw@mysql.com's avatar
jimw@mysql.com committed
3442
	if (hostname_requires_resolving(mem_check->host.hostname))
3443 3444 3445 3446
	{
          sql_print_warning("'procs_priv' entry '%s %s@%s' "
                            "ignored in --skip-name-resolve mode.",
                            mem_check->tname, mem_check->user,
3447 3448
                            mem_check->host.hostname ?
                            mem_check->host.hostname : "");
3449 3450
	  continue;
	}
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
3451
      }
3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467
      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
3468

3469 3470 3471
      mem_check->privs= fix_rights_for_procedure(mem_check->privs);
      if (! mem_check->ok())
	delete mem_check;
3472
      else if (my_hash_insert(hash, (byte*) mem_check))
3473 3474 3475 3476 3477
      {
	delete mem_check;
	grant_option= FALSE;
	goto end_unlock;
      }
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
3478
    }
3479
    while (!p_table->file->index_next(p_table->record[0]));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3480
  }
3481
  grant_option= TRUE;
3482 3483 3484
  return_val=0;					// Return ok

end_unlock:
3485
  t_table->file->ha_index_end();
3486
  p_table->file->ha_index_end();
3487
  my_pthread_setspecific_ptr(THR_MALLOC, save_mem_root_ptr);
3488
  DBUG_RETURN(return_val);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3489 3490 3491
}


3492
/*
3493
  Reload information about table and column level privileges if possible.
3494 3495 3496

  SYNOPSIS
    grant_reload()
3497
      thd  Current thread
3498 3499

  NOTES
3500 3501 3502 3503 3504 3505 3506 3507
    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
3508
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3509

3510
my_bool grant_reload(THD *thd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3511
{
3512
  TABLE_LIST tables[3];
3513
  HASH old_column_priv_hash, old_proc_priv_hash, old_func_priv_hash;
3514
  bool old_grant_option;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3515
  MEM_ROOT old_mem;
3516
  my_bool return_val= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3517 3518
  DBUG_ENTER("grant_reload");

3519 3520 3521 3522 3523
  /* Don't do anything if running with --skip-grant-tables */
  if (!initialized)
    DBUG_RETURN(0);

  bzero((char*) tables, sizeof(tables));
3524 3525 3526 3527 3528 3529 3530
  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;
3531 3532 3533 3534 3535 3536 3537 3538

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

3539
  rw_wrlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3540
  grant_version++;
3541
  old_column_priv_hash= column_priv_hash;
3542
  old_proc_priv_hash= proc_priv_hash;
3543
  old_func_priv_hash= func_priv_hash;
3544
  old_grant_option= grant_option;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3545
  old_mem= memex;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3546

3547
  if ((return_val= grant_load(tables)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3548
  {						// Error. Revert to old hash
3549
    DBUG_PRINT("error",("Reverting to old privileges"));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3550
    grant_free();				/* purecov: deadcode */
3551
    column_priv_hash= old_column_priv_hash;	/* purecov: deadcode */
3552
    proc_priv_hash= old_proc_priv_hash;
3553
    func_priv_hash= old_func_priv_hash;
3554
    grant_option= old_grant_option;		/* purecov: deadcode */
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3555
    memex= old_mem;				/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3556 3557 3558
  }
  else
  {
3559
    hash_free(&old_column_priv_hash);
3560
    hash_free(&old_proc_priv_hash);
3561
    hash_free(&old_func_priv_hash);
3562
    free_root(&old_mem,MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3563
  }
3564
  rw_unlock(&LOCK_grant);
3565 3566 3567
end:
  close_thread_tables(thd);
  DBUG_RETURN(return_val);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3568 3569 3570 3571
}


/****************************************************************************
3572
  Check table level grants
3573

3574
  SYNOPSIS
3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587
   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
3588
     1  Error: User did not have the requested privileges
3589 3590 3591 3592 3593 3594 3595

   NOTE
     This functions assumes that either number of tables to be inspected
     by it is limited explicitly (i.e. is is not UINT_MAX) or table list
     used and thd->lex->query_tables_own_last value correspond to each
     other (the latter should be either 0 or point to next_global member
     of one of elements of this table list).
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3596 3597
****************************************************************************/

3598
bool check_grant(THD *thd, ulong want_access, TABLE_LIST *tables,
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3599
		 uint show_table, uint number, bool no_errors)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3600
{
3601
  TABLE_LIST *table, *first_not_own_table= thd->lex->first_not_own_table();
3602
  Security_context *sctx= thd->security_ctx;
3603
  uint i;
3604
  ulong orig_want_access= want_access;
3605 3606
  DBUG_ENTER("check_grant");
  DBUG_ASSERT(number > 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3607

3608
  /*
3609 3610 3611 3612 3613 3614 3615 3616
    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.
3617 3618
  */
  for (i= 0, table= tables;
3619
       table != first_not_own_table && i < number;
3620 3621 3622 3623 3624 3625
       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);
  }

3626
  rw_rdlock(&LOCK_grant);
3627 3628 3629
  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
3630
  {
3631
    GRANT_TABLE *grant_table;
3632 3633 3634 3635 3636 3637 3638 3639
    sctx = test(table->security_ctx) ?
      table->security_ctx : thd->security_ctx;

    want_access= orig_want_access;
    want_access&= ~sctx->master_access;
    if (!want_access)
      continue;                                 // ok

3640
    if (!(~table->grant.privilege & want_access) || 
3641
        table->derived || table->schema_table)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3642
    {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3643 3644 3645 3646
      /*
        It is subquery in the FROM clause. VIEW set table->derived after
        table opening, but this function always called before table opening.
      */
3647 3648 3649 3650 3651 3652 3653 3654 3655 3656
      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
3657
    }
3658 3659 3660
    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
3661 3662 3663 3664
    {
      want_access &= ~table->grant.privilege;
      goto err;					// No grants
    }
monty@tramp.mysql.fi's avatar
monty@tramp.mysql.fi committed
3665 3666
    if (show_table)
      continue;					// We have some priv on this
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682

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

3686
err:
3687
  rw_unlock(&LOCK_grant);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
3688
  if (!no_errors)				// Not a silent skip of table
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3689
  {
3690 3691
    char command[128];
    get_privilege_desc(command, sizeof(command), want_access);
3692 3693
    my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0),
             command,
3694 3695
             sctx->priv_user,
             sctx->host_or_ip,
3696
             table ? table->table_name : "unknown");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3697
  }
3698
  DBUG_RETURN(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3699 3700 3701
}


3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719
/*
  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
3720
bool check_grant_column(THD *thd, GRANT_INFO *grant,
3721
			const char *db_name, const char *table_name,
3722
			const char *name, uint length,  Security_context *sctx)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3723 3724 3725
{
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3726
  ulong want_access= grant->want_privilege & ~grant->privilege;
monty@mysql.com's avatar
monty@mysql.com committed
3727
  DBUG_ENTER("check_grant_column");
3728
  DBUG_PRINT("enter", ("table: %s  want_access: %lu", table_name, want_access));
monty@mysql.com's avatar
monty@mysql.com committed
3729

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3730
  if (!want_access)
monty@mysql.com's avatar
monty@mysql.com committed
3731
    DBUG_RETURN(0);				// Already checked
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3732

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

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

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3737
  if (grant->version != grant_version)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3738
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3739
    grant->grant_table=
3740 3741
      table_hash_search(sctx->host, sctx->ip, db_name,
			sctx->priv_user,
monty@mysql.com's avatar
monty@mysql.com committed
3742
			table_name, 0);         /* purecov: inspected */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3743
    grant->version= grant_version;		/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3744
  }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3745
  if (!(grant_table= grant->grant_table))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3746 3747 3748 3749 3750
    goto err;					/* purecov: deadcode */

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

3755
err:
3756
  rw_unlock(&LOCK_grant);
3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800
  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
3801
  {
3802
    /* View or derived information schema table. */
3803
    ulong view_privs;
3804 3805 3806
    grant= &(table_ref->grant);
    db_name= table_ref->view_db.str;
    table_name= table_ref->view_name.str;
3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820
    if (table_ref->belong_to_view && 
        (thd->lex->sql_command == SQLCOM_SHOW_FIELDS ||
         thd->lex->sql_command == SQLCOM_SHOW_CREATE))
    {
      view_privs= get_column_grant(thd, grant, db_name, table_name, name);
      if (view_privs & VIEW_ANY_ACL)
      {
        table_ref->belong_to_view->allowed_show= TRUE;
        return FALSE;
      }
      table_ref->belong_to_view->allowed_show= FALSE;
      my_message(ER_VIEW_NO_EXPLAIN, ER(ER_VIEW_NO_EXPLAIN), MYF(0));
      return TRUE;
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3821
  }
3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836
  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
3837 3838 3839
}


bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3840
bool check_grant_all_columns(THD *thd, ulong want_access, GRANT_INFO *grant,
3841
                             const char* db_name, const char *table_name,
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3842
                             Field_iterator *fields)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3843
{
3844
  Security_context *sctx= thd->security_ctx;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3845 3846 3847
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3848
  want_access &= ~grant->privilege;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3849
  if (!want_access)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3850
    return 0;				// Already checked
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3851 3852
  if (!grant_option)
    goto err2;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3853

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

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

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3858
  if (grant->version != grant_version)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3859
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3860
    grant->grant_table=
3861 3862
      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
3863 3864
			table_name, 0);	/* purecov: inspected */
    grant->version= grant_version;		/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3865
  }
3866
  /* The following should always be true */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3867
  if (!(grant_table= grant->grant_table))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3868 3869
    goto err;					/* purecov: inspected */

3870
  for (; !fields->end_of_fields(); fields->next())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3871
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3872 3873 3874
    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
3875 3876 3877
    if (!grant_column || (~grant_column->rights & want_access))
      goto err;
  }
3878
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3879 3880
  return 0;

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3881
err:
3882
  rw_unlock(&LOCK_grant);
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3883
err2:
3884 3885
  char command[128];
  get_privilege_desc(command, sizeof(command), want_access);
3886 3887
  my_error(ER_COLUMNACCESS_DENIED_ERROR, MYF(0),
           command,
3888 3889
           sctx->priv_user,
           sctx->host_or_ip,
3890 3891
           fields->name(),
           table_name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3892 3893 3894 3895
  return 1;
}


3896
/*
3897
  Check if a user has the right to access a database
3898
  Access is accepted if he has a grant for any table/routine in the database
3899
  Return 1 if access is denied
3900
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3901 3902 3903

bool check_grant_db(THD *thd,const char *db)
{
3904
  Security_context *sctx= thd->security_ctx;
gluh@mysql.com/gluh.(none)'s avatar
gluh@mysql.com/gluh.(none) committed
3905
  char helping [NAME_LEN+USERNAME_LENGTH+2];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3906
  uint len;
3907
  bool error= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3908

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

3912
  for (uint idx=0 ; idx < column_priv_hash.records ; idx++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3913
  {
3914 3915
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  idx);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3916 3917
    if (len < grant_table->key_length &&
	!memcmp(grant_table->hash_key,helping,len) &&
3918
        compare_hostname(&grant_table->host, sctx->host, sctx->ip))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3919 3920 3921 3922 3923
    {
      error=0;					// Found match
      break;
    }
  }
3924
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3925 3926 3927
  return error;
}

3928 3929

/****************************************************************************
3930
  Check routine level grants
3931 3932

  SYNPOSIS
3933
   bool check_grant_routine()
3934 3935
   thd		Thread handler
   want_access  Bits of privileges user needs to have
3936 3937
   procs	List of routines to check. The user should have 'want_access'
   is_proc	True if the list is all procedures, else functions
3938 3939 3940 3941 3942 3943 3944 3945
   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
****************************************************************************/

3946
bool check_grant_routine(THD *thd, ulong want_access,
3947
			 TABLE_LIST *procs, bool is_proc, bool no_errors)
3948 3949
{
  TABLE_LIST *table;
3950
  Security_context *sctx= thd->security_ctx;
3951 3952
  char *user= sctx->priv_user;
  char *host= sctx->priv_host;
3953
  DBUG_ENTER("check_grant_routine");
3954

3955
  want_access&= ~sctx->master_access;
3956 3957 3958 3959 3960 3961 3962
  if (!want_access)
    DBUG_RETURN(0);                             // ok

  rw_rdlock(&LOCK_grant);
  for (table= procs; table; table= table->next_global)
  {
    GRANT_NAME *grant_proc;
3963
    if ((grant_proc= routine_hash_search(host, sctx->ip, table->db, user,
3964
					 table->table_name, is_proc, 0)))
3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981
      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)
3982
      strxmov(buff, table->db, ".", table->table_name, NullS);
3983 3984 3985
    if (want_access & EXECUTE_ACL)
      command= "execute";
    else if (want_access & ALTER_PROC_ACL)
3986
      command= "alter routine";
3987 3988 3989 3990 3991 3992 3993 3994 3995
    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);
}


3996 3997
/*
  Check if routine has any of the 
3998
  routine level grants
3999 4000 4001 4002 4003 4004 4005 4006 4007
  
  SYNPOSIS
   bool    check_routine_level_acl()
   thd	        Thread handler
   db           Database name
   name         Routine name

  RETURN
   0            Ok 
4008
   1            error
4009 4010
*/

acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
4011 4012
bool check_routine_level_acl(THD *thd, const char *db, const char *name, 
                             bool is_proc)
4013 4014 4015 4016 4017
{
  bool no_routine_acl= 1;
  if (grant_option)
  {
    GRANT_NAME *grant_proc;
4018
    Security_context *sctx= thd->security_ctx;
4019
    rw_rdlock(&LOCK_grant);
4020 4021 4022
    if ((grant_proc= routine_hash_search(sctx->priv_host,
                                         sctx->ip, db,
                                         sctx->priv_user,
4023
                                         name, is_proc, 0)))
4024 4025 4026 4027 4028 4029 4030
      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
4031
/*****************************************************************************
4032
  Functions to retrieve the grant for a table/column  (for SHOW functions)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4033 4034
*****************************************************************************/

4035
ulong get_table_grant(THD *thd, TABLE_LIST *table)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4036
{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4037
  ulong privilege;
4038
  Security_context *sctx= thd->security_ctx;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4039 4040 4041
  const char *db = table->db ? table->db : thd->db;
  GRANT_TABLE *grant_table;

4042
  rw_rdlock(&LOCK_grant);
4043 4044 4045
#ifdef EMBEDDED_LIBRARY
  grant_table= NULL;
#else
4046
  grant_table= table_hash_search(sctx->host, sctx->ip, db, sctx->priv_user,
4047
				 table->table_name, 0);
4048
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4049 4050 4051 4052
  table->grant.grant_table=grant_table; // Remember for column test
  table->grant.version=grant_version;
  if (grant_table)
    table->grant.privilege|= grant_table->privs;
4053
  privilege= table->grant.privilege;
4054
  rw_unlock(&LOCK_grant);
4055
  return privilege;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4056 4057 4058
}


4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076
/*
  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
4077 4078 4079
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
4080 4081 4082
{
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;
4083
  ulong priv;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4084

4085
  rw_rdlock(&LOCK_grant);
4086
  /* reload table if someone has modified any grants */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4087
  if (grant->version != grant_version)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4088
  {
4089
    Security_context *sctx= thd->security_ctx;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4090
    grant->grant_table=
4091 4092
      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
4093 4094
			table_name, 0);	        /* purecov: inspected */
    grant->version= grant_version;              /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4095 4096
  }

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4097 4098
  if (!(grant_table= grant->grant_table))
    priv= grant->privilege;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4099 4100
  else
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4101 4102
    grant_column= column_hash_search(grant_table, field_name,
                                     (uint) strlen(field_name));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4103
    if (!grant_column)
4104
      priv= (grant->privilege | grant_table->privs);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4105
    else
4106
      priv= (grant->privilege | grant_table->privs | grant_column->rights);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4107
  }
4108
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4109 4110 4111
  return priv;
}

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

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

4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126
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
4127 4128

static const char *command_array[]=
4129
{
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4130 4131 4132 4133
  "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",
4134
  "CREATE VIEW", "SHOW VIEW", "CREATE ROUTINE", "ALTER ROUTINE",
4135
  "CREATE USER"
4136
};
4137

4138 4139
static uint command_lengths[]=
{
4140 4141
  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
4142 4143
};

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

4145 4146 4147 4148 4149
static int show_routine_grants(THD *thd, LEX_USER *lex_user, HASH *hash,
                               const char *type, int typelen,
                               char *buff, int buffsize);


4150 4151 4152 4153 4154 4155 4156
/*
  SHOW GRANTS;  Send grants for a user to the client

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

4157
bool mysql_show_grants(THD *thd,LEX_USER *lex_user)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4158
{
4159 4160
  ulong want_access;
  uint counter,index;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4161
  int  error = 0;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4162 4163
  ACL_USER *acl_user;
  ACL_DB *acl_db;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4164
  char buff[1024];
4165
  Protocol *protocol= thd->protocol;
tonu@x153.internalnet's avatar
tonu@x153.internalnet committed
4166
  DBUG_ENTER("mysql_show_grants");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4167 4168 4169 4170

  LINT_INIT(acl_user);
  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
4171
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
4172
    DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4173
  }
monty@mysql.com's avatar
monty@mysql.com committed
4174

4175 4176 4177 4178 4179
  rw_rdlock(&LOCK_grant);
  VOID(pthread_mutex_lock(&acl_cache->lock));

  acl_user= find_acl_user(lex_user->host.str, lex_user->user.str, TRUE);
  if (!acl_user)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4180
  {
4181 4182 4183
    VOID(pthread_mutex_unlock(&acl_cache->lock));
    rw_unlock(&LOCK_grant);

guilhem@mysql.com's avatar
guilhem@mysql.com committed
4184 4185
    my_error(ER_NONEXISTING_GRANT, MYF(0),
             lex_user->user.str, lex_user->host.str);
4186
    DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4187 4188
  }

4189
  Item_string *field=new Item_string("",0,&my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4190 4191 4192 4193 4194 4195
  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);
4196 4197
  if (protocol->send_fields(&field_list,
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
4198 4199 4200
  {
    VOID(pthread_mutex_unlock(&acl_cache->lock));
    rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4201

4202 4203
    DBUG_RETURN(TRUE);
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4204 4205 4206

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

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4211
    want_access= acl_user->access;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4212
    if (test_all_bits(want_access, (GLOBAL_ACLS & ~ GRANT_ACL)))
4213
      global.append(STRING_WITH_LEN("ALL PRIVILEGES"));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4214
    else if (!(want_access & ~GRANT_ACL))
4215
      global.append(STRING_WITH_LEN("USAGE"));
peter@mysql.com's avatar
peter@mysql.com committed
4216
    else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4217 4218
    {
      bool found=0;
4219
      ulong j,test_access= want_access & ~GRANT_ACL;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4220 4221
      for (counter=0, j = SELECT_ACL;j <= GLOBAL_ACLS;counter++,j <<= 1)
      {
peter@mysql.com's avatar
peter@mysql.com committed
4222
	if (test_access & j)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4223 4224
	{
	  if (found)
4225
	    global.append(STRING_WITH_LEN(", "));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4226 4227 4228 4229 4230
	  found=1;
	  global.append(command_array[counter],command_lengths[counter]);
	}
      }
    }
4231
    global.append (STRING_WITH_LEN(" ON *.* TO '"));
4232 4233
    global.append(lex_user->user.str, lex_user->user.length,
		  system_charset_info);
4234
    global.append (STRING_WITH_LEN("'@'"));
4235 4236
    global.append(lex_user->host.str,lex_user->host.length,
		  system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4237
    global.append ('\'');
4238
    if (acl_user->salt_len)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4239
    {
4240 4241 4242 4243 4244
      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);
4245
      global.append(STRING_WITH_LEN(" IDENTIFIED BY PASSWORD '"));
4246
      global.append(passwd_buff);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4247 4248
      global.append('\'');
    }
4249 4250
    /* "show grants" SSL related stuff */
    if (acl_user->ssl_type == SSL_TYPE_ANY)
4251
      global.append(STRING_WITH_LEN(" REQUIRE SSL"));
4252
    else if (acl_user->ssl_type == SSL_TYPE_X509)
4253
      global.append(STRING_WITH_LEN(" REQUIRE X509"));
4254
    else if (acl_user->ssl_type == SSL_TYPE_SPECIFIED)
4255
    {
4256
      int ssl_options = 0;
4257
      global.append(STRING_WITH_LEN(" REQUIRE "));
4258 4259
      if (acl_user->x509_issuer)
      {
4260
	ssl_options++;
4261
	global.append(STRING_WITH_LEN("ISSUER \'"));
4262
	global.append(acl_user->x509_issuer,strlen(acl_user->x509_issuer));
4263
	global.append('\'');
4264
      }
4265 4266
      if (acl_user->x509_subject)
      {
4267 4268
	if (ssl_options++)
	  global.append(' ');
4269
	global.append(STRING_WITH_LEN("SUBJECT \'"));
4270 4271
	global.append(acl_user->x509_subject,strlen(acl_user->x509_subject),
                      system_charset_info);
4272
	global.append('\'');
tonu@x153.internalnet's avatar
tonu@x153.internalnet committed
4273
      }
4274 4275
      if (acl_user->ssl_cipher)
      {
4276 4277
	if (ssl_options++)
	  global.append(' ');
4278
	global.append(STRING_WITH_LEN("CIPHER '"));
4279 4280
	global.append(acl_user->ssl_cipher,strlen(acl_user->ssl_cipher),
                      system_charset_info);
4281
	global.append('\'');
4282 4283
      }
    }
4284
    if ((want_access & GRANT_ACL) ||
4285 4286 4287 4288
	(acl_user->user_resource.questions ||
         acl_user->user_resource.updates ||
         acl_user->user_resource.conn_per_hour ||
         acl_user->user_resource.user_conn))
4289
    {
4290
      global.append(STRING_WITH_LEN(" WITH"));
4291
      if (want_access & GRANT_ACL)
4292
	global.append(STRING_WITH_LEN(" GRANT OPTION"));
4293 4294 4295 4296
      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");
4297
      add_user_option(&global, acl_user->user_resource.conn_per_hour,
4298
		      "MAX_CONNECTIONS_PER_HOUR");
4299 4300
      add_user_option(&global, acl_user->user_resource.user_conn,
		      "MAX_USER_CONNECTIONS");
4301
    }
4302
    protocol->prepare_for_resend();
4303
    protocol->store(global.ptr(),global.length(),global.charset());
4304
    if (protocol->write())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4305
    {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4306
      error= -1;
4307
      goto end;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4308 4309 4310 4311 4312 4313
    }
  }

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

    acl_db=dynamic_element(&acl_dbs,counter,ACL_DB*);
    if (!(user=acl_db->user))
monty@mysql.com's avatar
monty@mysql.com committed
4318
      user= "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4319
    if (!(host=acl_db->host.hostname))
monty@mysql.com's avatar
monty@mysql.com committed
4320
      host= "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4321 4322

    if (!strcmp(lex_user->user.str,user) &&
4323
	!my_strcasecmp(system_charset_info, lex_user->host.str, host))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4324 4325
    {
      want_access=acl_db->access;
peter@mysql.com's avatar
peter@mysql.com committed
4326
      if (want_access)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4327
      {
4328
	String db(buff,sizeof(buff),system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4329
	db.length(0);
4330
	db.append(STRING_WITH_LEN("GRANT "));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4331 4332

	if (test_all_bits(want_access,(DB_ACLS & ~GRANT_ACL)))
4333
	  db.append(STRING_WITH_LEN("ALL PRIVILEGES"));
4334
	else if (!(want_access & ~GRANT_ACL))
4335
	  db.append(STRING_WITH_LEN("USAGE"));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4336 4337 4338
	else
	{
	  int found=0, cnt;
4339
	  ulong j,test_access= want_access & ~GRANT_ACL;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4340 4341 4342 4343 4344
	  for (cnt=0, j = SELECT_ACL; j <= DB_ACLS; cnt++,j <<= 1)
	  {
	    if (test_access & j)
	    {
	      if (found)
4345
		db.append(STRING_WITH_LEN(", "));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4346 4347 4348 4349 4350
	      found = 1;
	      db.append(command_array[cnt],command_lengths[cnt]);
	    }
	  }
	}
4351
	db.append (STRING_WITH_LEN(" ON "));
4352
	append_identifier(thd, &db, acl_db->db, strlen(acl_db->db));
4353
	db.append (STRING_WITH_LEN(".* TO '"));
4354 4355
	db.append(lex_user->user.str, lex_user->user.length,
		  system_charset_info);
4356
	db.append (STRING_WITH_LEN("'@'"));
4357 4358
	db.append(lex_user->host.str, lex_user->host.length,
                  system_charset_info);
peter@mysql.com's avatar
peter@mysql.com committed
4359
	db.append ('\'');
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4360
	if (want_access & GRANT_ACL)
4361
	  db.append(STRING_WITH_LEN(" WITH GRANT OPTION"));
4362
	protocol->prepare_for_resend();
4363
	protocol->store(db.ptr(),db.length(),db.charset());
4364
	if (protocol->write())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4365
	{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4366
	  error= -1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4367 4368 4369 4370 4371 4372
	  goto end;
	}
      }
    }
  }

4373
  /* Add table & column access */
4374
  for (index=0 ; index < column_priv_hash.records ; index++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4375
  {
4376
    const char *user, *host;
4377 4378
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  index);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4379 4380

    if (!(user=grant_table->user))
4381
      user= "";
4382 4383
    if (!(host= grant_table->host.hostname))
      host= "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4384 4385

    if (!strcmp(lex_user->user.str,user) &&
4386
	!my_strcasecmp(system_charset_info, lex_user->host.str, host))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4387
    {
4388 4389
      ulong table_access= grant_table->privs;
      if ((table_access | grant_table->cols) != 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4390
      {
4391
	String global(buff, sizeof(buff), system_charset_info);
4392 4393
	ulong test_access= (table_access | grant_table->cols) & ~GRANT_ACL;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
4394
	global.length(0);
4395
	global.append(STRING_WITH_LEN("GRANT "));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4396

4397
	if (test_all_bits(table_access, (TABLE_ACLS & ~GRANT_ACL)))
4398
	  global.append(STRING_WITH_LEN("ALL PRIVILEGES"));
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4399
	else if (!test_access)
4400
	  global.append(STRING_WITH_LEN("USAGE"));
peter@mysql.com's avatar
peter@mysql.com committed
4401
	else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4402
	{
4403
          /* Add specific column access */
4404
	  int found= 0;
4405
	  ulong j;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4406

4407
	  for (counter= 0, j= SELECT_ACL; j <= TABLE_ACLS; counter++, j<<= 1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4408
	  {
peter@mysql.com's avatar
peter@mysql.com committed
4409
	    if (test_access & j)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4410 4411
	    {
	      if (found)
4412
		global.append(STRING_WITH_LEN(", "));
4413
	      found= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4414 4415
	      global.append(command_array[counter],command_lengths[counter]);

peter@mysql.com's avatar
peter@mysql.com committed
4416
	      if (grant_table->cols)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4417
	      {
4418
		uint found_col= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4419 4420 4421 4422 4423 4424
		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
4425
		  if (grant_column->rights & j)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4426
		  {
peter@mysql.com's avatar
peter@mysql.com committed
4427
		    if (!found_col)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4428
		    {
4429 4430 4431 4432 4433 4434 4435
		      found_col= 1;
		      /*
			If we have a duplicated table level privilege, we
			must write the access privilege name again.
		      */
		      if (table_access & j)
		      {
4436
			global.append(STRING_WITH_LEN(", "));
4437 4438 4439
			global.append(command_array[counter],
				      command_lengths[counter]);
		      }
4440
		      global.append(STRING_WITH_LEN(" ("));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4441 4442
		    }
		    else
4443
		      global.append(STRING_WITH_LEN(", "));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4444
		    global.append(grant_column->column,
4445 4446
				  grant_column->key_length,
				  system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4447 4448 4449 4450 4451 4452 4453 4454
		  }
		}
		if (found_col)
		  global.append(')');
	      }
	    }
	  }
	}
4455
	global.append(STRING_WITH_LEN(" ON "));
4456 4457 4458 4459 4460
	append_identifier(thd, &global, grant_table->db,
			  strlen(grant_table->db));
	global.append('.');
	append_identifier(thd, &global, grant_table->tname,
			  strlen(grant_table->tname));
4461
	global.append(STRING_WITH_LEN(" TO '"));
4462 4463
	global.append(lex_user->user.str, lex_user->user.length,
		      system_charset_info);
4464
	global.append(STRING_WITH_LEN("'@'"));
4465 4466
	global.append(lex_user->host.str,lex_user->host.length,
		      system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4467
	global.append('\'');
4468
	if (table_access & GRANT_ACL)
4469
	  global.append(STRING_WITH_LEN(" WITH GRANT OPTION"));
4470
	protocol->prepare_for_resend();
4471
	protocol->store(global.ptr(),global.length(),global.charset());
4472
	if (protocol->write())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4473
	{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4474
	  error= -1;
4475
	  break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4476 4477 4478 4479
	}
      }
    }
  }
4480

4481
  if (show_routine_grants(thd, lex_user, &proc_priv_hash, 
4482
                          STRING_WITH_LEN("PROCEDURE"), buff, sizeof(buff)))
4483 4484 4485 4486 4487 4488
  {
    error= -1;
    goto end;
  }

  if (show_routine_grants(thd, lex_user, &func_priv_hash,
4489
                          STRING_WITH_LEN("FUNCTION"), buff, sizeof(buff)))
4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511
  {
    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++)
4512
  {
4513
    const char *user, *host;
4514
    GRANT_NAME *grant_proc= (GRANT_NAME*) hash_element(hash, index);
4515 4516 4517

    if (!(user=grant_proc->user))
      user= "";
4518 4519
    if (!(host= grant_proc->host.hostname))
      host= "";
4520 4521

    if (!strcmp(lex_user->user.str,user) &&
4522
	!my_strcasecmp(system_charset_info, lex_user->host.str, host))
4523 4524 4525 4526
    {
      ulong proc_access= grant_proc->privs;
      if (proc_access != 0)
      {
4527
	String global(buff, buffsize, system_charset_info);
4528 4529 4530
	ulong test_access= proc_access & ~GRANT_ACL;

	global.length(0);
4531
	global.append(STRING_WITH_LEN("GRANT "));
4532 4533

	if (!test_access)
4534
 	  global.append(STRING_WITH_LEN("USAGE"));
4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545
	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)
4546
		global.append(STRING_WITH_LEN(", "));
4547 4548 4549 4550 4551
	      found= 1;
	      global.append(command_array[counter],command_lengths[counter]);
	    }
	  }
	}
4552
	global.append(STRING_WITH_LEN(" ON "));
4553 4554
        global.append(type,typelen);
        global.append(' ');
4555 4556 4557 4558 4559
	append_identifier(thd, &global, grant_proc->db,
			  strlen(grant_proc->db));
	global.append('.');
	append_identifier(thd, &global, grant_proc->tname,
			  strlen(grant_proc->tname));
4560
	global.append(STRING_WITH_LEN(" TO '"));
4561 4562
	global.append(lex_user->user.str, lex_user->user.length,
		      system_charset_info);
4563
	global.append(STRING_WITH_LEN("'@'"));
4564 4565 4566 4567
	global.append(lex_user->host.str,lex_user->host.length,
		      system_charset_info);
	global.append('\'');
	if (proc_access & GRANT_ACL)
4568
	  global.append(STRING_WITH_LEN(" WITH GRANT OPTION"));
4569 4570 4571 4572 4573 4574 4575 4576 4577 4578
	protocol->prepare_for_resend();
	protocol->store(global.ptr(),global.length(),global.charset());
	if (protocol->write())
	{
	  error= -1;
	  break;
	}
      }
    }
  }
4579
  return error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4580 4581
}

4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609
/*
  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;
}


4610
void get_mqh(const char *user, const char *host, USER_CONN *uc)
4611 4612
{
  ACL_USER *acl_user;
4613 4614 4615

  pthread_mutex_lock(&acl_cache->lock);

4616
  if (initialized && (acl_user= find_acl_user(host,user, FALSE)))
4617 4618 4619
    uc->user_resources= acl_user->user_resource;
  else
    bzero((char*) &uc->user_resources, sizeof(uc->user_resources));
4620 4621

  pthread_mutex_unlock(&acl_cache->lock);
4622 4623
}

4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644
/*
  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.
*/

4645
#define GRANT_TABLES 5
4646 4647 4648 4649 4650 4651
int open_grant_tables(THD *thd, TABLE_LIST *tables)
{
  DBUG_ENTER("open_grant_tables");

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

4656
  bzero((char*) tables, GRANT_TABLES*sizeof(*tables));
4657 4658 4659 4660 4661
  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
4662 4663 4664
  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;
4665
  (tables+3)->next_local= (tables+3)->next_global= tables+4;
4666
  tables->lock_type= (tables+1)->lock_type=
4667 4668 4669 4670
    (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";
4671 4672 4673 4674 4675 4676

#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
4677 4678
  if (thd->slave_thread && table_rules_on)
  {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4679 4680 4681
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
4682
    */
4683 4684
    tables[0].updating=tables[1].updating=tables[2].updating=
      tables[3].updating=tables[4].updating=1;
4685
    if (!tables_ok(thd, tables))
4686
      DBUG_RETURN(1);
4687 4688
    tables[0].updating=tables[1].updating=tables[2].updating=
      tables[3].updating=tables[4].updating=0;;
4689
  }
4690 4691
#endif

4692
  if (simple_open_n_lock_tables(thd, tables))
4693 4694 4695 4696 4697 4698 4699 4700 4701
  {						// 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
4702
			 uint *acl_acl_userdx)
4703 4704 4705 4706
{
  ACL_USER *acl_user= 0;
  uint counter;

4707 4708
  safe_mutex_assert_owner(&acl_cache->lock);

4709 4710 4711 4712 4713
  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
4714
      user= "";
4715
    if (!(host=acl_user->host.hostname))
4716
      host= "";
4717 4718 4719 4720 4721 4722 4723
    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
4724
  *acl_acl_userdx= counter;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4725
  return acl_user;
4726
}
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4727

4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749
/*
  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)
4750
{
4751 4752
  int error;
  DBUG_ENTER("modify_grant_table");
4753

4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770
  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));
  }
4771

4772 4773
  DBUG_RETURN(error);
}
4774

4775 4776 4777 4778 4779 4780
/*
  Handle a privilege table.

  SYNOPSIS
    handle_grant_table()
    tables                      The array with the four open tables.
4781
    table_no                    The number of the table to handle (0..4).
4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798
    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
4799
    4 procs_priv
4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818

  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;
4819
  byte user_key[MAX_KEY_LENGTH];
4820
  uint key_prefix_length;
4821 4822
  DBUG_ENTER("handle_grant_table");

4823
  if (! table_no) // mysql.user table
4824
  {
4825 4826 4827 4828 4829 4830 4831 4832 4833 4834
    /*
      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'",
4835
                       table->s->table_name, user_str, host_str));
4836 4837
    host_field->store(host_str, user_from->host.length, system_charset_info);
    user_field->store(user_str, user_from->user.length, system_charset_info);
4838 4839 4840 4841 4842

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

4843
    if ((error= table->file->index_read_idx(table->record[0], 0,
4844
                                            user_key, key_prefix_length,
4845
                                            HA_READ_KEY_EXACT)))
4846
    {
4847 4848 4849 4850 4851
      if (error != HA_ERR_KEY_NOT_FOUND)
      {
        table->file->print_error(error, MYF(0));
        result= -1;
      }
4852
    }
4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869
    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)))
4870
    {
4871
      table->file->print_error(error, MYF(0));
4872
      result= -1;
4873 4874 4875 4876 4877
    }
    else
    {
#ifdef EXTRA_DEBUG
      DBUG_PRINT("info",("scan table: '%s'  search: '%s'@'%s'",
4878
                         table->s->table_name, user_str, host_str));
4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926
#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()
4927
    struct_no                   The number of the structure to handle (0..3).
4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942
    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
4943
    3 procs_priv_hash
4944 4945 4946 4947

  RETURN
    > 0         At least one element matched.
    0           OK, but no element matched.
4948
    -1		Wrong arguments to function
4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960
*/

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

4966 4967
  LINT_INIT(acl_user);
  LINT_INIT(acl_db);
4968
  LINT_INIT(grant_name);
4969

4970 4971
  safe_mutex_assert_owner(&acl_cache->lock);

4972
  /* Get the number of elements in the in-memory structure. */
4973
  switch (struct_no) {
4974 4975 4976 4977 4978 4979
  case 0:
    elements= acl_users.elements;
    break;
  case 1:
    elements= acl_dbs.elements;
    break;
4980
  case 2:
4981
    elements= column_priv_hash.records;
4982 4983 4984 4985 4986 4987
    break;
  case 3:
    elements= proc_priv_hash.records;
    break;
  default:
    return -1;
4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999
  }

#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.
    */
5000
    switch (struct_no) {
5001 5002 5003
    case 0:
      acl_user= dynamic_element(&acl_users, idx, ACL_USER*);
      user= acl_user->user;
5004 5005
      host= acl_user->host.hostname;
    break;
5006 5007 5008 5009

    case 1:
      acl_db= dynamic_element(&acl_dbs, idx, ACL_DB*);
      user= acl_db->user;
5010
      host= acl_db->host.hostname;
5011 5012
      break;

5013 5014 5015
    case 2:
      grant_name= (GRANT_NAME*) hash_element(&column_priv_hash, idx);
      user= grant_name->user;
5016
      host= grant_name->host.hostname;
5017 5018 5019 5020 5021
      break;

    case 3:
      grant_name= (GRANT_NAME*) hash_element(&proc_priv_hash, idx);
      user= grant_name->user;
5022
      host= grant_name->host.hostname;
5023
      break;
5024 5025
    default:
      assert(0);
5026 5027
    }
    if (! user)
5028
      user= "";
5029 5030 5031
    if (! host)
      host= "";

5032 5033 5034 5035 5036 5037
#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))
5038
      continue;
5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052

    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;

5053 5054 5055 5056 5057 5058 5059
      case 2:
        hash_delete(&column_priv_hash, (byte*) grant_name);
	break;

      case 3:
        hash_delete(&proc_priv_hash, (byte*) grant_name);
	break;
5060 5061 5062
      }
      elements--;
      idx--;
5063
    }
5064 5065
    else if ( user_to )
    {
5066
      switch ( struct_no ) {
5067 5068 5069 5070
      case 0:
        acl_user->user= strdup_root(&mem, user_to->user.str);
        acl_user->host.hostname= strdup_root(&mem, user_to->host.str);
        break;
5071

5072 5073 5074 5075 5076
      case 1:
        acl_db->user= strdup_root(&mem, user_to->user.str);
        acl_db->host.hostname= strdup_root(&mem, user_to->host.str);
        break;

5077 5078 5079
      case 2:
      case 3:
        grant_name->user= strdup_root(&mem, user_to->user.str);
5080 5081
        update_hostname(&grant_name->host,
                        strdup_root(&mem, user_to->host.str));
5082
	break;
5083 5084 5085
      }
    }
    else
5086
    {
5087 5088 5089 5090 5091 5092 5093
      /* 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
5094

5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138
  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. */
5139 5140
    if ((handle_grant_struct(0, drop, user_from, user_to) && ! result) ||
        found)
5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167
    {
      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;
    }
  }

5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186
  /* 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;
    }
  }

5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200
  /* 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;
5201
    }
5202 5203 5204

    /* Handle columns table. */
    if ((found= handle_grant_table(tables, 3, drop, user_from, user_to)) < 0)
5205
    {
5206
      /* Handle of table failed, don't touch the in-memory array. */
5207 5208
      result= -1;
    }
5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220
    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);
}

5221

5222 5223 5224 5225 5226 5227
static void append_user(String *str, LEX_USER *user)
{
  if (str->length())
    str->append(',');
  str->append('\'');
  str->append(user->user.str);
5228
  str->append(STRING_WITH_LEN("'@'"));
5229 5230 5231
  str->append(user->host.str);
  str->append('\'');
}
5232

5233

5234 5235 5236 5237 5238 5239 5240
/*
  Create a list of users.

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

5242 5243 5244 5245 5246 5247 5248 5249
  RETURN
    FALSE       OK.
    TRUE        Error.
*/

bool mysql_create_user(THD *thd, List <LEX_USER> &list)
{
  int result;
5250
  String wrong_users;
5251
  ulong sql_mode;
5252
  LEX_USER *user_name, *tmp_user_name;
5253
  List_iterator <LEX_USER> user_list(list);
5254
  TABLE_LIST tables[GRANT_TABLES];
5255 5256 5257 5258 5259 5260 5261 5262 5263
  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));

5264
  while ((tmp_user_name= user_list++))
5265
  {
5266 5267 5268 5269
    if (!(user_name= get_current_user(thd, tmp_user_name)))
    {
      result= TRUE;
      continue;
5270 5271
    }

5272 5273 5274 5275
    /*
      Search all in-memory structures and grant tables
      for a mention of the new user name.
    */
5276
    if (handle_grant_data(tables, 0, user_name, NULL))
5277
    {
5278
      append_user(&wrong_users, user_name);
5279
      result= TRUE;
5280
      continue;
5281
    }
5282

5283
    sql_mode= thd->variables.sql_mode;
serg@serg.mylan's avatar
serg@serg.mylan committed
5284
    if (replace_user_table(thd, tables[0].table, *user_name, 0, 0, 1, 0))
5285
    {
5286
      append_user(&wrong_users, user_name);
5287 5288 5289 5290 5291
      result= TRUE;
    }
  }

  VOID(pthread_mutex_unlock(&acl_cache->lock));
5292 5293 5294 5295 5296 5297 5298

  if (mysql_bin_log.is_open())
  {
    Query_log_event qinfo(thd, thd->query, thd->query_length, 0, FALSE);
    mysql_bin_log.write(&qinfo);
  }

5299 5300 5301
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
  if (result)
5302
    my_error(ER_CANNOT_USER, MYF(0), "CREATE USER", wrong_users.c_ptr_safe());
5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322
  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;
5323
  String wrong_users;
5324
  LEX_USER *user_name, *tmp_user_name;
5325
  List_iterator <LEX_USER> user_list(list);
5326
  TABLE_LIST tables[GRANT_TABLES];
5327 5328
  DBUG_ENTER("mysql_drop_user");

5329
  /* DROP USER may be skipped on replication client. */
5330 5331 5332 5333 5334 5335
  if ((result= open_grant_tables(thd, tables)))
    DBUG_RETURN(result != 1);

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

5336
  while ((tmp_user_name= user_list++))
5337
  {
5338 5339 5340 5341 5342 5343
    user_name= get_current_user(thd, tmp_user_name);
    if (!(user_name= get_current_user(thd, tmp_user_name)))
    {
      result= TRUE;
      continue;
    }  
5344
    if (handle_grant_data(tables, 1, user_name, NULL) <= 0)
5345
    {
5346
      append_user(&wrong_users, user_name);
5347
      result= TRUE;
5348
    }
5349
  }
5350

5351 5352 5353
  /* Rebuild 'acl_check_hosts' since 'acl_users' has been modified */
  rebuild_check_host();

5354
  VOID(pthread_mutex_unlock(&acl_cache->lock));
5355 5356 5357 5358 5359 5360 5361

  if (mysql_bin_log.is_open())
  {
    Query_log_event qinfo(thd, thd->query, thd->query_length, 0, FALSE);
    mysql_bin_log.write(&qinfo);
  }

5362 5363 5364
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
  if (result)
monty@mysql.com's avatar
monty@mysql.com committed
5365
    my_error(ER_CANNOT_USER, MYF(0), "DROP USER", wrong_users.c_ptr_safe());
5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384
  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)
{
5385
  int result;
5386
  String wrong_users;
5387 5388
  LEX_USER *user_from, *tmp_user_from;
  LEX_USER *user_to, *tmp_user_to;
5389
  List_iterator <LEX_USER> user_list(list);
5390
  TABLE_LIST tables[GRANT_TABLES];
5391 5392
  DBUG_ENTER("mysql_rename_user");

5393
  /* RENAME USER may be skipped on replication client. */
5394 5395 5396 5397 5398 5399
  if ((result= open_grant_tables(thd, tables)))
    DBUG_RETURN(result != 1);

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

5400
  while ((tmp_user_from= user_list++))
5401
  {
5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412
    if (!(user_from= get_current_user(thd, tmp_user_from)))
    {
      result= TRUE;
      continue;
    }  
    tmp_user_to= user_list++;
    if (!(user_to= get_current_user(thd, tmp_user_to)))
    {
      result= TRUE;
      continue;
    }  
5413
    DBUG_ASSERT(user_to != 0); /* Syntax enforces pairs of users. */
5414 5415 5416 5417 5418

    /*
      Search all in-memory structures and grant tables
      for a mention of the new user name.
    */
5419 5420
    if (handle_grant_data(tables, 0, user_to, NULL) ||
        handle_grant_data(tables, 0, user_from, user_to) <= 0)
5421
    {
5422
      append_user(&wrong_users, user_from);
5423 5424
      result= TRUE;
    }
5425
  }
5426
  
5427 5428 5429
  /* Rebuild 'acl_check_hosts' since 'acl_users' has been modified */
  rebuild_check_host();

5430
  VOID(pthread_mutex_unlock(&acl_cache->lock));
5431 5432 5433 5434 5435 5436 5437

  if (mysql_bin_log.is_open())
  {
    Query_log_event qinfo(thd, thd->query, thd->query_length, 0, FALSE);
    mysql_bin_log.write(&qinfo);
  }

5438 5439 5440
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
  if (result)
5441
    my_error(ER_CANNOT_USER, MYF(0), "RENAME USER", wrong_users.c_ptr_safe());
5442 5443 5444
  DBUG_RETURN(result);
}

5445

5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459
/*
  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.
*/

5460
bool mysql_revoke_all(THD *thd,  List <LEX_USER> &list)
5461
{
5462
  uint counter, revoked, is_proc;
5463
  int result;
5464
  ACL_DB *acl_db;
5465
  TABLE_LIST tables[GRANT_TABLES];
5466 5467 5468
  DBUG_ENTER("mysql_revoke_all");

  if ((result= open_grant_tables(thd, tables)))
5469
    DBUG_RETURN(result != 1);
5470 5471 5472 5473

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

5474
  LEX_USER *lex_user, *tmp_lex_user;
5475
  List_iterator <LEX_USER> user_list(list);
5476
  while ((tmp_lex_user= user_list++))
5477
  {
5478 5479 5480 5481 5482
    if (!(lex_user= get_current_user(thd, tmp_lex_user)))
    {
      result= -1;
      continue;
    }  
5483
    if (!find_acl_user(lex_user->host.str, lex_user->user.str, TRUE))
5484 5485 5486 5487
    {
      result= -1;
      continue;
    }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
5488

5489
    if (replace_user_table(thd, tables[0].table,
5490
			   *lex_user, ~(ulong)0, 1, 0, 0))
5491 5492 5493 5494 5495 5496
    {
      result= -1;
      continue;
    }

    /* Remove db access privileges */
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5497 5498 5499 5500 5501
    /*
      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
5502
    do
5503
    {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5504
      for (counter= 0, revoked= 0 ; counter < acl_dbs.elements ; )
5505
      {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5506
	const char *user,*host;
5507

dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5508 5509 5510 5511 5512
	acl_db=dynamic_element(&acl_dbs,counter,ACL_DB*);
	if (!(user=acl_db->user))
	  user= "";
	if (!(host=acl_db->host.hostname))
	  host= "";
5513

dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5514 5515 5516
	if (!strcmp(lex_user->user.str,user) &&
	    !my_strcasecmp(system_charset_info, lex_user->host.str, host))
	{
5517
	  if (!replace_db_table(tables[1].table, acl_db->db, *lex_user, ~(ulong)0, 1))
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5518
	  {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5519 5520 5521 5522 5523
	    /*
	      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
5524 5525
	    continue;
	  }
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5526
	  result= -1; // Something went wrong
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5527
	}
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5528
	counter++;
5529
      }
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5530
    } while (revoked);
5531 5532

    /* Remove column access */
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5533
    do
5534
    {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5535
      for (counter= 0, revoked= 0 ; counter < column_priv_hash.records ; )
5536
      {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5537 5538 5539 5540 5541
	const char *user,*host;
	GRANT_TABLE *grant_table= (GRANT_TABLE*)hash_element(&column_priv_hash,
							     counter);
	if (!(user=grant_table->user))
	  user= "";
5542
	if (!(host=grant_table->host.hostname))
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5543
	  host= "";
5544

dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5545 5546
	if (!strcmp(lex_user->user.str,user) &&
	    !my_strcasecmp(system_charset_info, lex_user->host.str, host))
5547
	{
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5548 5549 5550
	  if (replace_table_table(thd,grant_table,tables[2].table,*lex_user,
				  grant_table->db,
				  grant_table->tname,
5551
				  ~(ulong)0, 0, 1))
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5552
	  {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5553
	    result= -1;
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5554
	  }
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5555
	  else
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5556
	  {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5557
	    if (!grant_table->cols)
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5558
	    {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5559 5560
	      revoked= 1;
	      continue;
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5561
	    }
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5562 5563
	    List<LEX_COLUMN> columns;
	    if (!replace_column_table(grant_table,tables[3].table, *lex_user,
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5564 5565 5566
				      columns,
				      grant_table->db,
				      grant_table->tname,
5567
				      ~(ulong)0, 1))
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5568
	    {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5569
	      revoked= 1;
5570
	      continue;
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5571
	    }
5572
	    result= -1;
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5573
	  }
5574
	}
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5575
	counter++;
5576
      }
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5577
    } while (revoked);
5578 5579

    /* Remove procedure access */
5580 5581 5582
    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 ; )
5583 5584
      {
	const char *user,*host;
5585
	GRANT_NAME *grant_proc= (GRANT_NAME*) hash_element(hash, counter);
5586 5587
	if (!(user=grant_proc->user))
	  user= "";
5588
	if (!(host=grant_proc->host.hostname))
5589 5590 5591 5592 5593
	  host= "";

	if (!strcmp(lex_user->user.str,user) &&
	    !my_strcasecmp(system_charset_info, lex_user->host.str, host))
	{
5594
	  if (!replace_routine_table(thd,grant_proc,tables[4].table,*lex_user,
5595 5596
				  grant_proc->db,
				  grant_proc->tname,
5597
                                  is_proc,
5598
				  ~(ulong)0, 1))
5599 5600 5601 5602 5603 5604 5605 5606 5607
	  {
	    revoked= 1;
	    continue;
	  }
	  result= -1;	// Something went wrong
	}
	counter++;
      }
    } while (revoked);
5608
  }
5609

5610
  VOID(pthread_mutex_unlock(&acl_cache->lock));
5611 5612 5613 5614 5615 5616 5617

  if (mysql_bin_log.is_open())
  {
    Query_log_event qinfo(thd, thd->query, thd->query_length, 0, FALSE);
    mysql_bin_log.write(&qinfo);
  }

5618 5619
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
5620

5621
  if (result)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5622
    my_message(ER_REVOKE_GRANTS, ER(ER_REVOKE_GRANTS), MYF(0));
5623

5624 5625
  DBUG_RETURN(result);
}
5626

5627

5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641
/*
  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.
*/

5642 5643
bool sp_revoke_privileges(THD *thd, const char *sp_db, const char *sp_name,
                          bool is_proc)
5644 5645 5646 5647
{
  uint counter, revoked;
  int result;
  TABLE_LIST tables[GRANT_TABLES];
5648
  HASH *hash= is_proc ? &proc_priv_hash : &func_priv_hash;
5649 5650 5651 5652 5653 5654 5655 5656 5657
  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 */
5658 5659
  do
  {
5660
    for (counter= 0, revoked= 0 ; counter < hash->records ; )
5661
    {
5662
      GRANT_NAME *grant_proc= (GRANT_NAME*) hash_element(hash, counter);
5663 5664 5665 5666 5667 5668
      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);
5669 5670 5671 5672
	lex_user.host.str= grant_proc->host.hostname ?
	  grant_proc->host.hostname : (char*)"";
	lex_user.host.length= grant_proc->host.hostname ?
	  strlen(grant_proc->host.hostname) : 0;
5673 5674
	if (!replace_routine_table(thd,grant_proc,tables[4].table,lex_user,
				   grant_proc->db, grant_proc->tname,
5675
                                   is_proc, ~(ulong)0, 1))
5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710
	{
	  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.
*/

5711 5712
bool sp_grant_privileges(THD *thd, const char *sp_db, const char *sp_name,
                         bool is_proc)
5713
{
5714
  Security_context *sctx= thd->security_ctx;
5715 5716 5717 5718
  LEX_USER *combo;
  TABLE_LIST tables[1];
  List<LEX_USER> user_list;
  bool result;
5719 5720
  ACL_USER *au;
  char passwd_buff[SCRAMBLED_PASSWORD_CHAR_LENGTH+1];
5721
  DBUG_ENTER("sp_grant_privileges");
5722 5723 5724 5725

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

5726
  combo->user.str= sctx->user;
5727

5728
  VOID(pthread_mutex_lock(&acl_cache->lock));
5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742

  if ((au= find_acl_user(combo->host.str=(char*)sctx->host_or_ip,combo->user.str,FALSE)))
    goto found_acl;
  if ((au= find_acl_user(combo->host.str=(char*)sctx->host, combo->user.str,FALSE)))
    goto found_acl;
  if ((au= find_acl_user(combo->host.str=(char*)sctx->ip, combo->user.str,FALSE)))
    goto found_acl;
  if((au= find_acl_user(combo->host.str=(char*)"%", combo->user.str, FALSE)))
    goto found_acl;

  VOID(pthread_mutex_unlock(&acl_cache->lock));
  DBUG_RETURN(TRUE);

 found_acl:
5743
  VOID(pthread_mutex_unlock(&acl_cache->lock));
5744 5745 5746 5747 5748

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

  tables->db= (char*)sp_db;
5749
  tables->table_name= tables->alias= (char*)sp_name;
5750

5751 5752 5753 5754
  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);
5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780


  if(au && au->salt_len)
  {
    if (au->salt_len == SCRAMBLE_LENGTH)
    {
      make_password_from_salt(passwd_buff, au->salt);
      combo->password.length= SCRAMBLED_PASSWORD_CHAR_LENGTH;
    }
    else if (au->salt_len == SCRAMBLE_LENGTH_323)
    {
      make_password_from_salt_323(passwd_buff, (ulong *) au->salt);
      combo->password.length= SCRAMBLED_PASSWORD_CHAR_LENGTH_323;
    }
    else
    {
      my_error(ER_PASSWD_LENGTH, MYF(0), SCRAMBLED_PASSWORD_CHAR_LENGTH);
      return -1;
    }
    combo->password.str= passwd_buff;
  }
  else
  {
    combo->password.str= (char*)"";
    combo->password.length= 0;
  }
5781 5782 5783 5784 5785

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

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

5788
  result= mysql_routine_grant(thd, tables, is_proc, user_list,
5789 5790 5791 5792 5793
  				DEFAULT_CREATE_PROC_ACLS, 0, 1);
  DBUG_RETURN(result);
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
5794
/*****************************************************************************
5795
  Instantiate used templates
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5796 5797
*****************************************************************************/

5798
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5799 5800 5801 5802 5803
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
5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850

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

5851 5852 5853 5854 5855 5856 5857 5858

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;
5859
  restore_record(table, s->default_values);
5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880
  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;
5881
  bool no_global_access= check_access(thd, SELECT_ACL, "mysql",0,1,1,0);
5882
  char *curr_host= thd->security_ctx->priv_host_name();
5883
  DBUG_ENTER("fill_schema_user_privileges");
5884

5885 5886
  if (!initialized)
    DBUG_RETURN(0);
5887 5888
  pthread_mutex_lock(&acl_cache->lock);

5889 5890 5891 5892 5893 5894 5895 5896
  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= "";
5897 5898

    if (no_global_access &&
5899
        (strcmp(thd->security_ctx->priv_user, user) ||
5900 5901 5902
         my_strcasecmp(system_charset_info, curr_host, host)))
      continue;
      
5903 5904 5905 5906 5907 5908
    want_access= acl_user->access;
    if (!(want_access & GRANT_ACL))
      is_grantable= "NO";

    strxmov(buff,"'",user,"'@'",host,"'",NullS);
    if (!(want_access & ~GRANT_ACL))
5909 5910
      update_schema_privilege(table, buff, 0, 0, 0, 0,
                              STRING_WITH_LEN("USAGE"), is_grantable);
5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923
    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);
      }
    }
  }
5924 5925 5926

  pthread_mutex_unlock(&acl_cache->lock);

5927
  DBUG_RETURN(0);
5928 5929 5930
#else
  return(0);
#endif
5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941
}


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;
5942
  bool no_global_access= check_access(thd, SELECT_ACL, "mysql",0,1,1,0);
5943
  char *curr_host= thd->security_ctx->priv_host_name();
5944 5945
  DBUG_ENTER("fill_schema_schema_privileges");

5946 5947
  if (!initialized)
    DBUG_RETURN(0);
5948 5949
  pthread_mutex_lock(&acl_cache->lock);

5950 5951 5952 5953 5954 5955 5956 5957 5958 5959
  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= "";

5960
    if (no_global_access &&
5961
        (strcmp(thd->security_ctx->priv_user, user) ||
5962 5963 5964
         my_strcasecmp(system_charset_info, curr_host, host)))
      continue;

5965 5966 5967 5968 5969 5970 5971 5972 5973 5974
    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,
5975
                                0, STRING_WITH_LEN("USAGE"), is_grantable);
5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987
      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);
      }
    }
  }
5988 5989 5990

  pthread_mutex_unlock(&acl_cache->lock);

5991
  DBUG_RETURN(0);
5992 5993 5994
#else
  return (0);
#endif
5995 5996 5997 5998 5999 6000 6001 6002 6003
}


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;
6004
  bool no_global_access= check_access(thd, SELECT_ACL, "mysql",0,1,1,0);
6005
  char *curr_host= thd->security_ctx->priv_host_name();
6006 6007
  DBUG_ENTER("fill_schema_table_privileges");

6008 6009
  rw_rdlock(&LOCK_grant);

6010 6011
  for (index=0 ; index < column_priv_hash.records ; index++)
  {
6012
    const char *user, *host, *is_grantable= "YES";
6013 6014 6015 6016
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  index);
    if (!(user=grant_table->user))
      user= "";
6017 6018
    if (!(host= grant_table->host.hostname))
      host= "";
6019 6020

    if (no_global_access &&
6021
        (strcmp(thd->security_ctx->priv_user, user) ||
6022
         my_strcasecmp(system_charset_info, curr_host, host)))
6023 6024
      continue;

6025
    ulong table_access= grant_table->privs;
6026
    if (table_access)
6027 6028
    {
      ulong test_access= table_access & ~GRANT_ACL;
6029 6030 6031 6032
      /*
        We should skip 'usage' privilege on table if
        we have any privileges on column(s) of this table
      */
6033 6034
      if (!test_access && grant_table->cols)
        continue;
6035 6036 6037
      if (!(table_access & GRANT_ACL))
        is_grantable= "NO";

6038
      strxmov(buff, "'", user, "'@'", host, "'", NullS);
6039 6040
      if (!test_access)
        update_schema_privilege(table, buff, grant_table->db, grant_table->tname,
6041
                                0, 0, STRING_WITH_LEN("USAGE"), is_grantable);
6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055
      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);
        }
      }
    }
  }
6056 6057 6058

  rw_unlock(&LOCK_grant);

6059
  DBUG_RETURN(0);
6060 6061 6062
#else
  return (0);
#endif
6063 6064 6065 6066 6067 6068 6069 6070 6071
}


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;
6072
  bool no_global_access= check_access(thd, SELECT_ACL, "mysql",0,1,1,0);
6073
  char *curr_host= thd->security_ctx->priv_host_name();
6074 6075
  DBUG_ENTER("fill_schema_table_privileges");

6076 6077
  rw_rdlock(&LOCK_grant);

6078 6079
  for (index=0 ; index < column_priv_hash.records ; index++)
  {
6080
    const char *user, *host, *is_grantable= "YES";
6081 6082 6083 6084
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  index);
    if (!(user=grant_table->user))
      user= "";
6085 6086
    if (!(host= grant_table->host.hostname))
      host= "";
6087 6088

    if (no_global_access &&
6089
        (strcmp(thd->security_ctx->priv_user, user) ||
6090
         my_strcasecmp(system_charset_info, curr_host, host)))
6091 6092
      continue;

6093 6094 6095
    ulong table_access= grant_table->cols;
    if (table_access != 0)
    {
6096
      if (!(grant_table->privs & GRANT_ACL))
6097 6098
        is_grantable= "NO";

6099
      ulong test_access= table_access & ~GRANT_ACL;
6100
      strxmov(buff, "'", user, "'@'", host, "'", NullS);
6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129
      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);
            }
          }
        }
      }
    }
  }
6130 6131 6132

  rw_unlock(&LOCK_grant);

6133
  DBUG_RETURN(0);
6134 6135 6136
#else
  return (0);
#endif
6137 6138 6139
}


bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
6140 6141 6142 6143 6144
#ifndef NO_EMBEDDED_ACCESS_CHECKS
/*
  fill effective privileges for table

  SYNOPSIS
6145 6146
    fill_effective_table_privileges()
    thd     thread handler
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
6147 6148 6149 6150 6151 6152 6153 6154
    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)
{
6155
  Security_context *sctx= thd->security_ctx;
6156 6157 6158 6159 6160
  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));
6161 6162 6163
  /* --skip-grants */
  if (!initialized)
  {
6164
    DBUG_PRINT("info", ("skip grants"));
6165
    grant->privilege= ~NO_ACCESS;             // everything is allowed
6166 6167
    DBUG_PRINT("info", ("privilege 0x%lx", grant->privilege));
    DBUG_VOID_RETURN;
6168 6169
  }

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

6173
  if (!sctx->priv_user)
6174 6175 6176 6177
  {
    DBUG_PRINT("info", ("privilege 0x%lx", grant->privilege));
    DBUG_VOID_RETURN;                         // it is slave
  }
6178

6179
  /* db privileges */
6180
  grant->privilege|= acl_get(sctx->host, sctx->ip, sctx->priv_user, db, 0);
6181

6182
  if (!grant_option)
6183 6184 6185 6186
  {
    DBUG_PRINT("info", ("privilege 0x%lx", grant->privilege));
    DBUG_VOID_RETURN;
  }
6187

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
6188
  /* table privileges */
6189
  rw_rdlock(&LOCK_grant);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
6190 6191 6192
  if (grant->version != grant_version)
  {
    grant->grant_table=
6193 6194
      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
6195 6196 6197 6198 6199 6200 6201
			table, 0);              /* purecov: inspected */
    grant->version= grant_version;              /* purecov: inspected */
  }
  if (grant->grant_table != 0)
  {
    grant->privilege|= grant->grant_table->privs;
  }
6202 6203
  rw_unlock(&LOCK_grant);

6204 6205
  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
6206
}
6207 6208 6209 6210 6211 6212 6213

#else /* NO_EMBEDDED_ACCESS_CHECKS */

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

acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
6214 6215
bool check_routine_level_acl(THD *thd, const char *db, const char *name,
                             bool is_proc)
6216 6217 6218 6219
{
  return FALSE;
}

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