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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3 4 5 6
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
7

bk@work.mysql.com's avatar
bk@work.mysql.com committed
8 9 10 11
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
12

bk@work.mysql.com's avatar
bk@work.mysql.com committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
   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:
  mysql/user	 ; super user who are allowed to do almoust anything
  mysql/host	 ; host priviliges. This is used if host is empty in mysql/db.
  mysql/db	 ; database privileges / user

  data in tables is sorted according to how many not-wild-cards there is
  in the relevant fields. Empty strings comes last.
*/

#include "mysql_priv.h"
#include "hash_filo.h"
30 31 32
#ifdef HAVE_REPLICATION
#include "sql_repl.h" //for tables_ok()
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
33 34 35
#include <m_ctype.h>
#include <stdarg.h>

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

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

46

bk@work.mysql.com's avatar
bk@work.mysql.com committed
47 48 49 50 51 52 53
static byte* acl_entry_get_key(acl_entry *entry,uint *length,
			       my_bool not_used __attribute__((unused)))
{
  *length=(uint) entry->length;
  return (byte*) entry->key;
}

serg@serg.mylan's avatar
serg@serg.mylan committed
54
#define IP_ADDR_STRLEN (3+1+3+1+3+1+3)
55
#define ACL_KEY_LENGTH (IP_ADDR_STRLEN+1+NAME_LEN+1+USERNAME_LENGTH+1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
56 57 58 59 60

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

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

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

118

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

  SYNOPSIS
    acl_init()
124
    thd				Thread handler
125 126 127 128 129 130 131 132
    dont_read_acl_tables	Set to 1 if run with --skip-grant

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


133
my_bool acl_init(THD *org_thd, bool dont_read_acl_tables)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
134
{
135
  THD  *thd;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
136 137 138
  TABLE_LIST tables[3];
  TABLE *table;
  READ_RECORD read_record_info;
139 140
  MYSQL_LOCK *lock;
  my_bool return_val=1;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
141
  bool check_no_resolve= specialflag & SPECIAL_NO_RESOLVE;
142
  char tmp_name[NAME_LEN+1];
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
143

bk@work.mysql.com's avatar
bk@work.mysql.com committed
144 145 146 147 148
  DBUG_ENTER("acl_init");

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

155
  priv_version++; /* Privileges updated */
peter@mysql.com's avatar
peter@mysql.com committed
156

157 158 159
  /*
    To be able to run this from boot, we allocate a temporary THD
  */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
160 161
  if (!(thd=new THD))
    DBUG_RETURN(1); /* purecov: inspected */
162 163
  thd->store_globals();

bk@work.mysql.com's avatar
bk@work.mysql.com committed
164
  acl_cache->clear(1);				// Clear locked hostname cache
165 166
  thd->db= my_strdup("mysql",MYF(0));
  thd->db_length=5;				// Safety
bk@work.mysql.com's avatar
bk@work.mysql.com committed
167
  bzero((char*) &tables,sizeof(tables));
168 169 170
  tables[0].alias=tables[0].real_name=(char*) "host";
  tables[1].alias=tables[1].real_name=(char*) "user";
  tables[2].alias=tables[2].real_name=(char*) "db";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
171 172 173 174 175
  tables[0].next=tables+1;
  tables[1].next=tables+2;
  tables[0].lock_type=tables[1].lock_type=tables[2].lock_type=TL_READ;
  tables[0].db=tables[1].db=tables[2].db=thd->db;

176 177
  uint counter;
  if (open_tables(thd, tables, &counter))
178 179 180
  {
    sql_print_error("Fatal error: Can't open privilege tables: %s",
		    thd->net.last_error);
181
    goto end;
182
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
183 184 185 186
  TABLE *ptr[3];				// Lock tables for quick update
  ptr[0]= tables[0].table;
  ptr[1]= tables[1].table;
  ptr[2]= tables[2].table;
187
  if (! (lock= mysql_lock_tables(thd, ptr, 3, 0)))
188 189 190
  {
    sql_print_error("Fatal error: Can't lock privilege tables: %s",
		    thd->net.last_error);
191
    goto end;
192
  }
193
  init_sql_alloc(&mem, ACL_ALLOC_BLOCK_SIZE, 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
194
  init_read_record(&read_record_info,thd,table= tables[0].table,NULL,1,0);
195
  VOID(my_init_dynamic_array(&acl_hosts,sizeof(ACL_HOST),20,50));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
196 197 198
  while (!(read_record_info.read_record(&read_record_info)))
  {
    ACL_HOST host;
199 200
    update_hostname(&host.host,get_field(&mem, table->field[0]));
    host.db=	 get_field(&mem, table->field[1]);
201 202 203 204
    if (lower_case_table_names)
    {
      /*
       We make a temporary copy of the database, force it to lower case,
205
       and then check it against the original name.
206
      */
207 208
      (void)strnmov(tmp_name, host.db, sizeof(tmp_name));
      my_casedn_str(files_charset_info, host.db);
209 210 211 212
      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 "
213 214
                          "lower_case_table_names is set. It will not be "
                          "possible to remove this privilege using REVOKE.",
215 216 217
                          host.host.hostname, host.db);
      }
    }
218 219
    host.access= get_access(table,2);
    host.access= fix_rights_for_db(host.access);
220
    host.sort=	 get_sort(2,host.host.hostname,host.db);
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
221 222
    if (check_no_resolve && hostname_requires_resolving(host.host.hostname))
    {
serg@serg.mylan's avatar
serg@serg.mylan committed
223
      sql_print_warning("'host' entry '%s|%s' "
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
224
		      "ignored in --skip-name-resolve mode.",
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
225 226 227
		      host.host.hostname, host.db, host.host.hostname);
      continue;
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
228 229 230 231
#ifndef TO_BE_REMOVED
    if (table->fields ==  8)
    {						// Without grant
      if (host.access & CREATE_ACL)
232
	host.access|=REFERENCES_ACL | INDEX_ACL | ALTER_ACL | CREATE_TMP_ACL;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
233 234 235 236 237 238 239 240 241 242
    }
#endif
    VOID(push_dynamic(&acl_hosts,(gptr) &host));
  }
  qsort((gptr) dynamic_element(&acl_hosts,0,ACL_HOST*),acl_hosts.elements,
	sizeof(ACL_HOST),(qsort_cmp) acl_compare);
  end_read_record(&read_record_info);
  freeze_size(&acl_hosts);

  init_read_record(&read_record_info,thd,table=tables[1].table,NULL,1,0);
243
  VOID(my_init_dynamic_array(&acl_users,sizeof(ACL_USER),50,100));
244
  if (table->field[2]->field_length < SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
245
  {
246 247 248
    sql_print_error("Fatal error: mysql.user table is damaged or in "
                    "unsupported 3.20 format.");
    goto end;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
249 250
  }

251 252
  DBUG_PRINT("info",("user table fields: %d, password length: %d",
		     table->fields, table->field[2]->field_length));
253 254 255
  
  pthread_mutex_lock(&LOCK_global_system_variables);
  if (table->field[2]->field_length < SCRAMBLED_PASSWORD_CHAR_LENGTH)
256
  {
257 258 259 260 261 262 263 264 265 266 267 268 269 270
    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);
271 272 273
      sql_print_warning("mysql.user table is not updated to new password format; "
                        "Disabling new password usage until "
                        "mysql_fix_privilege_tables is run");
274 275 276 277
    }
    thd->variables.old_passwords= 1;
  }
  else
278
  {
279 280
    sys_old_passwords.after_update= 0;
    pthread_mutex_unlock(&LOCK_global_system_variables);
281 282
  }

bk@work.mysql.com's avatar
bk@work.mysql.com committed
283 284 285 286
  allow_all_hosts=0;
  while (!(read_record_info.read_record(&read_record_info)))
  {
    ACL_USER user;
287 288
    update_hostname(&user.host, get_field(&mem, table->field[0]));
    user.user= get_field(&mem, table->field[1]);
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
289 290
    if (check_no_resolve && hostname_requires_resolving(user.host.hostname))
    {
serg@serg.mylan's avatar
serg@serg.mylan committed
291 292
      sql_print_warning("'user' entry '%s@%s' "
                        "ignored in --skip-name-resolve mode.",
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
293 294 295 296
		      user.user, user.host.hostname, user.host.hostname);
      continue;
    }

297 298 299 300
    const char *password= get_field(&mem, table->field[2]);
    uint password_len= password ? strlen(password) : 0;
    set_user_salt(&user, password, password_len);
    if (user.salt_len == 0 && password_len != 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
301
    {
302 303
      switch (password_len) {
      case 45: /* 4.1: to be removed */
serg@serg.mylan's avatar
serg@serg.mylan committed
304 305 306 307 308
        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 : "");
309 310
        break;
      default:
serg@serg.mylan's avatar
serg@serg.mylan committed
311 312 313
        sql_print_warning("Found invalid password for user: '%s@%s'; "
                          "Ignoring user", user.user ? user.user : "",
                           user.host.hostname ? user.host.hostname : "");
314 315
        break;
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
316
    }
317
    else                                        // password is correct
bk@work.mysql.com's avatar
bk@work.mysql.com committed
318
    {
319 320
      uint next_field;
      user.access= get_access(table,3,&next_field) & GLOBAL_ACLS;
321 322 323
      user.sort= get_sort(2,user.host.hostname,user.user);
      user.hostname_length= (user.host.hostname ?
                             (uint) strlen(user.host.hostname) : 0);
324
      if (table->fields >= 31)	 /* Starting from 4.0.2 we have more fields */
325
      {
326
        char *ssl_type=get_field(&mem, table->field[next_field++]);
327 328 329 330 331 332 333 334 335
        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;

336 337 338
        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++]);
339

340 341 342 343 344 345
        char *ptr = get_field(&mem, table->field[next_field++]);
        user.user_resource.questions=ptr ? atoi(ptr) : 0;
        ptr = get_field(&mem, table->field[next_field++]);
        user.user_resource.updates=ptr ? atoi(ptr) : 0;
        ptr = get_field(&mem, table->field[next_field++]);
        user.user_resource.connections=ptr ? atoi(ptr) : 0;
346 347 348
        if (user.user_resource.questions || user.user_resource.updates ||
            user.user_resource.connections)
          mqh_used=1;
349
      }
350 351 352
      else
      {
        user.ssl_type=SSL_TYPE_NONE;
353
        bzero((char *)&(user.user_resource),sizeof(user.user_resource));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
354
#ifndef TO_BE_REMOVED
355 356 357 358 359 360 361 362 363 364 365
        if (table->fields <= 13)
        {						// Without grant
          if (user.access & CREATE_ACL)
            user.access|=REFERENCES_ACL | INDEX_ACL | ALTER_ACL;
        }
        /* Convert old privileges */
        user.access|= LOCK_TABLES_ACL | CREATE_TMP_ACL | SHOW_DB_ACL;
        if (user.access & FILE_ACL)
          user.access|= REPL_CLIENT_ACL | REPL_SLAVE_ACL;
        if (user.access & PROCESS_ACL)
          user.access|= SUPER_ACL | EXECUTE_ACL;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
366
#endif
367 368 369 370 371
      }
      VOID(push_dynamic(&acl_users,(gptr) &user));
      if (!user.host.hostname || user.host.hostname[0] == wild_many &&
          !user.host.hostname[1])
        allow_all_hosts=1;			// Anyone can connect
372
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
373 374 375 376 377
  }
  qsort((gptr) dynamic_element(&acl_users,0,ACL_USER*),acl_users.elements,
	sizeof(ACL_USER),(qsort_cmp) acl_compare);
  end_read_record(&read_record_info);
  freeze_size(&acl_users);
peter@mysql.com's avatar
peter@mysql.com committed
378

bk@work.mysql.com's avatar
bk@work.mysql.com committed
379
  init_read_record(&read_record_info,thd,table=tables[2].table,NULL,1,0);
380
  VOID(my_init_dynamic_array(&acl_dbs,sizeof(ACL_DB),50,100));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
381 382 383
  while (!(read_record_info.read_record(&read_record_info)))
  {
    ACL_DB db;
384 385
    update_hostname(&db.host,get_field(&mem, table->field[0]));
    db.db=get_field(&mem, table->field[1]);
386 387
    if (!db.db)
    {
serg@serg.mylan's avatar
serg@serg.mylan committed
388
      sql_print_warning("Found an entry in the 'db' table with empty database name; Skipped");
389
      continue;
390
    }
391
    db.user=get_field(&mem, table->field[2]);
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
392 393
    if (check_no_resolve && hostname_requires_resolving(db.host.hostname))
    {
serg@serg.mylan's avatar
serg@serg.mylan committed
394 395 396
      sql_print_warning("'db' entry '%s %s@%s' "
		        "ignored in --skip-name-resolve mode.",
		        db.db, db.user, db.host.hostname, db.host.hostname);
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
397 398
      continue;
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
399 400
    db.access=get_access(table,3);
    db.access=fix_rights_for_db(db.access);
401 402 403 404
    if (lower_case_table_names)
    {
      /*
       We make a temporary copy of the database, force it to lower case,
405
       and then check it against the original name.
406
      */
407 408
      (void)strnmov(tmp_name, db.db, sizeof(tmp_name));
      my_casedn_str(files_charset_info, db.db);
409 410 411 412
      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 "
413 414
                          "lower_case_table_names is set. It will not be "
                          "possible to remove this privilege using REVOKE.",
415 416 417
		          db.db, db.user, db.host.hostname, db.host.hostname);
      }
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
    db.sort=get_sort(3,db.host.hostname,db.db,db.user);
#ifndef TO_BE_REMOVED
    if (table->fields <=  9)
    {						// Without grant
      if (db.access & CREATE_ACL)
	db.access|=REFERENCES_ACL | INDEX_ACL | ALTER_ACL;
    }
#endif
    VOID(push_dynamic(&acl_dbs,(gptr) &db));
  }
  qsort((gptr) dynamic_element(&acl_dbs,0,ACL_DB*),acl_dbs.elements,
	sizeof(ACL_DB),(qsort_cmp) acl_compare);
  end_read_record(&read_record_info);
  freeze_size(&acl_dbs);
  init_check_host();

  mysql_unlock_tables(thd, lock);
435
  initialized=1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
436
  thd->version--;				// Force close to free memory
437 438 439
  return_val=0;

end:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
440 441
  close_thread_tables(thd);
  delete thd;
442 443
  if (org_thd)
    org_thd->store_globals();			/* purecov: inspected */
444 445 446 447 448
  else
  {
    /* Remember that we don't have a THD */
    my_pthread_setspecific_ptr(THR_THD,  0);
  }
449
  DBUG_RETURN(return_val);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
450 451 452 453 454
}


void acl_free(bool end)
{
455
  free_root(&mem,MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
456 457 458 459 460 461 462 463 464 465 466 467 468 469
  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;
  }
}

470 471 472 473 474 475

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

  SYNOPSIS
    acl_reload()
476
    thd			Thread handle (can be NULL)
477
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
478

479
void acl_reload(THD *thd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
480 481 482 483 484 485
{
  DYNAMIC_ARRAY old_acl_hosts,old_acl_users,old_acl_dbs;
  MEM_ROOT old_mem;
  bool old_initialized;
  DBUG_ENTER("acl_reload");

486
  if (thd && thd->locked_tables)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
487
  {					// Can't have locked tables here
488 489 490
    thd->lock=thd->locked_tables;
    thd->locked_tables=0;
    close_thread_tables(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
491 492 493 494 495 496 497 498 499 500 501
  }
  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);

502
  if (acl_init(thd, 0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
503
  {					// Error. Revert to old list
504
    DBUG_PRINT("error",("Reverting to old privileges"));
505
    acl_free();				/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
506 507 508 509 510 511 512 513
    acl_hosts=old_acl_hosts;
    acl_users=old_acl_users;
    acl_dbs=old_acl_dbs;
    mem=old_mem;
    init_check_host();
  }
  else
  {
514
    free_root(&old_mem,MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
515 516 517 518 519 520 521 522 523 524
    delete_dynamic(&old_acl_hosts);
    delete_dynamic(&old_acl_users);
    delete_dynamic(&old_acl_dbs);
  }
  if (old_initialized)
    VOID(pthread_mutex_unlock(&acl_cache->lock));
  DBUG_VOID_RETURN;
}


525 526
/*
  Get all access bits from table after fieldnr
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541

  IMPLEMENTATION
    We know that the access privileges ends when there is no more fields
    or the field is not an enum with two elements.

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

544
static ulong get_access(TABLE *form, uint fieldnr, uint *next_field)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
545
{
546
  ulong access_bits=0,bit;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
547
  char buff[2];
548
  String res(buff,sizeof(buff),&my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
549 550
  Field **pos;

551 552 553
  for (pos=form->field+fieldnr, bit=1;
       *pos && (*pos)->real_type() == FIELD_TYPE_ENUM &&
	 ((Field_enum*) (*pos))->typelib->count == 2 ;
554
       pos++, fieldnr++, bit<<=1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
555
  {
556
    (*pos)->val_str(&res);
557
    if (my_toupper(&my_charset_latin1, res[0]) == 'Y')
558
      access_bits|= bit;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
559
  }
560 561
  if (next_field)
    *next_field=fieldnr;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
562 563 564 565 566
  return access_bits;
}


/*
567 568 569 570 571
  Return a number which, if sorted 'desc', puts strings in this order:
    no wildcards
    wildcards
    empty string
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
572 573 574 575 576 577 578

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

579 580 581
  /* Should not use this function with more than 4 arguments for compare. */
  DBUG_ASSERT(count <= 4);

bk@work.mysql.com's avatar
bk@work.mysql.com committed
582 583
  while (count--)
  {
584 585 586
    char *start, *str= va_arg(args,char*);
    uint chars= 0;
    uint wild_pos= 0;           /* first wildcard position */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
587

monty@mysql.com's avatar
monty@mysql.com committed
588
    if ((start= str))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
589 590 591 592
    {
      for (; *str ; str++)
      {
	if (*str == wild_many || *str == wild_one || *str == wild_prefix)
593
        {
monty@mysql.com's avatar
monty@mysql.com committed
594
          wild_pos= (uint) (str - start) + 1;
595 596
          break;
        }
monty@mysql.com's avatar
monty@mysql.com committed
597
        chars= 128;                             // Marker that chars existed
bk@work.mysql.com's avatar
bk@work.mysql.com committed
598 599
      }
    }
monty@mysql.com's avatar
monty@mysql.com committed
600
    sort= (sort << 8) + (wild_pos ? min(wild_pos, 127) : chars);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
  }
  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;
}

616

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

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
621 622 623 624
  IMPLEMENTATION
   This function does not check if the user has any sensible privileges:
   only user's existence and  validity is checked.
   Note, that entire operation is protected by acl_cache_lock.
peter@mysql.com's avatar
peter@mysql.com committed
625

626
  SYNOPSIS
627 628 629 630 631 632 633 634 635 636 637 638 639 640
    acl_getroot()
    thd         thread handle. If all checks are OK,
                thd->priv_user, thd->master_access are updated.
                thd->host, thd->ip, thd->user are used for checks.
    mqh         user resources; on success mqh is reset, else
                unchanged
    passwd      scrambled & crypted password, recieved from client
                (to check): thd->scramble or thd->scramble_323 is
                used to decrypt passwd, so they must contain
                original random string,
    passwd_len  length of passwd, must be one of 0, 8,
                SCRAMBLE_LENGTH_323, SCRAMBLE_LENGTH
    'thd' and 'mqh' are updated on success; other params are IN.
  
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
641
  RETURN VALUE
642 643
    0  success: thd->priv_user, thd->priv_host, thd->master_access, mqh are
       updated
644
    1  user not found or authentification failure
645
    2  user found, has long (4.1.1) salt, but passwd is in old (3.23) format.
646
   -1  user found, has short (3.23) salt, but passwd is in new (4.1.1) format.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
647 648
*/

649 650
int acl_getroot(THD *thd, USER_RESOURCES  *mqh,
                const char *passwd, uint passwd_len)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
651
{
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
652 653 654
  ulong user_access= NO_ACCESS;
  int res= 1;
  ACL_USER *acl_user= 0;
655
  DBUG_ENTER("acl_getroot");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
656 657

  if (!initialized)
658
  {
659 660 661 662 663 664
    /* 
      here if mysqld's been started with --skip-grant-tables option.
    */
    thd->priv_user= (char *) "";                // privileges for
    *thd->priv_host= '\0';                      // the user are unknown
    thd->master_access= ~NO_ACCESS;             // everything is allowed
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
665
    bzero((char*) mqh, sizeof(*mqh));
666
    DBUG_RETURN(0);
667
  }
668

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
671
  /*
672 673 674
    Find acl entry in user database. Note, that find_acl_user is not the same,
    because it doesn't take into account the case when user is not empty,
    but acl_user->user is empty
bk@work.mysql.com's avatar
bk@work.mysql.com committed
675
  */
peter@mysql.com's avatar
peter@mysql.com committed
676

677
  for (uint i=0 ; i < acl_users.elements ; i++)
678
  {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
679 680
    ACL_USER *acl_user_tmp= dynamic_element(&acl_users,i,ACL_USER*);
    if (!acl_user_tmp->user || !strcmp(thd->user, acl_user_tmp->user))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
681
    {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
682
      if (compare_hostname(&acl_user_tmp->host, thd->host, thd->ip))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
683
      {
684
        /* check password: it should be empty or valid */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
685
        if (passwd_len == acl_user_tmp->salt_len)
peter@mysql.com's avatar
peter@mysql.com committed
686
        {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
687
          if (acl_user_tmp->salt_len == 0 ||
serg@serg.mylan's avatar
serg@serg.mylan committed
688 689
              (acl_user_tmp->salt_len == SCRAMBLE_LENGTH ?
              check_scramble(passwd, thd->scramble, acl_user_tmp->salt) :
690
              check_scramble_323(passwd, thd->scramble,
serg@serg.mylan's avatar
serg@serg.mylan committed
691
                                 (ulong *) acl_user_tmp->salt)) == 0)
692
          {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
693
            acl_user= acl_user_tmp;
694 695
            res= 0;
          }
peter@mysql.com's avatar
peter@mysql.com committed
696
        }
697
        else if (passwd_len == SCRAMBLE_LENGTH &&
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
698
                 acl_user_tmp->salt_len == SCRAMBLE_LENGTH_323)
699
          res= -1;
700
        else if (passwd_len == SCRAMBLE_LENGTH_323 &&
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
701
                 acl_user_tmp->salt_len == SCRAMBLE_LENGTH)
702
          res= 2;
703 704
        /* linear search complete: */
        break;
peter@mysql.com's avatar
peter@mysql.com committed
705
      }
peter@mysql.com's avatar
peter@mysql.com committed
706
    }
707
  }
708 709 710 711
  /*
    This was moved to separate tree because of heavy HAVE_OPENSSL case.
    If acl_user is not null, res is 0.
  */
peter@mysql.com's avatar
peter@mysql.com committed
712 713 714

  if (acl_user)
  {
715
    /* OK. User found and password checked continue validation */
716
#ifdef HAVE_OPENSSL
717
    Vio *vio=thd->net.vio;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
718
    SSL *ssl= (SSL*) vio->ssl_arg;
719
#endif
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
720

721
    /*
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
722
      At this point we know that user is allowed to connect
723 724 725 726 727 728
      from given host by given username/password pair. Now
      we check if SSL is required, if user is using SSL and
      if X509 certificate attributes are OK
    */
    switch (acl_user->ssl_type) {
    case SSL_TYPE_NOT_SPECIFIED:		// Impossible
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
729 730
    case SSL_TYPE_NONE:				// SSL is not required
      user_access= acl_user->access;
731
      break;
732
#ifdef HAVE_OPENSSL
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
733
    case SSL_TYPE_ANY:				// Any kind of SSL is ok
734
      if (vio_type(vio) == VIO_TYPE_SSL)
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
735
	user_access= acl_user->access;
736 737 738 739 740
      break;
    case SSL_TYPE_X509: /* Client should have any valid certificate. */
      /*
	Connections with non-valid certificates are dropped already
	in sslaccept() anyway, so we do not check validity here.
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
741

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
742 743
	We need to check for absence of SSL because without SSL
	we should reject connection.
744
      */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
745
      if (vio_type(vio) == VIO_TYPE_SSL &&
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
746 747
	  SSL_get_verify_result(ssl) == X509_V_OK &&
	  SSL_get_peer_certificate(ssl))
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
748
	user_access= acl_user->access;
749 750 751 752 753 754 755 756
      break;
    case SSL_TYPE_SPECIFIED: /* Client should have specified attrib */
      /*
	We do not check for absence of SSL because without SSL it does
	not pass all checks here anyway.
	If cipher name is specified, we compare it to actual cipher in
	use.
      */
monty@mysql.com's avatar
monty@mysql.com committed
757
      X509 *cert;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
758
      if (vio_type(vio) != VIO_TYPE_SSL ||
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
759
	  SSL_get_verify_result(ssl) != X509_V_OK)
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
760
	break;
761
      if (acl_user->ssl_cipher)
peter@mysql.com's avatar
peter@mysql.com committed
762
      {
763
	DBUG_PRINT("info",("comparing ciphers: '%s' and '%s'",
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
764 765
			   acl_user->ssl_cipher,SSL_get_cipher(ssl)));
	if (!strcmp(acl_user->ssl_cipher,SSL_get_cipher(ssl)))
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
766
	  user_access= acl_user->access;
767 768
	else
	{
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
769
	  if (global_system_variables.log_warnings)
serg@serg.mylan's avatar
serg@serg.mylan committed
770 771 772
	    sql_print_information("X509 ciphers mismatch: should be '%s' but is '%s'",
			      acl_user->ssl_cipher,
			      SSL_get_cipher(ssl));
773 774
	  break;
	}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
775
      }
776 777
      /* Prepare certificate (if exists) */
      DBUG_PRINT("info",("checkpoint 1"));
monty@mysql.com's avatar
monty@mysql.com committed
778 779 780 781 782
      if (!(cert= SSL_get_peer_certificate(ssl)))
      {
	user_access=NO_ACCESS;
	break;
      }
783 784 785
      DBUG_PRINT("info",("checkpoint 2"));
      /* If X509 issuer is speified, we check it... */
      if (acl_user->x509_issuer)
peter@mysql.com's avatar
peter@mysql.com committed
786
      {
kostja@oak.local's avatar
kostja@oak.local committed
787
        DBUG_PRINT("info",("checkpoint 3"));
788 789 790
	char *ptr = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
	DBUG_PRINT("info",("comparing issuers: '%s' and '%s'",
			   acl_user->x509_issuer, ptr));
kostja@oak.local's avatar
kostja@oak.local committed
791
        if (strcmp(acl_user->x509_issuer, ptr))
792
        {
kostja@oak.local's avatar
kostja@oak.local committed
793
          if (global_system_variables.log_warnings)
serg@serg.mylan's avatar
serg@serg.mylan committed
794 795
            sql_print_information("X509 issuer mismatch: should be '%s' "
			      "but is '%s'", acl_user->x509_issuer, ptr);
796
          free(ptr);
kostja@oak.local's avatar
kostja@oak.local committed
797
          break;
798
        }
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
799
        user_access= acl_user->access;
kostja@oak.local's avatar
kostja@oak.local committed
800
        free(ptr);
peter@mysql.com's avatar
peter@mysql.com committed
801
      }
802 803 804 805
      DBUG_PRINT("info",("checkpoint 4"));
      /* X509 subject is specified, we check it .. */
      if (acl_user->x509_subject)
      {
kostja@oak.local's avatar
kostja@oak.local committed
806 807 808 809
        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))
810
        {
kostja@oak.local's avatar
kostja@oak.local committed
811
          if (global_system_variables.log_warnings)
serg@serg.mylan's avatar
serg@serg.mylan committed
812
            sql_print_information("X509 subject mismatch: '%s' vs '%s'",
kostja@oak.local's avatar
kostja@oak.local committed
813
                            acl_user->x509_subject, ptr);
814
        }
kostja@oak.local's avatar
kostja@oak.local committed
815
        else
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
816
          user_access= acl_user->access;
kostja@oak.local's avatar
kostja@oak.local committed
817
        free(ptr);
818 819
      }
      break;
peter@mysql.com's avatar
peter@mysql.com committed
820
#else  /* HAVE_OPENSSL */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
821
    default:
822
      /*
kostja@oak.local's avatar
kostja@oak.local committed
823 824 825
        If we don't have SSL but SSL is required for this user the 
        authentication should fail.
      */
826 827
      break;
#endif /* HAVE_OPENSSL */
peter@mysql.com's avatar
peter@mysql.com committed
828
    }
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
829
    thd->master_access= user_access;
830 831
    thd->priv_user= acl_user->user ? thd->user : (char *) "";
    *mqh= acl_user->user_resource;
832

833 834 835 836 837
    if (acl_user->host.hostname)
      strmake(thd->priv_host, acl_user->host.hostname, MAX_HOSTNAME);
    else
      *thd->priv_host= 0;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
838
  VOID(pthread_mutex_unlock(&acl_cache->lock));
839
  DBUG_RETURN(res);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
840 841 842 843 844 845 846 847 848 849
}


static byte* check_get_key(ACL_USER *buff,uint *length,
			   my_bool not_used __attribute__((unused)))
{
  *length=buff->hostname_length;
  return (byte*) buff->host.hostname;
}

850

bk@work.mysql.com's avatar
bk@work.mysql.com committed
851
static void acl_update_user(const char *user, const char *host,
852
			    const char *password, uint password_len,
853 854 855 856
			    enum SSL_type ssl_type,
			    const char *ssl_cipher,
			    const char *x509_issuer,
			    const char *x509_subject,
peter@mysql.com's avatar
peter@mysql.com committed
857
			    USER_RESOURCES  *mqh,
858
			    ulong privileges)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
859 860 861 862 863 864 865 866 867
{
  for (uint i=0 ; i < acl_users.elements ; i++)
  {
    ACL_USER *acl_user=dynamic_element(&acl_users,i,ACL_USER*);
    if (!acl_user->user && !user[0] ||
	acl_user->user &&
	!strcmp(user,acl_user->user))
    {
      if (!acl_user->host.hostname && !host[0] ||
868
	  acl_user->host.hostname &&
869
	  !my_strcasecmp(&my_charset_latin1, host, acl_user->host.hostname))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
870 871
      {
	acl_user->access=privileges;
872
	if (mqh->bits & 1)
873
	  acl_user->user_resource.questions=mqh->questions;
874
	if (mqh->bits & 2)
875
	  acl_user->user_resource.updates=mqh->updates;
876
	if (mqh->bits & 4)
877
	  acl_user->user_resource.connections=mqh->connections;
878 879 880 881 882 883 884 885 886 887
	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);
	}
888 889
	if (password)
	  set_user_salt(acl_user, password, password_len);
890
        /* search complete: */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
891 892 893 894 895 896 897 898
	break;
      }
    }
  }
}


static void acl_insert_user(const char *user, const char *host,
899
			    const char *password, uint password_len,
900 901 902 903
			    enum SSL_type ssl_type,
			    const char *ssl_cipher,
			    const char *x509_issuer,
			    const char *x509_subject,
904
			    USER_RESOURCES *mqh,
905
			    ulong privileges)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
906 907
{
  ACL_USER acl_user;
908
  acl_user.user=*user ? strdup_root(&mem,user) : 0;
monty@mysql.com's avatar
monty@mysql.com committed
909
  update_hostname(&acl_user.host, *host ? strdup_root(&mem, host): 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
910
  acl_user.access=privileges;
911
  acl_user.user_resource = *mqh;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
912
  acl_user.sort=get_sort(2,acl_user.host.hostname,acl_user.user);
913
  acl_user.hostname_length=(uint) strlen(host);
914 915 916 917 918
  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;
919 920

  set_user_salt(&acl_user, password, password_len);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
921 922 923 924

  VOID(push_dynamic(&acl_users,(gptr) &acl_user));
  if (!acl_user.host.hostname || acl_user.host.hostname[0] == wild_many
      && !acl_user.host.hostname[1])
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
925
    allow_all_hosts=1;		// Anyone can connect /* purecov: tested */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
926 927 928 929 930 931 932 933 934 935 936
  qsort((gptr) dynamic_element(&acl_users,0,ACL_USER*),acl_users.elements,
	sizeof(ACL_USER),(qsort_cmp) acl_compare);

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


static void acl_update_db(const char *user, const char *host, const char *db,
937
			  ulong privileges)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
938 939 940 941 942 943 944 945 946
{
  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] ||
947
	  acl_db->host.hostname &&
948
	  !my_strcasecmp(&my_charset_latin1, host, acl_db->host.hostname))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
      {
	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);
	}
      }
    }
  }
}


964 965 966 967 968 969 970 971 972 973 974 975 976 977
/*
  Insert a user/db/host combination into the global acl_cache

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

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
978
static void acl_insert_db(const char *user, const char *host, const char *db,
979
			  ulong privileges)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
980 981
{
  ACL_DB acl_db;
982
  safe_mutex_assert_owner(&acl_cache->lock);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
983 984 985 986 987 988 989 990 991 992 993
  acl_db.user=strdup_root(&mem,user);
  update_hostname(&acl_db.host,strdup_root(&mem,host));
  acl_db.db=strdup_root(&mem,db);
  acl_db.access=privileges;
  acl_db.sort=get_sort(3,acl_db.host.hostname,acl_db.db,acl_db.user);
  VOID(push_dynamic(&acl_dbs,(gptr) &acl_db));
  qsort((gptr) dynamic_element(&acl_dbs,0,ACL_DB*),acl_dbs.elements,
	sizeof(ACL_DB),(qsort_cmp) acl_compare);
}


994 995 996

/*
  Get privilege for a host, user and db combination
997 998 999

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

1002
ulong acl_get(const char *host, const char *ip,
1003
              const char *user, const char *db, my_bool db_is_pattern)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1004
{
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
1005
  ulong host_access= ~0,db_access= 0;
1006
  uint i,key_length;
1007
  char key[ACL_KEY_LENGTH],*tmp_db,*end;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1008
  acl_entry *entry;
monty@mysql.com's avatar
monty@mysql.com committed
1009
  DBUG_ENTER("acl_get");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1010 1011

  VOID(pthread_mutex_lock(&acl_cache->lock));
1012
  end=strmov((tmp_db=strmov(strmov(key, ip ? ip : "")+1,user)+1),db);
1013 1014
  if (lower_case_table_names)
  {
1015
    my_casedn_str(files_charset_info, tmp_db);
1016 1017
    db=tmp_db;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1018
  key_length=(uint) (end-key);
1019
  if (!db_is_pattern && (entry=(acl_entry*) acl_cache->search(key,key_length)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1020 1021 1022
  {
    db_access=entry->access;
    VOID(pthread_mutex_unlock(&acl_cache->lock));
monty@mysql.com's avatar
monty@mysql.com committed
1023 1024
    DBUG_PRINT("exit", ("access: 0x%lx", db_access));
    DBUG_RETURN(db_access);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
  }

  /*
    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))
      {
1037
	if (!acl_db->db || !wild_compare(db,acl_db->db,db_is_pattern))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
	{
	  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))
    {
1059
      if (!acl_host->db || !wild_compare(db,acl_host->db,db_is_pattern))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1060 1061 1062 1063 1064 1065 1066 1067
      {
	host_access=acl_host->access;		// Fully specified. Take it
	break;
      }
    }
  }
exit:
  /* Save entry in cache for quick retrieval */
1068 1069
  if (!db_is_pattern &&
      (entry= (acl_entry*) malloc(sizeof(acl_entry)+key_length)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1070 1071 1072 1073 1074 1075 1076
  {
    entry->access=(db_access & host_access);
    entry->length=key_length;
    memcpy((gptr) entry->key,key,key_length);
    acl_cache->add(entry);
  }
  VOID(pthread_mutex_unlock(&acl_cache->lock));
monty@mysql.com's avatar
monty@mysql.com committed
1077 1078
  DBUG_PRINT("exit", ("access: 0x%lx", db_access & host_access));
  DBUG_RETURN(db_access & host_access);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1079 1080
}

1081 1082 1083 1084 1085 1086 1087
/*
  Check if there are any possible matching entries for this host

  NOTES
    All host names without wild cards are stored in a hash table,
    entries with wildcards are stored in a dynamic array
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1088 1089 1090 1091

static void init_check_host(void)
{
  DBUG_ENTER("init_check_host");
1092
  VOID(my_init_dynamic_array(&acl_wild_hosts,sizeof(struct acl_host_and_ip),
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1093
			  acl_users.elements,1));
1094
  VOID(hash_init(&acl_check_hosts,&my_charset_latin1,acl_users.elements,0,0,
1095
		 (hash_get_key) check_get_key,0,0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
  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 *);
1110
	  if (!my_strcasecmp(&my_charset_latin1,
1111
                             acl_user->host.hostname, acl->hostname))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1112 1113 1114 1115 1116 1117
	    break;				// already stored
	}
	if (j == acl_wild_hosts.elements)	// If new
	  (void) push_dynamic(&acl_wild_hosts,(char*) &acl_user->host);
      }
      else if (!hash_search(&acl_check_hosts,(byte*) &acl_user->host,
1118
			    (uint) strlen(acl_user->host.hostname)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1119
      {
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1120
	if (my_hash_insert(&acl_check_hosts,(byte*) acl_user))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
	{					// End of memory
	  allow_all_hosts=1;			// Should never happen
	  DBUG_VOID_RETURN;
	}
      }
    }
  }
  freeze_size(&acl_wild_hosts);
  freeze_size(&acl_check_hosts.array);
  DBUG_VOID_RETURN;
}


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

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

1142 1143
  if (host && hash_search(&acl_check_hosts,(byte*) host,(uint) strlen(host)) ||
      ip && hash_search(&acl_check_hosts,(byte*) ip,(uint) strlen(ip)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
  {
    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
}


1162 1163 1164 1165 1166 1167 1168 1169
/*
  Check if the user is allowed to change password

  SYNOPSIS:
    check_change_password()
    thd		THD
    host	hostname for the user
    user	user name
1170 1171 1172 1173
    new_password new password

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

1175
    RETURN VALUE
1176 1177
      0		OK
      1		ERROR  ; In this case the error is sent to the client.
1178 1179
*/

1180
bool check_change_password(THD *thd, const char *host, const char *user,
1181
                           char *new_password, uint new_password_len)
1182
{
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1183 1184
  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
1185
    net_printf(thd,ER_OPTION_PREVENTS_STATEMENT,
1186 1187
             "--skip-grant-tables");
    return(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1188
  }
1189 1190
  if (!thd->slave_thread &&
      (strcmp(thd->user,user) ||
1191
       my_strcasecmp(&my_charset_latin1, host, thd->host_or_ip)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1192
  {
hf@deer.(none)'s avatar
hf@deer.(none) committed
1193
    if (check_access(thd, UPDATE_ACL, "mysql",0,1,0))
1194
      return(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1195
  }
1196 1197
  if (!thd->slave_thread && !thd->user[0])
  {
1198
    send_error(thd, ER_PASSWORD_ANONYMOUS_USER);
1199
    return(1);
1200
  }
1201
  uint len=strlen(new_password);
1202
  if (len && len != SCRAMBLED_PASSWORD_CHAR_LENGTH &&
1203 1204 1205 1206 1207 1208 1209
      len != SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
  {
    net_printf(thd, 0,
               "Password hash should be a %d-digit hexadecimal number",
               SCRAMBLED_PASSWORD_CHAR_LENGTH);
    return -1;
  }
1210 1211 1212 1213
  return(0);
}


1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
/*
  Change a password for a user

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

  RETURN VALUES
    0	ok
    1	ERROR; In this case the error is sent to the client.
peter@mysql.com's avatar
peter@mysql.com committed
1227
*/
1228

1229 1230 1231
bool change_password(THD *thd, const char *host, const char *user,
		     char *new_password)
{
1232
  uint new_password_len= strlen(new_password);
1233 1234 1235 1236 1237
  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

1238
  if (check_change_password(thd, host, user, new_password, new_password_len))
1239 1240
    DBUG_RETURN(1);

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1241 1242
  VOID(pthread_mutex_lock(&acl_cache->lock));
  ACL_USER *acl_user;
1243
  if (!(acl_user= find_acl_user(host, user)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1244 1245
  {
    VOID(pthread_mutex_unlock(&acl_cache->lock));
1246
    send_error(thd, ER_PASSWORD_NO_MATCH);
1247
    DBUG_RETURN(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1248
  }
1249 1250 1251
  /* update loaded acl entry: */
  set_user_salt(acl_user, new_password, new_password_len);

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1252 1253
  if (update_user_table(thd,
			acl_user->host.hostname ? acl_user->host.hostname : "",
1254
			acl_user->user ? acl_user->user : "",
1255
			new_password, new_password_len))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1256 1257
  {
    VOID(pthread_mutex_unlock(&acl_cache->lock)); /* purecov: deadcode */
1258
    send_error(thd,0); /* purecov: deadcode */
1259
    DBUG_RETURN(1); /* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1260
  }
peter@mysql.com's avatar
peter@mysql.com committed
1261

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1262 1263 1264
  acl_cache->clear(1);				// Clear locked hostname cache
  VOID(pthread_mutex_unlock(&acl_cache->lock));

1265
  char buff[512]; /* Extend with extended password length*/
1266
  ulong query_length=
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1267 1268
    my_sprintf(buff,
	       (buff,"SET PASSWORD FOR \"%-.120s\"@\"%-.120s\"=\"%-.120s\"",
1269
		acl_user->user ? acl_user->user : "",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1270 1271
		acl_user->host.hostname ? acl_user->host.hostname : "",
		new_password));
guilhem@mysql.com's avatar
guilhem@mysql.com committed
1272
  thd->clear_error();
1273
  mysql_update_log.write(thd, buff, query_length);
1274
  Query_log_event qinfo(thd, buff, query_length, 0, FALSE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1275
  mysql_bin_log.write(&qinfo);
1276
  DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
}


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

static ACL_USER *
find_acl_user(const char *host, const char *user)
{
1287
  DBUG_ENTER("find_acl_user");
1288
  DBUG_PRINT("enter",("host: '%s'  user: '%s'",host,user));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1289 1290 1291
  for (uint i=0 ; i < acl_users.elements ; i++)
  {
    ACL_USER *acl_user=dynamic_element(&acl_users,i,ACL_USER*);
1292
    DBUG_PRINT("info",("strcmp('%s','%s'), compare_hostname('%s','%s'),",
1293 1294 1295 1296 1297
		       user,
		       acl_user->user ? acl_user->user : "",
		       host,
		       acl_user->host.hostname ? acl_user->host.hostname :
		       ""));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1298 1299 1300
    if (!acl_user->user && !user[0] ||
	acl_user->user && !strcmp(user,acl_user->user))
    {
1301
      if (compare_hostname(&acl_user->host,host,host))
1302 1303 1304
      {
	DBUG_RETURN(acl_user);
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1305 1306
    }
  }
1307
  DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1308 1309 1310
}


1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
/*
  Comparing of hostnames

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

  A net mask of 0.0.0.0 is not allowed.
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344

static const char *calc_ip(const char *ip, long *val, char end)
{
  long ip_val,tmp;
  if (!(ip=str2int(ip,10,0,255,&ip_val)) || *ip != '.')
    return 0;
  ip_val<<=24;
  if (!(ip=str2int(ip+1,10,0,255,&tmp)) || *ip != '.')
    return 0;
  ip_val+=tmp<<16;
  if (!(ip=str2int(ip+1,10,0,255,&tmp)) || *ip != '.')
    return 0;
  ip_val+=tmp<<8;
  if (!(ip=str2int(ip+1,10,0,255,&tmp)) || *ip != end)
    return 0;
  *val=ip_val+tmp;
  return ip;
}


static void update_hostname(acl_host_and_ip *host, const char *hostname)
{
  host->hostname=(char*) hostname;		// This will not be modified!
1345
  if (!hostname ||
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1346 1347 1348
      (!(hostname=calc_ip(hostname,&host->ip,'/')) ||
       !(hostname=calc_ip(hostname+1,&host->ip_mask,'\0'))))
  {
1349
    host->ip= host->ip_mask=0;			// Not a masked ip
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
  }
}


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 ||
1363
	  (hostname && !wild_case_compare(&my_charset_latin1,
1364
                                          hostname,host->hostname)) ||
1365
	  (ip && !wild_compare(ip,host->hostname,0)));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1366 1367
}

hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1368 1369 1370 1371
bool hostname_requires_resolving(const char *hostname)
{
  char cur;
  if (!hostname)
monty@mysql.com's avatar
monty@mysql.com committed
1372
    return FALSE;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1373 1374 1375 1376 1377
  int namelen= strlen(hostname);
  int lhlen= strlen(my_localhost);
  if ((namelen == lhlen) &&
      !my_strnncoll(&my_charset_latin1, (const uchar *)hostname,  namelen,
		    (const uchar *)my_localhost, strlen(my_localhost)))
monty@mysql.com's avatar
monty@mysql.com committed
1378
    return FALSE;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1379 1380
  for (; (cur=*hostname); hostname++)
  {
1381
    if ((cur != '%') && (cur != '_') && (cur != '.') && (cur != '/') &&
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1382
	((cur < '0') || (cur > '9')))
monty@mysql.com's avatar
monty@mysql.com committed
1383
      return TRUE;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1384
  }
monty@mysql.com's avatar
monty@mysql.com committed
1385
  return FALSE;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1386
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1387

1388 1389 1390
/*
  Update grants in the user and database privilege tables
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1391 1392

static bool update_user_table(THD *thd, const char *host, const char *user,
1393
			      const char *new_password, uint new_password_len)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1394 1395 1396 1397 1398 1399 1400 1401
{
  TABLE_LIST tables;
  TABLE *table;
  bool error=1;
  DBUG_ENTER("update_user_table");
  DBUG_PRINT("enter",("user: %s  host: %s",user,host));

  bzero((char*) &tables,sizeof(tables));
1402
  tables.alias=tables.real_name=(char*) "user";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1403
  tables.db=(char*) "mysql";
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1404

1405 1406 1407 1408 1409 1410 1411
#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
  if (thd->slave_thread && table_rules_on)
  {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1412 1413 1414
    /*
      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.
1415
    */
1416
    tables.updating= 1;
1417 1418 1419 1420 1421 1422
    /* Thanks to bzero, tables.next==0 */
    if (!tables_ok(0, &tables))
      DBUG_RETURN(0);
  }
#endif

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1423 1424
  if (!(table=open_ltable(thd,&tables,TL_WRITE)))
    DBUG_RETURN(1); /* purecov: deadcode */
1425 1426
  table->field[0]->store(host,(uint) strlen(host), &my_charset_latin1);
  table->field[1]->store(user,(uint) strlen(user), &my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1427

1428
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1429
  if (table->file->index_read_idx(table->record[0],0,
1430 1431
				  (byte*) table->field[0]->ptr,
				  table->key_info[0].key_length,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1432 1433 1434 1435 1436
				  HA_READ_KEY_EXACT))
  {
    my_error(ER_PASSWORD_NO_MATCH,MYF(0));	/* purecov: deadcode */
    DBUG_RETURN(1);				/* purecov: deadcode */
  }
1437
  store_record(table,record[1]);
1438
  table->field[2]->store(new_password, new_password_len, &my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
  if ((error=table->file->update_row(table->record[1],table->record[0])))
  {
    table->file->print_error(error,MYF(0));	/* purecov: deadcode */
    goto end;					/* purecov: deadcode */
  }
  error=0;					// Record updated

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

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1451 1452 1453 1454 1455 1456 1457 1458 1459

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

static bool test_if_create_new_users(THD *thd)
{
  bool create_new_users=1;    // Assume that we are allowed to create new users
  if (opt_safe_user_create && !(thd->master_access & INSERT_ACL))
  {
    TABLE_LIST tl;
1460
    ulong db_access;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1461 1462
    bzero((char*) &tl,sizeof(tl));
    tl.db=	   (char*) "mysql";
1463
    tl.real_name=  (char*) "user";
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1464

1465
    db_access=acl_get(thd->host, thd->ip,
1466
		      thd->priv_user, tl.db, 0);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1467 1468
    if (!(db_access & INSERT_ACL))
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1469
      if (check_grant(thd, INSERT_ACL, &tl, 0, UINT_MAX, 1))
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1470 1471 1472 1473 1474 1475 1476
	create_new_users=0;
    }
  }
  return create_new_users;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
1477
/****************************************************************************
1478
  Handle GRANT commands
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1479 1480
****************************************************************************/

1481
static int replace_user_table(THD *thd, TABLE *table, const LEX_USER &combo,
1482 1483
			      ulong rights, bool revoke_grant,
			      bool create_user)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1484 1485
{
  int error = -1;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1486
  bool old_row_exists=0;
1487
  const char *password= "";
1488
  uint password_len= 0;
1489
  char what= (revoke_grant) ? 'N' : 'Y';
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1490
  DBUG_ENTER("replace_user_table");
1491
  safe_mutex_assert_owner(&acl_cache->lock);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1492 1493

  if (combo.password.str && combo.password.str[0])
1494
  {
1495 1496
    if (combo.password.length != SCRAMBLED_PASSWORD_CHAR_LENGTH &&
        combo.password.length != SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
1497
    {
1498
      my_printf_error(ER_UNKNOWN_ERROR,
1499 1500
                      "Password hash should be a %d-digit hexadecimal number",
                      MYF(0), SCRAMBLED_PASSWORD_CHAR_LENGTH);
1501
      DBUG_RETURN(-1);
1502
    }
1503
    password_len= combo.password.length;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1504
    password=combo.password.str;
1505
  }
peter@mysql.com's avatar
peter@mysql.com committed
1506

1507 1508
  table->field[0]->store(combo.host.str,combo.host.length, &my_charset_latin1);
  table->field[1]->store(combo.user.str,combo.user.length, &my_charset_latin1);
1509
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
1510
  if (table->file->index_read_idx(table->record[0], 0,
1511 1512 1513
				  (byte*) table->field[0]->ptr,
				  table->key_info[0].key_length,
				  HA_READ_KEY_EXACT))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1514
  {
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1515
    if (!create_user)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1516
    {
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1517
      if (what == 'N')
guilhem@mysql.com's avatar
guilhem@mysql.com committed
1518
	my_error(ER_NONEXISTING_GRANT, MYF(0), combo.user.str, combo.host.str);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1519
      else
guilhem@mysql.com's avatar
guilhem@mysql.com committed
1520 1521
	my_error(ER_NO_PERMISSION_TO_CREATE_USER, MYF(0),
                 thd->user, thd->host_or_ip);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1522 1523
      goto end;
    }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1524
    old_row_exists = 0;
1525 1526 1527 1528 1529 1530 1531
    restore_record(table,default_values);       // cp empty row from default_values
    table->field[0]->store(combo.host.str,combo.host.length,
                           &my_charset_latin1);
    table->field[1]->store(combo.user.str,combo.user.length,
                           &my_charset_latin1);
    table->field[2]->store(password, password_len,
                           &my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1532 1533 1534
  }
  else
  {
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1535
    old_row_exists = 1;
1536
    store_record(table,record[1]);			// Save copy for update
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1537
    if (combo.password.str)			// If password given
1538
      table->field[2]->store(password, password_len, &my_charset_latin1);
1539 1540 1541 1542 1543
    else if (!rights && !revoke_grant && thd->lex->ssl_type == SSL_TYPE_NOT_SPECIFIED &&
	     !thd->lex->mqh.bits)
    {
      DBUG_RETURN(0);
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1544 1545
  }

1546 1547 1548 1549
  /* Update table columns with new privileges */

  Field **tmp_field;
  ulong priv;
1550
  uint next_field;
1551 1552 1553 1554
  for (tmp_field= table->field+3, priv = SELECT_ACL;
       *tmp_field && (*tmp_field)->real_type() == FIELD_TYPE_ENUM &&
	 ((Field_enum*) (*tmp_field))->typelib->count == 2 ;
       tmp_field++, priv <<= 1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1555
  {
1556
    if (priv & rights)				 // set requested privileges
1557
      (*tmp_field)->store(&what, 1, &my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1558
  }
1559
  rights= get_access(table, 3, &next_field);
1560
  DBUG_PRINT("info",("table->fields: %d",table->fields));
1561
  if (table->fields >= 31)		/* From 4.0.0 we have more fields */
1562
  {
1563
    /* We write down SSL related ACL stuff */
1564
    switch (thd->lex->ssl_type) {
1565
    case SSL_TYPE_ANY:
1566 1567 1568 1569
      table->field[next_field]->store("ANY", 3, &my_charset_latin1);
      table->field[next_field+1]->store("", 0, &my_charset_latin1);
      table->field[next_field+2]->store("", 0, &my_charset_latin1);
      table->field[next_field+3]->store("", 0, &my_charset_latin1);
1570 1571
      break;
    case SSL_TYPE_X509:
1572 1573 1574 1575
      table->field[next_field]->store("X509", 4, &my_charset_latin1);
      table->field[next_field+1]->store("", 0, &my_charset_latin1);
      table->field[next_field+2]->store("", 0, &my_charset_latin1);
      table->field[next_field+3]->store("", 0, &my_charset_latin1);
1576 1577
      break;
    case SSL_TYPE_SPECIFIED:
1578 1579 1580 1581
      table->field[next_field]->store("SPECIFIED", 9, &my_charset_latin1);
      table->field[next_field+1]->store("", 0, &my_charset_latin1);
      table->field[next_field+2]->store("", 0, &my_charset_latin1);
      table->field[next_field+3]->store("", 0, &my_charset_latin1);
1582
      if (thd->lex->ssl_cipher)
1583 1584 1585
        table->field[next_field+1]->store(thd->lex->ssl_cipher,
                                          strlen(thd->lex->ssl_cipher),
                                          &my_charset_latin1);
1586
      if (thd->lex->x509_issuer)
1587 1588 1589
        table->field[next_field+2]->store(thd->lex->x509_issuer,
                                          strlen(thd->lex->x509_issuer),
                                          &my_charset_latin1);
1590
      if (thd->lex->x509_subject)
1591 1592 1593
        table->field[next_field+3]->store(thd->lex->x509_subject,
                                          strlen(thd->lex->x509_subject),
                                          &my_charset_latin1);
1594
      break;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1595
    case SSL_TYPE_NOT_SPECIFIED:
gluh@gluh.(none)'s avatar
gluh@gluh.(none) committed
1596 1597
      break;
    case SSL_TYPE_NONE:
1598 1599 1600 1601
      table->field[next_field]->store("", 0, &my_charset_latin1);
      table->field[next_field+1]->store("", 0, &my_charset_latin1);
      table->field[next_field+2]->store("", 0, &my_charset_latin1);
      table->field[next_field+3]->store("", 0, &my_charset_latin1);
gluh@gluh.(none)'s avatar
gluh@gluh.(none) committed
1602
      break;
1603
    }
1604

1605 1606 1607
    /* Skip over SSL related fields to first user limits related field */
    next_field+= 4;

1608
    USER_RESOURCES mqh= thd->lex->mqh;
1609
    if (mqh.bits & 1)
1610
      table->field[next_field]->store((longlong) mqh.questions);
1611
    if (mqh.bits & 2)
1612
      table->field[next_field+1]->store((longlong) mqh.updates);
1613
    if (mqh.bits & 4)
1614
      table->field[next_field+2]->store((longlong) mqh.connections);
1615
    mqh_used = mqh_used || mqh.questions || mqh.updates || mqh.connections;
1616
  }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1617
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1618 1619 1620 1621 1622
  {
    /*
      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!
    */
1623
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
1624
    if (cmp_record(table,record[1]) &&
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643
	(error=table->file->update_row(table->record[1],table->record[0])))
    {						// This should never happen
      table->file->print_error(error,MYF(0));	/* purecov: deadcode */
      error= -1;				/* purecov: deadcode */
      goto end;					/* purecov: deadcode */
    }
  }
  else if ((error=table->file->write_row(table->record[0]))) // insert
  {						// This should never happen
    if (error && error != HA_ERR_FOUND_DUPP_KEY &&
	error != HA_ERR_FOUND_DUPP_UNIQUE)	/* purecov: inspected */
    {
      table->file->print_error(error,MYF(0));	/* purecov: deadcode */
      error= -1;				/* purecov: deadcode */
      goto end;					/* purecov: deadcode */
    }
  }
  error=0;					// Privileges granted / revoked

1644
end:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1645 1646 1647
  if (!error)
  {
    acl_cache->clear(1);			// Clear privilege cache
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1648
    if (old_row_exists)
1649 1650
      acl_update_user(combo.user.str, combo.host.str,
                      combo.password.str, password_len,
1651 1652 1653 1654 1655
		      thd->lex->ssl_type,
		      thd->lex->ssl_cipher,
		      thd->lex->x509_issuer,
		      thd->lex->x509_subject,
		      &thd->lex->mqh,
1656
		      rights);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1657
    else
1658
      acl_insert_user(combo.user.str, combo.host.str, password, password_len,
1659 1660 1661 1662 1663
		      thd->lex->ssl_type,
		      thd->lex->ssl_cipher,
		      thd->lex->x509_issuer,
		      thd->lex->x509_subject,
		      &thd->lex->mqh,
1664
		      rights);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1665 1666 1667 1668 1669 1670
  }
  DBUG_RETURN(error);
}


/*
1671
  change grants in the mysql.db table
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1672 1673 1674 1675
*/

static int replace_db_table(TABLE *table, const char *db,
			    const LEX_USER &combo,
1676
			    ulong rights, bool revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1677
{
1678 1679
  uint i;
  ulong priv,store_rights;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1680
  bool old_row_exists=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1681
  int error;
1682
  char what= (revoke_grant) ? 'N' : 'Y';
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1683 1684
  DBUG_ENTER("replace_db_table");

1685 1686
  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
1687
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
1688 1689 1690
    DBUG_RETURN(-1);
  }

1691
  /* Check if there is such a user in user table in memory? */
1692
  if (!find_acl_user(combo.host.str,combo.user.str))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1693 1694 1695 1696 1697
  {
    my_error(ER_PASSWORD_NO_MATCH,MYF(0));
    DBUG_RETURN(-1);
  }

1698 1699 1700
  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);
1701 1702 1703 1704 1705
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
  if (table->file->index_read_idx(table->record[0],0,
				  (byte*) table->field[0]->ptr,
				  table->key_info[0].key_length,
				  HA_READ_KEY_EXACT))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1706 1707 1708
  {
    if (what == 'N')
    { // no row, no revoke
guilhem@mysql.com's avatar
guilhem@mysql.com committed
1709
      my_error(ER_NONEXISTING_GRANT, MYF(0), combo.user.str, combo.host.str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1710 1711
      goto abort;
    }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1712
    old_row_exists = 0;
1713
    restore_record(table,default_values);			// cp empty row from default_values
1714 1715 1716
    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);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1717 1718 1719
  }
  else
  {
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1720
    old_row_exists = 1;
1721
    store_record(table,record[1]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1722 1723 1724
  }

  store_rights=get_rights_for_db(rights);
1725
  for (i= 3, priv= 1; i < table->fields; i++, priv <<= 1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1726
  {
1727
    if (priv & store_rights)			// do it if priv is chosen
1728
      table->field [i]->store(&what,1, &my_charset_latin1);// set requested privileges
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1729 1730 1731 1732
  }
  rights=get_access(table,3);
  rights=fix_rights_for_db(rights);

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1733
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1734
  {
1735
    /* update old existing row */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1736 1737
    if (rights)
    {
1738
      table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1739 1740 1741 1742 1743 1744 1745 1746 1747
      if ((error=table->file->update_row(table->record[1],table->record[0])))
	goto table_error;			/* purecov: deadcode */
    }
    else	/* must have been a revoke of all privileges */
    {
      if ((error = table->file->delete_row(table->record[1])))
	goto table_error;			/* purecov: deadcode */
    }
  }
1748
  else if (rights && (error=table->file->write_row(table->record[0])))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1749 1750 1751 1752 1753 1754
  {
    if (error && error != HA_ERR_FOUND_DUPP_KEY) /* purecov: inspected */
      goto table_error; /* purecov: deadcode */
  }

  acl_cache->clear(1);				// Clear privilege cache
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1755
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1756 1757
    acl_update_db(combo.user.str,combo.host.str,db,rights);
  else
1758
  if (rights)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1759 1760 1761 1762
    acl_insert_db(combo.user.str,combo.host.str,db,rights);
  DBUG_RETURN(0);

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

1766
abort:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1767 1768 1769 1770 1771 1772 1773 1774
  DBUG_RETURN(-1);
}


class GRANT_COLUMN :public Sql_alloc
{
public:
  char *column;
1775 1776 1777
  ulong rights;
  uint key_length;
  GRANT_COLUMN(String &c,  ulong y) :rights (y)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1778
  {
1779
    column= memdup_root(&memex,c.ptr(), key_length=c.length());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1780 1781 1782
  }
};

1783

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1784 1785 1786 1787 1788 1789 1790
static byte* get_key_column(GRANT_COLUMN *buff,uint *length,
			    my_bool not_used __attribute__((unused)))
{
  *length=buff->key_length;
  return (byte*) buff->column;
}

1791

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1792 1793 1794
class GRANT_TABLE :public Sql_alloc
{
public:
1795 1796
  acl_host_and_ip host;
  char *db, *user, *tname, *hash_key;
1797
  ulong privs, cols;
1798
  ulong sort;
1799
  uint key_length;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1800
  HASH hash_columns;
monty@mysql.com's avatar
monty@mysql.com committed
1801 1802 1803 1804

  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);
1805 1806
  bool ok() { return privs != 0 || cols != 0; }
};
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1807

1808

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

1810 1811 1812 1813 1814
GRANT_TABLE::GRANT_TABLE(const char *h, const char *d,const char *u,
                         const char *t, ulong p, ulong c)
  :privs(p), cols(c)
{
  /* Host given by user */
1815
  update_hostname(&host, strdup_root(&memex, h));
1816 1817
  db =   strdup_root(&memex,d);
  user = strdup_root(&memex,u);
1818
  sort=  get_sort(3,host.hostname,db,user);
1819 1820
  tname= strdup_root(&memex,t);
  if (lower_case_table_names)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1821
  {
1822 1823
    my_casedn_str(files_charset_info, db);
    my_casedn_str(files_charset_info, tname);
1824 1825 1826 1827
  }
  key_length =(uint) strlen(d)+(uint) strlen(u)+(uint) strlen(t)+3;
  hash_key = (char*) alloc_root(&memex,key_length);
  strmov(strmov(strmov(hash_key,user)+1,db)+1,tname);
monty@mysql.com's avatar
monty@mysql.com committed
1828 1829
  (void) hash_init(&hash_columns,&my_charset_latin1,
                   0,0,0, (hash_get_key) get_key_column,0,0);
1830
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1831

1832 1833 1834 1835 1836

GRANT_TABLE::GRANT_TABLE(TABLE *form, TABLE *col_privs)
{
  byte key[MAX_KEY_LENGTH];

1837
  update_hostname(&host, get_field(&memex, form->field[0]));
monty@mysql.com's avatar
monty@mysql.com committed
1838 1839
  db=    get_field(&memex,form->field[1]);
  user=  get_field(&memex,form->field[2]);
1840 1841
  if (!user)
    user= (char*) "";
1842
  sort=  get_sort(3, host.hostname, db, user);
monty@mysql.com's avatar
monty@mysql.com committed
1843
  tname= get_field(&memex,form->field[3]);
1844 1845 1846 1847 1848 1849 1850 1851
  if (!db || !tname)
  {
    /* Wrong table row; Ignore it */
    privs = cols = 0;				/* purecov: inspected */
    return;					/* purecov: inspected */
  }
  if (lower_case_table_names)
  {
1852 1853
    my_casedn_str(files_charset_info, db);
    my_casedn_str(files_charset_info, tname);
1854 1855 1856 1857 1858 1859 1860 1861 1862 1863
  }
  key_length = ((uint) strlen(db) + (uint) strlen(user) +
                (uint) strlen(tname) + 3);
  hash_key = (char*) alloc_root(&memex,key_length);
  strmov(strmov(strmov(hash_key,user)+1,db)+1,tname);
  privs = (ulong) form->field[6]->val_int();
  cols  = (ulong) form->field[7]->val_int();
  privs = fix_rights_for_table(privs);
  cols =  fix_rights_for_column(cols);

monty@mysql.com's avatar
monty@mysql.com committed
1864 1865
  (void) hash_init(&hash_columns,&my_charset_latin1,
                   0,0,0, (hash_get_key) get_key_column,0,0);
1866 1867 1868
  if (cols)
  {
    int key_len;
1869
    col_privs->field[0]->store(host.hostname,(uint) strlen(host.hostname),
monty@mysql.com's avatar
monty@mysql.com committed
1870 1871 1872 1873
                               &my_charset_latin1);
    col_privs->field[1]->store(db,(uint) strlen(db), &my_charset_latin1);
    col_privs->field[2]->store(user,(uint) strlen(user), &my_charset_latin1);
    col_privs->field[3]->store(tname,(uint) strlen(tname), &my_charset_latin1);
1874 1875 1876 1877 1878
    key_len=(col_privs->field[0]->pack_length()+
             col_privs->field[1]->pack_length()+
             col_privs->field[2]->pack_length()+
             col_privs->field[3]->pack_length());
    key_copy(key,col_privs,0,key_len);
monty@mysql.com's avatar
monty@mysql.com committed
1879
    col_privs->field[4]->store("",0, &my_charset_latin1);
1880 1881
    col_privs->file->ha_index_init(0);
    if (col_privs->file->index_read(col_privs->record[0],
1882 1883
                                    (byte*) col_privs->field[0]->ptr,
                                    key_len, HA_READ_KEY_EXACT))
1884
    {
1885
      cols = 0; /* purecov: deadcode */
1886
      col_privs->file->ha_index_end();
1887
      return;
1888
    }
1889
    do
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1890
    {
1891 1892 1893
      String *res,column_name;
      GRANT_COLUMN *mem_check;
      /* As column name is a string, we don't have to supply a buffer */
monty@mysql.com's avatar
monty@mysql.com committed
1894
      res=col_privs->field[4]->val_str(&column_name);
1895 1896 1897
      ulong priv= (ulong) col_privs->field[6]->val_int();
      if (!(mem_check = new GRANT_COLUMN(*res,
                                         fix_rights_for_column(priv))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1898
      {
1899 1900 1901
        /* Don't use this entry */
        privs = cols = 0;			/* purecov: deadcode */
        return;				/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1902
      }
monty@mysql.com's avatar
monty@mysql.com committed
1903
      my_hash_insert(&hash_columns, (byte *) mem_check);
1904
    } while (!col_privs->file->index_next(col_privs->record[0]) &&
1905
             !key_cmp_if_same(col_privs,key,0,key_len));
1906
    col_privs->file->ha_index_end();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1907
  }
1908
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1909

1910

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1911 1912 1913 1914 1915 1916 1917
static byte* get_grant_table(GRANT_TABLE *buff,uint *length,
			     my_bool not_used __attribute__((unused)))
{
  *length=buff->key_length;
  return (byte*) buff->hash_key;
}

1918

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1919 1920 1921 1922 1923
void free_grant_table(GRANT_TABLE *grant_table)
{
  hash_free(&grant_table->hash_columns);
}

1924

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936
/* Search after a matching grant. Prefer exact grants before not exact ones */

static GRANT_TABLE *table_hash_search(const char *host,const char* ip,
				      const char *db,
				      const char *user, const char *tname,
				      bool exact)
{
  char helping [NAME_LEN*2+USERNAME_LENGTH+3];
  uint len;
  GRANT_TABLE *grant_table,*found=0;

  len  = (uint) (strmov(strmov(strmov(helping,user)+1,db)+1,tname)-helping)+ 1;
1937 1938
  for (grant_table=(GRANT_TABLE*) hash_search(&column_priv_hash,
					      (byte*) helping,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1939 1940
					      len) ;
       grant_table ;
1941 1942
       grant_table= (GRANT_TABLE*) hash_next(&column_priv_hash,(byte*) helping,
					     len))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1943 1944 1945
  {
    if (exact)
    {
1946
      if (compare_hostname(&grant_table->host, host, ip))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1947 1948 1949 1950
	return grant_table;
    }
    else
    {
1951
      if (compare_hostname(&grant_table->host, host, ip) &&
1952
          (!found || found->sort < grant_table->sort))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1953 1954 1955 1956 1957 1958 1959 1960
	found=grant_table;					// Host ok
    }
  }
  return found;
}



1961
inline GRANT_COLUMN *
1962
column_hash_search(GRANT_TABLE *t, const char *cname, uint length)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1963 1964 1965 1966 1967 1968 1969 1970 1971
{
  return (GRANT_COLUMN*) hash_search(&t->hash_columns, (byte*) cname,length);
}


static int replace_column_table(GRANT_TABLE *g_t,
				TABLE *table, const LEX_USER &combo,
				List <LEX_COLUMN> &columns,
				const char *db, const char *table_name,
1972
				ulong rights, bool revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1973 1974 1975 1976 1977 1978
{
  int error=0,result=0;
  uint key_length;
  byte key[MAX_KEY_LENGTH];
  DBUG_ENTER("replace_column_table");

1979 1980 1981 1982
  table->field[0]->store(combo.host.str,combo.host.length, &my_charset_latin1);
  table->field[1]->store(db,(uint) strlen(db), &my_charset_latin1);
  table->field[2]->store(combo.user.str,combo.user.length, &my_charset_latin1);
  table->field[3]->store(table_name,(uint) strlen(table_name), &my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1983 1984 1985 1986 1987 1988 1989 1990 1991 1992
  key_length=(table->field[0]->pack_length()+ table->field[1]->pack_length()+
	      table->field[2]->pack_length()+ table->field[3]->pack_length());
  key_copy(key,table,0,key_length);

  rights &= COL_ACLS;				// Only ACL for columns

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

  List_iterator <LEX_COLUMN> iter(columns);
  class LEX_COLUMN *xx;
1993
  table->file->ha_index_init(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1994 1995
  while ((xx=iter++))
  {
1996
    ulong privileges = xx->rights;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1997
    bool old_row_exists=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1998
    key_restore(table,key,0,key_length);
1999 2000
    table->field[4]->store(xx->column.ptr(),xx->column.length(),
                           &my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2001

2002
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2003
    if (table->file->index_read(table->record[0],(byte*) table->field[0]->ptr,
2004 2005
				table->key_info[0].key_length,
				HA_READ_KEY_EXACT))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2006 2007 2008
    {
      if (revoke_grant)
      {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2009 2010
	my_error(ER_NONEXISTING_TABLE_GRANT, MYF(0),
                 combo.user.str, combo.host.str, table_name); /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2011 2012 2013
	result= -1; /* purecov: inspected */
	continue; /* purecov: inspected */
      }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2014
      old_row_exists = 0;
2015
      restore_record(table,default_values);		// Get empty record
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2016
      key_restore(table,key,0,key_length);
2017 2018
      table->field[4]->store(xx->column.ptr(),xx->column.length(),
                             &my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2019 2020 2021
    }
    else
    {
2022
      ulong tmp= (ulong) table->field[6]->val_int();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2023 2024 2025 2026 2027 2028
      tmp=fix_rights_for_column(tmp);

      if (revoke_grant)
	privileges = tmp & ~(privileges | rights);
      else
	privileges |= tmp;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2029
      old_row_exists = 1;
2030
      store_record(table,record[1]);			// copy original row
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2031 2032 2033 2034
    }

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

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2035
    if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
    {
      if (privileges)
	error=table->file->update_row(table->record[1],table->record[0]);
      else
	error=table->file->delete_row(table->record[1]);
      if (error)
      {
	table->file->print_error(error,MYF(0)); /* purecov: inspected */
	result= -1;				/* purecov: inspected */
	goto end;				/* purecov: inspected */
      }
      GRANT_COLUMN *grant_column = column_hash_search(g_t,
						      xx->column.ptr(),
						      xx->column.length());
      if (grant_column)				// Should always be true
	grant_column->rights = privileges;	// Update hash
    }
    else					// new grant
    {
      if ((error=table->file->write_row(table->record[0])))
      {
	table->file->print_error(error,MYF(0)); /* purecov: inspected */
	result= -1;				/* purecov: inspected */
	goto end;				/* purecov: inspected */
      }
      GRANT_COLUMN *grant_column = new GRANT_COLUMN(xx->column,privileges);
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2062
      my_hash_insert(&g_t->hash_columns,(byte*) grant_column);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2063 2064 2065 2066 2067 2068 2069 2070 2071 2072
    }
  }

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

  if (revoke_grant)
  {
2073
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2074
    if (table->file->index_read(table->record[0], (byte*) table->field[0]->ptr,
2075
                                key_length,
2076
				HA_READ_KEY_EXACT))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2077 2078
      goto end;

2079
    /* Scan through all rows with the same host,db,user and table */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2080 2081
    do
    {
2082
      ulong privileges = (ulong) table->field[6]->val_int();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2083
      privileges=fix_rights_for_column(privileges);
2084
      store_record(table,record[1]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2085 2086 2087 2088 2089

      if (privileges & rights)	// is in this record the priv to be revoked ??
      {
	GRANT_COLUMN *grant_column = NULL;
	char  colum_name_buf[HOSTNAME_LENGTH+1];
2090
	String column_name(colum_name_buf,sizeof(colum_name_buf),&my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2091 2092 2093 2094

	privileges&= ~rights;
	table->field[6]->store((longlong)
			       get_rights_for_column(privileges));
2095
	table->field[4]->val_str(&column_name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
	grant_column = column_hash_search(g_t,
					  column_name.ptr(),
					  column_name.length());
	if (privileges)
	{
	  int tmp_error;
	  if ((tmp_error=table->file->update_row(table->record[1],
						 table->record[0])))
	  {					/* purecov: deadcode */
	    table->file->print_error(tmp_error,MYF(0)); /* purecov: deadcode */
	    result= -1;				/* purecov: deadcode */
	    goto end;				/* purecov: deadcode */
	  }
	  if (grant_column)
	    grant_column->rights  = privileges; // Update hash
	}
	else
	{
	  int tmp_error;
	  if ((tmp_error = table->file->delete_row(table->record[1])))
	  {					/* purecov: deadcode */
	    table->file->print_error(tmp_error,MYF(0)); /* purecov: deadcode */
	    result= -1;				/* purecov: deadcode */
	    goto end;				/* purecov: deadcode */
	  }
	  if (grant_column)
	    hash_delete(&g_t->hash_columns,(byte*) grant_column);
	}
      }
    } while (!table->file->index_next(table->record[0]) &&
2126
	     !key_cmp_if_same(table,key,0,key_length));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2127 2128
  }

2129
end:
2130
  table->file->ha_index_end();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2131 2132 2133 2134 2135 2136 2137
  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,
2138 2139
			       ulong rights, ulong col_rights,
			       bool revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2140
{
2141
  char grantor[HOSTNAME_LENGTH+USERNAME_LENGTH+2];
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2142
  int old_row_exists = 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2143
  int error=0;
2144
  ulong store_table_rights, store_col_rights;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2145 2146
  DBUG_ENTER("replace_table_table");

2147
  strxmov(grantor, thd->user, "@", thd->host_or_ip, NullS);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2148

2149 2150 2151 2152
  /*
    The following should always succeed as new users are created before
    this function is called!
  */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2153 2154 2155 2156 2157 2158
  if (!find_acl_user(combo.host.str,combo.user.str))
  {
    my_error(ER_PASSWORD_NO_MATCH,MYF(0));	/* purecov: deadcode */
    DBUG_RETURN(-1);				/* purecov: deadcode */
  }

2159
  restore_record(table,default_values);			// Get empty record
2160 2161 2162 2163
  table->field[0]->store(combo.host.str,combo.host.length, &my_charset_latin1);
  table->field[1]->store(db,(uint) strlen(db), &my_charset_latin1);
  table->field[2]->store(combo.user.str,combo.user.length, &my_charset_latin1);
  table->field[3]->store(table_name,(uint) strlen(table_name), &my_charset_latin1);
2164
  store_record(table,record[1]);			// store at pos 1
2165
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2166
  if (table->file->index_read_idx(table->record[0],0,
2167 2168
				  (byte*) table->field[0]->ptr,
				  table->key_info[0].key_length,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2169 2170 2171 2172 2173 2174 2175 2176 2177
				  HA_READ_KEY_EXACT))
  {
    /*
      The following should never happen as we first check the in memory
      grant tables for the user.  There is however always a small change that
      the user has modified the grant tables directly.
    */
    if (revoke_grant)
    { // no row, no revoke
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2178 2179 2180
      my_error(ER_NONEXISTING_TABLE_GRANT, MYF(0),
               combo.user.str, combo.host.str,
               table_name);		/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2181 2182
      DBUG_RETURN(-1);				/* purecov: deadcode */
    }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2183
    old_row_exists = 0;
2184
    restore_record(table,record[1]);			// Get saved record
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2185 2186
  }

2187 2188
  store_table_rights= get_rights_for_table(rights);
  store_col_rights=   get_rights_for_column(col_rights);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2189
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2190
  {
2191
    ulong j,k;
2192
    store_record(table,record[1]);
2193 2194
    j = (ulong) table->field[6]->val_int();
    k = (ulong) table->field[7]->val_int();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2195 2196 2197

    if (revoke_grant)
    {
2198
      /* column rights are already fixed in mysql_table_grant */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2199 2200 2201 2202
      store_table_rights=j & ~store_table_rights;
    }
    else
    {
2203 2204
      store_table_rights|= j;
      store_col_rights|=   k;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2205 2206 2207
    }
  }

2208
  table->field[4]->store(grantor,(uint) strlen(grantor), &my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2209 2210 2211
  table->field[6]->store((longlong) store_table_rights);
  table->field[7]->store((longlong) store_col_rights);
  rights=fix_rights_for_table(store_table_rights);
2212
  col_rights=fix_rights_for_column(store_col_rights);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2213

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2214
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230
  {
    if (store_table_rights || store_col_rights)
    {
      if ((error=table->file->update_row(table->record[1],table->record[0])))
	goto table_error;			/* purecov: deadcode */
    }
    else if ((error = table->file->delete_row(table->record[1])))
      goto table_error;				/* purecov: deadcode */
  }
  else
  {
    error=table->file->write_row(table->record[0]);
    if (error && error != HA_ERR_FOUND_DUPP_KEY)
      goto table_error;				/* purecov: deadcode */
  }

2231
  if (rights | col_rights)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2232
  {
2233
    grant_table->privs= rights;
2234
    grant_table->cols=	col_rights;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2235 2236 2237
  }
  else
  {
2238
    hash_delete(&column_priv_hash,(byte*) grant_table);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2239 2240 2241
  }
  DBUG_RETURN(0);

2242 2243
  /* This should never happen */
table_error:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2244 2245 2246 2247 2248
  table->file->print_error(error,MYF(0)); /* purecov: deadcode */
  DBUG_RETURN(-1); /* purecov: deadcode */
}


2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265
/*
  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
    0	ok
    1	error
*/

2266 2267 2268 2269
int mysql_table_grant(THD *thd, TABLE_LIST *table_list,
		      List <LEX_USER> &user_list,
		      List <LEX_COLUMN> &columns, ulong rights,
		      bool revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2270
{
2271
  ulong column_priv= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2272 2273 2274
  List_iterator <LEX_USER> str_list (user_list);
  LEX_USER *Str;
  TABLE_LIST tables[3];
2275
  bool create_new_users=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2276 2277 2278 2279
  DBUG_ENTER("mysql_table_grant");

  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2280 2281 2282
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0),
             "--skip-grant-tables");	/* purecov: inspected */
    DBUG_RETURN(-1);				/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2283 2284 2285 2286 2287 2288 2289
  }
  if (rights & ~TABLE_ACLS)
  {
    my_error(ER_ILLEGAL_GRANT_FOR_TABLE,MYF(0));
    DBUG_RETURN(-1);
  }

2290
  if (!revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2291
  {
2292
    if (columns.elements && !revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2293
    {
2294 2295 2296 2297 2298 2299 2300
      TABLE *table;
      class LEX_COLUMN *column;
      List_iterator <LEX_COLUMN> column_iter(columns);

      if (!(table=open_ltable(thd,table_list,TL_READ)))
        DBUG_RETURN(-1);
      while ((column = column_iter++))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2301
      {
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
2302
        uint unused_field_idx= NO_CACHED_FIELD_INDEX;
2303
        Field *f= find_field_in_table(thd,table,column->column.ptr(),
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
2304
                              column->column.length(),1,0,&unused_field_idx);
2305 2306
        if (!f)
        {
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
2307 2308
          my_error(ER_BAD_FIELD_ERROR, MYF(0),
                   column->column.c_ptr(), table_list->alias);
2309 2310 2311 2312 2313 2314 2315
          DBUG_RETURN(-1);
        }
        if (f == (Field*)-1)
        {
          DBUG_RETURN(-1);
        }
        column_priv|= column->rights;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2316
      }
2317
      close_thread_tables(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2318
    }
2319
    else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2320
    {
2321 2322 2323 2324 2325 2326 2327 2328
      if (!(rights & CREATE_ACL))
      {
        char buf[FN_REFLEN];
        sprintf(buf,"%s/%s/%s.frm",mysql_data_home, table_list->db,
                table_list->real_name);
        fn_format(buf,buf,"","",4+16+32);
        if (access(buf,F_OK))
        {
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
2329
          my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->alias);
2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341
          DBUG_RETURN(-1);
        }
      }
      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),
	         command, thd->priv_user, thd->host_or_ip, table_list->alias);
        DBUG_RETURN(-1);
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2342 2343 2344 2345 2346 2347
    }
  }

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

  bzero((char*) &tables,sizeof(tables));
2348 2349 2350
  tables[0].alias=tables[0].real_name= (char*) "user";
  tables[1].alias=tables[1].real_name= (char*) "tables_priv";
  tables[2].alias=tables[2].real_name= (char*) "columns_priv";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2351 2352 2353 2354 2355 2356 2357 2358
  tables[0].next=tables+1;
  /* Don't open column table if we don't need it ! */
  tables[1].next=((column_priv ||
		   (revoke_grant && ((rights & COL_ACLS) || columns.elements)))
		  ? tables+2 : 0);
  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";

2359 2360 2361 2362 2363
#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
2364 2365
  if (thd->slave_thread && table_rules_on)
  {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2366 2367 2368
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
2369
    */
2370
    tables[0].updating= tables[1].updating= tables[2].updating= 1;
2371 2372 2373
    if (!tables_ok(0, tables))
      DBUG_RETURN(0);
  }
2374 2375
#endif

2376
  if (simple_open_n_lock_tables(thd,tables))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2377 2378 2379 2380 2381
  {						// Should never happen
    close_thread_tables(thd);			/* purecov: deadcode */
    DBUG_RETURN(-1);				/* purecov: deadcode */
  }

2382 2383
  if (!revoke_grant)
    create_new_users= test_if_create_new_users(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2384
  int result=0;
2385
  rw_wrlock(&LOCK_grant);
2386 2387
  MEM_ROOT *old_root= thd->mem_root;
  thd->mem_root= &memex;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2388 2389 2390

  while ((Str = str_list++))
  {
2391
    int error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2392 2393 2394 2395 2396 2397 2398 2399 2400
    GRANT_TABLE *grant_table;
    if (Str->host.length > HOSTNAME_LENGTH ||
	Str->user.length > USERNAME_LENGTH)
    {
      my_error(ER_GRANT_WRONG_HOST_OR_USER,MYF(0));
      result= -1;
      continue;
    }
    /* Create user if needed */
2401
    pthread_mutex_lock(&acl_cache->lock);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2402 2403
    error=replace_user_table(thd, tables[0].table, *Str,
			     0, revoke_grant, create_new_users);
2404 2405
    pthread_mutex_unlock(&acl_cache->lock);
    if (error)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2406 2407 2408 2409 2410 2411 2412 2413
    {
      result= -1;				// Remember error
      continue;					// Add next user
    }

    /* Find/create cached table grant */
    grant_table= table_hash_search(Str->host.str,NullS,table_list->db,
				   Str->user.str,
2414
				   table_list->real_name,1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2415 2416 2417 2418
    if (!grant_table)
    {
      if (revoke_grant)
      {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2419 2420
	my_error(ER_NONEXISTING_TABLE_GRANT, MYF(0),
                 Str->user.str, Str->host.str, table_list->real_name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2421 2422 2423 2424 2425
	result= -1;
	continue;
      }
      grant_table = new GRANT_TABLE (Str->host.str,table_list->db,
				     Str->user.str,
2426
				     table_list->real_name,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2427 2428 2429 2430 2431 2432 2433
				     rights,
				     column_priv);
      if (!grant_table)				// end of memory
      {
	result= -1;				/* purecov: deadcode */
	continue;				/* purecov: deadcode */
      }
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2434
      my_hash_insert(&column_priv_hash,(byte*) grant_table);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2435 2436 2437 2438 2439
    }

    /* If revoke_grant, calculate the new column privilege for tables_priv */
    if (revoke_grant)
    {
2440 2441
      class LEX_COLUMN *column;
      List_iterator <LEX_COLUMN> column_iter(columns);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2442 2443 2444
      GRANT_COLUMN *grant_column;

      /* Fix old grants */
2445
      while ((column = column_iter++))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2446 2447
      {
	grant_column = column_hash_search(grant_table,
2448 2449
					  column->column.ptr(),
					  column->column.length());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2450
	if (grant_column)
2451
	  grant_column->rights&= ~(column->rights | rights);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2452 2453
      }
      /* scan trough all columns to get new column grant */
2454
      column_priv= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472
      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 */

    if (replace_table_table(thd,grant_table,tables[1].table,*Str,
			    table_list->db,
2473
			    table_list->real_name,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2474
			    rights, column_priv, revoke_grant))
2475 2476
    {
      /* Should only happen if table is crashed */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2477 2478 2479 2480 2481 2482 2483
      result= -1;			       /* purecov: deadcode */
    }
    else if (tables[2].table)
    {
      if ((replace_column_table(grant_table,tables[2].table, *Str,
				columns,
				table_list->db,
2484
				table_list->real_name,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2485 2486 2487 2488 2489 2490 2491
				rights, revoke_grant)))
      {
	result= -1;
      }
    }
  }
  grant_option=TRUE;
2492
  thd->mem_root= old_root;
2493
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2494
  if (!result)
2495
    send_ok(thd);
2496
  /* Tables are automatically closed */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2497 2498 2499 2500
  DBUG_RETURN(result);
}


monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2501 2502
int mysql_grant(THD *thd, const char *db, List <LEX_USER> &list,
		ulong rights, bool revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2503 2504 2505
{
  List_iterator <LEX_USER> str_list (list);
  LEX_USER *Str;
2506
  char tmp_db[NAME_LEN+1];
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2507
  bool create_new_users=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2508 2509 2510 2511
  TABLE_LIST tables[2];
  DBUG_ENTER("mysql_grant");
  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2512 2513
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0),
             "--skip-grant-tables");	/* purecov: tested */
2514
    DBUG_RETURN(-1);				/* purecov: tested */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2515 2516
  }

2517 2518 2519
  if (lower_case_table_names && db)
  {
    strmov(tmp_db,db);
2520
    my_casedn_str(files_charset_info, tmp_db);
2521 2522
    db=tmp_db;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2523 2524

  /* open the mysql.user and mysql.db tables */
2525
  bzero((char*) &tables,sizeof(tables));
2526 2527
  tables[0].alias=tables[0].real_name=(char*) "user";
  tables[1].alias=tables[1].real_name=(char*) "db";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2528 2529 2530 2531 2532
  tables[0].next=tables+1;
  tables[1].next=0;
  tables[0].lock_type=tables[1].lock_type=TL_WRITE;
  tables[0].db=tables[1].db=(char*) "mysql";
  tables[0].table=tables[1].table=0;
2533 2534 2535 2536 2537 2538

#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
2539 2540
  if (thd->slave_thread && table_rules_on)
  {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2541 2542 2543
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
2544
    */
2545
    tables[0].updating= tables[1].updating= 1;
2546 2547 2548
    if (!tables_ok(0, tables))
      DBUG_RETURN(0);
  }
2549 2550
#endif

2551
  if (simple_open_n_lock_tables(thd,tables))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2552 2553 2554 2555 2556
  {						// This should never happen
    close_thread_tables(thd);			/* purecov: deadcode */
    DBUG_RETURN(-1);				/* purecov: deadcode */
  }

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2557 2558
  if (!revoke_grant)
    create_new_users= test_if_create_new_users(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2559

2560
  /* go through users in user_list */
2561
  rw_wrlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574
  VOID(pthread_mutex_lock(&acl_cache->lock));
  grant_version++;

  int result=0;
  while ((Str = str_list++))
  {
    if (Str->host.length > HOSTNAME_LENGTH ||
	Str->user.length > USERNAME_LENGTH)
    {
      my_error(ER_GRANT_WRONG_HOST_OR_USER,MYF(0));
      result= -1;
      continue;
    }
2575
    if ((replace_user_table(thd,
2576
			    tables[0].table,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2577
			    *Str,
2578 2579
			    (!db ? rights : 0), revoke_grant,
			    create_new_users)))
2580
      result= -1;
2581
    else if (db)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2582
    {
2583 2584 2585 2586 2587 2588 2589 2590 2591
      ulong db_rights= rights & DB_ACLS;
      if (db_rights  == rights)
      {
	if (replace_db_table(tables[1].table, db, *Str, db_rights,
			     revoke_grant))
	  result= -1;
      }
      else
      {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2592
	my_error(ER_WRONG_USAGE, MYF(0), "DB GRANT", "GLOBAL PRIVILEGES");
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2593
	result= -1;
2594
      }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2595
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2596 2597
  }
  VOID(pthread_mutex_unlock(&acl_cache->lock));
2598
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2599 2600 2601
  close_thread_tables(thd);

  if (!result)
2602
    send_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2603 2604 2605
  DBUG_RETURN(result);
}

2606 2607

/* Free grant array if possible */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2608 2609 2610 2611 2612

void  grant_free(void)
{
  DBUG_ENTER("grant_free");
  grant_option = FALSE;
2613
  hash_free(&column_priv_hash);
2614
  free_root(&memex,MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2615 2616 2617 2618 2619 2620
  DBUG_VOID_RETURN;
}


/* Init grant array if possible */

2621
my_bool grant_init(THD *org_thd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2622
{
2623
  THD  *thd;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2624
  TABLE_LIST tables[2];
2625
  MYSQL_LOCK *lock;
2626
  MEM_ROOT *memex_ptr;
2627
  my_bool return_val= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2628
  TABLE *t_table, *c_table;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2629
  bool check_no_resolve= specialflag & SPECIAL_NO_RESOLVE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2630 2631 2632
  DBUG_ENTER("grant_init");

  grant_option = FALSE;
2633
  (void) hash_init(&column_priv_hash,&my_charset_latin1,
2634
		   0,0,0, (hash_get_key) get_grant_table,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2635
		   (hash_free_key) free_grant_table,0);
2636
  init_sql_alloc(&memex, ACL_ALLOC_BLOCK_SIZE, 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2637

2638
  /* Don't do anything if running with --skip-grant */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2639 2640
  if (!initialized)
    DBUG_RETURN(0);				/* purecov: tested */
2641

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2642 2643
  if (!(thd=new THD))
    DBUG_RETURN(1);				/* purecov: deadcode */
2644
  thd->store_globals();
2645 2646
  thd->db= my_strdup("mysql",MYF(0));
  thd->db_length=5;				// Safety
2647
  bzero((char*) &tables, sizeof(tables));
2648 2649
  tables[0].alias=tables[0].real_name= (char*) "tables_priv";
  tables[1].alias=tables[1].real_name= (char*) "columns_priv";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2650 2651 2652 2653
  tables[0].next=tables+1;
  tables[0].lock_type=tables[1].lock_type=TL_READ;
  tables[0].db=tables[1].db=thd->db;

2654 2655
  uint counter;
  if (open_tables(thd, tables, &counter))
2656 2657
    goto end;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2658 2659 2660
  TABLE *ptr[2];				// Lock tables for quick update
  ptr[0]= tables[0].table;
  ptr[1]= tables[1].table;
2661
  if (! (lock= mysql_lock_tables(thd, ptr, 2, 0)))
2662
    goto end;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2663 2664

  t_table = tables[0].table; c_table = tables[1].table;
2665
  t_table->file->ha_index_init(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2666 2667
  if (t_table->file->index_first(t_table->record[0]))
  {
2668
    return_val= 0;
2669
    goto end_unlock;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2670
  }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2671
  grant_option= TRUE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2672

2673
  /* Will be restored by org_thd->store_globals() */
2674 2675
  memex_ptr= &memex;
  my_pthread_setspecific_ptr(THR_MALLOC, &memex_ptr);
2676
  do
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2677 2678
  {
    GRANT_TABLE *mem_check;
Sinisa@sinisa.nasamreza.org's avatar
Sinisa@sinisa.nasamreza.org committed
2679
    if (!(mem_check=new GRANT_TABLE(t_table,c_table)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2680 2681
    {
      /* This could only happen if we are out memory */
2682
      grant_option= FALSE;			/* purecov: deadcode */
2683
      goto end_unlock;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2684
    }
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2685 2686 2687

    if (check_no_resolve)
    {
2688
      if (hostname_requires_resolving(mem_check->host.hostname))
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2689
      {
serg@serg.mylan's avatar
serg@serg.mylan committed
2690 2691 2692 2693
        sql_print_warning("'tables_priv' entry '%s %s@%s' "
                          "ignored in --skip-name-resolve mode.",
                          mem_check->tname, mem_check->user,
                          mem_check->host, mem_check->host);
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2694 2695 2696 2697
	continue;
      }
    }

Sinisa@sinisa.nasamreza.org's avatar
Sinisa@sinisa.nasamreza.org committed
2698
    if (mem_check->ok() && my_hash_insert(&column_priv_hash,(byte*) mem_check))
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2699 2700 2701 2702
    {
      grant_option= FALSE;
      goto end_unlock;
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2703
  }
2704 2705 2706 2707 2708
  while (!t_table->file->index_next(t_table->record[0]));

  return_val=0;					// Return ok

end_unlock:
2709
  t_table->file->ha_index_end();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2710 2711
  mysql_unlock_tables(thd, lock);
  thd->version--;				// Force close to free memory
2712 2713

end:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2714 2715
  close_thread_tables(thd);
  delete thd;
2716 2717
  if (org_thd)
    org_thd->store_globals();
2718 2719 2720 2721 2722
  else
  {
    /* Remember that we don't have a THD */
    my_pthread_setspecific_ptr(THR_THD,  0);
  }
2723
  DBUG_RETURN(return_val);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2724 2725 2726
}


2727
/*
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2728
 Reload grant array (table and column privileges) if possible
2729 2730 2731

  SYNOPSIS
    grant_reload()
2732
    thd			Thread handler (can be NULL)
2733 2734 2735 2736

  NOTES
    Locked tables are checked by acl_init and doesn't have to be checked here
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2737

2738
void grant_reload(THD *thd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2739
{
2740 2741
  HASH old_column_priv_hash;
  bool old_grant_option;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2742 2743 2744
  MEM_ROOT old_mem;
  DBUG_ENTER("grant_reload");

2745
  rw_wrlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2746
  grant_version++;
2747
  old_column_priv_hash= column_priv_hash;
2748
  old_grant_option= grant_option;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2749
  old_mem= memex;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2750

2751
  if (grant_init(thd))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2752
  {						// Error. Revert to old hash
2753
    DBUG_PRINT("error",("Reverting to old privileges"));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2754
    grant_free();				/* purecov: deadcode */
2755
    column_priv_hash= old_column_priv_hash;	/* purecov: deadcode */
2756
    grant_option= old_grant_option;		/* purecov: deadcode */
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2757
    memex= old_mem;				/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2758 2759 2760
  }
  else
  {
2761
    hash_free(&old_column_priv_hash);
2762
    free_root(&old_mem,MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2763
  }
2764
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2765 2766 2767 2768 2769
  DBUG_VOID_RETURN;
}


/****************************************************************************
2770
  Check table level grants
2771
  All errors are written directly to the client if no_errors is given !
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2772 2773
****************************************************************************/

2774
bool check_grant(THD *thd, ulong want_access, TABLE_LIST *tables,
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2775
		 uint show_table, uint number, bool no_errors)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2776 2777 2778
{
  TABLE_LIST *table;
  char *user = thd->priv_user;
monty@mysql.com's avatar
monty@mysql.com committed
2779
  DBUG_ENTER("check_grant");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2780 2781 2782

  want_access &= ~thd->master_access;
  if (!want_access)
monty@mysql.com's avatar
monty@mysql.com committed
2783
    DBUG_RETURN(0);                             // ok
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2784

2785
  rw_rdlock(&LOCK_grant);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2786
  for (table= tables; table && number--; table= table->next)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2787
  {
2788
    if (!(~table->grant.privilege & want_access) || table->derived)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2789 2790 2791 2792
    {
      table->grant.want_privilege=0;
      continue;					// Already checked
    }
2793 2794
    GRANT_TABLE *grant_table = table_hash_search(thd->host,thd->ip,
						 table->db,user,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2795 2796 2797 2798 2799 2800
						 table->real_name,0);
    if (!grant_table)
    {
      want_access &= ~table->grant.privilege;
      goto err;					// No grants
    }
monty@tramp.mysql.fi's avatar
monty@tramp.mysql.fi committed
2801 2802
    if (show_table)
      continue;					// We have some priv on this
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818

    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
    }
  }
2819
  rw_unlock(&LOCK_grant);
monty@mysql.com's avatar
monty@mysql.com committed
2820
  DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2821

2822
err:
2823
  rw_unlock(&LOCK_grant);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2824
  if (!no_errors)				// Not a silent skip of table
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2825
  {
2826 2827
    char command[128];
    get_privilege_desc(command, sizeof(command), want_access);
2828
    net_printf(thd,ER_TABLEACCESS_DENIED_ERROR,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2829 2830
	       command,
	       thd->priv_user,
2831
	       thd->host_or_ip,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2832 2833
	       table ? table->real_name : "unknown");
  }
monty@mysql.com's avatar
monty@mysql.com committed
2834
  DBUG_RETURN(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2835 2836 2837
}


2838 2839
bool check_grant_column(THD *thd,TABLE *table, const char *name,
			uint length, uint show_tables)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2840 2841 2842 2843
{
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;

2844
  ulong want_access=table->grant.want_privilege;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2845 2846 2847
  if (!want_access)
    return 0;					// Already checked

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

2850
  /* reload table if someone has modified any grants */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2851 2852 2853 2854

  if (table->grant.version != grant_version)
  {
    table->grant.grant_table=
2855
      table_hash_search(thd->host, thd->ip, table->table_cache_key,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2856
			thd->priv_user,
2857
			table->real_name, 0);	/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2858 2859 2860 2861 2862 2863 2864 2865
    table->grant.version=grant_version;		/* purecov: inspected */
  }
  if (!(grant_table=table->grant.grant_table))
    goto err;					/* purecov: deadcode */

  grant_column=column_hash_search(grant_table, name, length);
  if (grant_column && !(~grant_column->rights & want_access))
  {
2866
    rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2867 2868 2869 2870 2871
    return 0;
  }
#ifdef NOT_USED
  if (show_tables && (grant_column || table->grant.privilege & COL_ACLS))
  {
2872
    rw_unlock(&LOCK_grant);			/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2873 2874 2875 2876 2877
    return 0;					/* purecov: deadcode */
  }
#endif

  /* We must use my_printf_error() here! */
2878
err:
2879
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2880 2881
  if (!show_tables)
  {
2882 2883
    char command[128];
    get_privilege_desc(command, sizeof(command), want_access);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2884 2885 2886 2887 2888
    my_printf_error(ER_COLUMNACCESS_DENIED_ERROR,
		    ER(ER_COLUMNACCESS_DENIED_ERROR),
		    MYF(0),
		    command,
		    thd->priv_user,
2889
		    thd->host_or_ip,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2890 2891 2892 2893 2894 2895 2896
		    name,
		    table ? table->real_name : "unknown");
  }
  return 1;
}


2897
bool check_grant_all_columns(THD *thd, ulong want_access, TABLE *table)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2898 2899 2900 2901 2902 2903 2904
{
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;
  Field *field=0,**ptr;

  want_access &= ~table->grant.privilege;
  if (!want_access)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2905
    return 0;				// Already checked
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2906
  if (!grant_option)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2907 2908
  {
    field= table->field[0];		// To give a meaningful error message
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2909
    goto err2;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2910
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2911

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

2914
  /* reload table if someone has modified any grants */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2915 2916 2917 2918

  if (table->grant.version != grant_version)
  {
    table->grant.grant_table=
2919
      table_hash_search(thd->host, thd->ip, table->table_cache_key,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2920 2921 2922 2923
			thd->priv_user,
			table->real_name,0);	/* purecov: inspected */
    table->grant.version=grant_version;		/* purecov: inspected */
  }
2924
  /* The following should always be true */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2925 2926 2927 2928 2929 2930
  if (!(grant_table=table->grant.grant_table))
    goto err;					/* purecov: inspected */

  for (ptr=table->field; (field= *ptr) ; ptr++)
  {
    grant_column=column_hash_search(grant_table, field->field_name,
2931
				    (uint) strlen(field->field_name));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2932 2933 2934
    if (!grant_column || (~grant_column->rights & want_access))
      goto err;
  }
2935
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2936 2937 2938
  return 0;

  /* We must use my_printf_error() here! */
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2939
err:
2940
  rw_unlock(&LOCK_grant);
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2941
err2:
2942 2943
  char command[128];
  get_privilege_desc(command, sizeof(command), want_access);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2944 2945 2946 2947 2948
  my_printf_error(ER_COLUMNACCESS_DENIED_ERROR,
		  ER(ER_COLUMNACCESS_DENIED_ERROR),
		  MYF(0),
		  command,
		  thd->priv_user,
2949
		  thd->host_or_ip,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2950 2951 2952 2953 2954 2955
		  field ? field->field_name : "unknown",
		  table->real_name);
  return 1;
}


2956
/*
2957 2958 2959
  Check if a user has the right to access a database
  Access is accepted if he has a grant for any table in the database
  Return 1 if access is denied
2960
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2961 2962 2963 2964 2965 2966 2967 2968

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

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

2971
  for (uint idx=0 ; idx < column_priv_hash.records ; idx++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2972
  {
2973 2974
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  idx);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2975 2976
    if (len < grant_table->key_length &&
	!memcmp(grant_table->hash_key,helping,len) &&
2977
        compare_hostname(&grant_table->host, thd->host, thd->ip))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2978 2979 2980 2981 2982
    {
      error=0;					// Found match
      break;
    }
  }
2983
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2984 2985 2986 2987
  return error;
}

/*****************************************************************************
2988
  Functions to retrieve the grant for a table/column  (for SHOW functions)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2989 2990
*****************************************************************************/

2991
ulong get_table_grant(THD *thd, TABLE_LIST *table)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2992
{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2993
  ulong privilege;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2994 2995 2996 2997
  char *user = thd->priv_user;
  const char *db = table->db ? table->db : thd->db;
  GRANT_TABLE *grant_table;

2998
  rw_rdlock(&LOCK_grant);
2999 3000 3001
#ifdef EMBEDDED_LIBRARY
  grant_table= NULL;
#else
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3002 3003
  grant_table= table_hash_search(thd->host, thd->ip, db, user,
				 table->real_name, 0);
3004
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3005 3006 3007 3008
  table->grant.grant_table=grant_table; // Remember for column test
  table->grant.version=grant_version;
  if (grant_table)
    table->grant.privilege|= grant_table->privs;
3009
  privilege= table->grant.privilege;
3010
  rw_unlock(&LOCK_grant);
3011
  return privilege;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3012 3013 3014
}


3015
ulong get_column_grant(THD *thd, TABLE_LIST *table, Field *field)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3016 3017 3018
{
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;
3019
  ulong priv;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3020

3021
  rw_rdlock(&LOCK_grant);
3022
  /* reload table if someone has modified any grants */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3023 3024 3025
  if (table->grant.version != grant_version)
  {
    table->grant.grant_table=
3026
      table_hash_search(thd->host, thd->ip, table->db,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3027 3028 3029 3030 3031 3032 3033 3034 3035 3036
			thd->priv_user,
			table->real_name,0);	/* purecov: inspected */
    table->grant.version=grant_version;		/* purecov: inspected */
  }

  if (!(grant_table=table->grant.grant_table))
    priv=table->grant.privilege;
  else
  {
    grant_column=column_hash_search(grant_table, field->field_name,
3037
				    (uint) strlen(field->field_name));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3038 3039 3040 3041 3042
    if (!grant_column)
      priv=table->grant.privilege;
    else
      priv=table->grant.privilege | grant_column->rights;
  }
3043
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3044 3045 3046
  return priv;
}

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

3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060
static void add_user_option(String *grant, ulong value, const char *name)
{
  if (value)
  {
    char buff[22], *p; // just as in int2str
    grant->append(' ');
    grant->append(name, strlen(name));
    grant->append(' ');
    p=int10_to_str(value, buff, 10);
    grant->append(buff,p-buff);
  }
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3061 3062

static const char *command_array[]=
3063 3064 3065 3066 3067 3068
{
  "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",
};
3069

3070 3071 3072 3073 3074
static uint command_lengths[]=
{
  6,6,6,6,6,4,6,8,7,4,5,10,5,5,14,5,23,11,7,17,18
};

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

3076 3077 3078 3079 3080 3081 3082
/*
  SHOW GRANTS;  Send grants for a user to the client

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

peter@mysql.com's avatar
peter@mysql.com committed
3083
int mysql_show_grants(THD *thd,LEX_USER *lex_user)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3084
{
3085 3086
  ulong want_access;
  uint counter,index;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3087
  int  error = 0;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3088 3089
  ACL_USER *acl_user;
  ACL_DB *acl_db;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3090
  char buff[1024];
3091
  Protocol *protocol= thd->protocol;
tonu@x153.internalnet's avatar
tonu@x153.internalnet committed
3092
  DBUG_ENTER("mysql_show_grants");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3093 3094 3095 3096

  LINT_INIT(acl_user);
  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3097 3098
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
    DBUG_RETURN(-1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3099
  }
monty@mysql.com's avatar
monty@mysql.com committed
3100 3101 3102 3103 3104 3105

  if (!lex_user->host.str)
  {
    lex_user->host.str= (char*) "%";
    lex_user->host.length=1;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117
  if (lex_user->host.length > HOSTNAME_LENGTH ||
      lex_user->user.length > USERNAME_LENGTH)
  {
    my_error(ER_GRANT_WRONG_HOST_OR_USER,MYF(0));
    DBUG_RETURN(-1);
  }

  for (counter=0 ; counter < acl_users.elements ; counter++)
  {
    const char *user,*host;
    acl_user=dynamic_element(&acl_users,counter,ACL_USER*);
    if (!(user=acl_user->user))
monty@mysql.com's avatar
monty@mysql.com committed
3118
      user= "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3119
    if (!(host=acl_user->host.hostname))
monty@mysql.com's avatar
monty@mysql.com committed
3120
      host= "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3121
    if (!strcmp(lex_user->user.str,user) &&
3122
	!my_strcasecmp(&my_charset_latin1, lex_user->host.str, host))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3123 3124
      break;
  }
peter@mysql.com's avatar
peter@mysql.com committed
3125
  if (counter == acl_users.elements)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3126
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3127 3128
    my_error(ER_NONEXISTING_GRANT, MYF(0),
             lex_user->user.str, lex_user->host.str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3129 3130 3131
    DBUG_RETURN(-1);
  }

3132
  Item_string *field=new Item_string("",0,&my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3133 3134 3135 3136 3137 3138
  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);
3139
  if (protocol->send_fields(&field_list,1))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3140 3141
    DBUG_RETURN(-1);

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3142
  rw_wrlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3143 3144 3145 3146
  VOID(pthread_mutex_lock(&acl_cache->lock));

  /* Add first global access grants */
  {
3147
    String global(buff,sizeof(buff),system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3148 3149 3150
    global.length(0);
    global.append("GRANT ",6);

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3151
    want_access= acl_user->access;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3152 3153 3154 3155
    if (test_all_bits(want_access, (GLOBAL_ACLS & ~ GRANT_ACL)))
      global.append("ALL PRIVILEGES",14);
    else if (!(want_access & ~GRANT_ACL))
      global.append("USAGE",5);
peter@mysql.com's avatar
peter@mysql.com committed
3156
    else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3157 3158
    {
      bool found=0;
3159
      ulong j,test_access= want_access & ~GRANT_ACL;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3160 3161
      for (counter=0, j = SELECT_ACL;j <= GLOBAL_ACLS;counter++,j <<= 1)
      {
peter@mysql.com's avatar
peter@mysql.com committed
3162
	if (test_access & j)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3163 3164 3165 3166 3167 3168 3169 3170 3171
	{
	  if (found)
	    global.append(", ",2);
	  found=1;
	  global.append(command_array[counter],command_lengths[counter]);
	}
      }
    }
    global.append (" ON *.* TO '",12);
3172 3173
    global.append(lex_user->user.str, lex_user->user.length,
		  system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3174 3175 3176
    global.append ("'@'",3);
    global.append(lex_user->host.str,lex_user->host.length);
    global.append ('\'');
3177
    if (acl_user->salt_len)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3178
    {
3179 3180 3181 3182 3183
      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);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3184
      global.append(" IDENTIFIED BY PASSWORD '",25);
3185
      global.append(passwd_buff);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3186 3187
      global.append('\'');
    }
3188 3189
    /* "show grants" SSL related stuff */
    if (acl_user->ssl_type == SSL_TYPE_ANY)
3190
      global.append(" REQUIRE SSL",12);
3191
    else if (acl_user->ssl_type == SSL_TYPE_X509)
3192
      global.append(" REQUIRE X509",13);
3193
    else if (acl_user->ssl_type == SSL_TYPE_SPECIFIED)
3194
    {
3195
      int ssl_options = 0;
3196
      global.append(" REQUIRE ",9);
3197 3198
      if (acl_user->x509_issuer)
      {
3199 3200 3201
	ssl_options++;
	global.append("ISSUER \'",8);
	global.append(acl_user->x509_issuer,strlen(acl_user->x509_issuer));
3202
	global.append('\'');
3203
      }
3204 3205
      if (acl_user->x509_subject)
      {
3206 3207 3208 3209
	if (ssl_options++)
	  global.append(' ');
	global.append("SUBJECT \'",9);
	global.append(acl_user->x509_subject,strlen(acl_user->x509_subject));
3210
	global.append('\'');
tonu@x153.internalnet's avatar
tonu@x153.internalnet committed
3211
      }
3212 3213
      if (acl_user->ssl_cipher)
      {
3214 3215 3216 3217
	if (ssl_options++)
	  global.append(' ');
	global.append("CIPHER '",8);
	global.append(acl_user->ssl_cipher,strlen(acl_user->ssl_cipher));
3218
	global.append('\'');
3219 3220
      }
    }
3221 3222 3223
    if ((want_access & GRANT_ACL) ||
	(acl_user->user_resource.questions | acl_user->user_resource.updates |
	 acl_user->user_resource.connections))
3224
    {
peter@mysql.com's avatar
peter@mysql.com committed
3225
      global.append(" WITH",5);
3226
      if (want_access & GRANT_ACL)
peter@mysql.com's avatar
peter@mysql.com committed
3227
	global.append(" GRANT OPTION",13);
3228 3229 3230 3231 3232 3233
      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");
      add_user_option(&global, acl_user->user_resource.connections,
		      "MAX_CONNECTIONS_PER_HOUR");
3234
    }
3235
    protocol->prepare_for_resend();
3236
    protocol->store(global.ptr(),global.length(),global.charset());
3237
    if (protocol->write())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3238
    {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3239
      error= -1;
3240
      goto end;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3241 3242 3243 3244 3245 3246
    }
  }

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

    acl_db=dynamic_element(&acl_dbs,counter,ACL_DB*);
    if (!(user=acl_db->user))
monty@mysql.com's avatar
monty@mysql.com committed
3251
      user= "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3252
    if (!(host=acl_db->host.hostname))
monty@mysql.com's avatar
monty@mysql.com committed
3253
      host= "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3254 3255

    if (!strcmp(lex_user->user.str,user) &&
3256
	!my_strcasecmp(&my_charset_latin1, lex_user->host.str, host))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3257 3258
    {
      want_access=acl_db->access;
peter@mysql.com's avatar
peter@mysql.com committed
3259
      if (want_access)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3260
      {
3261
	String db(buff,sizeof(buff),system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3262 3263 3264 3265 3266
	db.length(0);
	db.append("GRANT ",6);

	if (test_all_bits(want_access,(DB_ACLS & ~GRANT_ACL)))
	  db.append("ALL PRIVILEGES",14);
3267
	else if (!(want_access & ~GRANT_ACL))
3268
	  db.append("USAGE",5);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3269 3270 3271
	else
	{
	  int found=0, cnt;
3272
	  ulong j,test_access= want_access & ~GRANT_ACL;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283
	  for (cnt=0, j = SELECT_ACL; j <= DB_ACLS; cnt++,j <<= 1)
	  {
	    if (test_access & j)
	    {
	      if (found)
		db.append(", ",2);
	      found = 1;
	      db.append(command_array[cnt],command_lengths[cnt]);
	    }
	  }
	}
3284 3285 3286
	db.append (" ON ",4);
	append_identifier(thd, &db, acl_db->db, strlen(acl_db->db));
	db.append (".* TO '",7);
3287 3288
	db.append(lex_user->user.str, lex_user->user.length,
		  system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3289 3290
	db.append ("'@'",3);
	db.append(lex_user->host.str, lex_user->host.length);
peter@mysql.com's avatar
peter@mysql.com committed
3291
	db.append ('\'');
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3292
	if (want_access & GRANT_ACL)
3293
	  db.append(" WITH GRANT OPTION",18);
3294
	protocol->prepare_for_resend();
3295
	protocol->store(db.ptr(),db.length(),db.charset());
3296
	if (protocol->write())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3297
	{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3298
	  error= -1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3299 3300 3301 3302 3303 3304
	  goto end;
	}
      }
    }
  }

3305
  /* Add table & column access */
3306
  for (index=0 ; index < column_priv_hash.records ; index++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3307
  {
monty@mysql.com's avatar
monty@mysql.com committed
3308
    const char *user;
3309 3310
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  index);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3311 3312

    if (!(user=grant_table->user))
3313
      user= "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3314 3315

    if (!strcmp(lex_user->user.str,user) &&
monty@mysql.com's avatar
monty@mysql.com committed
3316
	!my_strcasecmp(&my_charset_latin1, lex_user->host.str,
3317
                       grant_table->host.hostname))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3318
    {
3319 3320
      ulong table_access= grant_table->privs;
      if ((table_access | grant_table->cols) != 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3321
      {
3322
	String global(buff, sizeof(buff), system_charset_info);
3323 3324
	ulong test_access= (table_access | grant_table->cols) & ~GRANT_ACL;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3325 3326 3327
	global.length(0);
	global.append("GRANT ",6);

3328
	if (test_all_bits(table_access, (TABLE_ACLS & ~GRANT_ACL)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3329
	  global.append("ALL PRIVILEGES",14);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3330
	else if (!test_access)
3331
 	  global.append("USAGE",5);
peter@mysql.com's avatar
peter@mysql.com committed
3332
	else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3333
	{
3334
          /* Add specific column access */
3335
	  int found= 0;
3336
	  ulong j;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3337

3338
	  for (counter= 0, j= SELECT_ACL; j <= TABLE_ACLS; counter++, j<<= 1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3339
	  {
peter@mysql.com's avatar
peter@mysql.com committed
3340
	    if (test_access & j)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3341 3342 3343
	    {
	      if (found)
		global.append(", ",2);
3344
	      found= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3345 3346
	      global.append(command_array[counter],command_lengths[counter]);

peter@mysql.com's avatar
peter@mysql.com committed
3347
	      if (grant_table->cols)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3348
	      {
3349
		uint found_col= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3350 3351 3352 3353 3354 3355
		for (uint col_index=0 ;
		     col_index < grant_table->hash_columns.records ;
		     col_index++)
		{
		  GRANT_COLUMN *grant_column = (GRANT_COLUMN*)
		    hash_element(&grant_table->hash_columns,col_index);
peter@mysql.com's avatar
peter@mysql.com committed
3356
		  if (grant_column->rights & j)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3357
		  {
peter@mysql.com's avatar
peter@mysql.com committed
3358
		    if (!found_col)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3359
		    {
3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370
		      found_col= 1;
		      /*
			If we have a duplicated table level privilege, we
			must write the access privilege name again.
		      */
		      if (table_access & j)
		      {
			global.append(", ", 2);
			global.append(command_array[counter],
				      command_lengths[counter]);
		      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3371 3372 3373 3374 3375
		      global.append(" (",2);
		    }
		    else
		      global.append(", ",2);
		    global.append(grant_column->column,
3376 3377
				  grant_column->key_length,
				  system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3378 3379 3380 3381 3382 3383 3384 3385
		  }
		}
		if (found_col)
		  global.append(')');
	      }
	    }
	  }
	}
3386 3387 3388 3389 3390 3391 3392
	global.append(" ON ",4);
	append_identifier(thd, &global, grant_table->db,
			  strlen(grant_table->db));
	global.append('.');
	append_identifier(thd, &global, grant_table->tname,
			  strlen(grant_table->tname));
	global.append(" TO '",5);
3393 3394
	global.append(lex_user->user.str, lex_user->user.length,
		      system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3395
	global.append("'@'",3);
peter@mysql.com's avatar
peter@mysql.com committed
3396
	global.append(lex_user->host.str,lex_user->host.length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3397
	global.append('\'');
3398
	if (table_access & GRANT_ACL)
peter@mysql.com's avatar
peter@mysql.com committed
3399
	  global.append(" WITH GRANT OPTION",18);
3400
	protocol->prepare_for_resend();
3401
	protocol->store(global.ptr(),global.length(),global.charset());
3402
	if (protocol->write())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3403
	{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3404
	  error= -1;
3405
	  break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3406 3407 3408 3409
	}
      }
    }
  }
3410
end:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3411
  VOID(pthread_mutex_unlock(&acl_cache->lock));
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3412
  rw_unlock(&LOCK_grant);
3413

3414
  send_eof(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3415 3416 3417 3418
  DBUG_RETURN(error);
}


3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446
/*
  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;
}


3447
void get_mqh(const char *user, const char *host, USER_CONN *uc)
3448 3449
{
  ACL_USER *acl_user;
3450 3451 3452 3453
  if (initialized && (acl_user= find_acl_user(host,user)))
    uc->user_resources= acl_user->user_resource;
  else
    bzero((char*) &uc->user_resources, sizeof(uc->user_resources));
3454 3455
}

3456 3457 3458 3459 3460 3461
int open_grant_tables(THD *thd, TABLE_LIST *tables)
{
  DBUG_ENTER("open_grant_tables");

  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3462
    net_printf(thd,ER_OPTION_PREVENTS_STATEMENT, "--skip-grant-tables");
3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483
    DBUG_RETURN(-1);
  }

  bzero((char*) tables, 4*sizeof(*tables));
  tables->alias= tables->real_name= (char*) "user";
  (tables+1)->alias= (tables+1)->real_name= (char*) "db";
  (tables+2)->alias= (tables+2)->real_name= (char*) "tables_priv";
  (tables+3)->alias= (tables+3)->real_name= (char*) "columns_priv";
  tables->next= tables+1;
  (tables+1)->next= tables+2;
  (tables+2)->next= tables+3;
  (tables+3)->next= 0;
  tables->lock_type= (tables+1)->lock_type=
    (tables+2)->lock_type= (tables+3)->lock_type= TL_WRITE;
  tables->db= (tables+1)->db= (tables+2)->db= (tables+3)->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.
  */
3484 3485
  if (thd->slave_thread && table_rules_on)
  {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3486 3487 3488
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
3489 3490 3491 3492 3493 3494
    */
    tables[0].updating=tables[1].updating=tables[2].updating=tables[3].updating=1;
    if (!tables_ok(0, tables))
      DBUG_RETURN(1);
    tables[0].updating=tables[1].updating=tables[2].updating=tables[3].updating=0;
  }
3495 3496
#endif

3497
  if (simple_open_n_lock_tables(thd, tables))
3498 3499 3500 3501 3502 3503 3504 3505 3506
  {						// This should never happen
    close_thread_tables(thd);
    DBUG_RETURN(-1);
  }

  DBUG_RETURN(0);
}

ACL_USER *check_acl_user(LEX_USER *user_name,
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
3507
			 uint *acl_acl_userdx)
3508 3509 3510 3511 3512 3513 3514 3515 3516
{
  ACL_USER *acl_user= 0;
  uint counter;

  for (counter= 0 ; counter < acl_users.elements ; counter++)
  {
    const char *user,*host;
    acl_user= dynamic_element(&acl_users, counter, ACL_USER*);
    if (!(user=acl_user->user))
monty@mysql.com's avatar
monty@mysql.com committed
3517
      user= "";
3518
    if (!(host=acl_user->host.hostname))
monty@mysql.com's avatar
monty@mysql.com committed
3519
      host= "%";
3520 3521 3522 3523 3524 3525 3526
    if (!strcmp(user_name->user.str,user) &&
	!my_strcasecmp(system_charset_info, user_name->host.str, host))
      break;
  }
  if (counter == acl_users.elements)
    return 0;

monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
3527
  *acl_acl_userdx= counter;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3528
  return acl_user;
3529 3530
}

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

3532 3533
int mysql_drop_user(THD *thd, List <LEX_USER> &list)
{
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
3534
  uint counter, acl_userd;
3535 3536 3537 3538 3539 3540 3541 3542
  int result;
  ACL_USER *acl_user;
  ACL_DB *acl_db;
  TABLE_LIST tables[4];

  DBUG_ENTER("mysql_drop_user");

  if ((result= open_grant_tables(thd, tables)))
3543
    DBUG_RETURN(result == 1 ? 0 : 1);
3544 3545 3546 3547 3548 3549 3550 3551 3552 3553

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

  LEX_USER *user_name;
  List_iterator <LEX_USER> user_list(list);
  while ((user_name=user_list++))
  {
    if (!(acl_user= check_acl_user(user_name, &counter)))
    {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3554
      sql_print_error("DROP USER: Can't drop user: '%s'@'%s'; No such user",
3555 3556 3557 3558 3559 3560 3561
		      user_name->user.str,
		      user_name->host.str);
      result= -1;
      continue;
    }
    if ((acl_user->access & ~0))
    {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3562
      sql_print_error("DROP USER: Can't drop user: '%s'@'%s'; Global privileges exists",
3563 3564 3565 3566 3567
		      user_name->user.str,
		      user_name->host.str);
      result= -1;
      continue;
    }
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
3568
    acl_userd= counter;
3569 3570 3571 3572 3573 3574

    for (counter= 0 ; counter < acl_dbs.elements ; counter++)
    {
      const char *user,*host;
      acl_db=dynamic_element(&acl_dbs,counter,ACL_DB*);
      if (!(user= acl_db->user))
monty@mysql.com's avatar
monty@mysql.com committed
3575
	user= "";
3576
      if (!(host= acl_db->host.hostname))
monty@mysql.com's avatar
monty@mysql.com committed
3577
	host= "";
3578 3579 3580 3581 3582 3583 3584

      if (!strcmp(user_name->user.str,user) &&
	  !my_strcasecmp(system_charset_info, user_name->host.str, host))
	break;
    }
    if (counter != acl_dbs.elements)
    {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3585
      sql_print_error("DROP USER: Can't drop user: '%s'@'%s'; Database privileges exists",
3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597
		      user_name->user.str,
		      user_name->host.str);
      result= -1;
      continue;
    }

    for (counter= 0 ; counter < column_priv_hash.records ; counter++)
    {
      const char *user,*host;
      GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							    counter);
      if (!(user=grant_table->user))
monty@mysql.com's avatar
monty@mysql.com committed
3598
	user= "";
3599
      if (!(host=grant_table->host.hostname))
monty@mysql.com's avatar
monty@mysql.com committed
3600
	host= "";
3601 3602 3603 3604 3605 3606 3607

      if (!strcmp(user_name->user.str,user) &&
	  !my_strcasecmp(system_charset_info, user_name->host.str, host))
	break;
    }
    if (counter != column_priv_hash.records)
    {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3608
      sql_print_error("DROP USER: Can't drop user: '%s'@'%s';  Table privileges exists",
3609 3610 3611 3612 3613 3614
		      user_name->user.str,
		      user_name->host.str);
      result= -1;
      continue;
    }

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3615
    tables[0].table->field[0]->store(user_name->host.str,(uint)
3616 3617
				     user_name->host.length,
				     system_charset_info);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3618
    tables[0].table->field[1]->store(user_name->user.str,(uint)
3619 3620
				     user_name->user.length,
				     system_charset_info);
3621
    tables[0].table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
3622
    if (!tables[0].table->file->index_read_idx(tables[0].table->record[0],0,
3623
					       (byte*) tables[0].table->
3624 3625 3626
					       field[0]->ptr,
					       tables[0].table->
					       key_info[0].key_length,
3627 3628 3629
					       HA_READ_KEY_EXACT))
    {
      int error;
3630 3631
      if ((error = tables[0].table->file->delete_row(tables[0].table->
						     record[0])))
3632 3633 3634 3635
      {
	tables[0].table->file->print_error(error, MYF(0));
	DBUG_RETURN(-1);
      }
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
3636
      delete_dynamic_element(&acl_users, acl_userd);
3637 3638
    }
  }
3639

3640 3641 3642 3643 3644 3645 3646 3647 3648 3649
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
  if (result)
    my_error(ER_DROP_USER, MYF(0));
  DBUG_RETURN(result);
}

int mysql_revoke_all(THD *thd,  List <LEX_USER> &list)
{
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3650
  uint counter, revoked;
3651
  int result;
3652
  ACL_DB *acl_db;
3653 3654 3655 3656
  TABLE_LIST tables[4];
  DBUG_ENTER("mysql_revoke_all");

  if ((result= open_grant_tables(thd, tables)))
3657
    DBUG_RETURN(result == 1 ? 0 : 1);
3658 3659 3660 3661 3662 3663 3664 3665

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

  LEX_USER *lex_user;
  List_iterator <LEX_USER> user_list(list);
  while ((lex_user=user_list++))
  {
3666
    if (!check_acl_user(lex_user, &counter))
3667 3668 3669 3670 3671 3672 3673
    {
      sql_print_error("REVOKE ALL PRIVILEGES, GRANT: User '%s'@'%s' not exists",
		      lex_user->user.str,
		      lex_user->host.str);
      result= -1;
      continue;
    }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3674

3675 3676 3677 3678 3679 3680 3681 3682
    if (replace_user_table(thd, tables[0].table,
			   *lex_user, ~0, 1, 0))
    {
      result= -1;
      continue;
    }

    /* Remove db access privileges */
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3683 3684 3685 3686 3687
    /*
      Because acl_dbs and column_priv_hash shrink and may re-order
      as privileges are removed, removal occurs in a repeated loop
      until no more privileges are revoked.
     */
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3688
    do
3689
    {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3690
      for (counter= 0, revoked= 0 ; counter < acl_dbs.elements ; )
3691
      {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702
	const char *user,*host;
	
	acl_db=dynamic_element(&acl_dbs,counter,ACL_DB*);
	if (!(user=acl_db->user))
	  user= "";
	if (!(host=acl_db->host.hostname))
	  host= "";
	
	if (!strcmp(lex_user->user.str,user) &&
	    !my_strcasecmp(system_charset_info, lex_user->host.str, host))
	{
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3703
	  if (!replace_db_table(tables[1].table, acl_db->db, *lex_user, ~0, 1))
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3704
	  {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3705 3706 3707 3708 3709
	    /*
	      Don't increment counter as replace_db_table deleted the
	      current element in acl_dbs.
	     */
	    revoked= 1;
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3710 3711
	    continue;
	  }
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3712
	  result= -1; // Something went wrong
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3713
	}
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3714
	counter++;
3715
      }
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3716
    } while (revoked);
3717 3718

    /* Remove column access */
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3719
    do
3720
    {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3721
      for (counter= 0, revoked= 0 ; counter < column_priv_hash.records ; )
3722
      {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3723 3724 3725 3726 3727
	const char *user,*host;
	GRANT_TABLE *grant_table= (GRANT_TABLE*)hash_element(&column_priv_hash,
							     counter);
	if (!(user=grant_table->user))
	  user= "";
3728
	if (!(host=grant_table->host.hostname))
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3729 3730 3731 3732
	  host= "";
	
	if (!strcmp(lex_user->user.str,user) &&
	    !my_strcasecmp(system_charset_info, lex_user->host.str, host))
3733
	{
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3734 3735 3736 3737
	  if (replace_table_table(thd,grant_table,tables[2].table,*lex_user,
				  grant_table->db,
				  grant_table->tname,
				  ~0, 0, 1))
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3738
	  {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3739
	    result= -1;
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3740
	  }
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3741
	  else
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3742
	  {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3743
	    if (!grant_table->cols)
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3744
	    {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3745 3746
	      revoked= 1;
	      continue;
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3747
	    }
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3748 3749
	    List<LEX_COLUMN> columns;
	    if (!replace_column_table(grant_table,tables[3].table, *lex_user,
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3750 3751 3752 3753
				      columns,
				      grant_table->db,
				      grant_table->tname,
				      ~0, 1))
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3754
	    {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3755
	      revoked= 1;
3756
	      continue;
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3757
	    }
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3758
	    result= -1;
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3759
	  }
3760
	}
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3761
	counter++;
3762
      }
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3763
    } while (revoked);
3764
  }
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3765
  
3766 3767 3768
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3769
  
3770 3771
  if (result)
    my_error(ER_REVOKE_GRANTS, MYF(0));
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
3772
  
3773 3774
  DBUG_RETURN(result);
}
3775

3776

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3777
/*****************************************************************************
3778
  Instantiate used templates
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3779 3780 3781 3782 3783 3784 3785 3786
*****************************************************************************/

#ifdef __GNUC__
template class List_iterator<LEX_COLUMN>;
template class List_iterator<LEX_USER>;
template class List<LEX_COLUMN>;
template class List<LEX_USER>;
#endif
hf@deer.(none)'s avatar
hf@deer.(none) committed
3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833

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