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

unknown's avatar
unknown 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
unknown's avatar
unknown committed
5
   the Free Software Foundation; version 2 of the License.
unknown's avatar
unknown committed
6

unknown's avatar
unknown 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.
unknown's avatar
unknown committed
11

unknown's avatar
unknown 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.
unknown's avatar
unknown committed
21 22 23 24 25 26 27 28 29 30
  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"
#include <m_ctype.h>
#include <stdarg.h>
31 32
#include "sp_head.h"
#include "sp.h"
unknown's avatar
unknown committed
33

34 35 36 37
time_t mysql_db_table_last_check= 0L;

TABLE_FIELD_W_TYPE mysql_db_table_fields[MYSQL_DB_FIELD_COUNT] = {
  {
unknown's avatar
unknown committed
38 39
    { C_STRING_WITH_LEN("Host") },            
    { C_STRING_WITH_LEN("char(60)") },
40 41 42
    {NULL, 0}
  }, 
  {
unknown's avatar
unknown committed
43 44
    { C_STRING_WITH_LEN("Db") },            
    { C_STRING_WITH_LEN("char(64)") },
45 46 47
    {NULL, 0}
  }, 
  {
unknown's avatar
unknown committed
48 49
    { C_STRING_WITH_LEN("User") },
    { C_STRING_WITH_LEN("char(16)") },
50 51 52
    {NULL, 0}
  },
  {
unknown's avatar
unknown committed
53 54 55
    { C_STRING_WITH_LEN("Select_priv") },
    { C_STRING_WITH_LEN("enum('N','Y')") },
    { C_STRING_WITH_LEN("utf8") }
56 57
  },
  {
unknown's avatar
unknown committed
58 59 60
    { C_STRING_WITH_LEN("Insert_priv") },
    { C_STRING_WITH_LEN("enum('N','Y')") },
    { C_STRING_WITH_LEN("utf8") }
61 62
  },
  {
unknown's avatar
unknown committed
63 64 65
    { C_STRING_WITH_LEN("Update_priv") },
    { C_STRING_WITH_LEN("enum('N','Y')") },
    { C_STRING_WITH_LEN("utf8") }
66 67
  },
  {
unknown's avatar
unknown committed
68 69 70
    { C_STRING_WITH_LEN("Delete_priv") },
    { C_STRING_WITH_LEN("enum('N','Y')") },
    { C_STRING_WITH_LEN("utf8") }
71 72
  },
  {
unknown's avatar
unknown committed
73 74 75
    { C_STRING_WITH_LEN("Create_priv") },
    { C_STRING_WITH_LEN("enum('N','Y')") },
    { C_STRING_WITH_LEN("utf8") }
76 77
  },
  {
unknown's avatar
unknown committed
78 79 80
    { C_STRING_WITH_LEN("Drop_priv") },
    { C_STRING_WITH_LEN("enum('N','Y')") },
    { C_STRING_WITH_LEN("utf8") }
81 82
  },
  {
unknown's avatar
unknown committed
83 84 85
    { C_STRING_WITH_LEN("Grant_priv") },
    { C_STRING_WITH_LEN("enum('N','Y')") },
    { C_STRING_WITH_LEN("utf8") }
86 87
  },
  {
unknown's avatar
unknown committed
88 89 90
    { C_STRING_WITH_LEN("References_priv") },
    { C_STRING_WITH_LEN("enum('N','Y')") },
    { C_STRING_WITH_LEN("utf8") }
91 92
  },
  {
unknown's avatar
unknown committed
93 94 95
    { C_STRING_WITH_LEN("Index_priv") },
    { C_STRING_WITH_LEN("enum('N','Y')") },
    { C_STRING_WITH_LEN("utf8") }
96 97
  },
  {
unknown's avatar
unknown committed
98 99 100
    { C_STRING_WITH_LEN("Alter_priv") },
    { C_STRING_WITH_LEN("enum('N','Y')") },
    { C_STRING_WITH_LEN("utf8") }
101 102
  },
  {
unknown's avatar
unknown committed
103 104 105
    { C_STRING_WITH_LEN("Create_tmp_table_priv") },
    { C_STRING_WITH_LEN("enum('N','Y')") },
    { C_STRING_WITH_LEN("utf8") }
106 107
  },
  {
unknown's avatar
unknown committed
108 109 110
    { C_STRING_WITH_LEN("Lock_tables_priv") },
    { C_STRING_WITH_LEN("enum('N','Y')") },
    { C_STRING_WITH_LEN("utf8") }
111 112
  },
  {
unknown's avatar
unknown committed
113 114 115
    { C_STRING_WITH_LEN("Create_view_priv") },
    { C_STRING_WITH_LEN("enum('N','Y')") },
    { C_STRING_WITH_LEN("utf8") }
116 117
  },
  {
unknown's avatar
unknown committed
118 119 120
    { C_STRING_WITH_LEN("Show_view_priv") },
    { C_STRING_WITH_LEN("enum('N','Y')") },
    { C_STRING_WITH_LEN("utf8") }
121 122
  },
  {
unknown's avatar
unknown committed
123 124 125
    { C_STRING_WITH_LEN("Create_routine_priv") },
    { C_STRING_WITH_LEN("enum('N','Y')") },
    { C_STRING_WITH_LEN("utf8") }
126 127
  },
  {
unknown's avatar
unknown committed
128 129 130
    { C_STRING_WITH_LEN("Alter_routine_priv") },
    { C_STRING_WITH_LEN("enum('N','Y')") },
    { C_STRING_WITH_LEN("utf8") }
131 132
  },
  {
unknown's avatar
unknown committed
133 134 135
    { C_STRING_WITH_LEN("Execute_priv") },
    { C_STRING_WITH_LEN("enum('N','Y')") },
    { C_STRING_WITH_LEN("utf8") }
136 137
  },
  {
unknown's avatar
unknown committed
138 139 140
    { C_STRING_WITH_LEN("Event_priv") },
    { C_STRING_WITH_LEN("enum('N','Y')") },
    { C_STRING_WITH_LEN("utf8") }
141 142
  },
  {
unknown's avatar
unknown committed
143 144 145
    { C_STRING_WITH_LEN("Trigger_priv") },
    { C_STRING_WITH_LEN("enum('N','Y')") },
    { C_STRING_WITH_LEN("utf8") }
146 147 148 149
  }
};


150 151 152 153
#ifndef NO_EMBEDDED_ACCESS_CHECKS

#define FIRST_NON_YN_FIELD 26

unknown's avatar
unknown committed
154 155 156
class acl_entry :public hash_filo_element
{
public:
unknown's avatar
unknown committed
157
  ulong access;
unknown's avatar
unknown committed
158 159 160 161
  uint16 length;
  char key[1];					// Key will be stored here
};

unknown's avatar
unknown committed
162

163 164
static uchar* acl_entry_get_key(acl_entry *entry, size_t *length,
                                my_bool not_used __attribute__((unused)))
unknown's avatar
unknown committed
165 166
{
  *length=(uint) entry->length;
167
  return (uchar*) entry->key;
unknown's avatar
unknown committed
168 169
}

unknown's avatar
unknown committed
170
#define IP_ADDR_STRLEN (3+1+3+1+3+1+3)
unknown's avatar
unknown committed
171
#define ACL_KEY_LENGTH (IP_ADDR_STRLEN+1+NAME_LEN+1+USERNAME_LENGTH+1)
unknown's avatar
unknown committed
172 173 174 175 176

static DYNAMIC_ARRAY acl_hosts,acl_users,acl_dbs;
static MEM_ROOT mem, memex;
static bool initialized=0;
static bool allow_all_hosts=1;
177
static HASH acl_check_hosts, column_priv_hash, proc_priv_hash, func_priv_hash;
unknown's avatar
unknown committed
178 179
static DYNAMIC_ARRAY acl_wild_hosts;
static hash_filo *acl_cache;
180
static uint grant_version=0; /* Version of priv tables. incremented by acl_load */
unknown's avatar
unknown committed
181
static ulong get_access(TABLE *form,uint fieldnr, uint *next_field=0);
unknown's avatar
unknown committed
182 183 184
static int acl_compare(ACL_ACCESS *a,ACL_ACCESS *b);
static ulong get_sort(uint count,...);
static void init_check_host(void);
185
static void rebuild_check_host(void);
186 187
static ACL_USER *find_acl_user(const char *host, const char *user,
                               my_bool exact);
188 189
static bool update_user_table(THD *thd, TABLE *table,
                              const char *host, const char *user,
190
			      const char *new_password, uint new_password_len);
unknown's avatar
unknown committed
191
static void update_hostname(acl_host_and_ip *host, const char *hostname);
192
static bool compare_hostname(const acl_host_and_ip *host,const char *hostname,
unknown's avatar
unknown committed
193
			     const char *ip);
194
static my_bool acl_load(THD *thd, TABLE_LIST *tables);
195
static my_bool grant_load(THD *thd, TABLE_LIST *tables);
unknown's avatar
unknown committed
196

197 198 199 200 201 202 203 204 205 206 207 208 209 210
/*
  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;
  }
211
  else if (password_len == SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
212 213
  {
    get_salt_from_password_323((ulong *) acl_user->salt, password);
214
    acl_user->salt_len= SCRAMBLE_LENGTH_323;
215 216 217 218 219
  }
  else
    acl_user->salt_len= 0;
}

220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
/*
  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;
}

238

239
/*
240 241
  Initialize structures responsible for user/db-level privilege checking and
  load privilege information for them from tables in the 'mysql' database.
242 243 244

  SYNOPSIS
    acl_init()
245 246 247 248 249 250
      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().
251 252 253 254 255 256

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

257
my_bool acl_init(bool dont_read_acl_tables)
unknown's avatar
unknown committed
258
{
unknown's avatar
unknown committed
259
  THD  *thd;
260
  my_bool return_val;
unknown's avatar
unknown committed
261 262
  DBUG_ENTER("acl_init");

263 264
  acl_cache= new hash_filo(ACL_CACHE_SIZE, 0, 0,
                           (hash_get_key) acl_entry_get_key,
265
                           (hash_free_key) free,
266 267
                           lower_case_file_system ?
                           system_charset_info : &my_charset_bin);
unknown's avatar
unknown committed
268
  if (dont_read_acl_tables)
269
  {
unknown's avatar
unknown committed
270
    DBUG_RETURN(0); /* purecov: tested */
unknown's avatar
unknown committed
271 272
  }

273 274 275
  /*
    To be able to run this from boot, we allocate a temporary THD
  */
unknown's avatar
unknown committed
276 277
  if (!(thd=new THD))
    DBUG_RETURN(1); /* purecov: inspected */
278
  thd->thread_stack= (char*) &thd;
279
  thd->store_globals();
280
  lex_start(thd);
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
  /*
    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;
unknown's avatar
unknown committed
315
  char tmp_name[NAME_LEN+1];
316
  int password_length;
317
  ulong old_sql_mode= thd->variables.sql_mode;
318 319
  DBUG_ENTER("acl_load");

320 321
  thd->variables.sql_mode&= ~MODE_PAD_CHAR_TO_FULL_LENGTH;

322
  grant_version++; /* Privileges updated */
323

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

326
  init_sql_alloc(&mem, ACL_ALLOC_BLOCK_SIZE, 0);
327 328
  init_read_record(&read_record_info,thd,table= tables[0].table,NULL,1,0, 
                   FALSE);
329
  table->use_all_columns();
330
  VOID(my_init_dynamic_array(&acl_hosts,sizeof(ACL_HOST),20,50));
unknown's avatar
unknown committed
331 332 333
  while (!(read_record_info.read_record(&read_record_info)))
  {
    ACL_HOST host;
334 335
    update_hostname(&host.host,get_field(&mem, table->field[0]));
    host.db=	 get_field(&mem, table->field[1]);
336
    if (lower_case_table_names && host.db)
337 338
    {
      /*
339 340
        convert db to lower case and give a warning if the db wasn't
        already in lower case
341
      */
342 343
      (void) strmov(tmp_name, host.db);
      my_casedn_str(files_charset_info, host.db);
344 345 346
      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 "
347 348
                          "lower_case_table_names is set. It will not be "
                          "possible to remove this privilege using REVOKE.",
349 350
                          host.host.hostname ? host.host.hostname : "",
                          host.db ? host.db : "");
351
    }
unknown's avatar
unknown committed
352 353
    host.access= get_access(table,2);
    host.access= fix_rights_for_db(host.access);
354
    host.sort=	 get_sort(2,host.host.hostname,host.db);
unknown's avatar
SCRUM  
unknown committed
355 356
    if (check_no_resolve && hostname_requires_resolving(host.host.hostname))
    {
unknown's avatar
unknown committed
357
      sql_print_warning("'host' entry '%s|%s' "
unknown's avatar
SCRUM  
unknown committed
358
		      "ignored in --skip-name-resolve mode.",
359 360
			host.host.hostname ? host.host.hostname : "",
			host.db ? host.db : "");
unknown's avatar
SCRUM  
unknown committed
361 362
      continue;
    }
unknown's avatar
unknown committed
363
#ifndef TO_BE_REMOVED
364
    if (table->s->fields == 8)
unknown's avatar
unknown committed
365 366
    {						// Without grant
      if (host.access & CREATE_ACL)
367
	host.access|=REFERENCES_ACL | INDEX_ACL | ALTER_ACL | CREATE_TMP_ACL;
unknown's avatar
unknown committed
368 369
    }
#endif
370
    VOID(push_dynamic(&acl_hosts,(uchar*) &host));
unknown's avatar
unknown committed
371
  }
372 373
  my_qsort((uchar*) dynamic_element(&acl_hosts,0,ACL_HOST*),acl_hosts.elements,
	   sizeof(ACL_HOST),(qsort_cmp) acl_compare);
unknown's avatar
unknown committed
374 375 376
  end_read_record(&read_record_info);
  freeze_size(&acl_hosts);

377
  init_read_record(&read_record_info,thd,table=tables[1].table,NULL,1,0,FALSE);
378
  table->use_all_columns();
379
  VOID(my_init_dynamic_array(&acl_users,sizeof(ACL_USER),50,100));
380 381 382
  password_length= table->field[2]->field_length /
    table->field[2]->charset()->mbmaxlen;
  if (password_length < SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
unknown's avatar
unknown committed
383
  {
384 385 386
    sql_print_error("Fatal error: mysql.user table is damaged or in "
                    "unsupported 3.20 format.");
    goto end;
unknown's avatar
unknown committed
387 388
  }

389
  DBUG_PRINT("info",("user table fields: %d, password length: %d",
390
		     table->s->fields, password_length));
391

392
  pthread_mutex_lock(&LOCK_global_system_variables);
393
  if (password_length < SCRAMBLED_PASSWORD_CHAR_LENGTH)
394
  {
395 396 397 398 399 400 401 402 403 404 405 406 407 408
    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);
409 410 411
      sql_print_warning("mysql.user table is not updated to new password format; "
                        "Disabling new password usage until "
                        "mysql_fix_privilege_tables is run");
412 413 414 415
    }
    thd->variables.old_passwords= 1;
  }
  else
416
  {
417 418
    sys_old_passwords.after_update= 0;
    pthread_mutex_unlock(&LOCK_global_system_variables);
419 420
  }

unknown's avatar
unknown committed
421 422 423 424
  allow_all_hosts=0;
  while (!(read_record_info.read_record(&read_record_info)))
  {
    ACL_USER user;
425 426
    update_hostname(&user.host, get_field(&mem, table->field[0]));
    user.user= get_field(&mem, table->field[1]);
unknown's avatar
SCRUM  
unknown committed
427 428
    if (check_no_resolve && hostname_requires_resolving(user.host.hostname))
    {
unknown's avatar
unknown committed
429 430
      sql_print_warning("'user' entry '%s@%s' "
                        "ignored in --skip-name-resolve mode.",
431 432
			user.user ? user.user : "",
			user.host.hostname ? user.host.hostname : "");
unknown's avatar
SCRUM  
unknown committed
433 434 435
      continue;
    }

436
    const char *password= get_field(thd->mem_root, table->field[2]);
437 438 439
    uint password_len= password ? strlen(password) : 0;
    set_user_salt(&user, password, password_len);
    if (user.salt_len == 0 && password_len != 0)
unknown's avatar
unknown committed
440
    {
441 442
      switch (password_len) {
      case 45: /* 4.1: to be removed */
unknown's avatar
unknown committed
443 444 445 446 447
        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 : "");
448 449
        break;
      default:
unknown's avatar
unknown committed
450 451 452
        sql_print_warning("Found invalid password for user: '%s@%s'; "
                          "Ignoring user", user.user ? user.user : "",
                           user.host.hostname ? user.host.hostname : "");
453 454
        break;
      }
unknown's avatar
unknown committed
455
    }
456
    else                                        // password is correct
unknown's avatar
unknown committed
457
    {
unknown's avatar
unknown committed
458 459
      uint next_field;
      user.access= get_access(table,3,&next_field) & GLOBAL_ACLS;
460 461 462 463
      /*
        if it is pre 5.0.1 privilege table then map CREATE privilege on
        CREATE VIEW & SHOW VIEW privileges
      */
464
      if (table->s->fields <= 31 && (user.access & CREATE_ACL))
465
        user.access|= (CREATE_VIEW_ACL | SHOW_VIEW_ACL);
466 467 468 469 470

      /*
        if it is pre 5.0.2 privilege table then map CREATE/ALTER privilege on
        CREATE PROCEDURE & ALTER PROCEDURE privileges
      */
471
      if (table->s->fields <= 33 && (user.access & CREATE_ACL))
472
        user.access|= CREATE_PROC_ACL;
473
      if (table->s->fields <= 33 && (user.access & ALTER_ACL))
474 475
        user.access|= ALTER_PROC_ACL;

476 477 478 479 480 481
      /*
        pre 5.0.3 did not have CREATE_USER_ACL
      */
      if (table->s->fields <= 36 && (user.access & GRANT_ACL))
        user.access|= CREATE_USER_ACL;

unknown's avatar
unknown committed
482 483

      /*
unknown's avatar
unknown committed
484
        if it is pre 5.1.6 privilege table then map CREATE privilege on
unknown's avatar
unknown committed
485 486
        CREATE|ALTER|DROP|EXECUTE EVENT
      */
unknown's avatar
unknown committed
487
      if (table->s->fields <= 37 && (user.access & SUPER_ACL))
unknown's avatar
unknown committed
488 489
        user.access|= EVENT_ACL;

490 491 492 493 494 495
      /*
        if it is pre 5.1.6 privilege then map TRIGGER privilege on CREATE.
      */
      if (table->s->fields <= 38 && (user.access & SUPER_ACL))
        user.access|= TRIGGER_ACL;

496 497 498
      user.sort= get_sort(2,user.host.hostname,user.user);
      user.hostname_length= (user.host.hostname ?
                             (uint) strlen(user.host.hostname) : 0);
unknown's avatar
VIEW  
unknown committed
499

500 501
      /* Starting from 4.0.2 we have more fields */
      if (table->s->fields >= 31)
502
      {
503
        char *ssl_type=get_field(thd->mem_root, table->field[next_field++]);
504 505 506 507 508 509 510 511 512
        if (!ssl_type)
          user.ssl_type=SSL_TYPE_NONE;
        else if (!strcmp(ssl_type, "ANY"))
          user.ssl_type=SSL_TYPE_ANY;
        else if (!strcmp(ssl_type, "X509"))
          user.ssl_type=SSL_TYPE_X509;
        else  /* !strcmp(ssl_type, "SPECIFIED") */
          user.ssl_type=SSL_TYPE_SPECIFIED;

unknown's avatar
unknown committed
513 514 515
        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++]);
516

517
        char *ptr = get_field(thd->mem_root, table->field[next_field++]);
unknown's avatar
unknown committed
518
        user.user_resource.questions=ptr ? atoi(ptr) : 0;
519
        ptr = get_field(thd->mem_root, table->field[next_field++]);
unknown's avatar
unknown committed
520
        user.user_resource.updates=ptr ? atoi(ptr) : 0;
521
        ptr = get_field(thd->mem_root, table->field[next_field++]);
522
        user.user_resource.conn_per_hour= ptr ? atoi(ptr) : 0;
523
        if (user.user_resource.questions || user.user_resource.updates ||
524
            user.user_resource.conn_per_hour)
525
          mqh_used=1;
526

527
        if (table->s->fields >= 36)
528 529
        {
          /* Starting from 5.0.3 we have max_user_connections field */
530
          ptr= get_field(thd->mem_root, table->field[next_field++]);
531 532 533 534
          user.user_resource.user_conn= ptr ? atoi(ptr) : 0;
        }
        else
          user.user_resource.user_conn= 0;
535
      }
536 537 538
      else
      {
        user.ssl_type=SSL_TYPE_NONE;
539
        bzero((char *)&(user.user_resource),sizeof(user.user_resource));
unknown's avatar
unknown committed
540
#ifndef TO_BE_REMOVED
541
        if (table->s->fields <= 13)
542 543 544 545 546 547 548 549 550 551
        {						// Without grant
          if (user.access & CREATE_ACL)
            user.access|=REFERENCES_ACL | INDEX_ACL | ALTER_ACL;
        }
        /* Convert old privileges */
        user.access|= LOCK_TABLES_ACL | CREATE_TMP_ACL | SHOW_DB_ACL;
        if (user.access & FILE_ACL)
          user.access|= REPL_CLIENT_ACL | REPL_SLAVE_ACL;
        if (user.access & PROCESS_ACL)
          user.access|= SUPER_ACL | EXECUTE_ACL;
unknown's avatar
unknown committed
552
#endif
553
      }
554
      VOID(push_dynamic(&acl_users,(uchar*) &user));
555 556
      if (!user.host.hostname ||
	  (user.host.hostname[0] == wild_many && !user.host.hostname[1]))
557
        allow_all_hosts=1;			// Anyone can connect
unknown's avatar
unknown committed
558
    }
unknown's avatar
unknown committed
559
  }
560 561
  my_qsort((uchar*) dynamic_element(&acl_users,0,ACL_USER*),acl_users.elements,
	   sizeof(ACL_USER),(qsort_cmp) acl_compare);
unknown's avatar
unknown committed
562 563
  end_read_record(&read_record_info);
  freeze_size(&acl_users);
unknown's avatar
unknown committed
564

565
  init_read_record(&read_record_info,thd,table=tables[2].table,NULL,1,0,FALSE);
566
  table->use_all_columns();
567
  VOID(my_init_dynamic_array(&acl_dbs,sizeof(ACL_DB),50,100));
unknown's avatar
unknown committed
568 569 570
  while (!(read_record_info.read_record(&read_record_info)))
  {
    ACL_DB db;
571 572
    update_hostname(&db.host,get_field(&mem, table->field[MYSQL_DB_FIELD_HOST]));
    db.db=get_field(&mem, table->field[MYSQL_DB_FIELD_DB]);
573 574
    if (!db.db)
    {
unknown's avatar
unknown committed
575
      sql_print_warning("Found an entry in the 'db' table with empty database name; Skipped");
576
      continue;
577
    }
578
    db.user=get_field(&mem, table->field[MYSQL_DB_FIELD_USER]);
unknown's avatar
SCRUM  
unknown committed
579 580
    if (check_no_resolve && hostname_requires_resolving(db.host.hostname))
    {
unknown's avatar
unknown committed
581 582
      sql_print_warning("'db' entry '%s %s@%s' "
		        "ignored in --skip-name-resolve mode.",
583 584 585
		        db.db,
			db.user ? db.user : "",
			db.host.hostname ? db.host.hostname : "");
unknown's avatar
SCRUM  
unknown committed
586 587
      continue;
    }
unknown's avatar
unknown committed
588 589
    db.access=get_access(table,3);
    db.access=fix_rights_for_db(db.access);
590 591 592
    if (lower_case_table_names)
    {
      /*
593 594
        convert db to lower case and give a warning if the db wasn't
        already in lower case
595 596
      */
      (void)strmov(tmp_name, db.db);
597
      my_casedn_str(files_charset_info, db.db);
598 599 600 601
      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 "
602 603
                          "lower_case_table_names is set. It will not be "
                          "possible to remove this privilege using REVOKE.",
604 605 606
		          db.db,
			  db.user ? db.user : "",
			  db.host.hostname ? db.host.hostname : "");
607 608
      }
    }
unknown's avatar
unknown committed
609 610
    db.sort=get_sort(3,db.host.hostname,db.db,db.user);
#ifndef TO_BE_REMOVED
611
    if (table->s->fields <=  9)
unknown's avatar
unknown committed
612 613 614 615 616
    {						// Without grant
      if (db.access & CREATE_ACL)
	db.access|=REFERENCES_ACL | INDEX_ACL | ALTER_ACL;
    }
#endif
617
    VOID(push_dynamic(&acl_dbs,(uchar*) &db));
unknown's avatar
unknown committed
618
  }
619 620
  my_qsort((uchar*) dynamic_element(&acl_dbs,0,ACL_DB*),acl_dbs.elements,
	   sizeof(ACL_DB),(qsort_cmp) acl_compare);
unknown's avatar
unknown committed
621 622 623 624
  end_read_record(&read_record_info);
  freeze_size(&acl_dbs);
  init_check_host();

625 626 627 628
  initialized=1;
  return_val=0;

end:
629
  thd->variables.sql_mode= old_sql_mode;
630
  DBUG_RETURN(return_val);
unknown's avatar
unknown committed
631 632 633 634 635
}


void acl_free(bool end)
{
636
  free_root(&mem,MYF(0));
unknown's avatar
unknown committed
637 638 639 640 641 642 643 644 645 646 647 648 649 650
  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;
  }
}

651 652

/*
653 654
  Forget current user/db-level privileges and read new privileges
  from the privilege tables.
655 656 657

  SYNOPSIS
    acl_reload()
658 659 660 661 662 663 664 665 666 667 668
      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
669
*/
unknown's avatar
unknown committed
670

671
my_bool acl_reload(THD *thd)
unknown's avatar
unknown committed
672
{
673
  TABLE_LIST tables[3];
unknown's avatar
unknown committed
674 675 676
  DYNAMIC_ARRAY old_acl_hosts,old_acl_users,old_acl_dbs;
  MEM_ROOT old_mem;
  bool old_initialized;
677
  my_bool return_val= 1;
unknown's avatar
unknown committed
678 679
  DBUG_ENTER("acl_reload");

680
  if (thd->locked_tables)
unknown's avatar
unknown committed
681
  {					// Can't have locked tables here
682 683 684
    thd->lock=thd->locked_tables;
    thd->locked_tables=0;
    close_thread_tables(thd);
unknown's avatar
unknown committed
685
  }
686 687 688 689 690 691

  /*
    To avoid deadlocks we should obtain table locks before
    obtaining acl_cache->lock mutex.
  */
  bzero((char*) tables, sizeof(tables));
692 693 694 695 696 697
  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;
698
  tables[0].lock_type=tables[1].lock_type=tables[2].lock_type=TL_READ;
699 700
  tables[0].skip_temporary= tables[1].skip_temporary=
    tables[2].skip_temporary= TRUE;
701 702 703 704

  if (simple_open_n_lock_tables(thd, tables))
  {
    sql_print_error("Fatal error: Can't open and lock privilege tables: %s",
705
		    thd->main_da.message());
706 707 708
    goto end;
  }

unknown's avatar
unknown committed
709 710 711 712 713 714 715 716 717 718
  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);

719
  if ((return_val= acl_load(thd, tables)))
unknown's avatar
unknown committed
720
  {					// Error. Revert to old list
721
    DBUG_PRINT("error",("Reverting to old privileges"));
722
    acl_free();				/* purecov: inspected */
unknown's avatar
unknown committed
723 724 725 726 727 728 729 730
    acl_hosts=old_acl_hosts;
    acl_users=old_acl_users;
    acl_dbs=old_acl_dbs;
    mem=old_mem;
    init_check_host();
  }
  else
  {
731
    free_root(&old_mem,MYF(0));
unknown's avatar
unknown committed
732 733 734 735 736 737
    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));
738 739 740
end:
  close_thread_tables(thd);
  DBUG_RETURN(return_val);
unknown's avatar
unknown committed
741 742 743
}


unknown's avatar
unknown committed
744 745
/*
  Get all access bits from table after fieldnr
unknown's avatar
unknown committed
746 747

  IMPLEMENTATION
unknown's avatar
unknown committed
748 749
  We know that the access privileges ends when there is no more fields
  or the field is not an enum with two elements.
unknown's avatar
unknown committed
750 751 752 753 754 755 756 757 758 759 760

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

  RETURN VALUE
    privilege mask
unknown's avatar
unknown committed
761
*/
unknown's avatar
unknown committed
762

unknown's avatar
unknown committed
763
static ulong get_access(TABLE *form, uint fieldnr, uint *next_field)
unknown's avatar
unknown committed
764
{
unknown's avatar
unknown committed
765
  ulong access_bits=0,bit;
unknown's avatar
unknown committed
766
  char buff[2];
unknown's avatar
unknown committed
767
  String res(buff,sizeof(buff),&my_charset_latin1);
unknown's avatar
unknown committed
768 769
  Field **pos;

unknown's avatar
unknown committed
770
  for (pos=form->field+fieldnr, bit=1;
771
       *pos && (*pos)->real_type() == MYSQL_TYPE_ENUM &&
unknown's avatar
unknown committed
772
	 ((Field_enum*) (*pos))->typelib->count == 2 ;
unknown's avatar
unknown committed
773
       pos++, fieldnr++, bit<<=1)
unknown's avatar
unknown committed
774
  {
775
    (*pos)->val_str(&res);
unknown's avatar
unknown committed
776
    if (my_toupper(&my_charset_latin1, res[0]) == 'Y')
unknown's avatar
unknown committed
777
      access_bits|= bit;
unknown's avatar
unknown committed
778
  }
unknown's avatar
unknown committed
779 780
  if (next_field)
    *next_field=fieldnr;
unknown's avatar
unknown committed
781 782 783 784 785
  return access_bits;
}


/*
unknown's avatar
unknown committed
786 787 788 789 790
  Return a number which, if sorted 'desc', puts strings in this order:
    no wildcards
    wildcards
    empty string
*/
unknown's avatar
unknown committed
791 792 793 794 795 796 797

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

798 799 800
  /* Should not use this function with more than 4 arguments for compare. */
  DBUG_ASSERT(count <= 4);

unknown's avatar
unknown committed
801 802
  while (count--)
  {
803 804 805
    char *start, *str= va_arg(args,char*);
    uint chars= 0;
    uint wild_pos= 0;           /* first wildcard position */
unknown's avatar
unknown committed
806

unknown's avatar
unknown committed
807
    if ((start= str))
unknown's avatar
unknown committed
808 809 810
    {
      for (; *str ; str++)
      {
811 812 813
        if (*str == wild_prefix && str[1])
          str++;
        else if (*str == wild_many || *str == wild_one)
814
        {
unknown's avatar
unknown committed
815
          wild_pos= (uint) (str - start) + 1;
816 817
          break;
        }
unknown's avatar
unknown committed
818
        chars= 128;                             // Marker that chars existed
unknown's avatar
unknown committed
819 820
      }
    }
unknown's avatar
unknown committed
821
    sort= (sort << 8) + (wild_pos ? min(wild_pos, 127) : chars);
unknown's avatar
unknown committed
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
  }
  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;
}

837

838
/*
unknown's avatar
unknown committed
839 840
  Seek ACL entry for a user, check password, SSL cypher, and if
  everything is OK, update THD user data and USER_RESOURCES struct.
841

unknown's avatar
unknown committed
842 843 844 845
  IMPLEMENTATION
   This function does not check if the user has any sensible privileges:
   only user's existence and  validity is checked.
   Note, that entire operation is protected by acl_cache_lock.
unknown's avatar
unknown committed
846

847
  SYNOPSIS
848 849
    acl_getroot()
    thd         thread handle. If all checks are OK,
850 851
                thd->security_ctx->priv_user/master_access are updated.
                thd->security_ctx->host/ip/user are used for checks.
852 853
    mqh         user resources; on success mqh is reset, else
                unchanged
854
    passwd      scrambled & crypted password, received from client
855 856 857 858 859 860 861
                (to check): thd->scramble or thd->scramble_323 is
                used to decrypt passwd, so they must contain
                original random string,
    passwd_len  length of passwd, must be one of 0, 8,
                SCRAMBLE_LENGTH_323, SCRAMBLE_LENGTH
    'thd' and 'mqh' are updated on success; other params are IN.
  
unknown's avatar
unknown committed
862
  RETURN VALUE
863 864
    0  success: thd->priv_user, thd->priv_host, thd->master_access, mqh are
       updated
865
    1  user not found or authentication failure
unknown's avatar
unknown committed
866
    2  user found, has long (4.1.1) salt, but passwd is in old (3.23) format.
867
   -1  user found, has short (3.23) salt, but passwd is in new (4.1.1) format.
unknown's avatar
unknown committed
868 869
*/

870 871
int acl_getroot(THD *thd, USER_RESOURCES  *mqh,
                const char *passwd, uint passwd_len)
unknown's avatar
unknown committed
872
{
unknown's avatar
merge  
unknown committed
873 874 875
  ulong user_access= NO_ACCESS;
  int res= 1;
  ACL_USER *acl_user= 0;
876
  Security_context *sctx= thd->security_ctx;
877
  DBUG_ENTER("acl_getroot");
unknown's avatar
unknown committed
878 879

  if (!initialized)
880
  {
881 882 883
    /* 
      here if mysqld's been started with --skip-grant-tables option.
    */
884
    sctx->skip_grants();
unknown's avatar
merge  
unknown committed
885
    bzero((char*) mqh, sizeof(*mqh));
886
    DBUG_RETURN(0);
887
  }
888

unknown's avatar
unknown committed
889
  VOID(pthread_mutex_lock(&acl_cache->lock));
unknown's avatar
unknown committed
890

unknown's avatar
unknown committed
891
  /*
892 893 894
    Find acl entry in user database. Note, that find_acl_user is not the same,
    because it doesn't take into account the case when user is not empty,
    but acl_user->user is empty
unknown's avatar
unknown committed
895
  */
unknown's avatar
unknown committed
896

897
  for (uint i=0 ; i < acl_users.elements ; i++)
898
  {
unknown's avatar
unknown committed
899
    ACL_USER *acl_user_tmp= dynamic_element(&acl_users,i,ACL_USER*);
900
    if (!acl_user_tmp->user || !strcmp(sctx->user, acl_user_tmp->user))
unknown's avatar
unknown committed
901
    {
902
      if (compare_hostname(&acl_user_tmp->host, sctx->host, sctx->ip))
unknown's avatar
unknown committed
903
      {
904
        /* check password: it should be empty or valid */
unknown's avatar
unknown committed
905
        if (passwd_len == acl_user_tmp->salt_len)
unknown's avatar
unknown committed
906
        {
unknown's avatar
unknown committed
907
          if (acl_user_tmp->salt_len == 0 ||
unknown's avatar
unknown committed
908 909
              (acl_user_tmp->salt_len == SCRAMBLE_LENGTH ?
              check_scramble(passwd, thd->scramble, acl_user_tmp->salt) :
910
              check_scramble_323(passwd, thd->scramble,
unknown's avatar
unknown committed
911
                                 (ulong *) acl_user_tmp->salt)) == 0)
912
          {
unknown's avatar
unknown committed
913
            acl_user= acl_user_tmp;
914 915
            res= 0;
          }
unknown's avatar
unknown committed
916
        }
917
        else if (passwd_len == SCRAMBLE_LENGTH &&
unknown's avatar
unknown committed
918
                 acl_user_tmp->salt_len == SCRAMBLE_LENGTH_323)
919
          res= -1;
unknown's avatar
unknown committed
920
        else if (passwd_len == SCRAMBLE_LENGTH_323 &&
unknown's avatar
unknown committed
921
                 acl_user_tmp->salt_len == SCRAMBLE_LENGTH)
unknown's avatar
unknown committed
922
          res= 2;
923 924
        /* linear search complete: */
        break;
unknown's avatar
unknown committed
925
      }
unknown's avatar
unknown committed
926
    }
927
  }
928 929 930 931
  /*
    This was moved to separate tree because of heavy HAVE_OPENSSL case.
    If acl_user is not null, res is 0.
  */
unknown's avatar
unknown committed
932 933 934

  if (acl_user)
  {
935
    /* OK. User found and password checked continue validation */
936
#ifdef HAVE_OPENSSL
unknown's avatar
unknown committed
937
    Vio *vio=thd->net.vio;
unknown's avatar
unknown committed
938
    SSL *ssl= (SSL*) vio->ssl_arg;
939
#endif
unknown's avatar
merge  
unknown committed
940

941
    /*
unknown's avatar
unknown committed
942
      At this point we know that user is allowed to connect
943 944 945 946 947 948
      from given host by given username/password pair. Now
      we check if SSL is required, if user is using SSL and
      if X509 certificate attributes are OK
    */
    switch (acl_user->ssl_type) {
    case SSL_TYPE_NOT_SPECIFIED:		// Impossible
unknown's avatar
merge  
unknown committed
949 950
    case SSL_TYPE_NONE:				// SSL is not required
      user_access= acl_user->access;
951
      break;
952
#ifdef HAVE_OPENSSL
unknown's avatar
merge  
unknown committed
953
    case SSL_TYPE_ANY:				// Any kind of SSL is ok
954
      if (vio_type(vio) == VIO_TYPE_SSL)
unknown's avatar
merge  
unknown committed
955
	user_access= acl_user->access;
956 957 958 959 960
      break;
    case SSL_TYPE_X509: /* Client should have any valid certificate. */
      /*
	Connections with non-valid certificates are dropped already
	in sslaccept() anyway, so we do not check validity here.
unknown's avatar
merge  
unknown committed
961

unknown's avatar
unknown committed
962 963
	We need to check for absence of SSL because without SSL
	we should reject connection.
964
      */
unknown's avatar
unknown committed
965
      if (vio_type(vio) == VIO_TYPE_SSL &&
unknown's avatar
unknown committed
966 967
	  SSL_get_verify_result(ssl) == X509_V_OK &&
	  SSL_get_peer_certificate(ssl))
unknown's avatar
merge  
unknown committed
968
	user_access= acl_user->access;
969 970 971 972 973 974 975 976
      break;
    case SSL_TYPE_SPECIFIED: /* Client should have specified attrib */
      /*
	We do not check for absence of SSL because without SSL it does
	not pass all checks here anyway.
	If cipher name is specified, we compare it to actual cipher in
	use.
      */
unknown's avatar
unknown committed
977
      X509 *cert;
unknown's avatar
unknown committed
978
      if (vio_type(vio) != VIO_TYPE_SSL ||
unknown's avatar
unknown committed
979
	  SSL_get_verify_result(ssl) != X509_V_OK)
unknown's avatar
unknown committed
980
	break;
981
      if (acl_user->ssl_cipher)
unknown's avatar
unknown committed
982
      {
983
	DBUG_PRINT("info",("comparing ciphers: '%s' and '%s'",
unknown's avatar
unknown committed
984 985
			   acl_user->ssl_cipher,SSL_get_cipher(ssl)));
	if (!strcmp(acl_user->ssl_cipher,SSL_get_cipher(ssl)))
unknown's avatar
merge  
unknown committed
986
	  user_access= acl_user->access;
987 988
	else
	{
unknown's avatar
unknown committed
989
	  if (global_system_variables.log_warnings)
unknown's avatar
unknown committed
990 991 992
	    sql_print_information("X509 ciphers mismatch: should be '%s' but is '%s'",
			      acl_user->ssl_cipher,
			      SSL_get_cipher(ssl));
993 994
	  break;
	}
unknown's avatar
unknown committed
995
      }
996 997
      /* Prepare certificate (if exists) */
      DBUG_PRINT("info",("checkpoint 1"));
unknown's avatar
unknown committed
998 999 1000 1001 1002
      if (!(cert= SSL_get_peer_certificate(ssl)))
      {
	user_access=NO_ACCESS;
	break;
      }
1003
      DBUG_PRINT("info",("checkpoint 2"));
1004
      /* If X509 issuer is specified, we check it... */
1005
      if (acl_user->x509_issuer)
unknown's avatar
unknown committed
1006
      {
unknown's avatar
unknown committed
1007
        DBUG_PRINT("info",("checkpoint 3"));
unknown's avatar
unknown committed
1008 1009
        char *ptr = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
        DBUG_PRINT("info",("comparing issuers: '%s' and '%s'",
1010
			   acl_user->x509_issuer, ptr));
unknown's avatar
unknown committed
1011
        if (strcmp(acl_user->x509_issuer, ptr))
1012
        {
unknown's avatar
unknown committed
1013
          if (global_system_variables.log_warnings)
unknown's avatar
unknown committed
1014 1015
            sql_print_information("X509 issuer mismatch: should be '%s' "
			      "but is '%s'", acl_user->x509_issuer, ptr);
1016
          free(ptr);
1017
          user_access=NO_ACCESS;
unknown's avatar
unknown committed
1018
          break;
1019
        }
unknown's avatar
merge  
unknown committed
1020
        user_access= acl_user->access;
unknown's avatar
unknown committed
1021
        free(ptr);
unknown's avatar
unknown committed
1022
      }
1023 1024 1025 1026
      DBUG_PRINT("info",("checkpoint 4"));
      /* X509 subject is specified, we check it .. */
      if (acl_user->x509_subject)
      {
unknown's avatar
unknown committed
1027 1028 1029 1030
        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))
1031
        {
unknown's avatar
unknown committed
1032
          if (global_system_variables.log_warnings)
1033
            sql_print_information("X509 subject mismatch: should be '%s' but is '%s'",
unknown's avatar
unknown committed
1034
                            acl_user->x509_subject, ptr);
1035 1036 1037
          free(ptr);
          user_access=NO_ACCESS;
          break;
1038
        }
1039
        user_access= acl_user->access;
unknown's avatar
unknown committed
1040
        free(ptr);
1041 1042
      }
      break;
unknown's avatar
unknown committed
1043
#else  /* HAVE_OPENSSL */
unknown's avatar
unknown committed
1044
    default:
1045
      /*
unknown's avatar
unknown committed
1046 1047 1048
        If we don't have SSL but SSL is required for this user the 
        authentication should fail.
      */
1049 1050
      break;
#endif /* HAVE_OPENSSL */
unknown's avatar
unknown committed
1051
    }
1052 1053
    sctx->master_access= user_access;
    sctx->priv_user= acl_user->user ? sctx->user : (char *) "";
1054
    *mqh= acl_user->user_resource;
1055

1056
    if (acl_user->host.hostname)
1057
      strmake(sctx->priv_host, acl_user->host.hostname, MAX_HOSTNAME);
1058
    else
1059
      *sctx->priv_host= 0;
1060
  }
unknown's avatar
unknown committed
1061
  VOID(pthread_mutex_unlock(&acl_cache->lock));
1062
  DBUG_RETURN(res);
unknown's avatar
unknown committed
1063 1064 1065
}


1066
/*
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
  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)
1085 1086
{
  int res= 1;
1087
  uint i;
1088 1089 1090
  ACL_USER *acl_user= 0;
  DBUG_ENTER("acl_getroot_no_password");

1091 1092
  DBUG_PRINT("enter", ("Host: '%s', Ip: '%s', User: '%s', db: '%s'",
                       (host ? host : "(NULL)"), (ip ? ip : "(NULL)"),
1093
                       user, (db ? db : "(NULL)")));
1094 1095 1096 1097 1098
  sctx->user= user;
  sctx->host= host;
  sctx->ip= ip;
  sctx->host_or_ip= host ? host : (ip ? ip : "");

1099 1100
  if (!initialized)
  {
1101
    /*
1102 1103
      here if mysqld's been started with --skip-grant-tables option.
    */
1104
    sctx->skip_grants();
1105
    DBUG_RETURN(FALSE);
1106 1107 1108 1109
  }

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

1110 1111
  sctx->master_access= 0;
  sctx->db_access= 0;
1112 1113
  sctx->priv_user= (char *) "";
  *sctx->priv_host= 0;
1114

1115 1116 1117
  /*
     Find acl entry in user database.
     This is specially tailored to suit the check we do for CALL of
1118
     a stored procedure; user is set to what is actually a
1119 1120
     priv_user, which can be ''.
  */
1121
  for (i=0 ; i < acl_users.elements ; i++)
1122
  {
1123 1124 1125
    ACL_USER *acl_user_tmp= dynamic_element(&acl_users,i,ACL_USER*);
    if ((!acl_user_tmp->user && !user[0]) ||
        (acl_user_tmp->user && strcmp(user, acl_user_tmp->user) == 0))
1126
    {
1127
      if (compare_hostname(&acl_user_tmp->host, host, ip))
1128
      {
1129 1130 1131
        acl_user= acl_user_tmp;
        res= 0;
        break;
1132 1133 1134 1135 1136 1137
      }
    }
  }

  if (acl_user)
  {
1138 1139 1140 1141
    for (i=0 ; i < acl_dbs.elements ; i++)
    {
      ACL_DB *acl_db= dynamic_element(&acl_dbs, i, ACL_DB*);
      if (!acl_db->user ||
1142
	  (user && user[0] && !strcmp(user, acl_db->user)))
1143
      {
1144
	if (compare_hostname(&acl_db->host, host, ip))
1145
	{
1146
	  if (!acl_db->db || (db && !wild_compare(db, acl_db->db, 0)))
1147
	  {
1148
	    sctx->db_access= acl_db->access;
1149 1150 1151 1152 1153
	    break;
	  }
	}
      }
    }
1154 1155
    sctx->master_access= acl_user->access;
    sctx->priv_user= acl_user->user ? user : (char *) "";
1156 1157

    if (acl_user->host.hostname)
1158
      strmake(sctx->priv_host, acl_user->host.hostname, MAX_HOSTNAME);
1159
    else
1160
      *sctx->priv_host= 0;
1161 1162 1163 1164 1165
  }
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  DBUG_RETURN(res);
}

1166 1167
static uchar* check_get_key(ACL_USER *buff, size_t *length,
                            my_bool not_used __attribute__((unused)))
unknown's avatar
unknown committed
1168 1169
{
  *length=buff->hostname_length;
1170
  return (uchar*) buff->host.hostname;
unknown's avatar
unknown committed
1171 1172
}

1173

unknown's avatar
unknown committed
1174
static void acl_update_user(const char *user, const char *host,
1175
			    const char *password, uint password_len,
1176 1177 1178 1179
			    enum SSL_type ssl_type,
			    const char *ssl_cipher,
			    const char *x509_issuer,
			    const char *x509_subject,
unknown's avatar
unknown committed
1180
			    USER_RESOURCES  *mqh,
unknown's avatar
unknown committed
1181
			    ulong privileges)
unknown's avatar
unknown committed
1182
{
1183 1184
  safe_mutex_assert_owner(&acl_cache->lock);

unknown's avatar
unknown committed
1185 1186 1187 1188
  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] ||
1189
	acl_user->user && !strcmp(user,acl_user->user))
unknown's avatar
unknown committed
1190 1191
    {
      if (!acl_user->host.hostname && !host[0] ||
unknown's avatar
unknown committed
1192
	  acl_user->host.hostname &&
1193
	  !my_strcasecmp(system_charset_info, host, acl_user->host.hostname))
unknown's avatar
unknown committed
1194 1195
      {
	acl_user->access=privileges;
1196
	if (mqh->specified_limits & USER_RESOURCES::QUERIES_PER_HOUR)
1197
	  acl_user->user_resource.questions=mqh->questions;
1198
	if (mqh->specified_limits & USER_RESOURCES::UPDATES_PER_HOUR)
1199
	  acl_user->user_resource.updates=mqh->updates;
1200 1201 1202 1203
	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;
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
	if (ssl_type != SSL_TYPE_NOT_SPECIFIED)
	{
	  acl_user->ssl_type= ssl_type;
	  acl_user->ssl_cipher= (ssl_cipher ? strdup_root(&mem,ssl_cipher) :
				 0);
	  acl_user->x509_issuer= (x509_issuer ? strdup_root(&mem,x509_issuer) :
				  0);
	  acl_user->x509_subject= (x509_subject ?
				   strdup_root(&mem,x509_subject) : 0);
	}
unknown's avatar
unknown committed
1214 1215
	if (password)
	  set_user_salt(acl_user, password, password_len);
1216
        /* search complete: */
unknown's avatar
unknown committed
1217 1218 1219 1220 1221 1222 1223 1224
	break;
      }
    }
  }
}


static void acl_insert_user(const char *user, const char *host,
1225
			    const char *password, uint password_len,
1226 1227 1228 1229
			    enum SSL_type ssl_type,
			    const char *ssl_cipher,
			    const char *x509_issuer,
			    const char *x509_subject,
1230
			    USER_RESOURCES *mqh,
unknown's avatar
unknown committed
1231
			    ulong privileges)
unknown's avatar
unknown committed
1232 1233
{
  ACL_USER acl_user;
1234 1235 1236

  safe_mutex_assert_owner(&acl_cache->lock);

1237
  acl_user.user=*user ? strdup_root(&mem,user) : 0;
unknown's avatar
unknown committed
1238
  update_hostname(&acl_user.host, *host ? strdup_root(&mem, host): 0);
unknown's avatar
unknown committed
1239
  acl_user.access=privileges;
1240
  acl_user.user_resource = *mqh;
unknown's avatar
unknown committed
1241
  acl_user.sort=get_sort(2,acl_user.host.hostname,acl_user.user);
1242
  acl_user.hostname_length=(uint) strlen(host);
1243 1244 1245 1246 1247
  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;
1248 1249

  set_user_salt(&acl_user, password, password_len);
unknown's avatar
unknown committed
1250

1251
  VOID(push_dynamic(&acl_users,(uchar*) &acl_user));
1252 1253
  if (!acl_user.host.hostname ||
      (acl_user.host.hostname[0] == wild_many && !acl_user.host.hostname[1]))
unknown's avatar
unknown committed
1254
    allow_all_hosts=1;		// Anyone can connect /* purecov: tested */
1255 1256
  my_qsort((uchar*) dynamic_element(&acl_users,0,ACL_USER*),acl_users.elements,
	   sizeof(ACL_USER),(qsort_cmp) acl_compare);
unknown's avatar
unknown committed
1257

1258 1259
  /* Rebuild 'acl_check_hosts' since 'acl_users' has been modified */
  rebuild_check_host();
unknown's avatar
unknown committed
1260 1261 1262 1263
}


static void acl_update_db(const char *user, const char *host, const char *db,
unknown's avatar
unknown committed
1264
			  ulong privileges)
unknown's avatar
unknown committed
1265
{
1266 1267
  safe_mutex_assert_owner(&acl_cache->lock);

unknown's avatar
unknown committed
1268 1269 1270 1271 1272 1273 1274 1275
  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] ||
1276
	  acl_db->host.hostname &&
1277
          !strcmp(host, acl_db->host.hostname))
unknown's avatar
unknown committed
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
      {
	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);
	}
      }
    }
  }
}


1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
/*
  Insert a user/db/host combination into the global acl_cache

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

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

unknown's avatar
unknown committed
1307
static void acl_insert_db(const char *user, const char *host, const char *db,
unknown's avatar
unknown committed
1308
			  ulong privileges)
unknown's avatar
unknown committed
1309 1310
{
  ACL_DB acl_db;
1311
  safe_mutex_assert_owner(&acl_cache->lock);
unknown's avatar
unknown committed
1312
  acl_db.user=strdup_root(&mem,user);
1313
  update_hostname(&acl_db.host, *host ? strdup_root(&mem,host) : 0);
unknown's avatar
unknown committed
1314 1315 1316
  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);
1317
  VOID(push_dynamic(&acl_dbs,(uchar*) &acl_db));
1318 1319
  my_qsort((uchar*) dynamic_element(&acl_dbs,0,ACL_DB*),acl_dbs.elements,
	   sizeof(ACL_DB),(qsort_cmp) acl_compare);
unknown's avatar
unknown committed
1320 1321 1322
}


1323 1324 1325

/*
  Get privilege for a host, user and db combination
1326 1327 1328

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

1331
ulong acl_get(const char *host, const char *ip,
1332
              const char *user, const char *db, my_bool db_is_pattern)
unknown's avatar
unknown committed
1333
{
1334
  ulong host_access= ~(ulong)0, db_access= 0;
1335 1336
  uint i;
  size_t key_length;
unknown's avatar
unknown committed
1337
  char key[ACL_KEY_LENGTH],*tmp_db,*end;
unknown's avatar
unknown committed
1338
  acl_entry *entry;
unknown's avatar
unknown committed
1339
  DBUG_ENTER("acl_get");
unknown's avatar
unknown committed
1340 1341

  VOID(pthread_mutex_lock(&acl_cache->lock));
1342
  end=strmov((tmp_db=strmov(strmov(key, ip ? ip : "")+1,user)+1),db);
unknown's avatar
unknown committed
1343 1344
  if (lower_case_table_names)
  {
1345
    my_casedn_str(files_charset_info, tmp_db);
unknown's avatar
unknown committed
1346 1347
    db=tmp_db;
  }
1348 1349 1350
  key_length= (size_t) (end-key);
  if (!db_is_pattern && (entry=(acl_entry*) acl_cache->search((uchar*) key,
                                                              key_length)))
unknown's avatar
unknown committed
1351 1352 1353
  {
    db_access=entry->access;
    VOID(pthread_mutex_unlock(&acl_cache->lock));
unknown's avatar
unknown committed
1354 1355
    DBUG_PRINT("exit", ("access: 0x%lx", db_access));
    DBUG_RETURN(db_access);
unknown's avatar
unknown committed
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
  }

  /*
    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))
      {
1368
	if (!acl_db->db || !wild_compare(db,acl_db->db,db_is_pattern))
unknown's avatar
unknown committed
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
	{
	  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))
    {
1390
      if (!acl_host->db || !wild_compare(db,acl_host->db,db_is_pattern))
unknown's avatar
unknown committed
1391 1392 1393 1394 1395 1396 1397 1398
      {
	host_access=acl_host->access;		// Fully specified. Take it
	break;
      }
    }
  }
exit:
  /* Save entry in cache for quick retrieval */
1399 1400
  if (!db_is_pattern &&
      (entry= (acl_entry*) malloc(sizeof(acl_entry)+key_length)))
unknown's avatar
unknown committed
1401 1402 1403
  {
    entry->access=(db_access & host_access);
    entry->length=key_length;
1404
    memcpy((uchar*) entry->key,key,key_length);
unknown's avatar
unknown committed
1405 1406 1407
    acl_cache->add(entry);
  }
  VOID(pthread_mutex_unlock(&acl_cache->lock));
unknown's avatar
unknown committed
1408 1409
  DBUG_PRINT("exit", ("access: 0x%lx", db_access & host_access));
  DBUG_RETURN(db_access & host_access);
unknown's avatar
unknown committed
1410 1411
}

1412 1413 1414 1415 1416 1417 1418
/*
  Check if there are any possible matching entries for this host

  NOTES
    All host names without wild cards are stored in a hash table,
    entries with wildcards are stored in a dynamic array
*/
unknown's avatar
unknown committed
1419 1420 1421 1422

static void init_check_host(void)
{
  DBUG_ENTER("init_check_host");
1423
  VOID(my_init_dynamic_array(&acl_wild_hosts,sizeof(struct acl_host_and_ip),
unknown's avatar
unknown committed
1424
			  acl_users.elements,1));
1425
  VOID(hash_init(&acl_check_hosts,system_charset_info,acl_users.elements,0,0,
unknown's avatar
unknown committed
1426
		 (hash_get_key) check_get_key,0,0));
unknown's avatar
unknown committed
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
  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 *);
1441
	  if (!my_strcasecmp(system_charset_info,
1442
                             acl_user->host.hostname, acl->hostname))
unknown's avatar
unknown committed
1443 1444 1445
	    break;				// already stored
	}
	if (j == acl_wild_hosts.elements)	// If new
1446
	  (void) push_dynamic(&acl_wild_hosts,(uchar*) &acl_user->host);
unknown's avatar
unknown committed
1447
      }
1448 1449
      else if (!hash_search(&acl_check_hosts,(uchar*) acl_user->host.hostname,
			    strlen(acl_user->host.hostname)))
unknown's avatar
unknown committed
1450
      {
1451
	if (my_hash_insert(&acl_check_hosts,(uchar*) acl_user))
unknown's avatar
unknown committed
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
	{					// 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;
}


1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480
/*
  Rebuild lists used for checking of allowed hosts

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


unknown's avatar
unknown committed
1481 1482 1483 1484 1485 1486 1487 1488
/* 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));

1489 1490
  if (host && hash_search(&acl_check_hosts,(uchar*) host,strlen(host)) ||
      ip && hash_search(&acl_check_hosts,(uchar*) ip, strlen(ip)))
unknown's avatar
unknown committed
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
  {
    VOID(pthread_mutex_unlock(&acl_cache->lock));
    return 0;					// Found host
  }
  for (uint i=0 ; i < acl_wild_hosts.elements ; i++)
  {
    acl_host_and_ip *acl=dynamic_element(&acl_wild_hosts,i,acl_host_and_ip*);
    if (compare_hostname(acl, host, ip))
    {
      VOID(pthread_mutex_unlock(&acl_cache->lock));
      return 0;					// Host ok
    }
  }
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  return 1;					// Host is not allowed
}


unknown's avatar
unknown committed
1509 1510 1511 1512 1513 1514 1515 1516
/*
  Check if the user is allowed to change password

  SYNOPSIS:
    check_change_password()
    thd		THD
    host	hostname for the user
    user	user name
1517 1518 1519 1520
    new_password new password

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

unknown's avatar
unknown committed
1522
    RETURN VALUE
1523 1524
      0		OK
      1		ERROR  ; In this case the error is sent to the client.
unknown's avatar
unknown committed
1525 1526
*/

1527
int check_change_password(THD *thd, const char *host, const char *user,
1528
                           char *new_password, uint new_password_len)
unknown's avatar
unknown committed
1529
{
unknown's avatar
unknown committed
1530 1531
  if (!initialized)
  {
unknown's avatar
unknown committed
1532
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
1533
    return(1);
unknown's avatar
unknown committed
1534
  }
unknown's avatar
unknown committed
1535
  if (!thd->slave_thread &&
1536 1537 1538
      (strcmp(thd->security_ctx->user, user) ||
       my_strcasecmp(system_charset_info, host,
                     thd->security_ctx->priv_host)))
unknown's avatar
unknown committed
1539
  {
1540
    if (check_access(thd, UPDATE_ACL, "mysql",0,1,0,0))
unknown's avatar
unknown committed
1541
      return(1);
unknown's avatar
unknown committed
1542
  }
1543
  if (!thd->slave_thread && !thd->security_ctx->user[0])
unknown's avatar
unknown committed
1544
  {
unknown's avatar
unknown committed
1545 1546
    my_message(ER_PASSWORD_ANONYMOUS_USER, ER(ER_PASSWORD_ANONYMOUS_USER),
               MYF(0));
unknown's avatar
unknown committed
1547
    return(1);
unknown's avatar
unknown committed
1548
  }
1549
  size_t len= strlen(new_password);
unknown's avatar
unknown committed
1550
  if (len && len != SCRAMBLED_PASSWORD_CHAR_LENGTH &&
1551 1552
      len != SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
  {
unknown's avatar
unknown committed
1553
    my_error(ER_PASSWD_LENGTH, MYF(0), SCRAMBLED_PASSWORD_CHAR_LENGTH);
1554 1555
    return -1;
  }
unknown's avatar
unknown committed
1556 1557 1558 1559
  return(0);
}


1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
/*
  Change a password for a user

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

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

unknown's avatar
unknown committed
1575 1576 1577
bool change_password(THD *thd, const char *host, const char *user,
		     char *new_password)
{
1578 1579 1580 1581 1582
  TABLE_LIST tables;
  TABLE *table;
  /* Buffer should be extended when password length is extended. */
  char buff[512];
  ulong query_length;
1583
  uint new_password_len= (uint) strlen(new_password);
1584
  bool result= 1;
unknown's avatar
unknown committed
1585 1586 1587 1588 1589
  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

1590
  if (check_change_password(thd, host, user, new_password, new_password_len))
unknown's avatar
unknown committed
1591 1592
    DBUG_RETURN(1);

1593
  bzero((char*) &tables, sizeof(tables));
1594
  tables.alias= tables.table_name= (char*) "user";
1595 1596 1597 1598 1599 1600 1601
  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.
  */
1602
  if (thd->slave_thread && rpl_filter->is_on())
1603 1604 1605 1606 1607 1608 1609
  {
    /*
      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 */
1610
    if (!(thd->spcont || rpl_filter->tables_ok(0, &tables)))
1611 1612 1613 1614
      DBUG_RETURN(0);
  }
#endif

1615
  if (!(table= open_ltable(thd, &tables, TL_WRITE, 0)))
1616 1617
    DBUG_RETURN(1);

unknown's avatar
unknown committed
1618 1619
  VOID(pthread_mutex_lock(&acl_cache->lock));
  ACL_USER *acl_user;
1620
  if (!(acl_user= find_acl_user(host, user, TRUE)))
unknown's avatar
unknown committed
1621 1622
  {
    VOID(pthread_mutex_unlock(&acl_cache->lock));
unknown's avatar
unknown committed
1623
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH), MYF(0));
1624
    goto end;
unknown's avatar
unknown committed
1625
  }
1626 1627 1628
  /* update loaded acl entry: */
  set_user_salt(acl_user, new_password, new_password_len);

1629
  if (update_user_table(thd, table,
unknown's avatar
unknown committed
1630
			acl_user->host.hostname ? acl_user->host.hostname : "",
unknown's avatar
unknown committed
1631
			acl_user->user ? acl_user->user : "",
1632
			new_password, new_password_len))
unknown's avatar
unknown committed
1633 1634
  {
    VOID(pthread_mutex_unlock(&acl_cache->lock)); /* purecov: deadcode */
1635
    goto end;
unknown's avatar
unknown committed
1636
  }
unknown's avatar
unknown committed
1637

unknown's avatar
unknown committed
1638 1639
  acl_cache->clear(1);				// Clear locked hostname cache
  VOID(pthread_mutex_unlock(&acl_cache->lock));
1640 1641 1642
  result= 0;
  if (mysql_bin_log.is_open())
  {
1643 1644
    query_length=
      my_sprintf(buff,
1645
                 (buff,"SET PASSWORD FOR '%-.120s'@'%-.120s'='%-.120s'",
1646 1647 1648
                  acl_user->user ? acl_user->user : "",
                  acl_user->host.hostname ? acl_user->host.hostname : "",
                  new_password));
1649
    thd->clear_error();
1650
    thd->binlog_query(THD::MYSQL_QUERY_TYPE, buff, query_length, FALSE, FALSE);
1651 1652 1653 1654
  }
end:
  close_thread_tables(thd);
  DBUG_RETURN(result);
unknown's avatar
unknown committed
1655 1656 1657
}


1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
/*
  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;
1674 1675 1676 1677 1678

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

1679
  VOID(pthread_mutex_lock(&acl_cache->lock));
1680
  res= find_acl_user(host, user, TRUE) != NULL;
1681 1682 1683 1684 1685
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  return res;
}


unknown's avatar
unknown committed
1686 1687 1688 1689 1690
/*
  Find first entry that matches the current user
*/

static ACL_USER *
1691
find_acl_user(const char *host, const char *user, my_bool exact)
unknown's avatar
unknown committed
1692
{
unknown's avatar
unknown committed
1693
  DBUG_ENTER("find_acl_user");
1694
  DBUG_PRINT("enter",("host: '%s'  user: '%s'",host,user));
1695 1696 1697

  safe_mutex_assert_owner(&acl_cache->lock);

unknown's avatar
unknown committed
1698 1699 1700
  for (uint i=0 ; i < acl_users.elements ; i++)
  {
    ACL_USER *acl_user=dynamic_element(&acl_users,i,ACL_USER*);
unknown's avatar
unknown committed
1701
    DBUG_PRINT("info",("strcmp('%s','%s'), compare_hostname('%s','%s'),",
1702 1703 1704 1705
                       user, acl_user->user ? acl_user->user : "",
                       host,
                       acl_user->host.hostname ? acl_user->host.hostname :
                       ""));
unknown's avatar
unknown committed
1706 1707 1708
    if (!acl_user->user && !user[0] ||
	acl_user->user && !strcmp(user,acl_user->user))
    {
1709
      if (exact ? !my_strcasecmp(system_charset_info, host,
1710 1711
                                 acl_user->host.hostname ?
				 acl_user->host.hostname : "") :
1712
          compare_hostname(&acl_user->host,host,host))
unknown's avatar
unknown committed
1713 1714 1715
      {
	DBUG_RETURN(acl_user);
      }
unknown's avatar
unknown committed
1716 1717
    }
  }
unknown's avatar
unknown committed
1718
  DBUG_RETURN(0);
unknown's avatar
unknown committed
1719 1720 1721
}


1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
/*
  Comparing of hostnames

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

  A net mask of 0.0.0.0 is not allowed.
*/
unknown's avatar
unknown committed
1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754

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)
{
1755
  host->hostname=(char*) hostname;             // This will not be modified!
1756
  if (!hostname ||
unknown's avatar
unknown committed
1757 1758 1759
      (!(hostname=calc_ip(hostname,&host->ip,'/')) ||
       !(hostname=calc_ip(hostname+1,&host->ip_mask,'\0'))))
  {
1760
    host->ip= host->ip_mask=0;			// Not a masked ip
unknown's avatar
unknown committed
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
  }
}


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 ||
1774
	  (hostname && !wild_case_compare(system_charset_info,
1775 1776
                                          hostname, host->hostname)) ||
	  (ip && !wild_compare(ip, host->hostname, 0)));
unknown's avatar
unknown committed
1777 1778
}

unknown's avatar
SCRUM  
unknown committed
1779 1780 1781 1782
bool hostname_requires_resolving(const char *hostname)
{
  char cur;
  if (!hostname)
unknown's avatar
unknown committed
1783
    return FALSE;
1784 1785
  size_t namelen= strlen(hostname);
  size_t lhlen= strlen(my_localhost);
unknown's avatar
SCRUM  
unknown committed
1786
  if ((namelen == lhlen) &&
1787
      !my_strnncoll(system_charset_info, (const uchar *)hostname,  namelen,
unknown's avatar
SCRUM  
unknown committed
1788
		    (const uchar *)my_localhost, strlen(my_localhost)))
unknown's avatar
unknown committed
1789
    return FALSE;
unknown's avatar
SCRUM  
unknown committed
1790 1791
  for (; (cur=*hostname); hostname++)
  {
1792
    if ((cur != '%') && (cur != '_') && (cur != '.') && (cur != '/') &&
unknown's avatar
SCRUM  
unknown committed
1793
	((cur < '0') || (cur > '9')))
unknown's avatar
unknown committed
1794
      return TRUE;
unknown's avatar
SCRUM  
unknown committed
1795
  }
unknown's avatar
unknown committed
1796
  return FALSE;
unknown's avatar
SCRUM  
unknown committed
1797
}
unknown's avatar
unknown committed
1798

1799

1800
/*
1801 1802 1803 1804 1805 1806 1807 1808 1809 1810
  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
1811
*/
unknown's avatar
unknown committed
1812

1813 1814
static bool update_user_table(THD *thd, TABLE *table,
                              const char *host, const char *user,
1815
			      const char *new_password, uint new_password_len)
unknown's avatar
unknown committed
1816
{
1817
  char user_key[MAX_KEY_LENGTH];
1818
  int error;
unknown's avatar
unknown committed
1819 1820 1821
  DBUG_ENTER("update_user_table");
  DBUG_PRINT("enter",("user: %s  host: %s",user,host));

1822
  table->use_all_columns();
1823 1824
  table->field[0]->store(host,(uint) strlen(host), system_charset_info);
  table->field[1]->store(user,(uint) strlen(user), system_charset_info);
1825
  key_copy((uchar *) user_key, table->record[0], table->key_info,
1826
           table->key_info->key_length);
unknown's avatar
unknown committed
1827

1828 1829 1830
  if (table->file->index_read_idx_map(table->record[0], 0,
                                      (uchar *) user_key, HA_WHOLE_KEY,
                                      HA_READ_KEY_EXACT))
unknown's avatar
unknown committed
1831
  {
unknown's avatar
unknown committed
1832 1833
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH),
               MYF(0));	/* purecov: deadcode */
unknown's avatar
unknown committed
1834 1835
    DBUG_RETURN(1);				/* purecov: deadcode */
  }
unknown's avatar
unknown committed
1836
  store_record(table,record[1]);
1837
  table->field[2]->store(new_password, new_password_len, system_charset_info);
1838 1839
  if ((error=table->file->ha_update_row(table->record[1],table->record[0])) &&
      error != HA_ERR_RECORD_IS_THE_SAME)
unknown's avatar
unknown committed
1840 1841
  {
    table->file->print_error(error,MYF(0));	/* purecov: deadcode */
1842
    DBUG_RETURN(1);
unknown's avatar
unknown committed
1843
  }
1844
  DBUG_RETURN(0);
unknown's avatar
unknown committed
1845 1846
}

unknown's avatar
unknown committed
1847

1848 1849 1850 1851 1852 1853
/*
  Return 1 if we are allowed to create new users
  the logic here is: INSERT_ACL is sufficient.
  It's also a requirement in opt_safe_user_create,
  otherwise CREATE_USER_ACL is enough.
*/
unknown's avatar
unknown committed
1854 1855 1856

static bool test_if_create_new_users(THD *thd)
{
1857
  Security_context *sctx= thd->security_ctx;
1858
  bool create_new_users= test(sctx->master_access & INSERT_ACL) ||
1859
                         (!opt_safe_user_create &&
1860
                          test(sctx->master_access & CREATE_USER_ACL));
1861
  if (!create_new_users)
unknown's avatar
unknown committed
1862 1863
  {
    TABLE_LIST tl;
unknown's avatar
unknown committed
1864
    ulong db_access;
unknown's avatar
unknown committed
1865 1866
    bzero((char*) &tl,sizeof(tl));
    tl.db=	   (char*) "mysql";
1867
    tl.table_name=  (char*) "user";
1868
    create_new_users= 1;
unknown's avatar
unknown committed
1869

1870 1871
    db_access=acl_get(sctx->host, sctx->ip,
		      sctx->priv_user, tl.db, 0);
unknown's avatar
unknown committed
1872 1873
    if (!(db_access & INSERT_ACL))
    {
unknown's avatar
unknown committed
1874
      if (check_grant(thd, INSERT_ACL, &tl, 0, UINT_MAX, 1))
unknown's avatar
unknown committed
1875 1876 1877 1878 1879 1880 1881
	create_new_users=0;
    }
  }
  return create_new_users;
}


unknown's avatar
unknown committed
1882
/****************************************************************************
1883
  Handle GRANT commands
unknown's avatar
unknown committed
1884 1885
****************************************************************************/

1886
static int replace_user_table(THD *thd, TABLE *table, const LEX_USER &combo,
unknown's avatar
unknown committed
1887
			      ulong rights, bool revoke_grant,
unknown's avatar
unknown committed
1888
			      bool can_create_user, bool no_auto_create)
unknown's avatar
unknown committed
1889 1890
{
  int error = -1;
unknown's avatar
unknown committed
1891
  bool old_row_exists=0;
1892
  const char *password= "";
1893
  uint password_len= 0;
unknown's avatar
unknown committed
1894
  char what= (revoke_grant) ? 'N' : 'Y';
1895
  uchar user_key[MAX_KEY_LENGTH];
1896
  LEX *lex= thd->lex;
unknown's avatar
unknown committed
1897
  DBUG_ENTER("replace_user_table");
unknown's avatar
unknown committed
1898

1899
  safe_mutex_assert_owner(&acl_cache->lock);
unknown's avatar
unknown committed
1900 1901

  if (combo.password.str && combo.password.str[0])
1902
  {
1903 1904
    if (combo.password.length != SCRAMBLED_PASSWORD_CHAR_LENGTH &&
        combo.password.length != SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
1905
    {
1906
      my_error(ER_PASSWD_LENGTH, MYF(0), SCRAMBLED_PASSWORD_CHAR_LENGTH);
unknown's avatar
unknown committed
1907
      DBUG_RETURN(-1);
1908
    }
1909
    password_len= combo.password.length;
unknown's avatar
unknown committed
1910
    password=combo.password.str;
1911
  }
unknown's avatar
unknown committed
1912

1913 1914 1915 1916 1917
  table->use_all_columns();
  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);
1918 1919 1920
  key_copy(user_key, table->record[0], table->key_info,
           table->key_info->key_length);

1921 1922 1923
  if (table->file->index_read_idx_map(table->record[0], 0, user_key,
                                      HA_WHOLE_KEY,
                                      HA_READ_KEY_EXACT))
unknown's avatar
unknown committed
1924
  {
1925 1926
    /* what == 'N' means revoke */
    if (what == 'N')
unknown's avatar
unknown committed
1927
    {
1928 1929 1930 1931
      my_error(ER_NONEXISTING_GRANT, MYF(0), combo.user.str, combo.host.str);
      goto end;
    }
    /*
1932 1933
      There are four options which affect the process of creation of
      a new user (mysqld option --safe-create-user, 'insert' privilege
1934 1935 1936 1937 1938 1939 1940
      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
1941 1942

      see also test_if_create_new_users()
1943
    */
unknown's avatar
unknown committed
1944 1945 1946 1947 1948 1949
    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)
1950
    {
unknown's avatar
unknown committed
1951
      my_error(ER_CANT_CREATE_USER_WITH_GRANT, MYF(0),
1952
               thd->security_ctx->user, thd->security_ctx->host_or_ip);
unknown's avatar
unknown committed
1953 1954
      goto end;
    }
unknown's avatar
unknown committed
1955
    old_row_exists = 0;
1956
    restore_record(table,s->default_values);
1957
    table->field[0]->store(combo.host.str,combo.host.length,
1958
                           system_charset_info);
1959
    table->field[1]->store(combo.user.str,combo.user.length,
1960
                           system_charset_info);
1961
    table->field[2]->store(password, password_len,
1962
                           system_charset_info);
unknown's avatar
unknown committed
1963 1964 1965
  }
  else
  {
unknown's avatar
unknown committed
1966
    old_row_exists = 1;
unknown's avatar
unknown committed
1967
    store_record(table,record[1]);			// Save copy for update
unknown's avatar
unknown committed
1968
    if (combo.password.str)			// If password given
1969
      table->field[2]->store(password, password_len, system_charset_info);
1970
    else if (!rights && !revoke_grant &&
1971 1972
             lex->ssl_type == SSL_TYPE_NOT_SPECIFIED &&
             !lex->mqh.specified_limits)
unknown's avatar
unknown committed
1973 1974 1975
    {
      DBUG_RETURN(0);
    }
unknown's avatar
unknown committed
1976 1977
  }

unknown's avatar
unknown committed
1978 1979 1980 1981
  /* Update table columns with new privileges */

  Field **tmp_field;
  ulong priv;
1982
  uint next_field;
unknown's avatar
unknown committed
1983
  for (tmp_field= table->field+3, priv = SELECT_ACL;
1984
       *tmp_field && (*tmp_field)->real_type() == MYSQL_TYPE_ENUM &&
unknown's avatar
unknown committed
1985 1986
	 ((Field_enum*) (*tmp_field))->typelib->count == 2 ;
       tmp_field++, priv <<= 1)
unknown's avatar
unknown committed
1987
  {
unknown's avatar
unknown committed
1988
    if (priv & rights)				 // set requested privileges
unknown's avatar
unknown committed
1989
      (*tmp_field)->store(&what, 1, &my_charset_latin1);
unknown's avatar
unknown committed
1990
  }
1991
  rights= get_access(table, 3, &next_field);
1992 1993
  DBUG_PRINT("info",("table fields: %d",table->s->fields));
  if (table->s->fields >= 31)		/* From 4.0.0 we have more fields */
1994
  {
unknown's avatar
unknown committed
1995
    /* We write down SSL related ACL stuff */
1996
    switch (lex->ssl_type) {
1997
    case SSL_TYPE_ANY:
1998 1999
      table->field[next_field]->store(STRING_WITH_LEN("ANY"),
                                      &my_charset_latin1);
2000 2001 2002
      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);
2003 2004
      break;
    case SSL_TYPE_X509:
2005 2006
      table->field[next_field]->store(STRING_WITH_LEN("X509"),
                                      &my_charset_latin1);
2007 2008 2009
      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);
2010 2011
      break;
    case SSL_TYPE_SPECIFIED:
2012 2013
      table->field[next_field]->store(STRING_WITH_LEN("SPECIFIED"),
                                      &my_charset_latin1);
2014 2015 2016
      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);
2017
      if (lex->ssl_cipher)
unknown's avatar
unknown committed
2018 2019
        table->field[next_field+1]->store(lex->ssl_cipher,
                                strlen(lex->ssl_cipher), system_charset_info);
2020
      if (lex->x509_issuer)
unknown's avatar
unknown committed
2021 2022
        table->field[next_field+2]->store(lex->x509_issuer,
                                strlen(lex->x509_issuer), system_charset_info);
2023
      if (lex->x509_subject)
unknown's avatar
unknown committed
2024 2025
        table->field[next_field+3]->store(lex->x509_subject,
                                strlen(lex->x509_subject), system_charset_info);
2026
      break;
unknown's avatar
unknown committed
2027
    case SSL_TYPE_NOT_SPECIFIED:
unknown's avatar
unknown committed
2028 2029
      break;
    case SSL_TYPE_NONE:
2030 2031 2032 2033
      table->field[next_field]->store("", 0, &my_charset_latin1);
      table->field[next_field+1]->store("", 0, &my_charset_latin1);
      table->field[next_field+2]->store("", 0, &my_charset_latin1);
      table->field[next_field+3]->store("", 0, &my_charset_latin1);
unknown's avatar
unknown committed
2034
      break;
2035
    }
unknown's avatar
unknown committed
2036
    next_field+=4;
unknown's avatar
unknown committed
2037

2038
    USER_RESOURCES mqh= lex->mqh;
2039
    if (mqh.specified_limits & USER_RESOURCES::QUERIES_PER_HOUR)
2040
      table->field[next_field]->store((longlong) mqh.questions, TRUE);
2041
    if (mqh.specified_limits & USER_RESOURCES::UPDATES_PER_HOUR)
2042
      table->field[next_field+1]->store((longlong) mqh.updates, TRUE);
2043
    if (mqh.specified_limits & USER_RESOURCES::CONNECTIONS_PER_HOUR)
2044
      table->field[next_field+2]->store((longlong) mqh.conn_per_hour, TRUE);
2045
    if (table->s->fields >= 36 &&
2046
        (mqh.specified_limits & USER_RESOURCES::USER_CONNECTIONS))
2047
      table->field[next_field+3]->store((longlong) mqh.user_conn, TRUE);
2048
    mqh_used= mqh_used || mqh.questions || mqh.updates || mqh.conn_per_hour;
2049
  }
unknown's avatar
unknown committed
2050
  if (old_row_exists)
unknown's avatar
unknown committed
2051 2052 2053 2054 2055
  {
    /*
      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!
    */
2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067
    if (cmp_record(table,record[1]))
    {
      if ((error=
           table->file->ha_update_row(table->record[1],table->record[0])) &&
          error != HA_ERR_RECORD_IS_THE_SAME)
      {						// This should never happen
        table->file->print_error(error,MYF(0));	/* purecov: deadcode */
        error= -1;				/* purecov: deadcode */
        goto end;				/* purecov: deadcode */
      }
      else
        error= 0;
unknown's avatar
unknown committed
2068 2069
    }
  }
2070
  else if ((error=table->file->ha_write_row(table->record[0]))) // insert
unknown's avatar
unknown committed
2071
  {						// This should never happen
2072
    if (table->file->is_fatal_error(error, HA_CHECK_DUP))
unknown's avatar
unknown committed
2073 2074 2075 2076 2077 2078 2079 2080
    {
      table->file->print_error(error,MYF(0));	/* purecov: deadcode */
      error= -1;				/* purecov: deadcode */
      goto end;					/* purecov: deadcode */
    }
  }
  error=0;					// Privileges granted / revoked

2081
end:
unknown's avatar
unknown committed
2082 2083 2084
  if (!error)
  {
    acl_cache->clear(1);			// Clear privilege cache
unknown's avatar
unknown committed
2085
    if (old_row_exists)
2086 2087
      acl_update_user(combo.user.str, combo.host.str,
                      combo.password.str, password_len,
2088 2089 2090 2091 2092
		      lex->ssl_type,
		      lex->ssl_cipher,
		      lex->x509_issuer,
		      lex->x509_subject,
		      &lex->mqh,
2093
		      rights);
unknown's avatar
unknown committed
2094
    else
2095
      acl_insert_user(combo.user.str, combo.host.str, password, password_len,
2096 2097 2098 2099 2100
		      lex->ssl_type,
		      lex->ssl_cipher,
		      lex->x509_issuer,
		      lex->x509_subject,
		      &lex->mqh,
2101
		      rights);
unknown's avatar
unknown committed
2102 2103 2104 2105 2106 2107
  }
  DBUG_RETURN(error);
}


/*
unknown's avatar
unknown committed
2108
  change grants in the mysql.db table
unknown's avatar
unknown committed
2109 2110 2111 2112
*/

static int replace_db_table(TABLE *table, const char *db,
			    const LEX_USER &combo,
unknown's avatar
unknown committed
2113
			    ulong rights, bool revoke_grant)
unknown's avatar
unknown committed
2114
{
unknown's avatar
unknown committed
2115 2116
  uint i;
  ulong priv,store_rights;
unknown's avatar
unknown committed
2117
  bool old_row_exists=0;
unknown's avatar
unknown committed
2118
  int error;
unknown's avatar
unknown committed
2119
  char what= (revoke_grant) ? 'N' : 'Y';
2120
  uchar user_key[MAX_KEY_LENGTH];
unknown's avatar
unknown committed
2121 2122
  DBUG_ENTER("replace_db_table");

2123 2124
  if (!initialized)
  {
unknown's avatar
unknown committed
2125
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
2126 2127 2128
    DBUG_RETURN(-1);
  }

2129
  /* Check if there is such a user in user table in memory? */
2130
  if (!find_acl_user(combo.host.str,combo.user.str, FALSE))
unknown's avatar
unknown committed
2131
  {
unknown's avatar
unknown committed
2132
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH), MYF(0));
unknown's avatar
unknown committed
2133 2134 2135
    DBUG_RETURN(-1);
  }

2136 2137 2138
  table->use_all_columns();
  table->field[0]->store(combo.host.str,combo.host.length,
                         system_charset_info);
2139
  table->field[1]->store(db,(uint) strlen(db), system_charset_info);
2140 2141
  table->field[2]->store(combo.user.str,combo.user.length,
                         system_charset_info);
2142 2143 2144
  key_copy(user_key, table->record[0], table->key_info,
           table->key_info->key_length);

2145 2146 2147
  if (table->file->index_read_idx_map(table->record[0],0, user_key,
                                      HA_WHOLE_KEY,
                                      HA_READ_KEY_EXACT))
unknown's avatar
unknown committed
2148 2149 2150
  {
    if (what == 'N')
    { // no row, no revoke
unknown's avatar
unknown committed
2151
      my_error(ER_NONEXISTING_GRANT, MYF(0), combo.user.str, combo.host.str);
unknown's avatar
unknown committed
2152 2153
      goto abort;
    }
unknown's avatar
unknown committed
2154
    old_row_exists = 0;
2155
    restore_record(table, s->default_values);
2156 2157
    table->field[0]->store(combo.host.str,combo.host.length,
                           system_charset_info);
2158
    table->field[1]->store(db,(uint) strlen(db), system_charset_info);
2159 2160
    table->field[2]->store(combo.user.str,combo.user.length,
                           system_charset_info);
unknown's avatar
unknown committed
2161 2162 2163
  }
  else
  {
unknown's avatar
unknown committed
2164
    old_row_exists = 1;
unknown's avatar
unknown committed
2165
    store_record(table,record[1]);
unknown's avatar
unknown committed
2166 2167 2168
  }

  store_rights=get_rights_for_db(rights);
2169
  for (i= 3, priv= 1; i < table->s->fields; i++, priv <<= 1)
unknown's avatar
unknown committed
2170
  {
unknown's avatar
unknown committed
2171
    if (priv & store_rights)			// do it if priv is chosen
unknown's avatar
unknown committed
2172
      table->field [i]->store(&what,1, &my_charset_latin1);// set requested privileges
unknown's avatar
unknown committed
2173 2174 2175 2176
  }
  rights=get_access(table,3);
  rights=fix_rights_for_db(rights);

unknown's avatar
unknown committed
2177
  if (old_row_exists)
unknown's avatar
unknown committed
2178
  {
2179
    /* update old existing row */
unknown's avatar
unknown committed
2180 2181
    if (rights)
    {
2182
      if ((error= table->file->ha_update_row(table->record[1],
2183 2184
                                             table->record[0])) &&
          error != HA_ERR_RECORD_IS_THE_SAME)
unknown's avatar
unknown committed
2185 2186 2187 2188
	goto table_error;			/* purecov: deadcode */
    }
    else	/* must have been a revoke of all privileges */
    {
2189
      if ((error= table->file->ha_delete_row(table->record[1])))
unknown's avatar
unknown committed
2190 2191 2192
	goto table_error;			/* purecov: deadcode */
    }
  }
2193
  else if (rights && (error= table->file->ha_write_row(table->record[0])))
unknown's avatar
unknown committed
2194
  {
2195
    if (table->file->is_fatal_error(error, HA_CHECK_DUP_KEY))
unknown's avatar
unknown committed
2196 2197 2198 2199
      goto table_error; /* purecov: deadcode */
  }

  acl_cache->clear(1);				// Clear privilege cache
unknown's avatar
unknown committed
2200
  if (old_row_exists)
unknown's avatar
unknown committed
2201 2202
    acl_update_db(combo.user.str,combo.host.str,db,rights);
  else
2203
  if (rights)
unknown's avatar
unknown committed
2204 2205 2206 2207
    acl_insert_db(combo.user.str,combo.host.str,db,rights);
  DBUG_RETURN(0);

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

2211
abort:
unknown's avatar
unknown committed
2212 2213 2214 2215 2216 2217 2218 2219
  DBUG_RETURN(-1);
}


class GRANT_COLUMN :public Sql_alloc
{
public:
  char *column;
unknown's avatar
unknown committed
2220 2221 2222
  ulong rights;
  uint key_length;
  GRANT_COLUMN(String &c,  ulong y) :rights (y)
unknown's avatar
unknown committed
2223
  {
2224
    column= (char*) memdup_root(&memex,c.ptr(), key_length=c.length());
unknown's avatar
unknown committed
2225 2226 2227
  }
};

unknown's avatar
unknown committed
2228

2229
static uchar* get_key_column(GRANT_COLUMN *buff, size_t *length,
unknown's avatar
unknown committed
2230 2231 2232
			    my_bool not_used __attribute__((unused)))
{
  *length=buff->key_length;
2233
  return (uchar*) buff->column;
unknown's avatar
unknown committed
2234 2235
}

unknown's avatar
unknown committed
2236

2237
class GRANT_NAME :public Sql_alloc
unknown's avatar
unknown committed
2238 2239
{
public:
2240 2241
  acl_host_and_ip host;
  char *db, *user, *tname, *hash_key;
2242
  ulong privs;
2243
  ulong sort;
2244
  size_t key_length;
2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256
  GRANT_NAME(const char *h, const char *d,const char *u,
             const char *t, ulong p);
  GRANT_NAME (TABLE *form);
  virtual ~GRANT_NAME() {};
  virtual bool ok() { return privs != 0; }
};


class GRANT_TABLE :public GRANT_NAME
{
public:
  ulong cols;
unknown's avatar
unknown committed
2257
  HASH hash_columns;
unknown's avatar
unknown committed
2258 2259 2260 2261

  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);
2262
  ~GRANT_TABLE();
2263 2264
  bool ok() { return privs != 0 || cols != 0; }
};
unknown's avatar
unknown committed
2265

2266

unknown's avatar
unknown committed
2267

2268 2269 2270
GRANT_NAME::GRANT_NAME(const char *h, const char *d,const char *u,
                       const char *t, ulong p)
  :privs(p)
2271 2272
{
  /* Host given by user */
2273
  update_hostname(&host, strdup_root(&memex, h));
2274 2275
  db =   strdup_root(&memex,d);
  user = strdup_root(&memex,u);
2276
  sort=  get_sort(3,host.hostname,db,user);
2277 2278
  tname= strdup_root(&memex,t);
  if (lower_case_table_names)
unknown's avatar
unknown committed
2279
  {
2280 2281
    my_casedn_str(files_charset_info, db);
    my_casedn_str(files_charset_info, tname);
2282
  }
2283 2284
  key_length= strlen(d) + strlen(u)+ strlen(t)+3;
  hash_key=   (char*) alloc_root(&memex,key_length);
2285
  strmov(strmov(strmov(hash_key,user)+1,db)+1,tname);
2286 2287 2288 2289 2290 2291 2292
}


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)
{
2293
  (void) hash_init2(&hash_columns,4,system_charset_info,
unknown's avatar
unknown committed
2294
                   0,0,0, (hash_get_key) get_key_column,0,0);
2295
}
unknown's avatar
unknown committed
2296

2297

2298
GRANT_NAME::GRANT_NAME(TABLE *form)
2299
{
2300
  update_hostname(&host, get_field(&memex, form->field[0]));
unknown's avatar
unknown committed
2301 2302
  db=    get_field(&memex,form->field[1]);
  user=  get_field(&memex,form->field[2]);
2303 2304
  if (!user)
    user= (char*) "";
2305
  sort=  get_sort(3, host.hostname, db, user);
unknown's avatar
unknown committed
2306
  tname= get_field(&memex,form->field[3]);
2307 2308 2309
  if (!db || !tname)
  {
    /* Wrong table row; Ignore it */
2310
    privs= 0;
2311 2312 2313 2314
    return;					/* purecov: inspected */
  }
  if (lower_case_table_names)
  {
2315 2316
    my_casedn_str(files_charset_info, db);
    my_casedn_str(files_charset_info, tname);
2317
  }
2318 2319
  key_length= (strlen(db) + strlen(user) + strlen(tname) + 3);
  hash_key=   (char*) alloc_root(&memex, key_length);
2320 2321 2322
  strmov(strmov(strmov(hash_key,user)+1,db)+1,tname);
  privs = (ulong) form->field[6]->val_int();
  privs = fix_rights_for_table(privs);
2323 2324 2325 2326 2327 2328
}


GRANT_TABLE::GRANT_TABLE(TABLE *form, TABLE *col_privs)
  :GRANT_NAME(form)
{
2329
  uchar key[MAX_KEY_LENGTH];
2330 2331 2332 2333 2334 2335 2336 2337 2338

  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();
2339 2340
  cols =  fix_rights_for_column(cols);

2341
  (void) hash_init2(&hash_columns,4,system_charset_info,
unknown's avatar
unknown committed
2342
                   0,0,0, (hash_get_key) get_key_column,0,0);
2343 2344
  if (cols)
  {
2345 2346
    uint key_prefix_len;
    KEY_PART_INFO *key_part= col_privs->key_info->key_part;
2347
    col_privs->field[0]->store(host.hostname,
2348 2349
                               host.hostname ? (uint) strlen(host.hostname) :
                               0,
2350 2351 2352 2353
                               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);
2354 2355 2356 2357 2358 2359

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

2362
    col_privs->file->ha_index_init(0, 1);
2363 2364
    if (col_privs->file->index_read_map(col_privs->record[0], (uchar*) key,
                                        (key_part_map)15, HA_READ_KEY_EXACT))
unknown's avatar
unknown committed
2365
    {
2366
      cols = 0; /* purecov: deadcode */
2367
      col_privs->file->ha_index_end();
2368
      return;
unknown's avatar
unknown committed
2369
    }
2370
    do
unknown's avatar
unknown committed
2371
    {
2372 2373 2374
      String *res,column_name;
      GRANT_COLUMN *mem_check;
      /* As column name is a string, we don't have to supply a buffer */
unknown's avatar
unknown committed
2375
      res=col_privs->field[4]->val_str(&column_name);
2376 2377 2378
      ulong priv= (ulong) col_privs->field[6]->val_int();
      if (!(mem_check = new GRANT_COLUMN(*res,
                                         fix_rights_for_column(priv))))
unknown's avatar
unknown committed
2379
      {
2380 2381 2382
        /* Don't use this entry */
        privs = cols = 0;			/* purecov: deadcode */
        return;				/* purecov: deadcode */
unknown's avatar
unknown committed
2383
      }
2384
      my_hash_insert(&hash_columns, (uchar *) mem_check);
2385
    } while (!col_privs->file->index_next(col_privs->record[0]) &&
2386
             !key_cmp_if_same(col_privs,key,0,key_prefix_len));
2387
    col_privs->file->ha_index_end();
unknown's avatar
unknown committed
2388
  }
2389
}
unknown's avatar
unknown committed
2390

unknown's avatar
unknown committed
2391

2392 2393 2394 2395 2396 2397
GRANT_TABLE::~GRANT_TABLE()
{
  hash_free(&hash_columns);
}


2398
static uchar* get_grant_table(GRANT_NAME *buff, size_t *length,
unknown's avatar
unknown committed
2399 2400 2401
			     my_bool not_used __attribute__((unused)))
{
  *length=buff->key_length;
2402
  return (uchar*) buff->hash_key;
unknown's avatar
unknown committed
2403 2404
}

unknown's avatar
unknown committed
2405

unknown's avatar
unknown committed
2406 2407 2408 2409 2410
void free_grant_table(GRANT_TABLE *grant_table)
{
  hash_free(&grant_table->hash_columns);
}

unknown's avatar
unknown committed
2411

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

2414
static GRANT_NAME *name_hash_search(HASH *name_hash,
unknown's avatar
unknown committed
2415 2416 2417 2418
                                    const char *host,const char* ip,
                                    const char *db,
                                    const char *user, const char *tname,
                                    bool exact)
unknown's avatar
unknown committed
2419
{
unknown's avatar
unknown committed
2420
  char helping [NAME_LEN*2+USERNAME_LENGTH+3];
unknown's avatar
unknown committed
2421
  uint len;
2422
  GRANT_NAME *grant_name,*found=0;
2423
  HASH_SEARCH_STATE state;
unknown's avatar
unknown committed
2424 2425

  len  = (uint) (strmov(strmov(strmov(helping,user)+1,db)+1,tname)-helping)+ 1;
2426
  for (grant_name= (GRANT_NAME*) hash_first(name_hash, (uchar*) helping,
2427
                                            len, &state);
2428
       grant_name ;
2429
       grant_name= (GRANT_NAME*) hash_next(name_hash,(uchar*) helping,
2430
                                           len, &state))
unknown's avatar
unknown committed
2431 2432 2433
  {
    if (exact)
    {
2434 2435
      if (!grant_name->host.hostname ||
          (host &&
2436
	   !my_strcasecmp(system_charset_info, host,
unknown's avatar
unknown committed
2437 2438
                          grant_name->host.hostname)) ||
	  (ip && !strcmp(ip, grant_name->host.hostname)))
2439
	return grant_name;
unknown's avatar
unknown committed
2440 2441 2442
    }
    else
    {
2443
      if (compare_hostname(&grant_name->host, host, ip) &&
2444 2445
          (!found || found->sort < grant_name->sort))
	found=grant_name;					// Host ok
unknown's avatar
unknown committed
2446 2447 2448 2449 2450 2451
    }
  }
  return found;
}


2452
inline GRANT_NAME *
2453 2454
routine_hash_search(const char *host, const char *ip, const char *db,
                 const char *user, const char *tname, bool proc, bool exact)
2455
{
2456 2457 2458
  return (GRANT_TABLE*)
    name_hash_search(proc ? &proc_priv_hash : &func_priv_hash,
		     host, ip, db, user, tname, exact);
2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469
}


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

unknown's avatar
unknown committed
2470

unknown's avatar
unknown committed
2471
inline GRANT_COLUMN *
unknown's avatar
unknown committed
2472
column_hash_search(GRANT_TABLE *t, const char *cname, uint length)
unknown's avatar
unknown committed
2473
{
2474
  return (GRANT_COLUMN*) hash_search(&t->hash_columns, (uchar*) cname,length);
unknown's avatar
unknown committed
2475 2476 2477 2478 2479 2480 2481
}


static int replace_column_table(GRANT_TABLE *g_t,
				TABLE *table, const LEX_USER &combo,
				List <LEX_COLUMN> &columns,
				const char *db, const char *table_name,
unknown's avatar
unknown committed
2482
				ulong rights, bool revoke_grant)
unknown's avatar
unknown committed
2483 2484
{
  int error=0,result=0;
2485
  uchar key[MAX_KEY_LENGTH];
2486 2487
  uint key_prefix_length;
  KEY_PART_INFO *key_part= table->key_info->key_part;
unknown's avatar
unknown committed
2488 2489
  DBUG_ENTER("replace_column_table");

2490
  table->use_all_columns();
unknown's avatar
unknown committed
2491 2492 2493 2494 2495 2496 2497 2498
  table->field[0]->store(combo.host.str,combo.host.length,
                         system_charset_info);
  table->field[1]->store(db,(uint) strlen(db),
                         system_charset_info);
  table->field[2]->store(combo.user.str,combo.user.length,
                         system_charset_info);
  table->field[3]->store(table_name,(uint) strlen(table_name),
                         system_charset_info);
unknown's avatar
unknown committed
2499

2500
  /* Get length of 4 first key parts */
2501 2502 2503
  key_prefix_length= (key_part[0].store_length + key_part[1].store_length +
                      key_part[2].store_length + key_part[3].store_length);
  key_copy(key, table->record[0], table->key_info, key_prefix_length);
unknown's avatar
unknown committed
2504

2505
  rights&= COL_ACLS;				// Only ACL for columns
unknown's avatar
unknown committed
2506 2507 2508 2509

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

  List_iterator <LEX_COLUMN> iter(columns);
unknown's avatar
unknown committed
2510
  class LEX_COLUMN *column;
2511
  table->file->ha_index_init(0, 1);
unknown's avatar
unknown committed
2512
  while ((column= iter++))
unknown's avatar
unknown committed
2513
  {
unknown's avatar
unknown committed
2514
    ulong privileges= column->rights;
unknown's avatar
unknown committed
2515
    bool old_row_exists=0;
2516
    uchar user_key[MAX_KEY_LENGTH];
2517 2518 2519

    key_restore(table->record[0],key,table->key_info,
                key_prefix_length);
unknown's avatar
unknown committed
2520
    table->field[4]->store(column->column.ptr(), column->column.length(),
2521
                           system_charset_info);
2522 2523 2524
    /* Get key for the first 4 columns */
    key_copy(user_key, table->record[0], table->key_info,
             table->key_info->key_length);
unknown's avatar
unknown committed
2525

2526 2527
    if (table->file->index_read_map(table->record[0], user_key, HA_WHOLE_KEY,
                                    HA_READ_KEY_EXACT))
unknown's avatar
unknown committed
2528 2529 2530
    {
      if (revoke_grant)
      {
unknown's avatar
unknown committed
2531
	my_error(ER_NONEXISTING_TABLE_GRANT, MYF(0),
2532
                 combo.user.str, combo.host.str,
unknown's avatar
unknown committed
2533 2534 2535
                 table_name);                   /* purecov: inspected */
	result= -1;                             /* purecov: inspected */
	continue;                               /* purecov: inspected */
unknown's avatar
unknown committed
2536
      }
unknown's avatar
unknown committed
2537
      old_row_exists = 0;
2538
      restore_record(table, s->default_values);		// Get empty record
2539 2540
      key_restore(table->record[0],key,table->key_info,
                  key_prefix_length);
unknown's avatar
unknown committed
2541
      table->field[4]->store(column->column.ptr(),column->column.length(),
2542
                             system_charset_info);
unknown's avatar
unknown committed
2543 2544 2545
    }
    else
    {
unknown's avatar
unknown committed
2546
      ulong tmp= (ulong) table->field[6]->val_int();
unknown's avatar
unknown committed
2547 2548 2549 2550 2551 2552
      tmp=fix_rights_for_column(tmp);

      if (revoke_grant)
	privileges = tmp & ~(privileges | rights);
      else
	privileges |= tmp;
unknown's avatar
unknown committed
2553
      old_row_exists = 1;
unknown's avatar
unknown committed
2554
      store_record(table,record[1]);			// copy original row
unknown's avatar
unknown committed
2555 2556
    }

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

unknown's avatar
unknown committed
2559
    if (old_row_exists)
unknown's avatar
unknown committed
2560
    {
unknown's avatar
unknown committed
2561
      GRANT_COLUMN *grant_column;
unknown's avatar
unknown committed
2562
      if (privileges)
2563
	error=table->file->ha_update_row(table->record[1],table->record[0]);
unknown's avatar
unknown committed
2564
      else
2565
	error=table->file->ha_delete_row(table->record[1]);
2566
      if (error && error != HA_ERR_RECORD_IS_THE_SAME)
unknown's avatar
unknown committed
2567 2568 2569 2570 2571
      {
	table->file->print_error(error,MYF(0)); /* purecov: inspected */
	result= -1;				/* purecov: inspected */
	goto end;				/* purecov: inspected */
      }
2572 2573
      else
        error= 0;
unknown's avatar
unknown committed
2574 2575
      grant_column= column_hash_search(g_t, column->column.ptr(),
                                       column->column.length());
unknown's avatar
unknown committed
2576
      if (grant_column)				// Should always be true
unknown's avatar
unknown committed
2577
	grant_column->rights= privileges;	// Update hash
unknown's avatar
unknown committed
2578 2579 2580
    }
    else					// new grant
    {
unknown's avatar
unknown committed
2581
      GRANT_COLUMN *grant_column;
2582
      if ((error=table->file->ha_write_row(table->record[0])))
unknown's avatar
unknown committed
2583 2584 2585 2586 2587
      {
	table->file->print_error(error,MYF(0)); /* purecov: inspected */
	result= -1;				/* purecov: inspected */
	goto end;				/* purecov: inspected */
      }
unknown's avatar
unknown committed
2588
      grant_column= new GRANT_COLUMN(column->column,privileges);
2589
      my_hash_insert(&g_t->hash_columns,(uchar*) grant_column);
unknown's avatar
unknown committed
2590 2591 2592 2593 2594 2595 2596 2597 2598 2599
    }
  }

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

  if (revoke_grant)
  {
2600
    uchar user_key[MAX_KEY_LENGTH];
2601
    key_copy(user_key, table->record[0], table->key_info,
unknown's avatar
unknown committed
2602 2603
             key_prefix_length);

2604 2605 2606
    if (table->file->index_read_map(table->record[0], user_key,
                                    (key_part_map)15,
                                    HA_READ_KEY_EXACT))
unknown's avatar
unknown committed
2607 2608
      goto end;

2609
    /* Scan through all rows with the same host,db,user and table */
unknown's avatar
unknown committed
2610 2611
    do
    {
unknown's avatar
unknown committed
2612
      ulong privileges = (ulong) table->field[6]->val_int();
unknown's avatar
unknown committed
2613
      privileges=fix_rights_for_column(privileges);
unknown's avatar
unknown committed
2614
      store_record(table,record[1]);
unknown's avatar
unknown committed
2615 2616 2617 2618 2619

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

	privileges&= ~rights;
	table->field[6]->store((longlong)
2625
			       get_rights_for_column(privileges), TRUE);
2626
	table->field[4]->val_str(&column_name);
unknown's avatar
unknown committed
2627 2628 2629 2630 2631 2632
	grant_column = column_hash_search(g_t,
					  column_name.ptr(),
					  column_name.length());
	if (privileges)
	{
	  int tmp_error;
2633
	  if ((tmp_error=table->file->ha_update_row(table->record[1],
2634 2635
						    table->record[0])) &&
              tmp_error != HA_ERR_RECORD_IS_THE_SAME)
unknown's avatar
unknown committed
2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646
	  {					/* 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;
2647
	  if ((tmp_error = table->file->ha_delete_row(table->record[1])))
unknown's avatar
unknown committed
2648 2649 2650 2651 2652 2653
	  {					/* purecov: deadcode */
	    table->file->print_error(tmp_error,MYF(0)); /* purecov: deadcode */
	    result= -1;				/* purecov: deadcode */
	    goto end;				/* purecov: deadcode */
	  }
	  if (grant_column)
2654
	    hash_delete(&g_t->hash_columns,(uchar*) grant_column);
unknown's avatar
unknown committed
2655 2656 2657
	}
      }
    } while (!table->file->index_next(table->record[0]) &&
2658
	     !key_cmp_if_same(table, key, 0, key_prefix_length));
unknown's avatar
unknown committed
2659 2660
  }

2661
end:
unknown's avatar
unknown committed
2662
  table->file->ha_index_end();
unknown's avatar
unknown committed
2663 2664 2665 2666 2667 2668 2669
  DBUG_RETURN(result);
}


static int replace_table_table(THD *thd, GRANT_TABLE *grant_table,
			       TABLE *table, const LEX_USER &combo,
			       const char *db, const char *table_name,
unknown's avatar
unknown committed
2670 2671
			       ulong rights, ulong col_rights,
			       bool revoke_grant)
unknown's avatar
unknown committed
2672
{
2673
  char grantor[USER_HOST_BUFF_SIZE];
unknown's avatar
unknown committed
2674
  int old_row_exists = 1;
unknown's avatar
unknown committed
2675
  int error=0;
unknown's avatar
unknown committed
2676
  ulong store_table_rights, store_col_rights;
2677
  uchar user_key[MAX_KEY_LENGTH];
unknown's avatar
unknown committed
2678 2679
  DBUG_ENTER("replace_table_table");

2680 2681
  strxmov(grantor, thd->security_ctx->user, "@",
          thd->security_ctx->host_or_ip, NullS);
unknown's avatar
unknown committed
2682

unknown's avatar
unknown committed
2683 2684 2685 2686
  /*
    The following should always succeed as new users are created before
    this function is called!
  */
2687
  if (!find_acl_user(combo.host.str,combo.user.str, FALSE))
unknown's avatar
unknown committed
2688
  {
unknown's avatar
unknown committed
2689 2690
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH),
               MYF(0));	/* purecov: deadcode */
unknown's avatar
unknown committed
2691 2692 2693
    DBUG_RETURN(-1);				/* purecov: deadcode */
  }

2694
  table->use_all_columns();
2695
  restore_record(table, s->default_values);     // Get empty record
2696 2697
  table->field[0]->store(combo.host.str,combo.host.length,
                         system_charset_info);
2698
  table->field[1]->store(db,(uint) strlen(db), system_charset_info);
2699 2700 2701 2702
  table->field[2]->store(combo.user.str,combo.user.length,
                         system_charset_info);
  table->field[3]->store(table_name,(uint) strlen(table_name),
                         system_charset_info);
unknown's avatar
unknown committed
2703
  store_record(table,record[1]);			// store at pos 1
2704 2705
  key_copy(user_key, table->record[0], table->key_info,
           table->key_info->key_length);
unknown's avatar
unknown committed
2706

2707 2708 2709
  if (table->file->index_read_idx_map(table->record[0], 0, user_key,
                                      HA_WHOLE_KEY,
                                      HA_READ_KEY_EXACT))
unknown's avatar
unknown committed
2710 2711 2712 2713 2714 2715 2716 2717
  {
    /*
      The following should never happen as we first check the in memory
      grant tables for the user.  There is however always a small change that
      the user has modified the grant tables directly.
    */
    if (revoke_grant)
    { // no row, no revoke
unknown's avatar
unknown committed
2718 2719
      my_error(ER_NONEXISTING_TABLE_GRANT, MYF(0),
               combo.user.str, combo.host.str,
2720
               table_name);		        /* purecov: deadcode */
unknown's avatar
unknown committed
2721 2722
      DBUG_RETURN(-1);				/* purecov: deadcode */
    }
unknown's avatar
unknown committed
2723
    old_row_exists = 0;
unknown's avatar
unknown committed
2724
    restore_record(table,record[1]);			// Get saved record
unknown's avatar
unknown committed
2725 2726
  }

unknown's avatar
unknown committed
2727 2728
  store_table_rights= get_rights_for_table(rights);
  store_col_rights=   get_rights_for_column(col_rights);
unknown's avatar
unknown committed
2729
  if (old_row_exists)
unknown's avatar
unknown committed
2730
  {
unknown's avatar
unknown committed
2731
    ulong j,k;
unknown's avatar
unknown committed
2732
    store_record(table,record[1]);
unknown's avatar
unknown committed
2733 2734
    j = (ulong) table->field[6]->val_int();
    k = (ulong) table->field[7]->val_int();
unknown's avatar
unknown committed
2735 2736 2737

    if (revoke_grant)
    {
2738
      /* column rights are already fixed in mysql_table_grant */
unknown's avatar
unknown committed
2739 2740 2741 2742
      store_table_rights=j & ~store_table_rights;
    }
    else
    {
unknown's avatar
unknown committed
2743 2744
      store_table_rights|= j;
      store_col_rights|=   k;
unknown's avatar
unknown committed
2745 2746 2747
    }
  }

2748
  table->field[4]->store(grantor,(uint) strlen(grantor), system_charset_info);
2749 2750
  table->field[6]->store((longlong) store_table_rights, TRUE);
  table->field[7]->store((longlong) store_col_rights, TRUE);
unknown's avatar
unknown committed
2751
  rights=fix_rights_for_table(store_table_rights);
unknown's avatar
unknown committed
2752
  col_rights=fix_rights_for_column(store_col_rights);
unknown's avatar
unknown committed
2753

unknown's avatar
unknown committed
2754
  if (old_row_exists)
unknown's avatar
unknown committed
2755 2756 2757
  {
    if (store_table_rights || store_col_rights)
    {
2758 2759 2760
      if ((error=table->file->ha_update_row(table->record[1],
                                            table->record[0])) &&
          error != HA_ERR_RECORD_IS_THE_SAME)
unknown's avatar
unknown committed
2761 2762
	goto table_error;			/* purecov: deadcode */
    }
2763
    else if ((error = table->file->ha_delete_row(table->record[1])))
unknown's avatar
unknown committed
2764 2765 2766 2767
      goto table_error;				/* purecov: deadcode */
  }
  else
  {
2768
    error=table->file->ha_write_row(table->record[0]);
2769
    if (table->file->is_fatal_error(error, HA_CHECK_DUP_KEY))
unknown's avatar
unknown committed
2770 2771 2772
      goto table_error;				/* purecov: deadcode */
  }

unknown's avatar
unknown committed
2773
  if (rights | col_rights)
unknown's avatar
unknown committed
2774
  {
unknown's avatar
unknown committed
2775
    grant_table->privs= rights;
2776
    grant_table->cols=	col_rights;
unknown's avatar
unknown committed
2777 2778 2779
  }
  else
  {
2780
    hash_delete(&column_priv_hash,(uchar*) grant_table);
unknown's avatar
unknown committed
2781 2782 2783
  }
  DBUG_RETURN(0);

2784 2785
  /* This should never happen */
table_error:
unknown's avatar
unknown committed
2786 2787 2788 2789 2790
  table->file->print_error(error,MYF(0)); /* purecov: deadcode */
  DBUG_RETURN(-1); /* purecov: deadcode */
}


2791 2792 2793 2794
/**
  @retval       0  success
  @retval      -1  error
*/
2795
static int replace_routine_table(THD *thd, GRANT_NAME *grant_name,
2796
			      TABLE *table, const LEX_USER &combo,
2797 2798
			      const char *db, const char *routine_name,
			      bool is_proc, ulong rights, bool revoke_grant)
2799
{
2800
  char grantor[USER_HOST_BUFF_SIZE];
2801 2802 2803
  int old_row_exists= 1;
  int error=0;
  ulong store_proc_rights;
2804
  DBUG_ENTER("replace_routine_table");
2805 2806 2807 2808 2809 2810 2811

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

2812 2813
  strxmov(grantor, thd->security_ctx->user, "@",
          thd->security_ctx->host_or_ip, NullS);
2814 2815

  /*
2816 2817 2818 2819
    New users are created before this function is called.

    There may be some cases where a routine's definer is removed but the
    routine remains.
2820 2821
  */

2822
  table->use_all_columns();
2823
  restore_record(table, s->default_values);		// Get empty record
2824 2825 2826
  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);
2827 2828
  table->field[3]->store(routine_name,(uint) strlen(routine_name),
                         &my_charset_latin1);
unknown's avatar
unknown committed
2829
  table->field[4]->store((longlong)(is_proc ?
2830 2831
                                    TYPE_ENUM_PROCEDURE : TYPE_ENUM_FUNCTION),
                         TRUE);
2832 2833
  store_record(table,record[1]);			// store at pos 1

2834 2835 2836 2837
  if (table->file->index_read_idx_map(table->record[0], 0,
                                      (uchar*) table->field[0]->ptr,
                                      HA_WHOLE_KEY,
                                      HA_READ_KEY_EXACT))
2838 2839 2840 2841 2842 2843 2844 2845 2846
  {
    /*
      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),
2847
               combo.user.str, combo.host.str, routine_name);
2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871
      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;
    }
  }

2872
  table->field[5]->store(grantor,(uint) strlen(grantor), &my_charset_latin1);
2873
  table->field[6]->store((longlong) store_proc_rights, TRUE);
2874 2875 2876 2877 2878 2879
  rights=fix_rights_for_procedure(store_proc_rights);

  if (old_row_exists)
  {
    if (store_proc_rights)
    {
2880 2881 2882
      if ((error=table->file->ha_update_row(table->record[1],
                                            table->record[0])) &&
          error != HA_ERR_RECORD_IS_THE_SAME)
2883 2884
	goto table_error;
    }
2885
    else if ((error= table->file->ha_delete_row(table->record[1])))
2886 2887 2888 2889
      goto table_error;
  }
  else
  {
2890
    error=table->file->ha_write_row(table->record[0]);
2891
    if (table->file->is_fatal_error(error, HA_CHECK_DUP_KEY))
2892 2893 2894 2895 2896 2897 2898 2899 2900
      goto table_error;
  }

  if (rights)
  {
    grant_name->privs= rights;
  }
  else
  {
2901
    hash_delete(is_proc ? &proc_priv_hash : &func_priv_hash,(uchar*) grant_name);
2902 2903 2904 2905 2906 2907 2908 2909 2910 2911
  }
  DBUG_RETURN(0);

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


2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924
/*
  Store table level and column level grants in the privilege tables

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

  RETURN
unknown's avatar
unknown committed
2925 2926
    FALSE ok
    TRUE  error
2927 2928
*/

2929
int mysql_table_grant(THD *thd, TABLE_LIST *table_list,
unknown's avatar
unknown committed
2930 2931 2932
		      List <LEX_USER> &user_list,
		      List <LEX_COLUMN> &columns, ulong rights,
		      bool revoke_grant)
unknown's avatar
unknown committed
2933
{
2934
  ulong column_priv= 0;
unknown's avatar
unknown committed
2935
  List_iterator <LEX_USER> str_list (user_list);
2936
  LEX_USER *Str, *tmp_Str;
unknown's avatar
unknown committed
2937
  TABLE_LIST tables[3];
unknown's avatar
unknown committed
2938
  bool create_new_users=0;
2939
  char *db_name, *table_name;
unknown's avatar
unknown committed
2940 2941 2942 2943
  DBUG_ENTER("mysql_table_grant");

  if (!initialized)
  {
unknown's avatar
unknown committed
2944 2945
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0),
             "--skip-grant-tables");	/* purecov: inspected */
unknown's avatar
unknown committed
2946
    DBUG_RETURN(TRUE);				/* purecov: inspected */
unknown's avatar
unknown committed
2947 2948 2949
  }
  if (rights & ~TABLE_ACLS)
  {
unknown's avatar
unknown committed
2950 2951
    my_message(ER_ILLEGAL_GRANT_FOR_TABLE, ER(ER_ILLEGAL_GRANT_FOR_TABLE),
               MYF(0));
unknown's avatar
unknown committed
2952
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
2953 2954
  }

2955
  if (!revoke_grant)
unknown's avatar
unknown committed
2956
  {
unknown's avatar
unknown committed
2957
    if (columns.elements)
unknown's avatar
unknown committed
2958
    {
2959 2960
      class LEX_COLUMN *column;
      List_iterator <LEX_COLUMN> column_iter(columns);
unknown's avatar
unknown committed
2961 2962 2963

      if (open_and_lock_tables(thd, table_list))
        DBUG_RETURN(TRUE);
2964 2965

      while ((column = column_iter++))
unknown's avatar
unknown committed
2966
      {
unknown's avatar
unknown committed
2967
        uint unused_field_idx= NO_CACHED_FIELD_INDEX;
unknown's avatar
unknown committed
2968 2969
        TABLE_LIST *dummy;
        Field *f=find_field_in_table_ref(thd, table_list, column->column.ptr(),
2970
                                         column->column.length(),
unknown's avatar
unknown committed
2971
                                         column->column.ptr(), NULL, NULL,
2972
                                         NULL, TRUE, FALSE,
unknown's avatar
unknown committed
2973
                                         &unused_field_idx, FALSE, &dummy);
unknown's avatar
unknown committed
2974
        if (f == (Field*)0)
2975
        {
unknown's avatar
unknown committed
2976 2977
          my_error(ER_BAD_FIELD_ERROR, MYF(0),
                   column->column.c_ptr(), table_list->alias);
unknown's avatar
unknown committed
2978
          DBUG_RETURN(TRUE);
2979
        }
unknown's avatar
unknown committed
2980 2981
        if (f == (Field *)-1)
          DBUG_RETURN(TRUE);
2982
        column_priv|= column->rights;
unknown's avatar
unknown committed
2983
      }
2984
      close_thread_tables(thd);
unknown's avatar
unknown committed
2985
    }
2986
    else
unknown's avatar
unknown committed
2987
    {
2988 2989 2990
      if (!(rights & CREATE_ACL))
      {
        char buf[FN_REFLEN];
2991
        build_table_filename(buf, sizeof(buf), table_list->db,
2992
                             table_list->table_name, reg_ext, 0);
2993 2994
        fn_format(buf, buf, "", "", MY_UNPACK_FILENAME  | MY_RESOLVE_SYMLINKS |
                                    MY_RETURN_REAL_PATH | MY_APPEND_EXT);
2995 2996
        if (access(buf,F_OK))
        {
unknown's avatar
unknown committed
2997
          my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->alias);
unknown's avatar
unknown committed
2998
          DBUG_RETURN(TRUE);
2999 3000 3001 3002 3003 3004 3005 3006
        }
      }
      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),
3007 3008
                 command, thd->security_ctx->priv_user,
                 thd->security_ctx->host_or_ip, table_list->alias);
3009 3010
        DBUG_RETURN(-1);
      }
unknown's avatar
unknown committed
3011 3012 3013 3014 3015 3016
    }
  }

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

  bzero((char*) &tables,sizeof(tables));
3017 3018 3019
  tables[0].alias=tables[0].table_name= (char*) "user";
  tables[1].alias=tables[1].table_name= (char*) "tables_priv";
  tables[2].alias=tables[2].table_name= (char*) "columns_priv";
unknown's avatar
VIEW  
unknown committed
3020
  tables[0].next_local= tables[0].next_global= tables+1;
unknown's avatar
unknown committed
3021
  /* Don't open column table if we don't need it ! */
unknown's avatar
VIEW  
unknown committed
3022 3023 3024 3025 3026
  tables[1].next_local=
    tables[1].next_global= ((column_priv ||
			     (revoke_grant &&
			      ((rights & COL_ACLS) || columns.elements)))
			    ? tables+2 : 0);
unknown's avatar
unknown committed
3027 3028 3029
  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";

3030 3031 3032 3033 3034 3035 3036
  /*
    This statement will be replicated as a statement, even when using
    row-based replication.  The flag will be reset at the end of the
    statement.
  */
  thd->clear_current_stmt_binlog_row_based();

3037 3038 3039 3040 3041
#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
3042
  if (thd->slave_thread && rpl_filter->is_on())
3043
  {
unknown's avatar
unknown committed
3044 3045 3046
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
3047
    */
3048
    tables[0].updating= tables[1].updating= tables[2].updating= 1;
unknown's avatar
unknown committed
3049
    if (!(thd->spcont || rpl_filter->tables_ok(0, tables)))
unknown's avatar
unknown committed
3050
      DBUG_RETURN(FALSE);
3051
  }
3052 3053
#endif

3054 3055 3056 3057 3058 3059
  /* 
    The lock api is depending on the thd->lex variable which needs to be
    re-initialized.
  */
  Query_tables_list backup;
  thd->lex->reset_n_backup_query_tables_list(&backup);
3060
  if (simple_open_n_lock_tables(thd,tables))
unknown's avatar
unknown committed
3061 3062
  {						// Should never happen
    close_thread_tables(thd);			/* purecov: deadcode */
unknown's avatar
unknown committed
3063
    DBUG_RETURN(TRUE);				/* purecov: deadcode */
unknown's avatar
unknown committed
3064 3065
  }

unknown's avatar
unknown committed
3066 3067
  if (!revoke_grant)
    create_new_users= test_if_create_new_users(thd);
unknown's avatar
unknown committed
3068
  bool result= FALSE;
3069
  rw_wrlock(&LOCK_grant);
3070
  pthread_mutex_lock(&acl_cache->lock);
unknown's avatar
unknown committed
3071 3072
  MEM_ROOT *old_root= thd->mem_root;
  thd->mem_root= &memex;
3073
  grant_version++;
unknown's avatar
unknown committed
3074

3075
  while ((tmp_Str = str_list++))
unknown's avatar
unknown committed
3076
  {
3077
    int error;
unknown's avatar
unknown committed
3078
    GRANT_TABLE *grant_table;
3079 3080 3081 3082 3083
    if (!(Str= get_current_user(thd, tmp_Str)))
    {
      result= TRUE;
      continue;
    }  
unknown's avatar
unknown committed
3084
    /* Create user if needed */
unknown's avatar
unknown committed
3085
    error=replace_user_table(thd, tables[0].table, *Str,
unknown's avatar
unknown committed
3086
			     0, revoke_grant, create_new_users,
unknown's avatar
unknown committed
3087 3088
                             test(thd->variables.sql_mode &
                                  MODE_NO_AUTO_CREATE_USER));
3089
    if (error)
unknown's avatar
unknown committed
3090
    {
unknown's avatar
unknown committed
3091
      result= TRUE;				// Remember error
unknown's avatar
unknown committed
3092 3093 3094
      continue;					// Add next user
    }

unknown's avatar
VIEW  
unknown committed
3095 3096 3097
    db_name= (table_list->view_db.length ?
	      table_list->view_db.str :
	      table_list->db);
3098
    table_name= (table_list->view_name.length ?
unknown's avatar
VIEW  
unknown committed
3099
		table_list->view_name.str :
3100
		table_list->table_name);
unknown's avatar
VIEW  
unknown committed
3101

unknown's avatar
unknown committed
3102
    /* Find/create cached table grant */
unknown's avatar
VIEW  
unknown committed
3103
    grant_table= table_hash_search(Str->host.str, NullS, db_name,
3104
				   Str->user.str, table_name, 1);
unknown's avatar
unknown committed
3105 3106 3107 3108
    if (!grant_table)
    {
      if (revoke_grant)
      {
unknown's avatar
unknown committed
3109
	my_error(ER_NONEXISTING_TABLE_GRANT, MYF(0),
3110
                 Str->user.str, Str->host.str, table_list->table_name);
unknown's avatar
unknown committed
3111
	result= TRUE;
unknown's avatar
unknown committed
3112 3113
	continue;
      }
unknown's avatar
VIEW  
unknown committed
3114
      grant_table = new GRANT_TABLE (Str->host.str, db_name,
3115
				     Str->user.str, table_name,
unknown's avatar
unknown committed
3116 3117 3118 3119
				     rights,
				     column_priv);
      if (!grant_table)				// end of memory
      {
unknown's avatar
unknown committed
3120
	result= TRUE;				/* purecov: deadcode */
unknown's avatar
unknown committed
3121 3122
	continue;				/* purecov: deadcode */
      }
3123
      my_hash_insert(&column_priv_hash,(uchar*) grant_table);
unknown's avatar
unknown committed
3124 3125 3126 3127 3128
    }

    /* If revoke_grant, calculate the new column privilege for tables_priv */
    if (revoke_grant)
    {
3129 3130
      class LEX_COLUMN *column;
      List_iterator <LEX_COLUMN> column_iter(columns);
unknown's avatar
unknown committed
3131 3132 3133
      GRANT_COLUMN *grant_column;

      /* Fix old grants */
3134
      while ((column = column_iter++))
unknown's avatar
unknown committed
3135 3136
      {
	grant_column = column_hash_search(grant_table,
3137 3138
					  column->column.ptr(),
					  column->column.length());
unknown's avatar
unknown committed
3139
	if (grant_column)
3140
	  grant_column->rights&= ~(column->rights | rights);
unknown's avatar
unknown committed
3141 3142
      }
      /* scan trough all columns to get new column grant */
3143
      column_priv= 0;
unknown's avatar
unknown committed
3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159
      for (uint idx=0 ; idx < grant_table->hash_columns.records ; idx++)
      {
	grant_column= (GRANT_COLUMN*) hash_element(&grant_table->hash_columns,
						   idx);
	grant_column->rights&= ~rights;		// Fix other columns
	column_priv|= grant_column->rights;
      }
    }
    else
    {
      column_priv|= grant_table->cols;
    }


    /* update table and columns */

unknown's avatar
VIEW  
unknown committed
3160
    if (replace_table_table(thd, grant_table, tables[1].table, *Str,
3161
			    db_name, table_name,
unknown's avatar
unknown committed
3162
			    rights, column_priv, revoke_grant))
3163 3164
    {
      /* Should only happen if table is crashed */
unknown's avatar
unknown committed
3165
      result= TRUE;			       /* purecov: deadcode */
unknown's avatar
unknown committed
3166 3167 3168
    }
    else if (tables[2].table)
    {
unknown's avatar
VIEW  
unknown committed
3169
      if ((replace_column_table(grant_table, tables[2].table, *Str,
unknown's avatar
unknown committed
3170
				columns,
3171
				db_name, table_name,
unknown's avatar
unknown committed
3172 3173
				rights, revoke_grant)))
      {
unknown's avatar
unknown committed
3174
	result= TRUE;
unknown's avatar
unknown committed
3175 3176 3177
      }
    }
  }
unknown's avatar
unknown committed
3178
  thd->mem_root= old_root;
3179
  pthread_mutex_unlock(&acl_cache->lock);
3180 3181 3182

  if (!result) /* success */
  {
3183
    write_bin_log(thd, TRUE, thd->query, thd->query_length);
3184 3185
  }

3186
  rw_unlock(&LOCK_grant);
3187 3188

  if (!result) /* success */
3189
    my_ok(thd);
3190

3191
  /* Tables are automatically closed */
3192
  thd->lex->restore_backup_query_tables_list(&backup);
unknown's avatar
unknown committed
3193 3194 3195 3196
  DBUG_RETURN(result);
}


3197
/*
3198
  Store routine level grants in the privilege tables
3199 3200

  SYNOPSIS
3201
    mysql_routine_grant()
3202
    thd			Thread handle
3203 3204
    table_list		List of routines to give grant
    is_proc             true indicates routine list are procedures
3205 3206 3207 3208 3209 3210 3211 3212 3213
    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
*/

3214 3215 3216
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)
3217 3218
{
  List_iterator <LEX_USER> str_list (user_list);
3219
  LEX_USER *Str, *tmp_Str;
3220 3221
  TABLE_LIST tables[2];
  bool create_new_users=0, result=0;
3222
  char *db_name, *table_name;
3223
  DBUG_ENTER("mysql_routine_grant");
3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241

  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)
  {
3242
    if (sp_exist_routines(thd, table_list, is_proc, no_error)<0)
3243 3244 3245 3246 3247 3248
      DBUG_RETURN(TRUE);
  }

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

  bzero((char*) &tables,sizeof(tables));
3249 3250
  tables[0].alias=tables[0].table_name= (char*) "user";
  tables[1].alias=tables[1].table_name= (char*) "procs_priv";
3251 3252 3253 3254
  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";

3255 3256 3257 3258 3259 3260 3261
  /*
    This statement will be replicated as a statement, even when using
    row-based replication.  The flag will be reset at the end of the
    statement.
  */
  thd->clear_current_stmt_binlog_row_based();

3262 3263 3264 3265 3266
#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
3267
  if (thd->slave_thread && rpl_filter->is_on())
3268 3269 3270 3271 3272 3273
  {
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
    */
    tables[0].updating= tables[1].updating= 1;
unknown's avatar
unknown committed
3274
    if (!(thd->spcont || rpl_filter->tables_ok(0, tables)))
3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287
      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);
3288
  pthread_mutex_lock(&acl_cache->lock);
3289 3290 3291 3292 3293
  MEM_ROOT *old_root= thd->mem_root;
  thd->mem_root= &memex;

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

3294
  while ((tmp_Str= str_list++))
3295 3296 3297
  {
    int error;
    GRANT_NAME *grant_name;
3298 3299 3300 3301 3302
    if (!(Str= get_current_user(thd, tmp_Str)))
    {
      result= TRUE;
      continue;
    }  
3303 3304
    /* Create user if needed */
    error=replace_user_table(thd, tables[0].table, *Str,
unknown's avatar
unknown committed
3305
			     0, revoke_grant, create_new_users,
unknown's avatar
unknown committed
3306 3307
                             test(thd->variables.sql_mode &
                                  MODE_NO_AUTO_CREATE_USER));
3308 3309 3310 3311 3312 3313 3314
    if (error)
    {
      result= TRUE;				// Remember error
      continue;					// Add next user
    }

    db_name= table_list->db;
3315
    table_name= table_list->table_name;
3316

3317 3318
    grant_name= routine_hash_search(Str->host.str, NullS, db_name,
                                    Str->user.str, table_name, is_proc, 1);
3319 3320 3321 3322 3323 3324
    if (!grant_name)
    {
      if (revoke_grant)
      {
        if (!no_error)
          my_error(ER_NONEXISTING_PROC_GRANT, MYF(0),
3325
		   Str->user.str, Str->host.str, table_name);
3326 3327 3328 3329
	result= TRUE;
	continue;
      }
      grant_name= new GRANT_NAME(Str->host.str, db_name,
3330
				 Str->user.str, table_name,
3331 3332 3333 3334 3335 3336
				 rights);
      if (!grant_name)
      {
        result= TRUE;
	continue;
      }
3337
      my_hash_insert(is_proc ? &proc_priv_hash : &func_priv_hash,(uchar*) grant_name);
3338
    }
3339

3340
    if (replace_routine_table(thd, grant_name, tables[1].table, *Str,
3341 3342
                              db_name, table_name, is_proc, rights, 
                              revoke_grant) != 0)
3343 3344 3345 3346 3347 3348
    {
      result= TRUE;
      continue;
    }
  }
  thd->mem_root= old_root;
3349
  pthread_mutex_unlock(&acl_cache->lock);
3350 3351
  if (!result && !no_error)
  {
3352
    write_bin_log(thd, TRUE, thd->query, thd->query_length);
3353 3354
  }

3355
  rw_unlock(&LOCK_grant);
3356

3357
  if (!result && !no_error)
3358
    my_ok(thd);
3359

3360 3361 3362 3363 3364
  /* Tables are automatically closed */
  DBUG_RETURN(result);
}


unknown's avatar
unknown committed
3365 3366
bool mysql_grant(THD *thd, const char *db, List <LEX_USER> &list,
                 ulong rights, bool revoke_grant)
unknown's avatar
unknown committed
3367 3368
{
  List_iterator <LEX_USER> str_list (list);
3369
  LEX_USER *Str, *tmp_Str;
unknown's avatar
unknown committed
3370
  char tmp_db[NAME_LEN+1];
unknown's avatar
unknown committed
3371
  bool create_new_users=0;
unknown's avatar
unknown committed
3372 3373 3374 3375
  TABLE_LIST tables[2];
  DBUG_ENTER("mysql_grant");
  if (!initialized)
  {
unknown's avatar
unknown committed
3376 3377
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0),
             "--skip-grant-tables");	/* purecov: tested */
unknown's avatar
unknown committed
3378
    DBUG_RETURN(TRUE);				/* purecov: tested */
unknown's avatar
unknown committed
3379 3380
  }

unknown's avatar
unknown committed
3381 3382 3383
  if (lower_case_table_names && db)
  {
    strmov(tmp_db,db);
3384
    my_casedn_str(files_charset_info, tmp_db);
unknown's avatar
unknown committed
3385 3386
    db=tmp_db;
  }
unknown's avatar
unknown committed
3387 3388

  /* open the mysql.user and mysql.db tables */
3389
  bzero((char*) &tables,sizeof(tables));
3390 3391
  tables[0].alias=tables[0].table_name=(char*) "user";
  tables[1].alias=tables[1].table_name=(char*) "db";
unknown's avatar
VIEW  
unknown committed
3392
  tables[0].next_local= tables[0].next_global= tables+1;
unknown's avatar
unknown committed
3393 3394
  tables[0].lock_type=tables[1].lock_type=TL_WRITE;
  tables[0].db=tables[1].db=(char*) "mysql";
3395

3396 3397 3398 3399 3400 3401 3402
  /*
    This statement will be replicated as a statement, even when using
    row-based replication.  The flag will be reset at the end of the
    statement.
  */
  thd->clear_current_stmt_binlog_row_based();

3403 3404 3405 3406 3407
#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
3408
  if (thd->slave_thread && rpl_filter->is_on())
3409
  {
unknown's avatar
unknown committed
3410 3411 3412
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
3413
    */
3414
    tables[0].updating= tables[1].updating= 1;
unknown's avatar
unknown committed
3415
    if (!(thd->spcont || rpl_filter->tables_ok(0, tables)))
unknown's avatar
unknown committed
3416
      DBUG_RETURN(FALSE);
3417
  }
3418 3419
#endif

3420
  if (simple_open_n_lock_tables(thd,tables))
unknown's avatar
unknown committed
3421 3422
  {						// This should never happen
    close_thread_tables(thd);			/* purecov: deadcode */
unknown's avatar
unknown committed
3423
    DBUG_RETURN(TRUE);				/* purecov: deadcode */
unknown's avatar
unknown committed
3424 3425
  }

unknown's avatar
unknown committed
3426 3427
  if (!revoke_grant)
    create_new_users= test_if_create_new_users(thd);
unknown's avatar
unknown committed
3428

3429
  /* go through users in user_list */
3430
  rw_wrlock(&LOCK_grant);
unknown's avatar
unknown committed
3431 3432 3433 3434
  VOID(pthread_mutex_lock(&acl_cache->lock));
  grant_version++;

  int result=0;
3435
  while ((tmp_Str = str_list++))
unknown's avatar
unknown committed
3436
  {
3437 3438 3439 3440
    if (!(Str= get_current_user(thd, tmp_Str)))
    {
      result= TRUE;
      continue;
unknown's avatar
unknown committed
3441
    }
unknown's avatar
unknown committed
3442 3443
    if (replace_user_table(thd, tables[0].table, *Str,
                           (!db ? rights : 0), revoke_grant, create_new_users,
unknown's avatar
unknown committed
3444 3445
                           test(thd->variables.sql_mode &
                                MODE_NO_AUTO_CREATE_USER)))
3446
      result= -1;
unknown's avatar
unknown committed
3447
    else if (db)
unknown's avatar
unknown committed
3448
    {
unknown's avatar
unknown committed
3449 3450 3451 3452 3453 3454 3455 3456 3457
      ulong db_rights= rights & DB_ACLS;
      if (db_rights  == rights)
      {
	if (replace_db_table(tables[1].table, db, *Str, db_rights,
			     revoke_grant))
	  result= -1;
      }
      else
      {
unknown's avatar
unknown committed
3458
	my_error(ER_WRONG_USAGE, MYF(0), "DB GRANT", "GLOBAL PRIVILEGES");
unknown's avatar
unknown committed
3459
	result= -1;
unknown's avatar
unknown committed
3460
      }
unknown's avatar
unknown committed
3461
    }
unknown's avatar
unknown committed
3462 3463
  }
  VOID(pthread_mutex_unlock(&acl_cache->lock));
3464 3465 3466

  if (!result)
  {
3467
    write_bin_log(thd, TRUE, thd->query, thd->query_length);
3468 3469
  }

3470
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
3471 3472 3473
  close_thread_tables(thd);

  if (!result)
3474
    my_ok(thd);
3475

unknown's avatar
unknown committed
3476 3477 3478
  DBUG_RETURN(result);
}

unknown's avatar
unknown committed
3479 3480

/* Free grant array if possible */
unknown's avatar
unknown committed
3481 3482 3483 3484

void  grant_free(void)
{
  DBUG_ENTER("grant_free");
3485
  hash_free(&column_priv_hash);
3486
  hash_free(&proc_priv_hash);
unknown's avatar
unknown committed
3487
  hash_free(&func_priv_hash);
3488
  free_root(&memex,MYF(0));
unknown's avatar
unknown committed
3489 3490 3491 3492
  DBUG_VOID_RETURN;
}


3493 3494 3495
/**
  @brief Initialize structures responsible for table/column-level privilege
   checking and load information for them from tables in the 'mysql' database.
unknown's avatar
unknown committed
3496

3497 3498 3499
  @return Error status
    @retval 0 OK
    @retval 1 Could not initialize grant subsystem.
3500
*/
unknown's avatar
unknown committed
3501

3502
my_bool grant_init()
unknown's avatar
unknown committed
3503
{
unknown's avatar
unknown committed
3504
  THD  *thd;
3505 3506 3507 3508 3509
  my_bool return_val;
  DBUG_ENTER("grant_init");

  if (!(thd= new THD))
    DBUG_RETURN(1);				/* purecov: deadcode */
3510
  thd->thread_stack= (char*) &thd;
3511
  thd->store_globals();
3512
  lex_start(thd);
3513 3514 3515 3516 3517 3518 3519 3520
  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);
}


3521 3522
/**
  @brief Helper function to grant_reload_procs_priv
3523

3524
  Reads the procs_priv table into memory hash.
3525

3526 3527 3528 3529 3530 3531 3532 3533
  @param table A pointer to the procs_priv table structure.

  @see grant_reload
  @see grant_reload_procs_priv

  @return Error state
    @retval TRUE An error occurred
    @retval FALSE Success
3534 3535
*/

3536
static my_bool grant_load_procs_priv(TABLE *p_table)
3537
{
unknown's avatar
unknown committed
3538
  MEM_ROOT *memex_ptr;
3539
  my_bool return_val= 1;
unknown's avatar
SCRUM  
unknown committed
3540
  bool check_no_resolve= specialflag & SPECIAL_NO_RESOLVE;
3541 3542
  MEM_ROOT **save_mem_root_ptr= my_pthread_getspecific_ptr(MEM_ROOT**,
                                                           THR_MALLOC);
3543
  DBUG_ENTER("grant_load_procs_priv");
3544
  (void) hash_init(&proc_priv_hash,system_charset_info,
3545 3546
                   0,0,0, (hash_get_key) get_grant_table,
                   0,0);
3547
  (void) hash_init(&func_priv_hash,system_charset_info,
3548 3549
                   0,0,0, (hash_get_key) get_grant_table,
                   0,0);
3550
  p_table->file->ha_index_init(0, 1);
3551
  p_table->use_all_columns();
3552 3553

  if (!p_table->file->index_first(p_table->record[0]))
unknown's avatar
unknown committed
3554
  {
3555 3556 3557 3558
    memex_ptr= &memex;
    my_pthread_setspecific_ptr(THR_MALLOC, &memex_ptr);
    do
    {
3559 3560 3561
      GRANT_NAME *mem_check;
      HASH *hash;
      if (!(mem_check=new (memex_ptr) GRANT_NAME(p_table)))
3562
      {
3563 3564
        /* This could only happen if we are out memory */
        goto end_unlock;
3565
      }
unknown's avatar
unknown committed
3566

3567 3568
      if (check_no_resolve)
      {
3569
	if (hostname_requires_resolving(mem_check->host.hostname))
3570
	{
3571
          sql_print_warning("'procs_priv' entry '%s %s@%s' "
3572
                            "ignored in --skip-name-resolve mode.",
3573
                            mem_check->tname, mem_check->user,
3574 3575
                            mem_check->host.hostname ?
                            mem_check->host.hostname : "");
3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593
          continue;
        }
      }
      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;
3594 3595
      }

3596
      mem_check->privs= fix_rights_for_procedure(mem_check->privs);
3597
      if (! mem_check->ok())
3598 3599
        delete mem_check;
      else if (my_hash_insert(hash, (uchar*) mem_check))
3600
      {
3601 3602
        delete mem_check;
        goto end_unlock;
3603 3604
      }
    }
3605
    while (!p_table->file->index_next(p_table->record[0]));
3606
  }
3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631
  /* Return ok */
  return_val= 0;

end_unlock:
  p_table->file->ha_index_end();
  my_pthread_setspecific_ptr(THR_MALLOC, save_mem_root_ptr);
  DBUG_RETURN(return_val);
}


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

  @param thd Current thread
  @param tables List containing open "mysql.tables_priv" and
    "mysql.columns_priv" tables.

  @see grant_reload

  @return Error state
    @retval FALSE Success
    @retval TRUE Error
*/

3632
static my_bool grant_load(THD *thd, TABLE_LIST *tables)
3633 3634 3635 3636 3637 3638 3639
{
  MEM_ROOT *memex_ptr;
  my_bool return_val= 1;
  TABLE *t_table= 0, *c_table= 0;
  bool check_no_resolve= specialflag & SPECIAL_NO_RESOLVE;
  MEM_ROOT **save_mem_root_ptr= my_pthread_getspecific_ptr(MEM_ROOT**,
                                                           THR_MALLOC);
3640
  ulong old_sql_mode= thd->variables.sql_mode;
3641
  DBUG_ENTER("grant_load");
3642 3643 3644

  thd->variables.sql_mode&= ~MODE_PAD_CHAR_TO_FULL_LENGTH;

3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655
  (void) hash_init(&column_priv_hash,system_charset_info,
                   0,0,0, (hash_get_key) get_grant_table,
                   (hash_free_key) free_grant_table,0);

  t_table = tables[0].table;
  c_table = tables[1].table;
  t_table->file->ha_index_init(0, 1);
  t_table->use_all_columns();
  c_table->use_all_columns();

  if (!t_table->file->index_first(t_table->record[0]))
unknown's avatar
unknown committed
3656
  {
3657 3658 3659
    memex_ptr= &memex;
    my_pthread_setspecific_ptr(THR_MALLOC, &memex_ptr);
    do
unknown's avatar
unknown committed
3660
    {
3661 3662
      GRANT_TABLE *mem_check;
      if (!(mem_check=new (memex_ptr) GRANT_TABLE(t_table,c_table)))
3663 3664 3665 3666
      {
	/* This could only happen if we are out memory */
	goto end_unlock;
      }
unknown's avatar
SCRUM  
unknown committed
3667

3668
      if (check_no_resolve)
unknown's avatar
SCRUM  
unknown committed
3669
      {
unknown's avatar
unknown committed
3670
	if (hostname_requires_resolving(mem_check->host.hostname))
3671
	{
3672
          sql_print_warning("'tables_priv' entry '%s %s@%s' "
3673
                            "ignored in --skip-name-resolve mode.",
3674 3675
                            mem_check->tname,
                            mem_check->user ? mem_check->user : "",
3676 3677
                            mem_check->host.hostname ?
                            mem_check->host.hostname : "");
3678 3679
	  continue;
	}
unknown's avatar
SCRUM  
unknown committed
3680 3681
      }

3682 3683
      if (! mem_check->ok())
	delete mem_check;
3684
      else if (my_hash_insert(&column_priv_hash,(uchar*) mem_check))
3685 3686 3687 3688
      {
	delete mem_check;
	goto end_unlock;
      }
unknown's avatar
SCRUM  
unknown committed
3689
    }
3690
    while (!t_table->file->index_next(t_table->record[0]));
unknown's avatar
unknown committed
3691
  }
3692

3693 3694 3695
  return_val=0;					// Return ok

end_unlock:
3696
  thd->variables.sql_mode= old_sql_mode;
unknown's avatar
unknown committed
3697
  t_table->file->ha_index_end();
3698
  my_pthread_setspecific_ptr(THR_MALLOC, save_mem_root_ptr);
3699
  DBUG_RETURN(return_val);
unknown's avatar
unknown committed
3700 3701 3702
}


3703 3704 3705
/**
  @brief Helper function to grant_reload. Reloads procs_priv table is it
    exists.
3706

3707
  @param thd A pointer to the thread handler object.
3708

3709
  @see grant_reload
3710

3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726
  @return Error state
    @retval FALSE Success
    @retval TRUE An error has occurred.
*/

static my_bool grant_reload_procs_priv(THD *thd)
{
  HASH old_proc_priv_hash, old_func_priv_hash;
  TABLE_LIST table;
  my_bool return_val= FALSE;
  DBUG_ENTER("grant_reload_procs_priv");

  bzero((char*) &table, sizeof(table));
  table.alias= table.table_name= (char*) "procs_priv";
  table.db= (char *) "mysql";
  table.lock_type= TL_READ;
3727
  table.skip_temporary= 1;
3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772

  if (simple_open_n_lock_tables(thd, &table))
  {
    close_thread_tables(thd);
    DBUG_RETURN(TRUE);
  }

  /* Save a copy of the current hash if we need to undo the grant load */
  old_proc_priv_hash= proc_priv_hash;
  old_func_priv_hash= func_priv_hash;

  rw_wrlock(&LOCK_grant);
  if ((return_val= grant_load_procs_priv(table.table)))
  {
    /* Error; Reverting to old hash */
    DBUG_PRINT("error",("Reverting to old privileges"));
    grant_free();
    proc_priv_hash= old_proc_priv_hash;
    func_priv_hash= old_func_priv_hash;
  }
  else
  {
    hash_free(&old_proc_priv_hash);
    hash_free(&old_func_priv_hash);
  }
  rw_unlock(&LOCK_grant);

  close_thread_tables(thd);
  DBUG_RETURN(return_val);
}


/**
  @brief Reload information about table and column level privileges if possible

  @param thd Current thread

  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 Error state
    @retval FALSE Success
    @retval TRUE  Error
3773
*/
unknown's avatar
unknown committed
3774

3775
my_bool grant_reload(THD *thd)
unknown's avatar
unknown committed
3776
{
3777 3778
  TABLE_LIST tables[2];
  HASH old_column_priv_hash;
unknown's avatar
unknown committed
3779
  MEM_ROOT old_mem;
3780
  my_bool return_val= 1;
unknown's avatar
unknown committed
3781 3782
  DBUG_ENTER("grant_reload");

3783 3784 3785 3786 3787
  /* Don't do anything if running with --skip-grant-tables */
  if (!initialized)
    DBUG_RETURN(0);

  bzero((char*) tables, sizeof(tables));
3788 3789
  tables[0].alias= tables[0].table_name= (char*) "tables_priv";
  tables[1].alias= tables[1].table_name= (char*) "columns_priv";
3790
  tables[0].db= tables[1].db= (char *) "mysql";
3791
  tables[0].next_local= tables[0].next_global= tables+1;
3792
  tables[0].lock_type= tables[1].lock_type= TL_READ;
3793
  tables[0].skip_temporary= tables[1].skip_temporary= TRUE;
3794 3795 3796 3797 3798 3799 3800
  /*
    To avoid deadlocks we should obtain table locks before
    obtaining LOCK_grant rwlock.
  */
  if (simple_open_n_lock_tables(thd, tables))
    goto end;

3801
  rw_wrlock(&LOCK_grant);
3802
  old_column_priv_hash= column_priv_hash;
3803 3804 3805 3806 3807

  /*
    Create a new memory pool but save the current memory pool to make an undo
    opertion possible in case of failure.
  */
unknown's avatar
unknown committed
3808
  old_mem= memex;
3809
  init_sql_alloc(&memex, ACL_ALLOC_BLOCK_SIZE, 0);
unknown's avatar
unknown committed
3810

3811
  if ((return_val= grant_load(thd, tables)))
unknown's avatar
unknown committed
3812
  {						// Error. Revert to old hash
3813
    DBUG_PRINT("error",("Reverting to old privileges"));
unknown's avatar
unknown committed
3814
    grant_free();				/* purecov: deadcode */
3815
    column_priv_hash= old_column_priv_hash;	/* purecov: deadcode */
unknown's avatar
unknown committed
3816
    memex= old_mem;				/* purecov: deadcode */
unknown's avatar
unknown committed
3817 3818 3819
  }
  else
  {
3820
    hash_free(&old_column_priv_hash);
3821
    free_root(&old_mem,MYF(0));
unknown's avatar
unknown committed
3822
  }
3823
  rw_unlock(&LOCK_grant);
3824
  close_thread_tables(thd);
3825 3826

  /*
3827
    It is OK failing to load procs_priv table because we may be
3828 3829 3830
    working with 4.1 privilege tables.
  */
  if (grant_reload_procs_priv(thd))
3831
    return_val= 1;
3832 3833 3834 3835 3836 3837

  rw_wrlock(&LOCK_grant);
  grant_version++;
  rw_unlock(&LOCK_grant);

end:
3838
  DBUG_RETURN(return_val);
unknown's avatar
unknown committed
3839 3840 3841
}

/****************************************************************************
3842
  Check table level grants
3843

3844
  SYNOPSIS
3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857
   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
3858
     1  Error: User did not have the requested privileges
3859 3860 3861 3862 3863 3864 3865

   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).
unknown's avatar
unknown committed
3866 3867
****************************************************************************/

unknown's avatar
unknown committed
3868
bool check_grant(THD *thd, ulong want_access, TABLE_LIST *tables,
unknown's avatar
unknown committed
3869
		 uint show_table, uint number, bool no_errors)
unknown's avatar
unknown committed
3870
{
3871
  TABLE_LIST *table, *first_not_own_table= thd->lex->first_not_own_table();
3872
  Security_context *sctx= thd->security_ctx;
3873
  uint i;
3874
  ulong orig_want_access= want_access;
3875 3876
  DBUG_ENTER("check_grant");
  DBUG_ASSERT(number > 0);
unknown's avatar
unknown committed
3877

3878
  /*
unknown's avatar
unknown committed
3879 3880 3881 3882 3883 3884 3885 3886
    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.
3887 3888
  */
  for (i= 0, table= tables;
3889
       i < number  && table != first_not_own_table;
3890 3891 3892 3893 3894 3895
       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);
  }

3896
  rw_rdlock(&LOCK_grant);
3897 3898 3899
  for (table= tables;
       table && number-- && table != first_not_own_table;
       table= table->next_global)
unknown's avatar
unknown committed
3900
  {
3901
    GRANT_TABLE *grant_table;
3902 3903 3904 3905 3906 3907 3908 3909
    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

3910
    if (!(~table->grant.privilege & want_access) || 
3911
        table->derived || table->schema_table)
unknown's avatar
unknown committed
3912
    {
unknown's avatar
VIEW  
unknown committed
3913 3914 3915 3916
      /*
        It is subquery in the FROM clause. VIEW set table->derived after
        table opening, but this function always called before table opening.
      */
3917 3918 3919 3920 3921 3922 3923 3924 3925 3926
      if (!table->referencing_view)
      {
        /*
          If it's a temporary table created for a subquery in the FROM
          clause, or an INFORMATION_SCHEMA table, drop the request for
          a privilege.
        */
        table->grant.want_privilege= 0;
      }
      continue;
unknown's avatar
unknown committed
3927
    }
3928 3929 3930
    if (!(grant_table= table_hash_search(sctx->host, sctx->ip,
                                         table->db, sctx->priv_user,
                                         table->table_name,0)))
unknown's avatar
unknown committed
3931 3932 3933 3934
    {
      want_access &= ~table->grant.privilege;
      goto err;					// No grants
    }
unknown's avatar
unknown committed
3935 3936
    if (show_table)
      continue;					// We have some priv on this
unknown's avatar
unknown committed
3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952

    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
    }
  }
3953
  rw_unlock(&LOCK_grant);
3954
  DBUG_RETURN(0);
unknown's avatar
unknown committed
3955

3956
err:
3957
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
3958
  if (!no_errors)				// Not a silent skip of table
unknown's avatar
unknown committed
3959
  {
3960 3961
    char command[128];
    get_privilege_desc(command, sizeof(command), want_access);
3962 3963
    my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0),
             command,
3964 3965
             sctx->priv_user,
             sctx->host_or_ip,
3966
             table ? table->table_name : "unknown");
unknown's avatar
unknown committed
3967
  }
3968
  DBUG_RETURN(1);
unknown's avatar
unknown committed
3969 3970 3971
}


3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989
/*
  Check column rights in given security context

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

  RETURN
    FALSE OK
    TRUE  access denied
*/

unknown's avatar
VIEW  
unknown committed
3990
bool check_grant_column(THD *thd, GRANT_INFO *grant,
3991
			const char *db_name, const char *table_name,
3992
			const char *name, uint length,  Security_context *sctx)
unknown's avatar
unknown committed
3993 3994 3995
{
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;
unknown's avatar
VIEW  
unknown committed
3996
  ulong want_access= grant->want_privilege & ~grant->privilege;
unknown's avatar
unknown committed
3997
  DBUG_ENTER("check_grant_column");
unknown's avatar
unknown committed
3998
  DBUG_PRINT("enter", ("table: %s  want_access: %lu", table_name, want_access));
unknown's avatar
unknown committed
3999

unknown's avatar
unknown committed
4000
  if (!want_access)
unknown's avatar
unknown committed
4001
    DBUG_RETURN(0);				// Already checked
unknown's avatar
unknown committed
4002

4003
  rw_rdlock(&LOCK_grant);
unknown's avatar
unknown committed
4004

4005
  /* reload table if someone has modified any grants */
unknown's avatar
unknown committed
4006

unknown's avatar
VIEW  
unknown committed
4007
  if (grant->version != grant_version)
unknown's avatar
unknown committed
4008
  {
unknown's avatar
VIEW  
unknown committed
4009
    grant->grant_table=
4010 4011
      table_hash_search(sctx->host, sctx->ip, db_name,
			sctx->priv_user,
unknown's avatar
unknown committed
4012
			table_name, 0);         /* purecov: inspected */
unknown's avatar
VIEW  
unknown committed
4013
    grant->version= grant_version;		/* purecov: inspected */
unknown's avatar
unknown committed
4014
  }
unknown's avatar
VIEW  
unknown committed
4015
  if (!(grant_table= grant->grant_table))
unknown's avatar
unknown committed
4016 4017 4018 4019 4020
    goto err;					/* purecov: deadcode */

  grant_column=column_hash_search(grant_table, name, length);
  if (grant_column && !(~grant_column->rights & want_access))
  {
4021
    rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
4022
    DBUG_RETURN(0);
unknown's avatar
unknown committed
4023 4024
  }

4025
err:
4026
  rw_unlock(&LOCK_grant);
4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070
  char command[128];
  get_privilege_desc(command, sizeof(command), want_access);
  my_error(ER_COLUMNACCESS_DENIED_ERROR, MYF(0),
           command,
           sctx->priv_user,
           sctx->host_or_ip,
           name,
           table_name);
  DBUG_RETURN(1);
}


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

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

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

  RETURN
    FALSE OK
    TRUE  access denied
*/

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

  if (table_ref->view || table_ref->field_translation)
unknown's avatar
unknown committed
4071
  {
4072
    /* View or derived information schema table. */
4073
    ulong view_privs;
4074 4075 4076
    grant= &(table_ref->grant);
    db_name= table_ref->view_db.str;
    table_name= table_ref->view_name.str;
4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090
    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;
    }
unknown's avatar
unknown committed
4091
  }
4092 4093 4094 4095 4096
  else
  {
    /* Normal or temporary table. */
    TABLE *table= table_ref->table;
    grant= &(table->grant);
unknown's avatar
unknown committed
4097 4098
    db_name= table->s->db.str;
    table_name= table->s->table_name.str;
4099 4100 4101 4102 4103 4104 4105 4106
  }

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

unknown's avatar
unknown committed
4107 4108 4109
}


4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126
/** 
  @brief check if a query can access a set of columns

  @param  thd  the current thread
  @param  want_access_arg  the privileges requested
  @param  fields an iterator over the fields of a table reference.
  @return Operation status
    @retval 0 Success
    @retval 1 Falure
  @details This function walks over the columns of a table reference 
   The columns may originate from different tables, depending on the kind of
   table reference, e.g. join.
   For each table it will retrieve the grant information and will use it
   to check the required access privileges for the fields requested from it.
*/    
bool check_grant_all_columns(THD *thd, ulong want_access_arg, 
                             Field_iterator_table_ref *fields)
unknown's avatar
unknown committed
4127
{
4128
  Security_context *sctx= thd->security_ctx;
4129 4130
  ulong want_access= want_access_arg;
  const char *table_name= NULL;
unknown's avatar
unknown committed
4131

4132 4133
  const char* db_name; 
  GRANT_INFO *grant;
4134 4135
  /* Initialized only to make gcc happy */
  GRANT_TABLE *grant_table= NULL;
unknown's avatar
unknown committed
4136

4137
  rw_rdlock(&LOCK_grant);
unknown's avatar
unknown committed
4138

4139
  for (; !fields->end_of_fields(); fields->next())
unknown's avatar
unknown committed
4140
  {
unknown's avatar
VIEW  
unknown committed
4141
    const char *field_name= fields->name();
unknown's avatar
unknown committed
4142

4143 4144 4145 4146 4147 4148 4149 4150
    if (table_name != fields->table_name())
    {
      table_name= fields->table_name();
      db_name= fields->db_name();
      grant= fields->grant();
      /* get a fresh one for each table */
      want_access= want_access_arg & ~grant->privilege;
      if (want_access)
4151
      {
4152 4153
        /* reload table if someone has modified any grants */
        if (grant->version != grant_version)
4154
        {
4155 4156 4157 4158 4159
          grant->grant_table=
            table_hash_search(sctx->host, sctx->ip, db_name,
                              sctx->priv_user,
                              table_name, 0);	/* purecov: inspected */
          grant->version= grant_version;	/* purecov: inspected */
4160 4161
        }

4162 4163
        grant_table= grant->grant_table;
        DBUG_ASSERT (grant_table);
4164 4165
      }
    }
unknown's avatar
unknown committed
4166

4167 4168 4169 4170 4171 4172 4173 4174
    if (want_access)
    {
      GRANT_COLUMN *grant_column= 
        column_hash_search(grant_table, field_name,
                           (uint) strlen(field_name));
      if (!grant_column || (~grant_column->rights & want_access))
        goto err;
    }
unknown's avatar
unknown committed
4175
  }
4176
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
4177 4178
  return 0;

unknown's avatar
unknown committed
4179
err:
4180
  rw_unlock(&LOCK_grant);
4181

4182 4183
  char command[128];
  get_privilege_desc(command, sizeof(command), want_access);
4184 4185
  my_error(ER_COLUMNACCESS_DENIED_ERROR, MYF(0),
           command,
4186 4187
           sctx->priv_user,
           sctx->host_or_ip,
4188 4189
           fields->name(),
           table_name);
unknown's avatar
unknown committed
4190 4191 4192 4193
  return 1;
}


4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213
static bool check_grant_db_routine(THD *thd, const char *db, HASH *hash)
{
  Security_context *sctx= thd->security_ctx;

  for (uint idx= 0; idx < hash->records; ++idx)
  {
    GRANT_NAME *item= (GRANT_NAME*) hash_element(hash, idx);

    if (strcmp(item->user, sctx->priv_user) == 0 &&
        strcmp(item->db, db) == 0 &&
        compare_hostname(&item->host, sctx->host, sctx->ip))
    {
      return FALSE;
    }
  }

  return TRUE;
}


4214
/*
unknown's avatar
unknown committed
4215
  Check if a user has the right to access a database
4216
  Access is accepted if he has a grant for any table/routine in the database
unknown's avatar
unknown committed
4217
  Return 1 if access is denied
4218
*/
unknown's avatar
unknown committed
4219 4220 4221

bool check_grant_db(THD *thd,const char *db)
{
4222
  Security_context *sctx= thd->security_ctx;
unknown's avatar
unknown committed
4223
  char helping [NAME_LEN+USERNAME_LENGTH+2];
unknown's avatar
unknown committed
4224
  uint len;
4225
  bool error= TRUE;
unknown's avatar
unknown committed
4226

4227
  len= (uint) (strmov(strmov(helping, sctx->priv_user) + 1, db) - helping) + 1;
4228

4229
  rw_rdlock(&LOCK_grant);
unknown's avatar
unknown committed
4230

4231
  for (uint idx=0 ; idx < column_priv_hash.records ; idx++)
unknown's avatar
unknown committed
4232
  {
4233 4234
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  idx);
unknown's avatar
unknown committed
4235 4236
    if (len < grant_table->key_length &&
	!memcmp(grant_table->hash_key,helping,len) &&
4237
        compare_hostname(&grant_table->host, sctx->host, sctx->ip))
unknown's avatar
unknown committed
4238
    {
4239
      error= FALSE; /* Found match. */
unknown's avatar
unknown committed
4240 4241 4242
      break;
    }
  }
4243 4244 4245 4246 4247

  if (error)
    error= check_grant_db_routine(thd, db, &proc_priv_hash) &&
           check_grant_db_routine(thd, db, &func_priv_hash);

4248
  rw_unlock(&LOCK_grant);
4249

unknown's avatar
unknown committed
4250 4251 4252
  return error;
}

4253 4254

/****************************************************************************
4255
  Check routine level grants
4256 4257

  SYNPOSIS
4258
   bool check_grant_routine()
4259 4260
   thd		Thread handler
   want_access  Bits of privileges user needs to have
4261 4262
   procs	List of routines to check. The user should have 'want_access'
   is_proc	True if the list is all procedures, else functions
4263 4264 4265 4266 4267 4268 4269 4270
   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
****************************************************************************/

4271
bool check_grant_routine(THD *thd, ulong want_access,
4272
			 TABLE_LIST *procs, bool is_proc, bool no_errors)
4273 4274
{
  TABLE_LIST *table;
4275
  Security_context *sctx= thd->security_ctx;
4276 4277
  char *user= sctx->priv_user;
  char *host= sctx->priv_host;
4278
  DBUG_ENTER("check_grant_routine");
4279

4280
  want_access&= ~sctx->master_access;
4281 4282 4283 4284 4285 4286 4287
  if (!want_access)
    DBUG_RETURN(0);                             // ok

  rw_rdlock(&LOCK_grant);
  for (table= procs; table; table= table->next_global)
  {
    GRANT_NAME *grant_proc;
4288
    if ((grant_proc= routine_hash_search(host, sctx->ip, table->db, user,
4289
					 table->table_name, is_proc, 0)))
4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306
      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)
4307
      strxmov(buff, table->db, ".", table->table_name, NullS);
4308 4309 4310
    if (want_access & EXECUTE_ACL)
      command= "execute";
    else if (want_access & ALTER_PROC_ACL)
4311
      command= "alter routine";
4312 4313 4314 4315 4316 4317 4318 4319 4320
    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);
}


4321 4322
/*
  Check if routine has any of the 
4323
  routine level grants
4324 4325 4326 4327 4328 4329 4330 4331 4332
  
  SYNPOSIS
   bool    check_routine_level_acl()
   thd	        Thread handler
   db           Database name
   name         Routine name

  RETURN
   0            Ok 
4333
   1            error
4334 4335
*/

unknown's avatar
unknown committed
4336 4337
bool check_routine_level_acl(THD *thd, const char *db, const char *name, 
                             bool is_proc)
4338 4339
{
  bool no_routine_acl= 1;
4340 4341 4342 4343 4344 4345 4346 4347 4348
  GRANT_NAME *grant_proc;
  Security_context *sctx= thd->security_ctx;
  rw_rdlock(&LOCK_grant);
  if ((grant_proc= routine_hash_search(sctx->priv_host,
                                       sctx->ip, db,
                                       sctx->priv_user,
                                       name, is_proc, 0)))
    no_routine_acl= !(grant_proc->privs & SHOW_PROC_ACLS);
  rw_unlock(&LOCK_grant);
4349 4350 4351 4352
  return no_routine_acl;
}


unknown's avatar
unknown committed
4353
/*****************************************************************************
unknown's avatar
unknown committed
4354
  Functions to retrieve the grant for a table/column  (for SHOW functions)
unknown's avatar
unknown committed
4355 4356
*****************************************************************************/

unknown's avatar
unknown committed
4357
ulong get_table_grant(THD *thd, TABLE_LIST *table)
unknown's avatar
unknown committed
4358
{
unknown's avatar
unknown committed
4359
  ulong privilege;
4360
  Security_context *sctx= thd->security_ctx;
unknown's avatar
unknown committed
4361 4362 4363
  const char *db = table->db ? table->db : thd->db;
  GRANT_TABLE *grant_table;

4364
  rw_rdlock(&LOCK_grant);
4365 4366 4367
#ifdef EMBEDDED_LIBRARY
  grant_table= NULL;
#else
4368
  grant_table= table_hash_search(sctx->host, sctx->ip, db, sctx->priv_user,
4369
				 table->table_name, 0);
4370
#endif
unknown's avatar
unknown committed
4371 4372 4373 4374
  table->grant.grant_table=grant_table; // Remember for column test
  table->grant.version=grant_version;
  if (grant_table)
    table->grant.privilege|= grant_table->privs;
4375
  privilege= table->grant.privilege;
4376
  rw_unlock(&LOCK_grant);
4377
  return privilege;
unknown's avatar
unknown committed
4378 4379 4380
}


unknown's avatar
unknown committed
4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398
/*
  Determine the access priviliges for a field.

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

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

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

unknown's avatar
VIEW  
unknown committed
4399 4400 4401
ulong get_column_grant(THD *thd, GRANT_INFO *grant,
                       const char *db_name, const char *table_name,
                       const char *field_name)
unknown's avatar
unknown committed
4402 4403 4404
{
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;
unknown's avatar
unknown committed
4405
  ulong priv;
unknown's avatar
unknown committed
4406

4407
  rw_rdlock(&LOCK_grant);
4408
  /* reload table if someone has modified any grants */
unknown's avatar
VIEW  
unknown committed
4409
  if (grant->version != grant_version)
unknown's avatar
unknown committed
4410
  {
4411
    Security_context *sctx= thd->security_ctx;
unknown's avatar
VIEW  
unknown committed
4412
    grant->grant_table=
4413 4414
      table_hash_search(sctx->host, sctx->ip,
                        db_name, sctx->priv_user,
unknown's avatar
VIEW  
unknown committed
4415 4416
			table_name, 0);	        /* purecov: inspected */
    grant->version= grant_version;              /* purecov: inspected */
unknown's avatar
unknown committed
4417 4418
  }

unknown's avatar
VIEW  
unknown committed
4419 4420
  if (!(grant_table= grant->grant_table))
    priv= grant->privilege;
unknown's avatar
unknown committed
4421 4422
  else
  {
unknown's avatar
VIEW  
unknown committed
4423 4424
    grant_column= column_hash_search(grant_table, field_name,
                                     (uint) strlen(field_name));
unknown's avatar
unknown committed
4425
    if (!grant_column)
4426
      priv= (grant->privilege | grant_table->privs);
unknown's avatar
unknown committed
4427
    else
4428
      priv= (grant->privilege | grant_table->privs | grant_column->rights);
unknown's avatar
unknown committed
4429
  }
4430
  rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
4431 4432 4433
  return priv;
}

unknown's avatar
VIEW  
unknown committed
4434

4435
/* Help function for mysql_show_grants */
unknown's avatar
unknown committed
4436

4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448
static void add_user_option(String *grant, ulong value, const char *name)
{
  if (value)
  {
    char buff[22], *p; // just as in int2str
    grant->append(' ');
    grant->append(name, strlen(name));
    grant->append(' ');
    p=int10_to_str(value, buff, 10);
    grant->append(buff,p-buff);
  }
}
unknown's avatar
unknown committed
4449 4450

static const char *command_array[]=
unknown's avatar
unknown committed
4451
{
unknown's avatar
VIEW  
unknown committed
4452 4453 4454 4455
  "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",
4456
  "CREATE VIEW", "SHOW VIEW", "CREATE ROUTINE", "ALTER ROUTINE",
4457
  "CREATE USER", "EVENT", "TRIGGER"
unknown's avatar
unknown committed
4458
};
4459

unknown's avatar
unknown committed
4460 4461
static uint command_lengths[]=
{
4462
  6, 6, 6, 6, 6, 4, 6, 8, 7, 4, 5, 10, 5, 5, 14, 5, 23, 11, 7, 17, 18, 11, 9,
4463
  14, 13, 11, 5, 7
unknown's avatar
unknown committed
4464 4465
};

unknown's avatar
unknown committed
4466

4467 4468 4469 4470 4471
static int show_routine_grants(THD *thd, LEX_USER *lex_user, HASH *hash,
                               const char *type, int typelen,
                               char *buff, int buffsize);


4472 4473 4474 4475 4476 4477 4478
/*
  SHOW GRANTS;  Send grants for a user to the client

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

unknown's avatar
unknown committed
4479
bool mysql_show_grants(THD *thd,LEX_USER *lex_user)
unknown's avatar
unknown committed
4480
{
unknown's avatar
unknown committed
4481 4482
  ulong want_access;
  uint counter,index;
unknown's avatar
unknown committed
4483
  int  error = 0;
unknown's avatar
unknown committed
4484 4485
  ACL_USER *acl_user;
  ACL_DB *acl_db;
unknown's avatar
unknown committed
4486
  char buff[1024];
4487
  Protocol *protocol= thd->protocol;
unknown's avatar
unknown committed
4488
  DBUG_ENTER("mysql_show_grants");
unknown's avatar
unknown committed
4489 4490 4491 4492

  LINT_INIT(acl_user);
  if (!initialized)
  {
unknown's avatar
unknown committed
4493
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
unknown's avatar
unknown committed
4494
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
4495
  }
unknown's avatar
unknown committed
4496

4497 4498 4499 4500 4501
  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)
unknown's avatar
unknown committed
4502
  {
4503 4504 4505
    VOID(pthread_mutex_unlock(&acl_cache->lock));
    rw_unlock(&LOCK_grant);

unknown's avatar
unknown committed
4506 4507
    my_error(ER_NONEXISTING_GRANT, MYF(0),
             lex_user->user.str, lex_user->host.str);
unknown's avatar
unknown committed
4508
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
4509 4510
  }

unknown's avatar
unknown committed
4511
  Item_string *field=new Item_string("",0,&my_charset_latin1);
unknown's avatar
unknown committed
4512 4513 4514 4515 4516 4517
  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);
4518 4519
  if (protocol->send_fields(&field_list,
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
4520 4521 4522
  {
    VOID(pthread_mutex_unlock(&acl_cache->lock));
    rw_unlock(&LOCK_grant);
unknown's avatar
unknown committed
4523

4524 4525
    DBUG_RETURN(TRUE);
  }
unknown's avatar
unknown committed
4526 4527 4528

  /* Add first global access grants */
  {
4529
    String global(buff,sizeof(buff),system_charset_info);
unknown's avatar
unknown committed
4530
    global.length(0);
4531
    global.append(STRING_WITH_LEN("GRANT "));
unknown's avatar
unknown committed
4532

unknown's avatar
unknown committed
4533
    want_access= acl_user->access;
unknown's avatar
unknown committed
4534
    if (test_all_bits(want_access, (GLOBAL_ACLS & ~ GRANT_ACL)))
4535
      global.append(STRING_WITH_LEN("ALL PRIVILEGES"));
unknown's avatar
unknown committed
4536
    else if (!(want_access & ~GRANT_ACL))
4537
      global.append(STRING_WITH_LEN("USAGE"));
unknown's avatar
unknown committed
4538
    else
unknown's avatar
unknown committed
4539 4540
    {
      bool found=0;
unknown's avatar
unknown committed
4541
      ulong j,test_access= want_access & ~GRANT_ACL;
unknown's avatar
unknown committed
4542 4543
      for (counter=0, j = SELECT_ACL;j <= GLOBAL_ACLS;counter++,j <<= 1)
      {
unknown's avatar
unknown committed
4544
	if (test_access & j)
unknown's avatar
unknown committed
4545 4546
	{
	  if (found)
4547
	    global.append(STRING_WITH_LEN(", "));
unknown's avatar
unknown committed
4548 4549 4550 4551 4552
	  found=1;
	  global.append(command_array[counter],command_lengths[counter]);
	}
      }
    }
4553
    global.append (STRING_WITH_LEN(" ON *.* TO '"));
4554 4555
    global.append(lex_user->user.str, lex_user->user.length,
		  system_charset_info);
4556
    global.append (STRING_WITH_LEN("'@'"));
4557 4558
    global.append(lex_user->host.str,lex_user->host.length,
		  system_charset_info);
unknown's avatar
unknown committed
4559
    global.append ('\'');
4560
    if (acl_user->salt_len)
unknown's avatar
unknown committed
4561
    {
4562 4563 4564 4565 4566
      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);
4567
      global.append(STRING_WITH_LEN(" IDENTIFIED BY PASSWORD '"));
4568
      global.append(passwd_buff);
unknown's avatar
unknown committed
4569 4570
      global.append('\'');
    }
4571 4572
    /* "show grants" SSL related stuff */
    if (acl_user->ssl_type == SSL_TYPE_ANY)
4573
      global.append(STRING_WITH_LEN(" REQUIRE SSL"));
4574
    else if (acl_user->ssl_type == SSL_TYPE_X509)
4575
      global.append(STRING_WITH_LEN(" REQUIRE X509"));
4576
    else if (acl_user->ssl_type == SSL_TYPE_SPECIFIED)
4577
    {
4578
      int ssl_options = 0;
4579
      global.append(STRING_WITH_LEN(" REQUIRE "));
4580 4581
      if (acl_user->x509_issuer)
      {
4582
	ssl_options++;
4583
	global.append(STRING_WITH_LEN("ISSUER \'"));
4584
	global.append(acl_user->x509_issuer,strlen(acl_user->x509_issuer));
4585
	global.append('\'');
4586
      }
4587 4588
      if (acl_user->x509_subject)
      {
4589 4590
	if (ssl_options++)
	  global.append(' ');
4591
	global.append(STRING_WITH_LEN("SUBJECT \'"));
4592 4593
	global.append(acl_user->x509_subject,strlen(acl_user->x509_subject),
                      system_charset_info);
4594
	global.append('\'');
unknown's avatar
unknown committed
4595
      }
4596 4597
      if (acl_user->ssl_cipher)
      {
4598 4599
	if (ssl_options++)
	  global.append(' ');
4600
	global.append(STRING_WITH_LEN("CIPHER '"));
4601 4602
	global.append(acl_user->ssl_cipher,strlen(acl_user->ssl_cipher),
                      system_charset_info);
4603
	global.append('\'');
4604 4605
      }
    }
unknown's avatar
unknown committed
4606
    if ((want_access & GRANT_ACL) ||
4607 4608 4609 4610
	(acl_user->user_resource.questions ||
         acl_user->user_resource.updates ||
         acl_user->user_resource.conn_per_hour ||
         acl_user->user_resource.user_conn))
4611
    {
4612
      global.append(STRING_WITH_LEN(" WITH"));
unknown's avatar
unknown committed
4613
      if (want_access & GRANT_ACL)
4614
	global.append(STRING_WITH_LEN(" GRANT OPTION"));
4615 4616 4617 4618
      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");
4619
      add_user_option(&global, acl_user->user_resource.conn_per_hour,
4620
		      "MAX_CONNECTIONS_PER_HOUR");
4621 4622
      add_user_option(&global, acl_user->user_resource.user_conn,
		      "MAX_USER_CONNECTIONS");
unknown's avatar
unknown committed
4623
    }
4624
    protocol->prepare_for_resend();
4625
    protocol->store(global.ptr(),global.length(),global.charset());
4626
    if (protocol->write())
unknown's avatar
unknown committed
4627
    {
unknown's avatar
unknown committed
4628
      error= -1;
4629
      goto end;
unknown's avatar
unknown committed
4630 4631 4632 4633 4634 4635
    }
  }

  /* Add database access */
  for (counter=0 ; counter < acl_dbs.elements ; counter++)
  {
unknown's avatar
unknown committed
4636
    const char *user, *host;
unknown's avatar
unknown committed
4637 4638 4639

    acl_db=dynamic_element(&acl_dbs,counter,ACL_DB*);
    if (!(user=acl_db->user))
unknown's avatar
unknown committed
4640
      user= "";
unknown's avatar
unknown committed
4641
    if (!(host=acl_db->host.hostname))
unknown's avatar
unknown committed
4642
      host= "";
unknown's avatar
unknown committed
4643

4644 4645 4646 4647 4648 4649 4650
    /*
      We do not make SHOW GRANTS case-sensitive here (like REVOKE),
      but make it case-insensitive because that's the way they are
      actually applied, and showing fewer privileges than are applied
      would be wrong from a security point of view.
    */

unknown's avatar
unknown committed
4651
    if (!strcmp(lex_user->user.str,user) &&
4652
	!my_strcasecmp(system_charset_info, lex_user->host.str, host))
unknown's avatar
unknown committed
4653 4654
    {
      want_access=acl_db->access;
unknown's avatar
unknown committed
4655
      if (want_access)
unknown's avatar
unknown committed
4656
      {
4657
	String db(buff,sizeof(buff),system_charset_info);
unknown's avatar
unknown committed
4658
	db.length(0);
4659
	db.append(STRING_WITH_LEN("GRANT "));
unknown's avatar
unknown committed
4660 4661

	if (test_all_bits(want_access,(DB_ACLS & ~GRANT_ACL)))
4662
	  db.append(STRING_WITH_LEN("ALL PRIVILEGES"));
4663
	else if (!(want_access & ~GRANT_ACL))
4664
	  db.append(STRING_WITH_LEN("USAGE"));
unknown's avatar
unknown committed
4665 4666 4667
	else
	{
	  int found=0, cnt;
unknown's avatar
unknown committed
4668
	  ulong j,test_access= want_access & ~GRANT_ACL;
unknown's avatar
unknown committed
4669 4670 4671 4672 4673
	  for (cnt=0, j = SELECT_ACL; j <= DB_ACLS; cnt++,j <<= 1)
	  {
	    if (test_access & j)
	    {
	      if (found)
4674
		db.append(STRING_WITH_LEN(", "));
unknown's avatar
unknown committed
4675 4676 4677 4678 4679
	      found = 1;
	      db.append(command_array[cnt],command_lengths[cnt]);
	    }
	  }
	}
4680
	db.append (STRING_WITH_LEN(" ON "));
4681
	append_identifier(thd, &db, acl_db->db, strlen(acl_db->db));
4682
	db.append (STRING_WITH_LEN(".* TO '"));
4683 4684
	db.append(lex_user->user.str, lex_user->user.length,
		  system_charset_info);
4685
	db.append (STRING_WITH_LEN("'@'"));
4686 4687
	// host and lex_user->host are equal except for case
	db.append(host, strlen(host), system_charset_info);
unknown's avatar
unknown committed
4688
	db.append ('\'');
unknown's avatar
unknown committed
4689
	if (want_access & GRANT_ACL)
4690
	  db.append(STRING_WITH_LEN(" WITH GRANT OPTION"));
4691
	protocol->prepare_for_resend();
4692
	protocol->store(db.ptr(),db.length(),db.charset());
4693
	if (protocol->write())
unknown's avatar
unknown committed
4694
	{
unknown's avatar
unknown committed
4695
	  error= -1;
unknown's avatar
unknown committed
4696 4697 4698 4699 4700 4701
	  goto end;
	}
      }
    }
  }

4702
  /* Add table & column access */
4703
  for (index=0 ; index < column_priv_hash.records ; index++)
unknown's avatar
unknown committed
4704
  {
4705
    const char *user, *host;
4706 4707
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  index);
unknown's avatar
unknown committed
4708 4709

    if (!(user=grant_table->user))
4710
      user= "";
4711 4712
    if (!(host= grant_table->host.hostname))
      host= "";
unknown's avatar
unknown committed
4713

4714 4715 4716 4717 4718 4719 4720
    /*
      We do not make SHOW GRANTS case-sensitive here (like REVOKE),
      but make it case-insensitive because that's the way they are
      actually applied, and showing fewer privileges than are applied
      would be wrong from a security point of view.
    */

unknown's avatar
unknown committed
4721
    if (!strcmp(lex_user->user.str,user) &&
4722
	!my_strcasecmp(system_charset_info, lex_user->host.str, host))
unknown's avatar
unknown committed
4723
    {
4724 4725
      ulong table_access= grant_table->privs;
      if ((table_access | grant_table->cols) != 0)
unknown's avatar
unknown committed
4726
      {
4727
	String global(buff, sizeof(buff), system_charset_info);
unknown's avatar
unknown committed
4728 4729
	ulong test_access= (table_access | grant_table->cols) & ~GRANT_ACL;

unknown's avatar
unknown committed
4730
	global.length(0);
4731
	global.append(STRING_WITH_LEN("GRANT "));
unknown's avatar
unknown committed
4732

4733
	if (test_all_bits(table_access, (TABLE_ACLS & ~GRANT_ACL)))
4734
	  global.append(STRING_WITH_LEN("ALL PRIVILEGES"));
unknown's avatar
unknown committed
4735
	else if (!test_access)
4736
	  global.append(STRING_WITH_LEN("USAGE"));
unknown's avatar
unknown committed
4737
	else
unknown's avatar
unknown committed
4738
	{
4739
          /* Add specific column access */
4740
	  int found= 0;
unknown's avatar
unknown committed
4741
	  ulong j;
unknown's avatar
unknown committed
4742

4743
	  for (counter= 0, j= SELECT_ACL; j <= TABLE_ACLS; counter++, j<<= 1)
unknown's avatar
unknown committed
4744
	  {
unknown's avatar
unknown committed
4745
	    if (test_access & j)
unknown's avatar
unknown committed
4746 4747
	    {
	      if (found)
4748
		global.append(STRING_WITH_LEN(", "));
4749
	      found= 1;
unknown's avatar
unknown committed
4750 4751
	      global.append(command_array[counter],command_lengths[counter]);

unknown's avatar
unknown committed
4752
	      if (grant_table->cols)
unknown's avatar
unknown committed
4753
	      {
4754
		uint found_col= 0;
unknown's avatar
unknown committed
4755 4756 4757 4758 4759 4760
		for (uint col_index=0 ;
		     col_index < grant_table->hash_columns.records ;
		     col_index++)
		{
		  GRANT_COLUMN *grant_column = (GRANT_COLUMN*)
		    hash_element(&grant_table->hash_columns,col_index);
unknown's avatar
unknown committed
4761
		  if (grant_column->rights & j)
unknown's avatar
unknown committed
4762
		  {
unknown's avatar
unknown committed
4763
		    if (!found_col)
unknown's avatar
unknown committed
4764
		    {
4765 4766 4767 4768 4769 4770 4771
		      found_col= 1;
		      /*
			If we have a duplicated table level privilege, we
			must write the access privilege name again.
		      */
		      if (table_access & j)
		      {
4772
			global.append(STRING_WITH_LEN(", "));
4773 4774 4775
			global.append(command_array[counter],
				      command_lengths[counter]);
		      }
4776
		      global.append(STRING_WITH_LEN(" ("));
unknown's avatar
unknown committed
4777 4778
		    }
		    else
4779
		      global.append(STRING_WITH_LEN(", "));
unknown's avatar
unknown committed
4780
		    global.append(grant_column->column,
4781 4782
				  grant_column->key_length,
				  system_charset_info);
unknown's avatar
unknown committed
4783 4784 4785 4786 4787 4788 4789 4790
		  }
		}
		if (found_col)
		  global.append(')');
	      }
	    }
	  }
	}
4791
	global.append(STRING_WITH_LEN(" ON "));
4792 4793 4794 4795 4796
	append_identifier(thd, &global, grant_table->db,
			  strlen(grant_table->db));
	global.append('.');
	append_identifier(thd, &global, grant_table->tname,
			  strlen(grant_table->tname));
4797
	global.append(STRING_WITH_LEN(" TO '"));
4798 4799
	global.append(lex_user->user.str, lex_user->user.length,
		      system_charset_info);
4800
	global.append(STRING_WITH_LEN("'@'"));
4801 4802
	// host and lex_user->host are equal except for case
	global.append(host, strlen(host), system_charset_info);
unknown's avatar
unknown committed
4803
	global.append('\'');
4804
	if (table_access & GRANT_ACL)
4805
	  global.append(STRING_WITH_LEN(" WITH GRANT OPTION"));
4806
	protocol->prepare_for_resend();
4807
	protocol->store(global.ptr(),global.length(),global.charset());
4808
	if (protocol->write())
unknown's avatar
unknown committed
4809
	{
unknown's avatar
unknown committed
4810
	  error= -1;
4811
	  break;
unknown's avatar
unknown committed
4812 4813 4814 4815
	}
      }
    }
  }
4816

4817
  if (show_routine_grants(thd, lex_user, &proc_priv_hash, 
4818
                          STRING_WITH_LEN("PROCEDURE"), buff, sizeof(buff)))
4819 4820 4821 4822 4823 4824
  {
    error= -1;
    goto end;
  }

  if (show_routine_grants(thd, lex_user, &func_priv_hash,
4825
                          STRING_WITH_LEN("FUNCTION"), buff, sizeof(buff)))
4826 4827 4828 4829 4830 4831 4832 4833 4834
  {
    error= -1;
    goto end;
  }

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

4835
  my_eof(thd);
4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847
  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++)
4848
  {
4849
    const char *user, *host;
4850
    GRANT_NAME *grant_proc= (GRANT_NAME*) hash_element(hash, index);
4851 4852 4853

    if (!(user=grant_proc->user))
      user= "";
4854 4855
    if (!(host= grant_proc->host.hostname))
      host= "";
4856

4857 4858 4859 4860 4861 4862 4863
    /*
      We do not make SHOW GRANTS case-sensitive here (like REVOKE),
      but make it case-insensitive because that's the way they are
      actually applied, and showing fewer privileges than are applied
      would be wrong from a security point of view.
    */

4864
    if (!strcmp(lex_user->user.str,user) &&
4865
	!my_strcasecmp(system_charset_info, lex_user->host.str, host))
4866 4867 4868 4869
    {
      ulong proc_access= grant_proc->privs;
      if (proc_access != 0)
      {
4870
	String global(buff, buffsize, system_charset_info);
4871 4872 4873
	ulong test_access= proc_access & ~GRANT_ACL;

	global.length(0);
4874
	global.append(STRING_WITH_LEN("GRANT "));
4875 4876

	if (!test_access)
4877
 	  global.append(STRING_WITH_LEN("USAGE"));
4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888
	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)
4889
		global.append(STRING_WITH_LEN(", "));
4890 4891 4892 4893 4894
	      found= 1;
	      global.append(command_array[counter],command_lengths[counter]);
	    }
	  }
	}
4895
	global.append(STRING_WITH_LEN(" ON "));
4896 4897
        global.append(type,typelen);
        global.append(' ');
4898 4899 4900 4901 4902
	append_identifier(thd, &global, grant_proc->db,
			  strlen(grant_proc->db));
	global.append('.');
	append_identifier(thd, &global, grant_proc->tname,
			  strlen(grant_proc->tname));
4903
	global.append(STRING_WITH_LEN(" TO '"));
4904 4905
	global.append(lex_user->user.str, lex_user->user.length,
		      system_charset_info);
4906
	global.append(STRING_WITH_LEN("'@'"));
4907 4908
	// host and lex_user->host are equal except for case
	global.append(host, strlen(host), system_charset_info);
4909 4910
	global.append('\'');
	if (proc_access & GRANT_ACL)
4911
	  global.append(STRING_WITH_LEN(" WITH GRANT OPTION"));
4912 4913 4914 4915 4916 4917 4918 4919 4920 4921
	protocol->prepare_for_resend();
	protocol->store(global.ptr(),global.length(),global.charset());
	if (protocol->write())
	{
	  error= -1;
	  break;
	}
      }
    }
  }
4922
  return error;
unknown's avatar
unknown committed
4923 4924
}

unknown's avatar
unknown committed
4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952
/*
  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;
}


4953
void get_mqh(const char *user, const char *host, USER_CONN *uc)
unknown's avatar
unknown committed
4954 4955
{
  ACL_USER *acl_user;
4956 4957 4958

  pthread_mutex_lock(&acl_cache->lock);

4959
  if (initialized && (acl_user= find_acl_user(host,user, FALSE)))
4960 4961 4962
    uc->user_resources= acl_user->user_resource;
  else
    bzero((char*) &uc->user_resources, sizeof(uc->user_resources));
4963 4964

  pthread_mutex_unlock(&acl_cache->lock);
unknown's avatar
unknown committed
4965 4966
}

4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987
/*
  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.
*/

4988
#define GRANT_TABLES 5
4989 4990 4991 4992 4993 4994
int open_grant_tables(THD *thd, TABLE_LIST *tables)
{
  DBUG_ENTER("open_grant_tables");

  if (!initialized)
  {
unknown's avatar
unknown committed
4995
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
4996 4997 4998
    DBUG_RETURN(-1);
  }

4999
  bzero((char*) tables, GRANT_TABLES*sizeof(*tables));
5000 5001 5002 5003 5004
  tables->alias= tables->table_name= (char*) "user";
  (tables+1)->alias= (tables+1)->table_name= (char*) "db";
  (tables+2)->alias= (tables+2)->table_name= (char*) "tables_priv";
  (tables+3)->alias= (tables+3)->table_name= (char*) "columns_priv";
  (tables+4)->alias= (tables+4)->table_name= (char*) "procs_priv";
unknown's avatar
VIEW  
unknown committed
5005 5006 5007
  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;
5008
  (tables+3)->next_local= (tables+3)->next_global= tables+4;
5009
  tables->lock_type= (tables+1)->lock_type=
5010 5011 5012 5013
    (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";
5014 5015 5016 5017 5018 5019

#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
5020
  if (thd->slave_thread && rpl_filter->is_on())
5021
  {
unknown's avatar
unknown committed
5022 5023 5024
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
5025
    */
5026 5027
    tables[0].updating=tables[1].updating=tables[2].updating=
      tables[3].updating=tables[4].updating=1;
unknown's avatar
unknown committed
5028
    if (!(thd->spcont || rpl_filter->tables_ok(0, tables)))
5029
      DBUG_RETURN(1);
5030 5031
    tables[0].updating=tables[1].updating=tables[2].updating=
      tables[3].updating=tables[4].updating=0;;
5032
  }
5033 5034
#endif

5035
  if (simple_open_n_lock_tables(thd, tables))
5036 5037 5038 5039 5040 5041 5042 5043 5044
  {						// This should never happen
    close_thread_tables(thd);
    DBUG_RETURN(-1);
  }

  DBUG_RETURN(0);
}

ACL_USER *check_acl_user(LEX_USER *user_name,
unknown's avatar
merge  
unknown committed
5045
			 uint *acl_acl_userdx)
5046 5047 5048 5049
{
  ACL_USER *acl_user= 0;
  uint counter;

5050 5051
  safe_mutex_assert_owner(&acl_cache->lock);

5052 5053 5054 5055 5056
  for (counter= 0 ; counter < acl_users.elements ; counter++)
  {
    const char *user,*host;
    acl_user= dynamic_element(&acl_users, counter, ACL_USER*);
    if (!(user=acl_user->user))
unknown's avatar
unknown committed
5057
      user= "";
5058
    if (!(host=acl_user->host.hostname))
5059
      host= "";
5060 5061 5062 5063 5064 5065 5066
    if (!strcmp(user_name->user.str,user) &&
	!my_strcasecmp(system_charset_info, user_name->host.str, host))
      break;
  }
  if (counter == acl_users.elements)
    return 0;

unknown's avatar
merge  
unknown committed
5067
  *acl_acl_userdx= counter;
unknown's avatar
unknown committed
5068
  return acl_user;
5069
}
unknown's avatar
unknown committed
5070

5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092
/*
  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)
5093
{
5094 5095
  int error;
  DBUG_ENTER("modify_grant_table");
5096

5097 5098 5099 5100 5101 5102 5103 5104
  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);
5105 5106 5107
    if ((error= table->file->ha_update_row(table->record[1], 
                                           table->record[0])) &&
        error != HA_ERR_RECORD_IS_THE_SAME)
5108
      table->file->print_error(error, MYF(0));
5109 5110
    else
      error= 0;
5111 5112 5113 5114
  }
  else
  {
    /* delete */
5115
    if ((error=table->file->ha_delete_row(table->record[0])))
5116 5117
      table->file->print_error(error, MYF(0));
  }
5118

5119 5120
  DBUG_RETURN(error);
}
5121

5122 5123 5124 5125 5126 5127
/*
  Handle a privilege table.

  SYNOPSIS
    handle_grant_table()
    tables                      The array with the four open tables.
5128
    table_no                    The number of the table to handle (0..4).
5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145
    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
5146
    4 procs_priv
5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165

  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;
5166
  uchar user_key[MAX_KEY_LENGTH];
unknown's avatar
unknown committed
5167
  uint key_prefix_length;
5168
  DBUG_ENTER("handle_grant_table");
5169
  THD *thd= current_thd;
5170

5171
  table->use_all_columns();
unknown's avatar
unknown committed
5172
  if (! table_no) // mysql.user table
5173
  {
5174 5175 5176 5177 5178 5179 5180 5181 5182 5183
    /*
      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'",
unknown's avatar
unknown committed
5184
                       table->s->table_name.str, user_str, host_str));
5185 5186
    host_field->store(host_str, user_from->host.length, system_charset_info);
    user_field->store(user_str, user_from->user.length, system_charset_info);
unknown's avatar
unknown committed
5187 5188 5189 5190 5191

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

5192 5193 5194
    if ((error= table->file->index_read_idx_map(table->record[0], 0,
                                                user_key, (key_part_map)3,
                                                HA_READ_KEY_EXACT)))
5195
    {
5196
      if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
5197 5198 5199 5200
      {
        table->file->print_error(error, MYF(0));
        result= -1;
      }
5201
    }
5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218
    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)))
5219
    {
5220
      table->file->print_error(error, MYF(0));
5221
      result= -1;
5222 5223 5224 5225 5226
    }
    else
    {
#ifdef EXTRA_DEBUG
      DBUG_PRINT("info",("scan table: '%s'  search: '%s'@'%s'",
unknown's avatar
unknown committed
5227
                         table->s->table_name.str, user_str, host_str));
5228 5229 5230 5231 5232 5233 5234 5235 5236 5237
#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;
        }
5238
        if (! (host= get_field(thd->mem_root, host_field)))
5239
          host= "";
5240
        if (! (user= get_field(thd->mem_root, user_field)))
5241 5242 5243 5244 5245
          user= "";

#ifdef EXTRA_DEBUG
        DBUG_PRINT("loop",("scan fields: '%s'@'%s' '%s' '%s' '%s'",
                           user, host,
5246 5247 5248 5249
                           get_field(thd->mem_root, table->field[1]) /*db*/,
                           get_field(thd->mem_root, table->field[3]) /*table*/,
                           get_field(thd->mem_root,
                                     table->field[4]) /*column*/));
5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276
#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()
5277
    struct_no                   The number of the structure to handle (0..3).
5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292
    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
5293
    3 procs_priv_hash
5294 5295 5296 5297

  RETURN
    > 0         At least one element matched.
    0           OK, but no element matched.
5298
    -1		Wrong arguments to function
5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310
*/

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;
5311
  GRANT_NAME *grant_name;
5312
  DBUG_ENTER("handle_grant_struct");
unknown's avatar
unknown committed
5313 5314 5315
  DBUG_PRINT("info",("scan struct: %u  search: '%s'@'%s'",
                     struct_no, user_from->user.str, user_from->host.str));

5316 5317
  LINT_INIT(acl_user);
  LINT_INIT(acl_db);
5318
  LINT_INIT(grant_name);
5319 5320
  LINT_INIT(user);
  LINT_INIT(host);
5321

5322 5323
  safe_mutex_assert_owner(&acl_cache->lock);

5324
  /* Get the number of elements in the in-memory structure. */
5325
  switch (struct_no) {
5326 5327 5328 5329 5330 5331
  case 0:
    elements= acl_users.elements;
    break;
  case 1:
    elements= acl_dbs.elements;
    break;
5332
  case 2:
5333
    elements= column_priv_hash.records;
5334 5335 5336 5337 5338 5339
    break;
  case 3:
    elements= proc_priv_hash.records;
    break;
  default:
    return -1;
5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351
  }

#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.
    */
5352
    switch (struct_no) {
5353 5354 5355
    case 0:
      acl_user= dynamic_element(&acl_users, idx, ACL_USER*);
      user= acl_user->user;
5356 5357
      host= acl_user->host.hostname;
    break;
5358 5359 5360 5361

    case 1:
      acl_db= dynamic_element(&acl_dbs, idx, ACL_DB*);
      user= acl_db->user;
5362
      host= acl_db->host.hostname;
5363 5364
      break;

5365 5366 5367
    case 2:
      grant_name= (GRANT_NAME*) hash_element(&column_priv_hash, idx);
      user= grant_name->user;
5368
      host= grant_name->host.hostname;
5369 5370 5371 5372 5373
      break;

    case 3:
      grant_name= (GRANT_NAME*) hash_element(&proc_priv_hash, idx);
      user= grant_name->user;
5374
      host= grant_name->host.hostname;
5375
      break;
unknown's avatar
unknown committed
5376 5377
    default:
      assert(0);
5378 5379
    }
    if (! user)
5380
      user= "";
5381 5382 5383
    if (! host)
      host= "";

5384 5385 5386 5387 5388 5389
#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))
5390
      continue;
5391 5392 5393 5394

    result= 1; /* At least one element found. */
    if ( drop )
    {
5395
      switch ( struct_no ) {
5396 5397 5398 5399 5400 5401 5402 5403
      case 0:
        delete_dynamic_element(&acl_users, idx);
        break;

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

5404
      case 2:
5405
        hash_delete(&column_priv_hash, (uchar*) grant_name);
5406 5407 5408
	break;

      case 3:
5409
        hash_delete(&proc_priv_hash, (uchar*) grant_name);
5410
	break;
5411 5412 5413
      }
      elements--;
      idx--;
5414
    }
5415 5416
    else if ( user_to )
    {
5417
      switch ( struct_no ) {
5418 5419 5420 5421
      case 0:
        acl_user->user= strdup_root(&mem, user_to->user.str);
        acl_user->host.hostname= strdup_root(&mem, user_to->host.str);
        break;
5422

5423 5424 5425 5426 5427
      case 1:
        acl_db->user= strdup_root(&mem, user_to->user.str);
        acl_db->host.hostname= strdup_root(&mem, user_to->host.str);
        break;

5428 5429 5430
      case 2:
      case 3:
        grant_name->user= strdup_root(&mem, user_to->user.str);
5431 5432
        update_hostname(&grant_name->host,
                        strdup_root(&mem, user_to->host.str));
5433
	break;
5434 5435 5436
      }
    }
    else
5437
    {
5438 5439 5440 5441 5442 5443 5444
      /* 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
5445

5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489
  DBUG_RETURN(result);
}


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

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

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

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

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

  /* Handle user table. */
  if ((found= handle_grant_table(tables, 0, drop, user_from, user_to)) < 0)
  {
    /* Handle of table failed, don't touch the in-memory array. */
    result= -1;
  }
  else
  {
    /* Handle user array. */
unknown's avatar
unknown committed
5490 5491
    if ((handle_grant_struct(0, drop, user_from, user_to) && ! result) ||
        found)
5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518
    {
      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;
    }
  }

5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537
  /* 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;
    }
  }

5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551
  /* 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;
5552
    }
5553 5554 5555

    /* Handle columns table. */
    if ((found= handle_grant_table(tables, 3, drop, user_from, user_to)) < 0)
5556
    {
5557
      /* Handle of table failed, don't touch the in-memory array. */
5558 5559
      result= -1;
    }
5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571
    else
    {
      /* Handle columns hash. */
      if (((handle_grant_struct(2, drop, user_from, user_to) && ! result) ||
           found) && ! result)
        result= 1; /* At least one record/element found. */
    }
  }
 end:
  DBUG_RETURN(result);
}

unknown's avatar
unknown committed
5572

unknown's avatar
unknown committed
5573 5574 5575 5576 5577 5578
static void append_user(String *str, LEX_USER *user)
{
  if (str->length())
    str->append(',');
  str->append('\'');
  str->append(user->user.str);
5579
  str->append(STRING_WITH_LEN("'@'"));
unknown's avatar
unknown committed
5580 5581 5582
  str->append(user->host.str);
  str->append('\'');
}
5583

unknown's avatar
unknown committed
5584

5585 5586 5587 5588 5589 5590 5591
/*
  Create a list of users.

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

5593 5594 5595 5596 5597 5598 5599 5600
  RETURN
    FALSE       OK.
    TRUE        Error.
*/

bool mysql_create_user(THD *thd, List <LEX_USER> &list)
{
  int result;
unknown's avatar
unknown committed
5601
  String wrong_users;
5602
  ulong sql_mode;
5603
  LEX_USER *user_name, *tmp_user_name;
5604
  List_iterator <LEX_USER> user_list(list);
5605
  TABLE_LIST tables[GRANT_TABLES];
5606
  bool some_users_created= FALSE;
5607 5608
  DBUG_ENTER("mysql_create_user");

5609 5610 5611 5612 5613 5614 5615
  /*
    This statement will be replicated as a statement, even when using
    row-based replication.  The flag will be reset at the end of the
    statement.
  */
  thd->clear_current_stmt_binlog_row_based();

5616 5617 5618 5619 5620 5621 5622
  /* 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));

5623
  while ((tmp_user_name= user_list++))
5624
  {
5625 5626 5627 5628
    if (!(user_name= get_current_user(thd, tmp_user_name)))
    {
      result= TRUE;
      continue;
5629 5630
    }

5631 5632 5633 5634
    /*
      Search all in-memory structures and grant tables
      for a mention of the new user name.
    */
5635
    if (handle_grant_data(tables, 0, user_name, NULL))
5636
    {
unknown's avatar
unknown committed
5637
      append_user(&wrong_users, user_name);
5638
      result= TRUE;
unknown's avatar
unknown committed
5639
      continue;
5640
    }
5641

5642
    some_users_created= TRUE;
5643
    sql_mode= thd->variables.sql_mode;
unknown's avatar
unknown committed
5644
    if (replace_user_table(thd, tables[0].table, *user_name, 0, 0, 1, 0))
5645
    {
unknown's avatar
unknown committed
5646
      append_user(&wrong_users, user_name);
5647 5648 5649 5650 5651
      result= TRUE;
    }
  }

  VOID(pthread_mutex_unlock(&acl_cache->lock));
5652

5653 5654 5655
  if (result)
    my_error(ER_CANNOT_USER, MYF(0), "CREATE USER", wrong_users.c_ptr_safe());

5656 5657
  if (some_users_created)
    write_bin_log(thd, FALSE, thd->query, thd->query_length);
5658

5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
  DBUG_RETURN(result);
}


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

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

  RETURN
    FALSE       OK.
    TRUE        Error.
*/

bool mysql_drop_user(THD *thd, List <LEX_USER> &list)
{
  int result;
unknown's avatar
unknown committed
5681
  String wrong_users;
5682
  LEX_USER *user_name, *tmp_user_name;
5683
  List_iterator <LEX_USER> user_list(list);
5684
  TABLE_LIST tables[GRANT_TABLES];
5685
  bool some_users_deleted= FALSE;
5686 5687
  DBUG_ENTER("mysql_drop_user");

5688 5689 5690 5691 5692 5693 5694
  /*
    This statement will be replicated as a statement, even when using
    row-based replication.  The flag will be reset at the end of the
    statement.
  */
  thd->clear_current_stmt_binlog_row_based();

unknown's avatar
unknown committed
5695
  /* DROP USER may be skipped on replication client. */
5696 5697 5698 5699 5700 5701
  if ((result= open_grant_tables(thd, tables)))
    DBUG_RETURN(result != 1);

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

5702
  while ((tmp_user_name= user_list++))
5703
  {
5704 5705 5706 5707 5708
    if (!(user_name= get_current_user(thd, tmp_user_name)))
    {
      result= TRUE;
      continue;
    }  
5709
    if (handle_grant_data(tables, 1, user_name, NULL) <= 0)
5710
    {
unknown's avatar
unknown committed
5711
      append_user(&wrong_users, user_name);
5712
      result= TRUE;
5713
      continue;
5714
    }
5715
    some_users_deleted= TRUE;
5716
  }
5717

5718 5719 5720
  /* Rebuild 'acl_check_hosts' since 'acl_users' has been modified */
  rebuild_check_host();

5721
  VOID(pthread_mutex_unlock(&acl_cache->lock));
5722

5723 5724 5725
  if (result)
    my_error(ER_CANNOT_USER, MYF(0), "DROP USER", wrong_users.c_ptr_safe());

5726 5727
  if (some_users_deleted)
    write_bin_log(thd, FALSE, thd->query, thd->query_length);
5728

5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
  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)
{
5750
  int result;
unknown's avatar
unknown committed
5751
  String wrong_users;
5752 5753
  LEX_USER *user_from, *tmp_user_from;
  LEX_USER *user_to, *tmp_user_to;
5754
  List_iterator <LEX_USER> user_list(list);
5755
  TABLE_LIST tables[GRANT_TABLES];
5756
  bool some_users_renamed= FALSE;
5757 5758
  DBUG_ENTER("mysql_rename_user");

5759 5760 5761 5762 5763 5764 5765
  /*
    This statement will be replicated as a statement, even when using
    row-based replication.  The flag will be reset at the end of the
    statement.
  */
  thd->clear_current_stmt_binlog_row_based();

unknown's avatar
unknown committed
5766
  /* RENAME USER may be skipped on replication client. */
5767 5768 5769 5770 5771 5772
  if ((result= open_grant_tables(thd, tables)))
    DBUG_RETURN(result != 1);

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

5773
  while ((tmp_user_from= user_list++))
5774
  {
5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785
    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;
    }  
5786
    DBUG_ASSERT(user_to != 0); /* Syntax enforces pairs of users. */
5787 5788 5789 5790 5791

    /*
      Search all in-memory structures and grant tables
      for a mention of the new user name.
    */
unknown's avatar
unknown committed
5792 5793
    if (handle_grant_data(tables, 0, user_to, NULL) ||
        handle_grant_data(tables, 0, user_from, user_to) <= 0)
5794
    {
unknown's avatar
unknown committed
5795
      append_user(&wrong_users, user_from);
5796
      result= TRUE;
5797
      continue;
5798
    }
5799
    some_users_renamed= TRUE;
5800
  }
unknown's avatar
unknown committed
5801
  
5802 5803 5804
  /* Rebuild 'acl_check_hosts' since 'acl_users' has been modified */
  rebuild_check_host();

5805
  VOID(pthread_mutex_unlock(&acl_cache->lock));
5806

5807 5808 5809 5810
  if (result)
    my_error(ER_CANNOT_USER, MYF(0), "RENAME USER", wrong_users.c_ptr_safe());
  
  if (some_users_renamed && mysql_bin_log.is_open())
5811
    write_bin_log(thd, FALSE, thd->query, thd->query_length);
5812

5813 5814 5815 5816 5817
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
  DBUG_RETURN(result);
}

5818

5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832
/*
  Revoke all privileges from a list of users.

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

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

unknown's avatar
unknown committed
5833
bool mysql_revoke_all(THD *thd,  List <LEX_USER> &list)
5834
{
5835
  uint counter, revoked, is_proc;
5836
  int result;
unknown's avatar
unknown committed
5837
  ACL_DB *acl_db;
5838
  TABLE_LIST tables[GRANT_TABLES];
5839 5840
  DBUG_ENTER("mysql_revoke_all");

5841 5842 5843 5844 5845 5846 5847
  /*
    This statement will be replicated as a statement, even when using
    row-based replication.  The flag will be reset at the end of the
    statement.
  */
  thd->clear_current_stmt_binlog_row_based();

5848
  if ((result= open_grant_tables(thd, tables)))
unknown's avatar
unknown committed
5849
    DBUG_RETURN(result != 1);
5850 5851 5852 5853

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

5854
  LEX_USER *lex_user, *tmp_lex_user;
5855
  List_iterator <LEX_USER> user_list(list);
5856
  while ((tmp_lex_user= user_list++))
5857
  {
5858 5859 5860 5861 5862
    if (!(lex_user= get_current_user(thd, tmp_lex_user)))
    {
      result= -1;
      continue;
    }  
5863
    if (!find_acl_user(lex_user->host.str, lex_user->user.str, TRUE))
5864 5865 5866 5867
    {
      result= -1;
      continue;
    }
unknown's avatar
unknown committed
5868

5869
    if (replace_user_table(thd, tables[0].table,
5870
			   *lex_user, ~(ulong)0, 1, 0, 0))
5871 5872 5873 5874 5875 5876
    {
      result= -1;
      continue;
    }

    /* Remove db access privileges */
unknown's avatar
unknown committed
5877 5878 5879 5880 5881
    /*
      Because acl_dbs and column_priv_hash shrink and may re-order
      as privileges are removed, removal occurs in a repeated loop
      until no more privileges are revoked.
     */
unknown's avatar
unknown committed
5882
    do
5883
    {
unknown's avatar
unknown committed
5884
      for (counter= 0, revoked= 0 ; counter < acl_dbs.elements ; )
5885
      {
unknown's avatar
unknown committed
5886
	const char *user,*host;
unknown's avatar
unknown committed
5887

unknown's avatar
unknown committed
5888 5889 5890 5891 5892
	acl_db=dynamic_element(&acl_dbs,counter,ACL_DB*);
	if (!(user=acl_db->user))
	  user= "";
	if (!(host=acl_db->host.hostname))
	  host= "";
unknown's avatar
unknown committed
5893

unknown's avatar
unknown committed
5894
	if (!strcmp(lex_user->user.str,user) &&
5895
            !strcmp(lex_user->host.str, host))
unknown's avatar
unknown committed
5896
	{
5897 5898
	  if (!replace_db_table(tables[1].table, acl_db->db, *lex_user,
                                ~(ulong)0, 1))
unknown's avatar
unknown committed
5899
	  {
unknown's avatar
unknown committed
5900 5901 5902 5903 5904
	    /*
	      Don't increment counter as replace_db_table deleted the
	      current element in acl_dbs.
	     */
	    revoked= 1;
unknown's avatar
unknown committed
5905 5906
	    continue;
	  }
unknown's avatar
unknown committed
5907
	  result= -1; // Something went wrong
unknown's avatar
unknown committed
5908
	}
unknown's avatar
unknown committed
5909
	counter++;
5910
      }
unknown's avatar
unknown committed
5911
    } while (revoked);
5912 5913

    /* Remove column access */
unknown's avatar
unknown committed
5914
    do
5915
    {
unknown's avatar
unknown committed
5916
      for (counter= 0, revoked= 0 ; counter < column_priv_hash.records ; )
5917
      {
unknown's avatar
unknown committed
5918 5919 5920 5921 5922
	const char *user,*host;
	GRANT_TABLE *grant_table= (GRANT_TABLE*)hash_element(&column_priv_hash,
							     counter);
	if (!(user=grant_table->user))
	  user= "";
5923
	if (!(host=grant_table->host.hostname))
unknown's avatar
unknown committed
5924
	  host= "";
unknown's avatar
unknown committed
5925

unknown's avatar
unknown committed
5926
	if (!strcmp(lex_user->user.str,user) &&
5927
            !strcmp(lex_user->host.str, host))
5928
	{
unknown's avatar
unknown committed
5929 5930 5931
	  if (replace_table_table(thd,grant_table,tables[2].table,*lex_user,
				  grant_table->db,
				  grant_table->tname,
5932
				  ~(ulong)0, 0, 1))
unknown's avatar
unknown committed
5933
	  {
unknown's avatar
unknown committed
5934
	    result= -1;
unknown's avatar
unknown committed
5935
	  }
unknown's avatar
unknown committed
5936
	  else
unknown's avatar
unknown committed
5937
	  {
unknown's avatar
unknown committed
5938
	    if (!grant_table->cols)
unknown's avatar
unknown committed
5939
	    {
unknown's avatar
unknown committed
5940 5941
	      revoked= 1;
	      continue;
unknown's avatar
unknown committed
5942
	    }
unknown's avatar
unknown committed
5943 5944
	    List<LEX_COLUMN> columns;
	    if (!replace_column_table(grant_table,tables[3].table, *lex_user,
unknown's avatar
unknown committed
5945 5946 5947
				      columns,
				      grant_table->db,
				      grant_table->tname,
5948
				      ~(ulong)0, 1))
unknown's avatar
unknown committed
5949
	    {
unknown's avatar
unknown committed
5950
	      revoked= 1;
5951
	      continue;
unknown's avatar
unknown committed
5952
	    }
5953
	    result= -1;
unknown's avatar
unknown committed
5954
	  }
5955
	}
unknown's avatar
unknown committed
5956
	counter++;
5957
      }
unknown's avatar
unknown committed
5958
    } while (revoked);
5959 5960

    /* Remove procedure access */
5961 5962 5963
    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 ; )
5964 5965
      {
	const char *user,*host;
5966
	GRANT_NAME *grant_proc= (GRANT_NAME*) hash_element(hash, counter);
5967 5968
	if (!(user=grant_proc->user))
	  user= "";
5969
	if (!(host=grant_proc->host.hostname))
5970 5971 5972
	  host= "";

	if (!strcmp(lex_user->user.str,user) &&
5973
            !strcmp(lex_user->host.str, host))
5974
	{
5975
	  if (replace_routine_table(thd,grant_proc,tables[4].table,*lex_user,
5976 5977
				  grant_proc->db,
				  grant_proc->tname,
5978
                                  is_proc,
5979
				  ~(ulong)0, 1) == 0)
5980 5981 5982 5983 5984 5985 5986 5987 5988
	  {
	    revoked= 1;
	    continue;
	  }
	  result= -1;	// Something went wrong
	}
	counter++;
      }
    } while (revoked);
5989
  }
unknown's avatar
unknown committed
5990

5991
  VOID(pthread_mutex_unlock(&acl_cache->lock));
5992

5993
  write_bin_log(thd, FALSE, thd->query, thd->query_length);
5994

5995 5996
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
unknown's avatar
unknown committed
5997

5998
  if (result)
unknown's avatar
unknown committed
5999
    my_message(ER_REVOKE_GRANTS, ER(ER_REVOKE_GRANTS), MYF(0));
unknown's avatar
unknown committed
6000

6001 6002
  DBUG_RETURN(result);
}
unknown's avatar
unknown committed
6003

6004

6005

6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062

/**
  If the defining user for a routine does not exist, then the ACL lookup
  code should raise two errors which we should intercept.  We convert the more
  descriptive error into a warning, and consume the other.

  If any other errors are raised, then we set a flag that should indicate
  that there was some failure we should complain at a higher level.
*/
class Silence_routine_definer_errors : public Internal_error_handler
{
public:
  Silence_routine_definer_errors()
    : is_grave(FALSE)
  {}

  virtual ~Silence_routine_definer_errors()
  {}

  virtual bool handle_error(uint sql_errno, const char *message,
                            MYSQL_ERROR::enum_warning_level level,
                            THD *thd);

  bool has_errors() { return is_grave; }

private:
  bool is_grave;
};

bool
Silence_routine_definer_errors::handle_error(uint sql_errno,
                                       const char *message,
                                       MYSQL_ERROR::enum_warning_level level,
                                       THD *thd)
{
  if (level == MYSQL_ERROR::WARN_LEVEL_ERROR)
  {
    switch (sql_errno)
    {
      case ER_NONEXISTING_PROC_GRANT:
        /* Convert the error into a warning. */
        push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, sql_errno, message);
        return TRUE;
      default:
        is_grave= TRUE;
    }
  }

  return FALSE;
}


/**
  Revoke privileges for all users on a stored procedure.  Use an error handler
  that converts errors about missing grants into warnings.

  @param
6063
    thd                         The current thread.
6064
  @param
6065
    db				DB of the stored procedure
6066
  @param
6067 6068
    name			Name of the stored procedure

6069
  @retval
6070
    0           OK.
6071
  @retval
6072 6073 6074
    < 0         Error. Error message not yet sent.
*/

6075 6076
bool sp_revoke_privileges(THD *thd, const char *sp_db, const char *sp_name,
                          bool is_proc)
6077 6078 6079 6080
{
  uint counter, revoked;
  int result;
  TABLE_LIST tables[GRANT_TABLES];
6081
  HASH *hash= is_proc ? &proc_priv_hash : &func_priv_hash;
6082
  Silence_routine_definer_errors error_handler;
6083 6084 6085 6086 6087
  DBUG_ENTER("sp_revoke_privileges");

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

6088 6089 6090
  /* Be sure to pop this before exiting this scope! */
  thd->push_internal_handler(&error_handler);

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

6094 6095 6096 6097 6098 6099 6100
  /*
    This statement will be replicated as a statement, even when using
    row-based replication.  The flag will be reset at the end of the
    statement.
  */
  thd->clear_current_stmt_binlog_row_based();

6101
  /* Remove procedure access */
6102 6103
  do
  {
6104
    for (counter= 0, revoked= 0 ; counter < hash->records ; )
6105
    {
6106
      GRANT_NAME *grant_proc= (GRANT_NAME*) hash_element(hash, counter);
6107 6108 6109 6110 6111 6112
      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);
6113 6114 6115 6116
	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;
6117 6118 6119 6120

	if (replace_routine_table(thd,grant_proc,tables[4].table,lex_user,
				  grant_proc->db, grant_proc->tname,
                                  is_proc, ~(ulong)0, 1) == 0)
6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133
	{
	  revoked= 1;
	  continue;
	}
      }
      counter++;
    }
  } while (revoked);

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

6134
  thd->pop_internal_handler();
6135

6136
  DBUG_RETURN(error_handler.has_errors());
6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153
}


/*
  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.
*/

6154
int sp_grant_privileges(THD *thd, const char *sp_db, const char *sp_name,
6155
                         bool is_proc)
6156
{
6157
  Security_context *sctx= thd->security_ctx;
6158 6159 6160 6161
  LEX_USER *combo;
  TABLE_LIST tables[1];
  List<LEX_USER> user_list;
  bool result;
6162 6163
  ACL_USER *au;
  char passwd_buff[SCRAMBLED_PASSWORD_CHAR_LENGTH+1];
6164
  DBUG_ENTER("sp_grant_privileges");
6165 6166 6167 6168

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

6169
  combo->user.str= sctx->user;
6170

6171
  VOID(pthread_mutex_lock(&acl_cache->lock));
6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185

  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:
6186
  VOID(pthread_mutex_unlock(&acl_cache->lock));
6187 6188 6189 6190 6191

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

  tables->db= (char*)sp_db;
6192
  tables->table_name= tables->alias= (char*)sp_name;
6193

6194 6195 6196 6197
  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);
6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223


  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;
  }
6224 6225 6226 6227 6228

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

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

6231
  result= mysql_routine_grant(thd, tables, is_proc, user_list,
6232 6233 6234 6235 6236
  				DEFAULT_CREATE_PROC_ACLS, 0, 1);
  DBUG_RETURN(result);
}


unknown's avatar
unknown committed
6237
/*****************************************************************************
unknown's avatar
unknown committed
6238
  Instantiate used templates
unknown's avatar
unknown committed
6239 6240
*****************************************************************************/

6241
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
unknown's avatar
unknown committed
6242 6243 6244 6245 6246
template class List_iterator<LEX_COLUMN>;
template class List_iterator<LEX_USER>;
template class List<LEX_COLUMN>;
template class List<LEX_USER>;
#endif
unknown's avatar
unknown committed
6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293

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

6294 6295 6296 6297 6298 6299 6300 6301

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;
6302
  restore_record(table, s->default_values);
6303
  table->field[0]->store(buff, (uint) strlen(buff), cs);
6304
  if (db)
6305
    table->field[i++]->store(db, (uint) strlen(db), cs);
6306
  if (t_name)
6307
    table->field[i++]->store(t_name, (uint) strlen(t_name), cs);
6308 6309 6310
  if (column)
    table->field[i++]->store(column, col_length, cs);
  table->field[i++]->store(priv, priv_length, cs);
6311
  table->field[i]->store(is_grantable, (uint) strlen(is_grantable), cs);
6312
  table->file->ha_write_row(table->record[0]);
6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323
}


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;
6324
  bool no_global_access= check_access(thd, SELECT_ACL, "mysql",0,1,1,0);
6325
  char *curr_host= thd->security_ctx->priv_host_name();
6326
  DBUG_ENTER("fill_schema_user_privileges");
6327

6328 6329
  if (!initialized)
    DBUG_RETURN(0);
6330 6331
  pthread_mutex_lock(&acl_cache->lock);

6332 6333 6334 6335 6336 6337 6338 6339
  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= "";
6340 6341

    if (no_global_access &&
6342
        (strcmp(thd->security_ctx->priv_user, user) ||
6343 6344 6345
         my_strcasecmp(system_charset_info, curr_host, host)))
      continue;
      
6346 6347 6348 6349 6350 6351
    want_access= acl_user->access;
    if (!(want_access & GRANT_ACL))
      is_grantable= "NO";

    strxmov(buff,"'",user,"'@'",host,"'",NullS);
    if (!(want_access & ~GRANT_ACL))
6352 6353
      update_schema_privilege(table, buff, 0, 0, 0, 0,
                              STRING_WITH_LEN("USAGE"), is_grantable);
6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366
    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);
      }
    }
  }
6367 6368 6369

  pthread_mutex_unlock(&acl_cache->lock);

6370
  DBUG_RETURN(0);
6371 6372 6373
#else
  return(0);
#endif
6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384
}


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;
6385
  bool no_global_access= check_access(thd, SELECT_ACL, "mysql",0,1,1,0);
6386
  char *curr_host= thd->security_ctx->priv_host_name();
6387 6388
  DBUG_ENTER("fill_schema_schema_privileges");

6389 6390
  if (!initialized)
    DBUG_RETURN(0);
6391 6392
  pthread_mutex_lock(&acl_cache->lock);

6393 6394 6395 6396 6397 6398 6399 6400 6401 6402
  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= "";

6403
    if (no_global_access &&
6404
        (strcmp(thd->security_ctx->priv_user, user) ||
6405 6406 6407
         my_strcasecmp(system_charset_info, curr_host, host)))
      continue;

6408 6409 6410 6411 6412 6413 6414 6415 6416 6417
    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,
6418
                                0, STRING_WITH_LEN("USAGE"), is_grantable);
6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430
      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);
      }
    }
  }
6431 6432 6433

  pthread_mutex_unlock(&acl_cache->lock);

6434
  DBUG_RETURN(0);
6435 6436 6437
#else
  return (0);
#endif
6438 6439 6440 6441 6442 6443 6444 6445 6446
}


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;
6447
  bool no_global_access= check_access(thd, SELECT_ACL, "mysql",0,1,1,0);
6448
  char *curr_host= thd->security_ctx->priv_host_name();
6449 6450
  DBUG_ENTER("fill_schema_table_privileges");

6451 6452
  rw_rdlock(&LOCK_grant);

6453 6454
  for (index=0 ; index < column_priv_hash.records ; index++)
  {
6455
    const char *user, *host, *is_grantable= "YES";
6456 6457 6458 6459
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  index);
    if (!(user=grant_table->user))
      user= "";
6460 6461
    if (!(host= grant_table->host.hostname))
      host= "";
6462 6463

    if (no_global_access &&
6464
        (strcmp(thd->security_ctx->priv_user, user) ||
6465
         my_strcasecmp(system_charset_info, curr_host, host)))
6466 6467
      continue;

6468
    ulong table_access= grant_table->privs;
6469
    if (table_access)
6470 6471
    {
      ulong test_access= table_access & ~GRANT_ACL;
unknown's avatar
unknown committed
6472 6473 6474 6475
      /*
        We should skip 'usage' privilege on table if
        we have any privileges on column(s) of this table
      */
6476 6477
      if (!test_access && grant_table->cols)
        continue;
6478 6479 6480
      if (!(table_access & GRANT_ACL))
        is_grantable= "NO";

6481
      strxmov(buff, "'", user, "'@'", host, "'", NullS);
6482 6483
      if (!test_access)
        update_schema_privilege(table, buff, grant_table->db, grant_table->tname,
6484
                                0, 0, STRING_WITH_LEN("USAGE"), is_grantable);
6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498
      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);
        }
      }
    }
  }
6499 6500 6501

  rw_unlock(&LOCK_grant);

6502
  DBUG_RETURN(0);
6503 6504 6505
#else
  return (0);
#endif
6506 6507 6508 6509 6510 6511 6512 6513 6514
}


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;
6515
  bool no_global_access= check_access(thd, SELECT_ACL, "mysql",0,1,1,0);
6516
  char *curr_host= thd->security_ctx->priv_host_name();
6517 6518
  DBUG_ENTER("fill_schema_table_privileges");

6519 6520
  rw_rdlock(&LOCK_grant);

6521 6522
  for (index=0 ; index < column_priv_hash.records ; index++)
  {
6523
    const char *user, *host, *is_grantable= "YES";
6524 6525 6526 6527
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  index);
    if (!(user=grant_table->user))
      user= "";
6528 6529
    if (!(host= grant_table->host.hostname))
      host= "";
6530 6531

    if (no_global_access &&
6532
        (strcmp(thd->security_ctx->priv_user, user) ||
6533
         my_strcasecmp(system_charset_info, curr_host, host)))
6534 6535
      continue;

6536 6537 6538
    ulong table_access= grant_table->cols;
    if (table_access != 0)
    {
unknown's avatar
unknown committed
6539
      if (!(grant_table->privs & GRANT_ACL))
6540 6541
        is_grantable= "NO";

unknown's avatar
unknown committed
6542
      ulong test_access= table_access & ~GRANT_ACL;
6543
      strxmov(buff, "'", user, "'@'", host, "'", NullS);
6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572
      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);
            }
          }
        }
      }
    }
  }
6573 6574 6575

  rw_unlock(&LOCK_grant);

6576
  DBUG_RETURN(0);
6577 6578 6579
#else
  return (0);
#endif
6580 6581 6582
}


unknown's avatar
VIEW  
unknown committed
6583 6584 6585 6586 6587
#ifndef NO_EMBEDDED_ACCESS_CHECKS
/*
  fill effective privileges for table

  SYNOPSIS
6588 6589
    fill_effective_table_privileges()
    thd     thread handler
unknown's avatar
VIEW  
unknown committed
6590 6591 6592 6593 6594 6595 6596 6597
    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)
{
6598
  Security_context *sctx= thd->security_ctx;
6599 6600 6601 6602 6603
  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));
6604 6605 6606
  /* --skip-grants */
  if (!initialized)
  {
6607
    DBUG_PRINT("info", ("skip grants"));
6608
    grant->privilege= ~NO_ACCESS;             // everything is allowed
6609 6610
    DBUG_PRINT("info", ("privilege 0x%lx", grant->privilege));
    DBUG_VOID_RETURN;
6611 6612
  }

unknown's avatar
VIEW  
unknown committed
6613
  /* global privileges */
6614
  grant->privilege= sctx->master_access;
6615

6616
  if (!sctx->priv_user)
6617 6618 6619 6620
  {
    DBUG_PRINT("info", ("privilege 0x%lx", grant->privilege));
    DBUG_VOID_RETURN;                         // it is slave
  }
6621

6622
  /* db privileges */
6623
  grant->privilege|= acl_get(sctx->host, sctx->ip, sctx->priv_user, db, 0);
6624

unknown's avatar
VIEW  
unknown committed
6625
  /* table privileges */
6626
  rw_rdlock(&LOCK_grant);
unknown's avatar
VIEW  
unknown committed
6627 6628 6629
  if (grant->version != grant_version)
  {
    grant->grant_table=
6630 6631
      table_hash_search(sctx->host, sctx->ip, db,
			sctx->priv_user,
unknown's avatar
VIEW  
unknown committed
6632 6633 6634 6635 6636 6637 6638
			table, 0);              /* purecov: inspected */
    grant->version= grant_version;              /* purecov: inspected */
  }
  if (grant->grant_table != 0)
  {
    grant->privilege|= grant->grant_table->privs;
  }
6639 6640
  rw_unlock(&LOCK_grant);

6641 6642
  DBUG_PRINT("info", ("privilege 0x%lx", grant->privilege));
  DBUG_VOID_RETURN;
unknown's avatar
VIEW  
unknown committed
6643
}
6644 6645 6646 6647 6648 6649 6650

#else /* NO_EMBEDDED_ACCESS_CHECKS */

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

unknown's avatar
unknown committed
6651 6652
bool check_routine_level_acl(THD *thd, const char *db, const char *name,
                             bool is_proc)
6653 6654 6655 6656
{
  return FALSE;
}

unknown's avatar
VIEW  
unknown committed
6657
#endif