sql_acl.cc 104 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 30
   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 "sql_acl.h"
#include "hash_filo.h"
31 32 33
#ifdef HAVE_REPLICATION
#include "sql_repl.h" //for tables_ok()
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
34 35 36
#include <m_ctype.h>
#include <stdarg.h>

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

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

47

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

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

static DYNAMIC_ARRAY acl_hosts,acl_users,acl_dbs;
static MEM_ROOT mem, memex;
static bool initialized=0;
static bool allow_all_hosts=1;
62
static HASH acl_check_hosts, column_priv_hash;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
63 64 65
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
66
static uint priv_version=0; /* Version of priv tables. incremented by acl_init */
67
static ulong get_access(TABLE *form,uint fieldnr);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
68 69 70 71 72
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,
73
			      const char *new_password, uint new_password_len);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
74
static void update_hostname(acl_host_and_ip *host, const char *hostname);
75
static bool compare_hostname(const acl_host_and_ip *host,const char *hostname,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
76 77
			     const char *ip);

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

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

119

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

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

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


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

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)))
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
    host.access= get_access(table,2);
    host.access= fix_rights_for_db(host.access);
203
    host.sort=	 get_sort(2,host.host.hostname,host.db);
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
204 205
    if (check_no_resolve && hostname_requires_resolving(host.host.hostname))
    {
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
206 207
      sql_print_error("Warning: 'host' entry '%s|%s' "
		      "ignored in --skip-name-resolve mode.",
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
208 209 210
		      host.host.hostname, host.db, host.host.hostname);
      continue;
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
211 212 213 214
#ifndef TO_BE_REMOVED
    if (table->fields ==  8)
    {						// Without grant
      if (host.access & CREATE_ACL)
215
	host.access|=REFERENCES_ACL | INDEX_ACL | ALTER_ACL | CREATE_TMP_ACL;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
216 217 218 219 220 221 222 223 224 225
    }
#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);
226
  VOID(my_init_dynamic_array(&acl_users,sizeof(ACL_USER),50,100));
227
  if (table->field[2]->field_length < SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
228
  {
229 230 231
    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
232 233
  }

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
266 267 268 269
  allow_all_hosts=0;
  while (!(read_record_info.read_record(&read_record_info)))
  {
    ACL_USER user;
270 271
    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
272 273
    if (check_no_resolve && hostname_requires_resolving(user.host.hostname))
    {
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
274 275
      sql_print_error("Warning: 'user' entry '%s@%s' "
		      "ignored in --skip-name-resolve mode.",
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
276 277 278 279
		      user.user, user.host.hostname, user.host.hostname);
      continue;
    }

280 281 282 283
    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
284
    {
285 286
      switch (password_len) {
      case 45: /* 4.1: to be removed */
287
        sql_print_error("Found 4.1 style password for user '%s@%s'. "
288 289
                        "Ignoring user. "
                        "You should change password for this user.",
290 291
                        user.user ? user.user : "",
                        user.host.hostname ? user.host.hostname : "");
292 293 294 295 296 297 298
        break;
      default:
        sql_print_error("Found invalid password for user: '%s@%s'; "
                        "Ignoring user", user.user ? user.user : "",
                        user.host.hostname ? user.host.hostname : "");
        break;
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
299
    }
300
    else                                        // password is correct
bk@work.mysql.com's avatar
bk@work.mysql.com committed
301
    {
302 303 304 305
      user.access= get_access(table,3) & GLOBAL_ACLS;
      user.sort= get_sort(2,user.host.hostname,user.user);
      user.hostname_length= (user.host.hostname ?
                             (uint) strlen(user.host.hostname) : 0);
306
      if (table->fields >= 31)	 /* Starting from 4.0.2 we have more fields */
307
      {
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
        char *ssl_type=get_field(&mem, table->field[24]);
        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;

        user.ssl_cipher=   get_field(&mem, table->field[25]);
        user.x509_issuer=  get_field(&mem, table->field[26]);
        user.x509_subject= get_field(&mem, table->field[27]);

        char *ptr = get_field(&mem, table->field[28]);
        user.user_resource.questions=atoi(ptr);
        ptr = get_field(&mem, table->field[29]);
        user.user_resource.updates=atoi(ptr);
        ptr = get_field(&mem, table->field[30]);
        user.user_resource.connections=atoi(ptr);
        if (user.user_resource.questions || user.user_resource.updates ||
            user.user_resource.connections)
          mqh_used=1;
331
      }
332 333 334
      else
      {
        user.ssl_type=SSL_TYPE_NONE;
335
        bzero((char *)&(user.user_resource),sizeof(user.user_resource));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
336
#ifndef TO_BE_REMOVED
337 338 339 340 341 342 343 344 345 346 347
        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
348
#endif
349 350 351 352 353
      }
      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
354
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
355 356 357 358 359
  }
  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
360

bk@work.mysql.com's avatar
bk@work.mysql.com committed
361
  init_read_record(&read_record_info,thd,table=tables[2].table,NULL,1,0);
362
  VOID(my_init_dynamic_array(&acl_dbs,sizeof(ACL_DB),50,100));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
363 364 365
  while (!(read_record_info.read_record(&read_record_info)))
  {
    ACL_DB db;
366 367
    update_hostname(&db.host,get_field(&mem, table->field[0]));
    db.db=get_field(&mem, table->field[1]);
368 369 370
    if (!db.db)
    {
      sql_print_error("Found an entry in the 'db' table with empty database name; Skipped");
371
      continue;
372
    }
373
    db.user=get_field(&mem, table->field[2]);
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
374 375
    if (check_no_resolve && hostname_requires_resolving(db.host.hostname))
    {
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
376 377
      sql_print_error("Warning: 'db' entry '%s %s@%s' "
		      "ignored in --skip-name-resolve mode.",
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
378 379 380
		      db.db, db.user, db.host.hostname, db.host.hostname);
      continue;
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
    db.access=get_access(table,3);
    db.access=fix_rights_for_db(db.access);
    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);
400
  initialized=1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
401
  thd->version--;				// Force close to free memory
402 403 404
  return_val=0;

end:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
405 406
  close_thread_tables(thd);
  delete thd;
407 408
  if (org_thd)
    org_thd->store_globals();			/* purecov: inspected */
409 410 411 412 413
  else
  {
    /* Remember that we don't have a THD */
    my_pthread_setspecific_ptr(THR_THD,  0);
  }
414
  DBUG_RETURN(return_val);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
415 416 417 418 419
}


void acl_free(bool end)
{
420
  free_root(&mem,MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
421 422 423 424 425 426 427 428 429 430 431 432 433 434
  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;
  }
}

435 436 437 438 439 440 441 442

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

  SYNOPSIS
    acl_reload()
    thd			Thread handle
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
443

444
void acl_reload(THD *thd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
445 446 447 448 449 450
{
  DYNAMIC_ARRAY old_acl_hosts,old_acl_users,old_acl_dbs;
  MEM_ROOT old_mem;
  bool old_initialized;
  DBUG_ENTER("acl_reload");

451
  if (thd && thd->locked_tables)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
452
  {					// Can't have locked tables here
453 454 455
    thd->lock=thd->locked_tables;
    thd->locked_tables=0;
    close_thread_tables(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
456 457 458 459 460 461 462 463 464 465 466
  }
  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);

467
  if (acl_init(thd, 0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
468
  {					// Error. Revert to old list
469
    DBUG_PRINT("error",("Reverting to old privileges"));
470
    acl_free();				/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
471 472 473 474 475 476 477 478
    acl_hosts=old_acl_hosts;
    acl_users=old_acl_users;
    acl_dbs=old_acl_dbs;
    mem=old_mem;
    init_check_host();
  }
  else
  {
479
    free_root(&old_mem,MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
480 481 482 483 484 485 486 487 488 489
    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;
}


490 491 492 493 494
/*
  Get all access bits from table after fieldnr
  We know that the access privileges ends when there is no more fields
  or the field is not an enum with two elements.
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
495

496
static ulong get_access(TABLE *form, uint fieldnr)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
497
{
498
  ulong access_bits=0,bit;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
499
  char buff[2];
500
  String res(buff,sizeof(buff),&my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
501 502
  Field **pos;

503 504 505 506
  for (pos=form->field+fieldnr, bit=1;
       *pos && (*pos)->real_type() == FIELD_TYPE_ENUM &&
	 ((Field_enum*) (*pos))->typelib->count == 2 ;
       pos++ , bit<<=1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
507
  {
508
    (*pos)->val_str(&res);
509
    if (my_toupper(&my_charset_latin1, res[0]) == 'Y')
510
      access_bits|= bit;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
511 512 513 514 515 516
  }
  return access_bits;
}


/*
517 518 519 520 521
  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
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559

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

  while (count--)
  {
    char *str=va_arg(args,char*);
    uint chars=0,wild=0;

    if (str)
    {
      for (; *str ; str++)
      {
	if (*str == wild_many || *str == wild_one || *str == wild_prefix)
	  wild++;
	else
	  chars++;
      }
    }
    sort= (sort << 8) + (wild ? 1 : chars ? 2 : 0);
  }
  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;
}

560

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

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
565 566 567 568
  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
569

570
  SYNOPSIS
571 572 573 574 575 576 577 578 579 580 581 582 583 584
    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
585
  RETURN VALUE
586 587
    0  success: thd->priv_user, thd->priv_host, thd->master_access, mqh are
       updated
588
    1  user not found or authentification failure
589
    2  user found, has long (4.1.1) salt, but passwd is in old (3.23) format.
590
   -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
591 592
*/

593 594
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
595
{
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
596 597 598
  ulong user_access= NO_ACCESS;
  int res= 1;
  ACL_USER *acl_user= 0;
599
  DBUG_ENTER("acl_getroot");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
600 601

  if (!initialized)
602
  {
603 604 605 606 607 608
    /* 
      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
609
    bzero((char*) mqh, sizeof(*mqh));
610
    DBUG_RETURN(0);
611
  }
612

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
615
  /*
616 617 618
    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
619
  */
peter@mysql.com's avatar
peter@mysql.com committed
620

621
  for (uint i=0 ; i < acl_users.elements ; i++)
622
  {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
623 624
    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
625
    {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
626
      if (compare_hostname(&acl_user_tmp->host, thd->host, thd->ip))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
627
      {
628
        /* check password: it should be empty or valid */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
629
        if (passwd_len == acl_user_tmp->salt_len)
peter@mysql.com's avatar
peter@mysql.com committed
630
        {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
631 632 633
          if (acl_user_tmp->salt_len == 0 ||
              acl_user_tmp->salt_len == SCRAMBLE_LENGTH &&
              check_scramble(passwd, thd->scramble, acl_user_tmp->salt) == 0 ||
634
              check_scramble_323(passwd, thd->scramble,
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
635
                                 (ulong *) acl_user_tmp->salt) == 0)
636
          {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
637
            acl_user= acl_user_tmp;
638 639
            res= 0;
          }
peter@mysql.com's avatar
peter@mysql.com committed
640
        }
641
        else if (passwd_len == SCRAMBLE_LENGTH &&
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
642
                 acl_user_tmp->salt_len == SCRAMBLE_LENGTH_323)
643
          res= -1;
644
        else if (passwd_len == SCRAMBLE_LENGTH_323 &&
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
645
                 acl_user_tmp->salt_len == SCRAMBLE_LENGTH)
646
          res= 2;
647 648
        /* linear search complete: */
        break;
peter@mysql.com's avatar
peter@mysql.com committed
649
      }
peter@mysql.com's avatar
peter@mysql.com committed
650
    }
651
  }
652 653 654 655
  /*
    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
656 657 658

  if (acl_user)
  {
659
    /* OK. User found and password checked continue validation */
660
#ifdef HAVE_OPENSSL
661
    Vio *vio=thd->net.vio;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
662
    SSL *ssl= (SSL*) vio->ssl_arg;
663
#endif
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
664

665
    /*
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
666
      At this point we know that user is allowed to connect
667 668 669 670 671 672
      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
673 674
    case SSL_TYPE_NONE:				// SSL is not required
      user_access= acl_user->access;
675
      break;
676
#ifdef HAVE_OPENSSL
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
677
    case SSL_TYPE_ANY:				// Any kind of SSL is ok
678
      if (vio_type(vio) == VIO_TYPE_SSL)
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
679
	user_access= acl_user->access;
680 681 682 683 684
      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
685

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
686 687
	We need to check for absence of SSL because without SSL
	we should reject connection.
688
      */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
689
      if (vio_type(vio) == VIO_TYPE_SSL &&
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
690 691
	  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
692
	user_access= acl_user->access;
693 694 695 696 697 698 699 700
      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
701
      X509 *cert;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
702
      if (vio_type(vio) != VIO_TYPE_SSL ||
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
703
	  SSL_get_verify_result(ssl) != X509_V_OK)
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
704
	break;
705
      if (acl_user->ssl_cipher)
peter@mysql.com's avatar
peter@mysql.com committed
706
      {
707
	DBUG_PRINT("info",("comparing ciphers: '%s' and '%s'",
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
708 709
			   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
710
	  user_access= acl_user->access;
711 712
	else
	{
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
713 714 715
	  if (global_system_variables.log_warnings)
	    sql_print_error("X509 ciphers mismatch: should be '%s' but is '%s'",
			    acl_user->ssl_cipher,
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
716
			    SSL_get_cipher(ssl));
717 718
	  break;
	}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
719
      }
720 721
      /* Prepare certificate (if exists) */
      DBUG_PRINT("info",("checkpoint 1"));
monty@mysql.com's avatar
monty@mysql.com committed
722 723 724 725 726
      if (!(cert= SSL_get_peer_certificate(ssl)))
      {
	user_access=NO_ACCESS;
	break;
      }
727 728 729
      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
730
      {
kostja@oak.local's avatar
kostja@oak.local committed
731
        DBUG_PRINT("info",("checkpoint 3"));
732 733 734
	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
735
        if (strcmp(acl_user->x509_issuer, ptr))
736
        {
kostja@oak.local's avatar
kostja@oak.local committed
737 738
          if (global_system_variables.log_warnings)
            sql_print_error("X509 issuer mismatch: should be '%s' "
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
739
			    "but is '%s'", acl_user->x509_issuer, ptr);
740
          free(ptr);
kostja@oak.local's avatar
kostja@oak.local committed
741
          break;
742
        }
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
743
        user_access= acl_user->access;
kostja@oak.local's avatar
kostja@oak.local committed
744
        free(ptr);
peter@mysql.com's avatar
peter@mysql.com committed
745
      }
746 747 748 749
      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
750 751 752 753
        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))
754
        {
kostja@oak.local's avatar
kostja@oak.local committed
755 756 757
          if (global_system_variables.log_warnings)
            sql_print_error("X509 subject mismatch: '%s' vs '%s'",
                            acl_user->x509_subject, ptr);
758
        }
kostja@oak.local's avatar
kostja@oak.local committed
759
        else
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
760
          user_access= acl_user->access;
kostja@oak.local's avatar
kostja@oak.local committed
761
        free(ptr);
762 763
      }
      break;
peter@mysql.com's avatar
peter@mysql.com committed
764
#else  /* HAVE_OPENSSL */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
765
    default:
766
      /*
kostja@oak.local's avatar
kostja@oak.local committed
767 768 769
        If we don't have SSL but SSL is required for this user the 
        authentication should fail.
      */
770 771
      break;
#endif /* HAVE_OPENSSL */
peter@mysql.com's avatar
peter@mysql.com committed
772
    }
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
773
    thd->master_access= user_access;
774 775
    thd->priv_user= acl_user->user ? thd->user : (char *) "";
    *mqh= acl_user->user_resource;
776

777 778 779 780 781
    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
782
  VOID(pthread_mutex_unlock(&acl_cache->lock));
783
  DBUG_RETURN(res);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
784 785 786 787 788 789 790 791 792 793
}


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

794

bk@work.mysql.com's avatar
bk@work.mysql.com committed
795
static void acl_update_user(const char *user, const char *host,
796
			    const char *password, uint password_len,
797 798 799 800
			    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
801
			    USER_RESOURCES  *mqh,
802
			    ulong privileges)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
803 804 805 806 807 808 809 810 811
{
  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] ||
812
	  acl_user->host.hostname &&
813
	  !my_strcasecmp(&my_charset_latin1, host, acl_user->host.hostname))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
814 815
      {
	acl_user->access=privileges;
816
	if (mqh->bits & 1)
817
	  acl_user->user_resource.questions=mqh->questions;
818
	if (mqh->bits & 2)
819
	  acl_user->user_resource.updates=mqh->updates;
820
	if (mqh->bits & 4)
821
	  acl_user->user_resource.connections=mqh->connections;
822 823 824 825 826 827 828 829 830 831
	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);
	}
832 833
	if (password)
	  set_user_salt(acl_user, password, password_len);
834
        /* search complete: */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
835 836 837 838 839 840 841 842
	break;
      }
    }
  }
}


static void acl_insert_user(const char *user, const char *host,
843
			    const char *password, uint password_len,
844 845 846 847
			    enum SSL_type ssl_type,
			    const char *ssl_cipher,
			    const char *x509_issuer,
			    const char *x509_subject,
848
			    USER_RESOURCES *mqh,
849
			    ulong privileges)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
850 851
{
  ACL_USER acl_user;
852
  acl_user.user=*user ? strdup_root(&mem,user) : 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
853 854
  update_hostname(&acl_user.host,strdup_root(&mem,host));
  acl_user.access=privileges;
855
  acl_user.user_resource = *mqh;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
856
  acl_user.sort=get_sort(2,acl_user.host.hostname,acl_user.user);
857
  acl_user.hostname_length=(uint) strlen(acl_user.host.hostname);
858 859 860 861 862
  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;
863 864

  set_user_salt(&acl_user, password, password_len);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
865 866 867 868

  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
869
    allow_all_hosts=1;		// Anyone can connect /* purecov: tested */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
870 871 872 873 874 875 876 877 878 879 880
  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,
881
			  ulong privileges)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
882 883 884 885 886 887 888 889 890
{
  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] ||
891
	  acl_db->host.hostname &&
892
	  !my_strcasecmp(&my_charset_latin1, host, acl_db->host.hostname))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
      {
	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);
	}
      }
    }
  }
}


908 909 910 911 912 913 914 915 916 917 918 919 920 921
/*
  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
922
static void acl_insert_db(const char *user, const char *host, const char *db,
923
			  ulong privileges)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
924 925
{
  ACL_DB acl_db;
926
  safe_mutex_assert_owner(&acl_cache->lock);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
927 928 929 930 931 932 933 934 935 936 937
  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);
}


938 939 940 941

/*
  Get privilege for a host, user and db combination
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
942

943
ulong acl_get(const char *host, const char *ip,
944
	     const char *user, const char *db, my_bool db_is_pattern)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
945
{
946 947
  ulong host_access,db_access;
  uint i,key_length;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
948
  db_access=0; host_access= ~0;
949
  char key[ACL_KEY_LENGTH],*tmp_db,*end;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
950 951 952
  acl_entry *entry;

  VOID(pthread_mutex_lock(&acl_cache->lock));
953
  end=strmov((tmp_db=strmov(strmov(key, ip ? ip : "")+1,user)+1),db);
954 955
  if (lower_case_table_names)
  {
956
    my_casedn_str(&my_charset_latin1, tmp_db);
957 958
    db=tmp_db;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
  key_length=(uint) (end-key);
  if ((entry=(acl_entry*) acl_cache->search(key,key_length)))
  {
    db_access=entry->access;
    VOID(pthread_mutex_unlock(&acl_cache->lock));
    return db_access;
  }

  /*
    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))
      {
977
	if (!acl_db->db || !wild_compare(db,acl_db->db,db_is_pattern))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
	{
	  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))
    {
999
      if (!acl_host->db || !wild_compare(db,acl_host->db,db_is_pattern))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
      {
	host_access=acl_host->access;		// Fully specified. Take it
	break;
      }
    }
  }
exit:
  /* Save entry in cache for quick retrieval */
  if ((entry= (acl_entry*) malloc(sizeof(acl_entry)+key_length)))
  {
    entry->access=(db_access & host_access);
    entry->length=key_length;
    memcpy((gptr) entry->key,key,key_length);
    acl_cache->add(entry);
  }
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  return (db_access & host_access);
}

1019 1020 1021 1022 1023 1024 1025
/*
  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
1026 1027 1028 1029

static void init_check_host(void)
{
  DBUG_ENTER("init_check_host");
1030
  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
1031
			  acl_users.elements,1));
1032
  VOID(hash_init(&acl_check_hosts,&my_charset_latin1,acl_users.elements,0,0,
1033
		 (hash_get_key) check_get_key,0,0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
  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 *);
1048
	  if (!my_strcasecmp(&my_charset_latin1,
1049
                             acl_user->host.hostname, acl->hostname))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1050 1051 1052 1053 1054 1055
	    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,
1056
			    (uint) strlen(acl_user->host.hostname)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1057
      {
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1058
	if (my_hash_insert(&acl_check_hosts,(byte*) acl_user))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
	{					// 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));

1080 1081
  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
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
  {
    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
}


1100 1101 1102 1103 1104 1105 1106 1107
/*
  Check if the user is allowed to change password

  SYNOPSIS:
    check_change_password()
    thd		THD
    host	hostname for the user
    user	user name
monty@hundin.mysql.fi's avatar
merge  
monty@hundin.mysql.fi committed
1108

1109
    RETURN VALUE
1110 1111
      0		OK
      1		ERROR  ; In this case the error is sent to the client.
1112 1113 1114 1115
*/

bool check_change_password(THD *thd, const char *host, const char *user)
{
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1116 1117
  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
1118 1119
    net_printf(thd,ER_OPTION_PREVENTS_STATEMENT,
             "--skip-grant-tables"); /* purecov: inspected */
1120
    return(1);                             /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1121
  }
1122 1123
  if (!thd->slave_thread &&
      (strcmp(thd->user,user) ||
1124
       my_strcasecmp(&my_charset_latin1, host, thd->host_or_ip)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1125
  {
hf@deer.(none)'s avatar
hf@deer.(none) committed
1126
    if (check_access(thd, UPDATE_ACL, "mysql",0,1,0))
1127
      return(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1128
  }
1129 1130
  if (!thd->slave_thread && !thd->user[0])
  {
1131
    send_error(thd, ER_PASSWORD_ANONYMOUS_USER);
1132
    return(1);
1133
  }
1134 1135 1136 1137
  return(0);
}


1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
/*
  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
1151
*/
1152

1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
bool change_password(THD *thd, const char *host, const char *user,
		     char *new_password)
{
  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

  if (check_change_password(thd, host, user))
    DBUG_RETURN(1);

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1164 1165
  VOID(pthread_mutex_lock(&acl_cache->lock));
  ACL_USER *acl_user;
1166
  if (!(acl_user= find_acl_user(host, user)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1167 1168
  {
    VOID(pthread_mutex_unlock(&acl_cache->lock));
1169
    send_error(thd, ER_PASSWORD_NO_MATCH);
1170
    DBUG_RETURN(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1171
  }
1172 1173 1174 1175
  /* update loaded acl entry: */
  uint new_password_len= new_password ? strlen(new_password) : 0;
  set_user_salt(acl_user, new_password, new_password_len);

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1176 1177
  if (update_user_table(thd,
			acl_user->host.hostname ? acl_user->host.hostname : "",
1178
			acl_user->user ? acl_user->user : "",
1179
			new_password, new_password_len))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1180 1181
  {
    VOID(pthread_mutex_unlock(&acl_cache->lock)); /* purecov: deadcode */
1182
    send_error(thd,0); /* purecov: deadcode */
1183
    DBUG_RETURN(1); /* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1184
  }
peter@mysql.com's avatar
peter@mysql.com committed
1185

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

1189
  char buff[512]; /* Extend with extended password length*/
1190
  ulong query_length=
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1191 1192
    my_sprintf(buff,
	       (buff,"SET PASSWORD FOR \"%-.120s\"@\"%-.120s\"=\"%-.120s\"",
1193
		acl_user->user ? acl_user->user : "",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1194 1195
		acl_user->host.hostname ? acl_user->host.hostname : "",
		new_password));
guilhem@mysql.com's avatar
guilhem@mysql.com committed
1196
  thd->clear_error();
1197
  mysql_update_log.write(thd, buff, query_length);
1198
  Query_log_event qinfo(thd, buff, query_length, 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1199
  mysql_bin_log.write(&qinfo);
1200
  DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
}


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

static ACL_USER *
find_acl_user(const char *host, const char *user)
{
1211
  DBUG_ENTER("find_acl_user");
1212
  DBUG_PRINT("enter",("host: '%s'  user: '%s'",host,user));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1213 1214 1215
  for (uint i=0 ; i < acl_users.elements ; i++)
  {
    ACL_USER *acl_user=dynamic_element(&acl_users,i,ACL_USER*);
1216
    DBUG_PRINT("info",("strcmp('%s','%s'), compare_hostname('%s','%s'),",
1217 1218 1219 1220 1221
		       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
1222 1223 1224
    if (!acl_user->user && !user[0] ||
	acl_user->user && !strcmp(user,acl_user->user))
    {
1225
      if (compare_hostname(&acl_user->host,host,host))
1226 1227 1228
      {
	DBUG_RETURN(acl_user);
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1229 1230
    }
  }
1231
  DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1232 1233 1234
}


1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
/*
  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
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268

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!
1269
  if (!hostname ||
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1270 1271 1272
      (!(hostname=calc_ip(hostname,&host->ip,'/')) ||
       !(hostname=calc_ip(hostname+1,&host->ip_mask,'\0'))))
  {
1273
    host->ip= host->ip_mask=0;			// Not a masked ip
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
  }
}


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 ||
1287
	  (hostname && !wild_case_compare(&my_charset_latin1,
1288
                                          hostname,host->hostname)) ||
1289
	  (ip && !wild_compare(ip,host->hostname,0)));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1290 1291
}

hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1292 1293 1294 1295
bool hostname_requires_resolving(const char *hostname)
{
  char cur;
  if (!hostname)
monty@mysql.com's avatar
monty@mysql.com committed
1296
    return FALSE;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1297 1298 1299 1300 1301
  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
1302
    return FALSE;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1303 1304 1305 1306
  for (; (cur=*hostname); hostname++)
  {
    if ((cur != '%') && (cur != '_') && (cur != '.') &&
	((cur < '0') || (cur > '9')))
monty@mysql.com's avatar
monty@mysql.com committed
1307
      return TRUE;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1308
  }
monty@mysql.com's avatar
monty@mysql.com committed
1309
  return FALSE;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1310
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1311

1312 1313 1314
/*
  Update grants in the user and database privilege tables
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1315 1316

static bool update_user_table(THD *thd, const char *host, const char *user,
1317
			      const char *new_password, uint new_password_len)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1318 1319 1320 1321 1322 1323 1324 1325
{
  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));
1326
  tables.alias=tables.real_name=(char*) "user";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1327
  tables.db=(char*) "mysql";
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1328

1329 1330 1331 1332 1333 1334 1335
#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
1336 1337 1338
    /*
      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.
1339
    */
1340
    tables.updating= 1;
1341 1342 1343 1344 1345 1346
    /* 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
1347 1348
  if (!(table=open_ltable(thd,&tables,TL_WRITE)))
    DBUG_RETURN(1); /* purecov: deadcode */
1349 1350
  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
1351 1352 1353 1354 1355 1356 1357 1358

  if (table->file->index_read_idx(table->record[0],0,
				  (byte*) table->field[0]->ptr,0,
				  HA_READ_KEY_EXACT))
  {
    my_error(ER_PASSWORD_NO_MATCH,MYF(0));	/* purecov: deadcode */
    DBUG_RETURN(1);				/* purecov: deadcode */
  }
1359
  store_record(table,record[1]);
1360
  table->field[2]->store(new_password, new_password_len, &my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
  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
1373 1374 1375 1376 1377 1378 1379 1380 1381

/* 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;
1382
    ulong db_access;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1383 1384
    bzero((char*) &tl,sizeof(tl));
    tl.db=	   (char*) "mysql";
1385
    tl.real_name=  (char*) "user";
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1386

1387
    db_access=acl_get(thd->host, thd->ip,
1388
		      thd->priv_user, tl.db, 0);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1389 1390
    if (!(db_access & INSERT_ACL))
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1391
      if (check_grant(thd, INSERT_ACL, &tl, 0, UINT_MAX, 1))
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1392 1393 1394 1395 1396 1397 1398
	create_new_users=0;
    }
  }
  return create_new_users;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
1399
/****************************************************************************
1400
  Handle GRANT commands
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1401 1402
****************************************************************************/

1403
static int replace_user_table(THD *thd, TABLE *table, const LEX_USER &combo,
1404 1405
			      ulong rights, bool revoke_grant,
			      bool create_user)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1406 1407
{
  int error = -1;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1408
  bool old_row_exists=0;
1409
  const char *password= "";
1410
  uint password_len= 0;
1411
  char what= (revoke_grant) ? 'N' : 'Y';
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1412
  DBUG_ENTER("replace_user_table");
1413
  safe_mutex_assert_owner(&acl_cache->lock);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1414 1415

  if (combo.password.str && combo.password.str[0])
1416
  {
1417 1418
    if (combo.password.length != SCRAMBLED_PASSWORD_CHAR_LENGTH &&
        combo.password.length != SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
1419
    {
1420
      my_printf_error(ER_PASSWORD_NO_MATCH,
1421 1422
                      "Password hash should be a %d-digit hexadecimal number",
                      MYF(0), SCRAMBLED_PASSWORD_CHAR_LENGTH);
1423
      DBUG_RETURN(-1);
1424
    }
1425
    password_len= combo.password.length;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1426
    password=combo.password.str;
1427
  }
peter@mysql.com's avatar
peter@mysql.com committed
1428

1429 1430
  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);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1431 1432 1433 1434 1435
  table->file->index_init(0);
  if (table->file->index_read(table->record[0],
			      (byte*) table->field[0]->ptr,0,
			      HA_READ_KEY_EXACT))
  {
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1436
    if (!create_user)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1437
    {
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1438
      if (what == 'N')
guilhem@mysql.com's avatar
guilhem@mysql.com committed
1439
	my_error(ER_NONEXISTING_GRANT, MYF(0), combo.user.str, combo.host.str);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1440
      else
guilhem@mysql.com's avatar
guilhem@mysql.com committed
1441 1442
	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
1443 1444 1445
      error= -1;
      goto end;
    }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1446
    old_row_exists = 0;
1447 1448 1449 1450 1451 1452 1453
    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
1454 1455 1456
  }
  else
  {
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1457
    old_row_exists = 1;
1458
    store_record(table,record[1]);			// Save copy for update
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1459
    if (combo.password.str)			// If password given
1460
      table->field[2]->store(password, password_len, &my_charset_latin1);
1461 1462 1463 1464 1465
    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
1466 1467
  }

1468 1469 1470 1471 1472 1473 1474 1475
  /* Update table columns with new privileges */

  Field **tmp_field;
  ulong priv;
  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
1476
  {
1477
    if (priv & rights)				 // set requested privileges
1478
      (*tmp_field)->store(&what, 1, &my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1479 1480
  }
  rights=get_access(table,3);
1481
  DBUG_PRINT("info",("table->fields: %d",table->fields));
1482
  if (table->fields >= 31)		/* From 4.0.0 we have more fields */
1483
  {
1484
    /* We write down SSL related ACL stuff */
1485
    switch (thd->lex->ssl_type) {
1486
    case SSL_TYPE_ANY:
1487 1488 1489 1490
      table->field[24]->store("ANY",3, &my_charset_latin1);
      table->field[25]->store("", 0, &my_charset_latin1);
      table->field[26]->store("", 0, &my_charset_latin1);
      table->field[27]->store("", 0, &my_charset_latin1);
1491 1492
      break;
    case SSL_TYPE_X509:
1493 1494 1495 1496
      table->field[24]->store("X509",4, &my_charset_latin1);
      table->field[25]->store("", 0, &my_charset_latin1);
      table->field[26]->store("", 0, &my_charset_latin1);
      table->field[27]->store("", 0, &my_charset_latin1);
1497 1498
      break;
    case SSL_TYPE_SPECIFIED:
1499 1500 1501 1502
      table->field[24]->store("SPECIFIED",9, &my_charset_latin1);
      table->field[25]->store("", 0, &my_charset_latin1);
      table->field[26]->store("", 0, &my_charset_latin1);
      table->field[27]->store("", 0, &my_charset_latin1);
1503 1504 1505 1506 1507 1508 1509 1510 1511
      if (thd->lex->ssl_cipher)
	table->field[25]->store(thd->lex->ssl_cipher,
				strlen(thd->lex->ssl_cipher), &my_charset_latin1);
      if (thd->lex->x509_issuer)
	table->field[26]->store(thd->lex->x509_issuer,
				strlen(thd->lex->x509_issuer), &my_charset_latin1);
      if (thd->lex->x509_subject)
	table->field[27]->store(thd->lex->x509_subject,
				strlen(thd->lex->x509_subject), &my_charset_latin1);
1512
      break;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1513
    case SSL_TYPE_NOT_SPECIFIED:
gluh@gluh.(none)'s avatar
gluh@gluh.(none) committed
1514 1515
      break;
    case SSL_TYPE_NONE:
1516 1517 1518 1519
      table->field[24]->store("", 0, &my_charset_latin1);
      table->field[25]->store("", 0, &my_charset_latin1);
      table->field[26]->store("", 0, &my_charset_latin1);
      table->field[27]->store("", 0, &my_charset_latin1);
gluh@gluh.(none)'s avatar
gluh@gluh.(none) committed
1520
      break;
1521
    }
1522

1523
    USER_RESOURCES mqh= thd->lex->mqh;
1524
    if (mqh.bits & 1)
1525
      table->field[28]->store((longlong) mqh.questions);
1526
    if (mqh.bits & 2)
1527
      table->field[29]->store((longlong) mqh.updates);
1528
    if (mqh.bits & 4)
1529
      table->field[30]->store((longlong) mqh.connections);
1530
    mqh_used = mqh_used || mqh.questions || mqh.updates || mqh.connections;
1531
  }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1532
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1533 1534 1535 1536 1537
  {
    /*
      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!
    */
1538
    if (cmp_record(table,record[1]) &&
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
	(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

1558
end:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1559 1560 1561
  if (!error)
  {
    acl_cache->clear(1);			// Clear privilege cache
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1562
    if (old_row_exists)
1563 1564
      acl_update_user(combo.user.str, combo.host.str,
                      combo.password.str, password_len,
1565 1566 1567 1568 1569
		      thd->lex->ssl_type,
		      thd->lex->ssl_cipher,
		      thd->lex->x509_issuer,
		      thd->lex->x509_subject,
		      &thd->lex->mqh,
1570
		      rights);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1571
    else
1572
      acl_insert_user(combo.user.str, combo.host.str, password, password_len,
1573 1574 1575 1576 1577
		      thd->lex->ssl_type,
		      thd->lex->ssl_cipher,
		      thd->lex->x509_issuer,
		      thd->lex->x509_subject,
		      &thd->lex->mqh,
1578
		      rights);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1579 1580 1581 1582 1583 1584 1585
  }
  table->file->index_end();
  DBUG_RETURN(error);
}


/*
1586
  change grants in the mysql.db table
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1587 1588 1589 1590
*/

static int replace_db_table(TABLE *table, const char *db,
			    const LEX_USER &combo,
1591
			    ulong rights, bool revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1592
{
1593 1594
  uint i;
  ulong priv,store_rights;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1595
  bool old_row_exists=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1596
  int error;
1597
  char what= (revoke_grant) ? 'N' : 'Y';
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1598 1599
  DBUG_ENTER("replace_db_table");

1600 1601
  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
1602
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
1603 1604 1605
    DBUG_RETURN(-1);
  }

1606
  /* Check if there is such a user in user table in memory? */
1607
  if (!find_acl_user(combo.host.str,combo.user.str))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1608 1609 1610 1611 1612
  {
    my_error(ER_PASSWORD_NO_MATCH,MYF(0));
    DBUG_RETURN(-1);
  }

1613 1614 1615
  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
1616 1617
  table->file->index_init(0);
  if (table->file->index_read(table->record[0],(byte*) table->field[0]->ptr,0,
1618
			      HA_READ_KEY_EXACT))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1619 1620 1621
  {
    if (what == 'N')
    { // no row, no revoke
guilhem@mysql.com's avatar
guilhem@mysql.com committed
1622
      my_error(ER_NONEXISTING_GRANT, MYF(0), combo.user.str, combo.host.str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1623 1624
      goto abort;
    }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1625
    old_row_exists = 0;
1626
    restore_record(table,default_values);			// cp empty row from default_values
1627 1628 1629
    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
1630 1631 1632
  }
  else
  {
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1633
    old_row_exists = 1;
1634
    store_record(table,record[1]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1635 1636 1637
  }

  store_rights=get_rights_for_db(rights);
1638
  for (i= 3, priv= 1; i < table->fields; i++, priv <<= 1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1639
  {
1640
    if (priv & store_rights)			// do it if priv is chosen
1641
      table->field [i]->store(&what,1, &my_charset_latin1);// set requested privileges
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1642 1643 1644 1645
  }
  rights=get_access(table,3);
  rights=fix_rights_for_db(rights);

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1646
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1647
  {
1648
    /* update old existing row */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
    if (rights)
    {
      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 */
    }
  }
  else if ((error=table->file->write_row(table->record[0])))
  {
    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
1667
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1668 1669 1670 1671 1672 1673 1674
    acl_update_db(combo.user.str,combo.host.str,db,rights);
  else
    acl_insert_db(combo.user.str,combo.host.str,db,rights);
  table->file->index_end();
  DBUG_RETURN(0);

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

1679
abort:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1680 1681 1682 1683 1684 1685 1686 1687
  DBUG_RETURN(-1);
}


class GRANT_COLUMN :public Sql_alloc
{
public:
  char *column;
1688 1689 1690
  ulong rights;
  uint key_length;
  GRANT_COLUMN(String &c,  ulong y) :rights (y)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1691
  {
1692
    column= memdup_root(&memex,c.ptr(), key_length=c.length());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1693 1694 1695
  }
};

1696

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1697 1698 1699 1700 1701 1702 1703
static byte* get_key_column(GRANT_COLUMN *buff,uint *length,
			    my_bool not_used __attribute__((unused)))
{
  *length=buff->key_length;
  return (byte*) buff->column;
}

1704

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1705 1706 1707 1708
class GRANT_TABLE :public Sql_alloc
{
public:
  char *host,*db,*user,*tname, *hash_key;
1709
  ulong privs, cols;
1710
  ulong sort;
1711
  uint key_length;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1712 1713
  HASH hash_columns;
  GRANT_TABLE (const char *h, const char *d,const char *u, const char *t,
1714
	       ulong p, ulong c)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1715 1716 1717 1718 1719
    : privs(p), cols(c)
  {
    host = strdup_root(&memex,h);
    db =   strdup_root(&memex,d);
    user = strdup_root(&memex,u);
1720
    sort=  get_sort(3,host,db,user);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1721
    tname= strdup_root(&memex,t);
1722 1723
    if (lower_case_table_names)
    {
1724 1725
      my_casedn_str(&my_charset_latin1, db);
      my_casedn_str(&my_charset_latin1, tname);
1726
    }
1727
    key_length =(uint) strlen(d)+(uint) strlen(u)+(uint) strlen(t)+3;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1728 1729
    hash_key = (char*) alloc_root(&memex,key_length);
    strmov(strmov(strmov(hash_key,user)+1,db)+1,tname);
1730
    (void) hash_init(&hash_columns,&my_charset_latin1,
1731
		     0,0,0, (hash_get_key) get_key_column,0,0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1732 1733 1734 1735 1736 1737
  }

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

1738 1739 1740
    host =  get_field(&memex,form->field[0]);
    db =    get_field(&memex,form->field[1]);
    user =  get_field(&memex,form->field[2]);
1741 1742
    if (!user)
      user=(char*) "";
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1743 1744
    sort=  get_sort(3,host,db,user);
    tname= get_field(&memex,form->field[3]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1745 1746 1747 1748 1749 1750
    if (!host || !db || !tname)
    {
      /* Wrong table row; Ignore it */
      privs = cols = 0;				/* purecov: inspected */
      return;					/* purecov: inspected */
    }
1751 1752
    if (lower_case_table_names)
    {
1753 1754
      my_casedn_str(&my_charset_latin1, db);
      my_casedn_str(&my_charset_latin1, tname);
1755 1756 1757
    }
    key_length = ((uint) strlen(db) + (uint) strlen(user) +
		  (uint) strlen(tname) + 3);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1758 1759
    hash_key = (char*) alloc_root(&memex,key_length);
    strmov(strmov(strmov(hash_key,user)+1,db)+1,tname);
1760 1761
    privs = (ulong) form->field[6]->val_int();
    cols  = (ulong) form->field[7]->val_int();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1762 1763 1764
    privs = fix_rights_for_table(privs);
    cols =  fix_rights_for_column(cols);

1765
    (void) hash_init(&hash_columns,&my_charset_latin1,
1766
		     0,0,0, (hash_get_key) get_key_column,0,0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1767 1768 1769
    if (cols)
    {
      int key_len;
1770 1771 1772 1773
      col_privs->field[0]->store(host,(uint) strlen(host), &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);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1774 1775 1776 1777 1778
      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);
1779
      col_privs->field[4]->store("",0, &my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792
      col_privs->file->index_init(0);
      if (col_privs->file->index_read(col_privs->record[0],
				      (byte*) col_privs->field[0]->ptr,
				      key_len, HA_READ_KEY_EXACT))
      {
	cols = 0; /* purecov: deadcode */
	return;
      }
      do
      {
	String *res,column_name;
	GRANT_COLUMN *mem_check;
	/* As column name is a string, we don't have to supply a buffer */
1793
	res=col_privs->field[4]->val_str(&column_name);
1794
	ulong priv= (ulong) col_privs->field[6]->val_int();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1795 1796 1797
	if (!(mem_check = new GRANT_COLUMN(*res,
					   fix_rights_for_column(priv))))
	{
1798
	  /* Don't use this entry */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1799 1800 1801
	  privs = cols = 0;			/* purecov: deadcode */
	  return;				/* purecov: deadcode */
	}
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1802
	my_hash_insert(&hash_columns, (byte *) mem_check);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1803 1804 1805 1806 1807 1808 1809
      } while (!col_privs->file->index_next(col_privs->record[0]) &&
	       !key_cmp(col_privs,key,0,key_len));
    }
  }
  bool ok() { return privs != 0 || cols != 0; }
};

1810

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1811 1812 1813 1814 1815 1816 1817
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;
}

1818

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1819 1820 1821 1822 1823
void free_grant_table(GRANT_TABLE *grant_table)
{
  hash_free(&grant_table->hash_columns);
}

1824

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836
/* 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;
1837 1838
  for (grant_table=(GRANT_TABLE*) hash_search(&column_priv_hash,
					      (byte*) helping,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1839 1840
					      len) ;
       grant_table ;
1841 1842
       grant_table= (GRANT_TABLE*) hash_next(&column_priv_hash,(byte*) helping,
					     len))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1843 1844 1845
  {
    if (exact)
    {
1846
      if ((host &&
1847
	   !my_strcasecmp(&my_charset_latin1, host, grant_table->host)) ||
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1848 1849 1850 1851 1852
	  (ip && !strcmp(ip,grant_table->host)))
	return grant_table;
    }
    else
    {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1853 1854 1855 1856
      if (((host && !wild_case_compare(&my_charset_latin1,
				       host,grant_table->host)) ||
	   (ip && !wild_case_compare(&my_charset_latin1,
				     ip,grant_table->host))) &&
1857
          (!found || found->sort < grant_table->sort))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1858 1859 1860 1861 1862 1863 1864 1865
	found=grant_table;					// Host ok
    }
  }
  return found;
}



1866
inline GRANT_COLUMN *
1867
column_hash_search(GRANT_TABLE *t, const char *cname, uint length)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1868 1869 1870 1871 1872 1873 1874 1875 1876
{
  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,
1877
				ulong rights, bool revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1878 1879 1880 1881 1882 1883
{
  int error=0,result=0;
  uint key_length;
  byte key[MAX_KEY_LENGTH];
  DBUG_ENTER("replace_column_table");

1884 1885 1886 1887
  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
1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900
  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;
  table->file->index_init(0);
  while ((xx=iter++))
  {
1901
    ulong privileges = xx->rights;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1902
    bool old_row_exists=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1903
    key_restore(table,key,0,key_length);
1904
    table->field[4]->store(xx->column.ptr(),xx->column.length(),&my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1905 1906 1907 1908 1909 1910

    if (table->file->index_read(table->record[0],(byte*) table->field[0]->ptr,
				0, HA_READ_KEY_EXACT))
    {
      if (revoke_grant)
      {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
1911 1912
	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
1913 1914 1915
	result= -1; /* purecov: inspected */
	continue; /* purecov: inspected */
      }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1916
      old_row_exists = 0;
1917
      restore_record(table,default_values);				// Get empty record
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1918
      key_restore(table,key,0,key_length);
1919
      table->field[4]->store(xx->column.ptr(),xx->column.length(), &my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1920 1921 1922
    }
    else
    {
1923
      ulong tmp= (ulong) table->field[6]->val_int();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1924 1925 1926 1927 1928 1929
      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
1930
      old_row_exists = 1;
1931
      store_record(table,record[1]);			// copy original row
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1932 1933 1934 1935
    }

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

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1936
    if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962
    {
      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
1963
      my_hash_insert(&g_t->hash_columns,(byte*) grant_column);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979
    }
  }
  table->file->index_end();

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

  if (revoke_grant)
  {
    table->file->index_init(0);
    if (table->file->index_read(table->record[0], (byte*) table->field[0]->ptr,
				key_length, HA_READ_KEY_EXACT))
      goto end;

1980
    /* Scan through all rows with the same host,db,user and table */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1981 1982
    do
    {
1983
      ulong privileges = (ulong) table->field[6]->val_int();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1984
      privileges=fix_rights_for_column(privileges);
1985
      store_record(table,record[1]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1986 1987 1988 1989 1990

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

	privileges&= ~rights;
	table->field[6]->store((longlong)
			       get_rights_for_column(privileges));
1996
	table->field[4]->val_str(&column_name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
	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]) &&
	     !key_cmp(table,key,0,key_length));
  }

2030
end:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2031 2032 2033 2034 2035 2036 2037 2038
  table->file->index_end();
  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,
2039 2040
			       ulong rights, ulong col_rights,
			       bool revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2041
{
2042
  char grantor[HOSTNAME_LENGTH+USERNAME_LENGTH+2];
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2043
  int old_row_exists = 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2044
  int error=0;
2045
  ulong store_table_rights, store_col_rights;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2046 2047
  DBUG_ENTER("replace_table_table");

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

2050 2051 2052 2053
  /*
    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
2054 2055 2056 2057 2058 2059
  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 */
  }

2060
  restore_record(table,default_values);			// Get empty record
2061 2062 2063 2064
  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);
2065
  store_record(table,record[1]);			// store at pos 1
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077

  if (table->file->index_read_idx(table->record[0],0,
				  (byte*) table->field[0]->ptr,0,
				  HA_READ_KEY_EXACT))
  {
    /*
      The following should never happen as we first check the in memory
      grant tables for the user.  There is however always a small change that
      the user has modified the grant tables directly.
    */
    if (revoke_grant)
    { // no row, no revoke
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2078 2079 2080
      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
2081 2082
      DBUG_RETURN(-1);				/* purecov: deadcode */
    }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2083
    old_row_exists = 0;
2084
    restore_record(table,record[1]);			// Get saved record
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2085 2086
  }

2087 2088
  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
2089
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2090
  {
2091
    ulong j,k;
2092
    store_record(table,record[1]);
2093 2094
    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
2095 2096 2097

    if (revoke_grant)
    {
2098
      /* column rights are already fixed in mysql_table_grant */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2099 2100 2101 2102
      store_table_rights=j & ~store_table_rights;
    }
    else
    {
2103 2104
      store_table_rights|= j;
      store_col_rights|=   k;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2105 2106 2107
    }
  }

2108
  table->field[4]->store(grantor,(uint) strlen(grantor), &my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2109 2110 2111
  table->field[6]->store((longlong) store_table_rights);
  table->field[7]->store((longlong) store_col_rights);
  rights=fix_rights_for_table(store_table_rights);
2112
  col_rights=fix_rights_for_column(store_col_rights);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2113

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2114
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130
  {
    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 */
  }

2131
  if (rights | col_rights)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2132
  {
2133
    grant_table->privs= rights;
2134
    grant_table->cols=	col_rights;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2135 2136 2137
  }
  else
  {
2138
    hash_delete(&column_priv_hash,(byte*) grant_table);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2139 2140 2141
  }
  DBUG_RETURN(0);

2142 2143
  /* This should never happen */
table_error:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2144 2145 2146 2147 2148
  table->file->print_error(error,MYF(0)); /* purecov: deadcode */
  DBUG_RETURN(-1); /* purecov: deadcode */
}


2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165
/*
  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
*/

2166 2167 2168 2169
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
2170
{
2171
  ulong column_priv= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2172 2173 2174
  List_iterator <LEX_USER> str_list (user_list);
  LEX_USER *Str;
  TABLE_LIST tables[3];
2175
  bool create_new_users=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2176 2177 2178 2179
  DBUG_ENTER("mysql_table_grant");

  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2180 2181 2182
    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
2183 2184 2185 2186 2187 2188 2189 2190 2191 2192
  }
  if (rights & ~TABLE_ACLS)
  {
    my_error(ER_ILLEGAL_GRANT_FOR_TABLE,MYF(0));
    DBUG_RETURN(-1);
  }

  if (columns.elements && !revoke_grant)
  {
    TABLE *table;
2193 2194
    class LEX_COLUMN *column;
    List_iterator <LEX_COLUMN> column_iter(columns);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2195 2196 2197

    if (!(table=open_ltable(thd,table_list,TL_READ)))
      DBUG_RETURN(-1);
2198
    while ((column = column_iter++))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2199
    {
2200
      uint unused_field_idx= NO_CACHED_FIELD_INDEX;
2201
      if (!find_field_in_table(thd,table,column->column.ptr(),
2202 2203
                               column->column.length(),0,0,
                               &unused_field_idx))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2204
      {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2205 2206
	my_error(ER_BAD_FIELD_ERROR, MYF(0),
                 column->column.c_ptr(), table_list->alias);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2207 2208
	DBUG_RETURN(-1);
      }
2209
      column_priv|= column->rights;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2210 2211 2212 2213 2214 2215
    }
    close_thread_tables(thd);
  }
  else if (!(rights & CREATE_ACL) && !revoke_grant)
  {
    char buf[FN_REFLEN];
2216 2217
    sprintf(buf,"%s/%s/%s.frm",mysql_data_home, table_list->db,
	    table_list->real_name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2218 2219 2220
    fn_format(buf,buf,"","",4+16+32);
    if (access(buf,F_OK))
    {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2221
      my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->alias);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2222 2223 2224 2225 2226 2227 2228
      DBUG_RETURN(-1);
    }
  }

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

  bzero((char*) &tables,sizeof(tables));
2229 2230 2231
  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
2232 2233 2234 2235 2236 2237 2238 2239
  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";

2240 2241 2242 2243 2244
#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
2245 2246
  if (thd->slave_thread && table_rules_on)
  {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2247 2248 2249
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
2250
    */
2251
    tables[0].updating= tables[1].updating= tables[2].updating= 1;
2252 2253 2254
    if (!tables_ok(0, tables))
      DBUG_RETURN(0);
  }
2255 2256
#endif

2257
  if (simple_open_n_lock_tables(thd,tables))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2258 2259 2260 2261 2262
  {						// Should never happen
    close_thread_tables(thd);			/* purecov: deadcode */
    DBUG_RETURN(-1);				/* purecov: deadcode */
  }

2263 2264
  if (!revoke_grant)
    create_new_users= test_if_create_new_users(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2265
  int result=0;
2266
  rw_wrlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2267 2268 2269 2270 2271
  MEM_ROOT *old_root=my_pthread_getspecific_ptr(MEM_ROOT*,THR_MALLOC);
  my_pthread_setspecific_ptr(THR_MALLOC,&memex);

  while ((Str = str_list++))
  {
2272
    int error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2273 2274 2275 2276 2277 2278 2279 2280 2281
    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 */
2282
    pthread_mutex_lock(&acl_cache->lock);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2283 2284
    error=replace_user_table(thd, tables[0].table, *Str,
			     0, revoke_grant, create_new_users);
2285 2286
    pthread_mutex_unlock(&acl_cache->lock);
    if (error)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2287 2288 2289 2290 2291 2292 2293 2294
    {
      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,
2295
				   table_list->real_name,1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2296 2297 2298 2299
    if (!grant_table)
    {
      if (revoke_grant)
      {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2300 2301
	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
2302 2303 2304 2305 2306
	result= -1;
	continue;
      }
      grant_table = new GRANT_TABLE (Str->host.str,table_list->db,
				     Str->user.str,
2307
				     table_list->real_name,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2308 2309 2310 2311 2312 2313 2314
				     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
2315
      my_hash_insert(&column_priv_hash,(byte*) grant_table);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2316 2317 2318 2319 2320
    }

    /* If revoke_grant, calculate the new column privilege for tables_priv */
    if (revoke_grant)
    {
2321 2322
      class LEX_COLUMN *column;
      List_iterator <LEX_COLUMN> column_iter(columns);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2323 2324 2325
      GRANT_COLUMN *grant_column;

      /* Fix old grants */
2326
      while ((column = column_iter++))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2327 2328
      {
	grant_column = column_hash_search(grant_table,
2329 2330
					  column->column.ptr(),
					  column->column.length());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2331
	if (grant_column)
2332
	  grant_column->rights&= ~(column->rights | rights);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2333 2334
      }
      /* scan trough all columns to get new column grant */
2335
      column_priv= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353
      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,
2354
			    table_list->real_name,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2355 2356 2357 2358 2359 2360 2361 2362 2363
			    rights, column_priv, revoke_grant))
    {						// Crashend table ??
      result= -1;			       /* purecov: deadcode */
    }
    else if (tables[2].table)
    {
      if ((replace_column_table(grant_table,tables[2].table, *Str,
				columns,
				table_list->db,
2364
				table_list->real_name,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2365 2366 2367 2368 2369 2370 2371 2372
				rights, revoke_grant)))
      {
	result= -1;
      }
    }
  }
  grant_option=TRUE;
  my_pthread_setspecific_ptr(THR_MALLOC,old_root);
2373
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2374
  if (!result)
2375
    send_ok(thd);
2376
  /* Tables are automatically closed */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2377 2378 2379 2380
  DBUG_RETURN(result);
}


monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2381 2382
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
2383 2384 2385
{
  List_iterator <LEX_USER> str_list (list);
  LEX_USER *Str;
2386
  char tmp_db[NAME_LEN+1];
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2387
  bool create_new_users=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2388 2389 2390 2391
  TABLE_LIST tables[2];
  DBUG_ENTER("mysql_grant");
  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2392 2393
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0),
             "--skip-grant-tables");	/* purecov: tested */
2394
    DBUG_RETURN(-1);				/* purecov: tested */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2395 2396
  }

2397 2398 2399
  if (lower_case_table_names && db)
  {
    strmov(tmp_db,db);
2400
    my_casedn_str(&my_charset_latin1, tmp_db);
2401 2402
    db=tmp_db;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2403 2404

  /* open the mysql.user and mysql.db tables */
2405
  bzero((char*) &tables,sizeof(tables));
2406 2407
  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
2408 2409 2410 2411 2412
  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;
2413 2414 2415 2416 2417 2418

#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
2419 2420
  if (thd->slave_thread && table_rules_on)
  {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2421 2422 2423
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
2424
    */
2425
    tables[0].updating= tables[1].updating= 1;
2426 2427 2428
    if (!tables_ok(0, tables))
      DBUG_RETURN(0);
  }
2429 2430
#endif

2431
  if (simple_open_n_lock_tables(thd,tables))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2432 2433 2434 2435 2436
  {						// 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
2437 2438
  if (!revoke_grant)
    create_new_users= test_if_create_new_users(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2439

2440
  /* go through users in user_list */
2441
  rw_wrlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454
  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;
    }
2455
    if ((replace_user_table(thd,
2456
			    tables[0].table,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2457
			    *Str,
2458 2459
			    (!db ? rights : 0), revoke_grant,
			    create_new_users)))
2460
      result= -1;
2461
    else if (db)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2462
    {
2463 2464 2465 2466 2467 2468 2469 2470 2471
      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
2472
	my_error(ER_WRONG_USAGE, MYF(0), "DB GRANT", "GLOBAL PRIVILEGES");
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2473
	result= -1;
2474
      }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2475
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2476 2477
  }
  VOID(pthread_mutex_unlock(&acl_cache->lock));
2478
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2479 2480 2481
  close_thread_tables(thd);

  if (!result)
2482
    send_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2483 2484 2485
  DBUG_RETURN(result);
}

2486 2487

/* Free grant array if possible */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2488 2489 2490 2491 2492

void  grant_free(void)
{
  DBUG_ENTER("grant_free");
  grant_option = FALSE;
2493
  hash_free(&column_priv_hash);
2494
  free_root(&memex,MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2495 2496 2497 2498 2499 2500
  DBUG_VOID_RETURN;
}


/* Init grant array if possible */

2501
my_bool grant_init(THD *org_thd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2502
{
2503
  THD  *thd;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2504
  TABLE_LIST tables[2];
2505 2506
  MYSQL_LOCK *lock;
  my_bool return_val= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2507
  TABLE *t_table, *c_table;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2508
  bool check_no_resolve= specialflag & SPECIAL_NO_RESOLVE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2509 2510 2511
  DBUG_ENTER("grant_init");

  grant_option = FALSE;
2512
  (void) hash_init(&column_priv_hash,&my_charset_latin1,
2513
		   0,0,0, (hash_get_key) get_grant_table,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2514
		   (hash_free_key) free_grant_table,0);
2515
  init_sql_alloc(&memex, ACL_ALLOC_BLOCK_SIZE, 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2516

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2521 2522
  if (!(thd=new THD))
    DBUG_RETURN(1);				/* purecov: deadcode */
2523
  thd->store_globals();
2524 2525
  thd->db= my_strdup("mysql",MYF(0));
  thd->db_length=5;				// Safety
2526
  bzero((char*) &tables, sizeof(tables));
2527 2528
  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
2529 2530 2531 2532
  tables[0].next=tables+1;
  tables[0].lock_type=tables[1].lock_type=TL_READ;
  tables[0].db=tables[1].db=thd->db;

2533 2534
  uint counter;
  if (open_tables(thd, tables, &counter))
2535 2536
    goto end;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2537 2538 2539
  TABLE *ptr[2];				// Lock tables for quick update
  ptr[0]= tables[0].table;
  ptr[1]= tables[1].table;
2540 2541
  if (!(lock=mysql_lock_tables(thd,ptr,2)))
    goto end;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2542 2543 2544 2545 2546 2547

  t_table = tables[0].table; c_table = tables[1].table;
  t_table->file->index_init(0);
  if (t_table->file->index_first(t_table->record[0]))
  {
    t_table->file->index_end();
2548
    return_val= 0;
2549
    goto end_unlock;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2550
  }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2551
  grant_option= TRUE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2552 2553
  t_table->file->index_end();

2554
  /* Will be restored by org_thd->store_globals() */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2555
  my_pthread_setspecific_ptr(THR_MALLOC,&memex);
2556
  do
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2557 2558
  {
    GRANT_TABLE *mem_check;
Sinisa@sinisa.nasamreza.org's avatar
Sinisa@sinisa.nasamreza.org committed
2559
    if (!(mem_check=new GRANT_TABLE(t_table,c_table)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2560 2561
    {
      /* This could only happen if we are out memory */
2562
      grant_option= FALSE;			/* purecov: deadcode */
2563
      goto end_unlock;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2564
    }
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2565 2566 2567 2568 2569

    if (check_no_resolve)
    {
      if (hostname_requires_resolving(mem_check->host))
      {
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2570 2571
	sql_print_error("Warning: 'tables_priv' entry '%s %s@%s' "
			"ignored in --skip-name-resolve mode.",
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2572 2573 2574 2575 2576 2577
			mem_check->tname, mem_check->user, 
			mem_check->host, mem_check->host);
	continue;
      }
    }

Sinisa@sinisa.nasamreza.org's avatar
Sinisa@sinisa.nasamreza.org committed
2578
    if (mem_check->ok() && my_hash_insert(&column_priv_hash,(byte*) mem_check))
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2579 2580 2581 2582
    {
      grant_option= FALSE;
      goto end_unlock;
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2583
  }
2584 2585 2586 2587 2588
  while (!t_table->file->index_next(t_table->record[0]));

  return_val=0;					// Return ok

end_unlock:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2589 2590
  mysql_unlock_tables(thd, lock);
  thd->version--;				// Force close to free memory
2591 2592

end:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2593 2594
  close_thread_tables(thd);
  delete thd;
2595 2596
  if (org_thd)
    org_thd->store_globals();
2597 2598 2599 2600 2601
  else
  {
    /* Remember that we don't have a THD */
    my_pthread_setspecific_ptr(THR_THD,  0);
  }
2602
  DBUG_RETURN(return_val);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2603 2604 2605
}


2606
/*
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2607
 Reload grant array (table and column privileges) if possible
2608 2609 2610 2611 2612 2613 2614 2615

  SYNOPSIS
    grant_reload()
    thd			Thread handler

  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
2616

2617
void grant_reload(THD *thd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2618
{
2619 2620
  HASH old_column_priv_hash;
  bool old_grant_option;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2621 2622 2623
  MEM_ROOT old_mem;
  DBUG_ENTER("grant_reload");

2624
  rw_wrlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2625
  grant_version++;
2626
  old_column_priv_hash= column_priv_hash;
2627
  old_grant_option= grant_option;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2628
  old_mem= memex;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2629

2630
  if (grant_init(thd))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2631
  {						// Error. Revert to old hash
2632
    DBUG_PRINT("error",("Reverting to old privileges"));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2633
    grant_free();				/* purecov: deadcode */
2634
    column_priv_hash= old_column_priv_hash;	/* purecov: deadcode */
2635
    grant_option= old_grant_option;		/* purecov: deadcode */
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2636
    memex= old_mem;				/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2637 2638 2639
  }
  else
  {
2640
    hash_free(&old_column_priv_hash);
2641
    free_root(&old_mem,MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2642
  }
2643
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2644 2645 2646 2647 2648
  DBUG_VOID_RETURN;
}


/****************************************************************************
2649
  Check grants
2650
  All errors are written directly to the client if no_errors is given !
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2651 2652
****************************************************************************/

2653
bool check_grant(THD *thd, ulong want_access, TABLE_LIST *tables,
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2654
		 uint show_table, uint number, bool no_errors)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2655 2656 2657 2658 2659 2660 2661 2662
{
  TABLE_LIST *table;
  char *user = thd->priv_user;

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

2663
  rw_rdlock(&LOCK_grant);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2664
  for (table= tables; table && number--; table= table->next)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2665
  {
2666
    if (!(~table->grant.privilege & want_access) || table->derived)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2667 2668 2669 2670
    {
      table->grant.want_privilege=0;
      continue;					// Already checked
    }
2671 2672
    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
2673 2674 2675 2676 2677 2678
						 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
2679 2680
    if (show_table)
      continue;					// We have some priv on this
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696

    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
    }
  }
2697
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2698 2699
  return 0;

2700
err:
2701
  rw_unlock(&LOCK_grant);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2702
  if (!no_errors)				// Not a silent skip of table
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2703 2704 2705
  {
    const char *command="";
    if (want_access & SELECT_ACL)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2706
      command= "select";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2707
    else if (want_access & INSERT_ACL)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2708
      command= "insert";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2709
    else if (want_access & UPDATE_ACL)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2710
      command= "update";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2711
    else if (want_access & DELETE_ACL)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2712
      command= "delete";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2713
    else if (want_access & DROP_ACL)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2714
      command= "drop";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2715
    else if (want_access & CREATE_ACL)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2716
      command= "create";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2717
    else if (want_access & ALTER_ACL)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2718
      command= "alter";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2719
    else if (want_access & INDEX_ACL)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2720
      command= "index";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2721
    else if (want_access & GRANT_ACL)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2722
      command= "grant";
2723
    net_printf(thd,ER_TABLEACCESS_DENIED_ERROR,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2724 2725
	       command,
	       thd->priv_user,
2726
	       thd->host_or_ip,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2727 2728 2729 2730 2731 2732
	       table ? table->real_name : "unknown");
  }
  return 1;
}


2733 2734
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
2735 2736 2737 2738
{
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;

2739
  ulong want_access=table->grant.want_privilege;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2740 2741 2742
  if (!want_access)
    return 0;					// Already checked

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

2745
  /* reload table if someone has modified any grants */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760

  if (table->grant.version != grant_version)
  {
    table->grant.grant_table=
      table_hash_search(thd->host,thd->ip,thd->db,
			thd->priv_user,
			table->real_name,0);	/* purecov: inspected */
    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))
  {
2761
    rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2762 2763 2764 2765 2766
    return 0;
  }
#ifdef NOT_USED
  if (show_tables && (grant_column || table->grant.privilege & COL_ACLS))
  {
2767
    rw_unlock(&LOCK_grant);			/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2768 2769 2770 2771 2772
    return 0;					/* purecov: deadcode */
  }
#endif

  /* We must use my_printf_error() here! */
2773
err:
2774
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2775 2776
  if (!show_tables)
  {
2777 2778
    char command[128];
    get_privilege_desc(command, sizeof(command), want_access);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2779 2780 2781 2782 2783
    my_printf_error(ER_COLUMNACCESS_DENIED_ERROR,
		    ER(ER_COLUMNACCESS_DENIED_ERROR),
		    MYF(0),
		    command,
		    thd->priv_user,
2784
		    thd->host_or_ip,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2785 2786 2787 2788 2789 2790 2791
		    name,
		    table ? table->real_name : "unknown");
  }
  return 1;
}


2792
bool check_grant_all_columns(THD *thd, ulong want_access, TABLE *table)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2793 2794 2795 2796 2797 2798 2799
{
  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
2800
    return 0;				// Already checked
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2801
  if (!grant_option)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2802 2803
  {
    field= table->field[0];		// To give a meaningful error message
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2804
    goto err2;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2805
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2806

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

2809
  /* reload table if someone has modified any grants */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2810 2811 2812 2813 2814 2815 2816 2817 2818

  if (table->grant.version != grant_version)
  {
    table->grant.grant_table=
      table_hash_search(thd->host,thd->ip,thd->db,
			thd->priv_user,
			table->real_name,0);	/* purecov: inspected */
    table->grant.version=grant_version;		/* purecov: inspected */
  }
2819
  /* The following should always be true */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2820 2821 2822 2823 2824 2825
  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,
2826
				    (uint) strlen(field->field_name));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2827 2828 2829
    if (!grant_column || (~grant_column->rights & want_access))
      goto err;
  }
2830
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2831 2832 2833
  return 0;

  /* We must use my_printf_error() here! */
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2834
err:
2835
  rw_unlock(&LOCK_grant);
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2836
err2:
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2837
  const char *command= "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2838
  if (want_access & SELECT_ACL)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2839
    command= "select";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2840
  else if (want_access & INSERT_ACL)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2841
    command= "insert";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2842 2843 2844 2845 2846
  my_printf_error(ER_COLUMNACCESS_DENIED_ERROR,
		  ER(ER_COLUMNACCESS_DENIED_ERROR),
		  MYF(0),
		  command,
		  thd->priv_user,
2847
		  thd->host_or_ip,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2848 2849 2850 2851 2852 2853
		  field ? field->field_name : "unknown",
		  table->real_name);
  return 1;
}


2854
/*
2855 2856 2857
  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
2858
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2859 2860 2861 2862 2863 2864 2865 2866

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;
2867
  rw_rdlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2868

2869
  for (uint idx=0 ; idx < column_priv_hash.records ; idx++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2870
  {
2871 2872
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  idx);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2873 2874
    if (len < grant_table->key_length &&
	!memcmp(grant_table->hash_key,helping,len) &&
2875
	(thd->host && !wild_case_compare(&my_charset_latin1,
2876
                                         thd->host,grant_table->host) ||
2877
	 (thd->ip && !wild_case_compare(&my_charset_latin1,
2878
                                        thd->ip,grant_table->host))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2879 2880 2881 2882 2883
    {
      error=0;					// Found match
      break;
    }
  }
2884
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2885 2886 2887 2888
  return error;
}

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

2892
ulong get_table_grant(THD *thd, TABLE_LIST *table)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2893
{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2894
  ulong privilege;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2895 2896 2897 2898
  char *user = thd->priv_user;
  const char *db = table->db ? table->db : thd->db;
  GRANT_TABLE *grant_table;

2899
  rw_rdlock(&LOCK_grant);
2900 2901 2902
#ifdef EMBEDDED_LIBRARY
  grant_table= NULL;
#else
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2903 2904
  grant_table= table_hash_search(thd->host, thd->ip, db, user,
				 table->real_name, 0);
2905
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2906 2907 2908 2909
  table->grant.grant_table=grant_table; // Remember for column test
  table->grant.version=grant_version;
  if (grant_table)
    table->grant.privilege|= grant_table->privs;
2910
  privilege= table->grant.privilege;
2911
  rw_unlock(&LOCK_grant);
2912
  return privilege;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2913 2914 2915
}


2916
ulong get_column_grant(THD *thd, TABLE_LIST *table, Field *field)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2917 2918 2919
{
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;
2920
  ulong priv;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2921

2922
  rw_rdlock(&LOCK_grant);
2923
  /* reload table if someone has modified any grants */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937
  if (table->grant.version != grant_version)
  {
    table->grant.grant_table=
      table_hash_search(thd->host,thd->ip,thd->db,
			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,
2938
				    (uint) strlen(field->field_name));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2939 2940 2941 2942 2943
    if (!grant_column)
      priv=table->grant.privilege;
    else
      priv=table->grant.privilege | grant_column->rights;
  }
2944
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2945 2946 2947
  return priv;
}

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

2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961
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
2962 2963

static const char *command_array[]=
2964 2965 2966 2967 2968 2969
{
  "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",
};
2970

2971 2972 2973 2974 2975
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
2976

2977 2978 2979 2980 2981 2982 2983
/*
  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
2984
int mysql_show_grants(THD *thd,LEX_USER *lex_user)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2985
{
2986 2987
  ulong want_access;
  uint counter,index;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2988
  int  error = 0;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2989 2990
  ACL_USER *acl_user;
  ACL_DB *acl_db;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2991
  char buff[1024];
2992
  Protocol *protocol= thd->protocol;
tonu@x153.internalnet's avatar
tonu@x153.internalnet committed
2993
  DBUG_ENTER("mysql_show_grants");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2994 2995 2996 2997

  LINT_INIT(acl_user);
  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2998 2999
    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
3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016
  }
  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))
      user="";
    if (!(host=acl_user->host.hostname))
      host="%";
    if (!strcmp(lex_user->user.str,user) &&
3017
	!my_strcasecmp(&my_charset_latin1, lex_user->host.str, host))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3018 3019
      break;
  }
peter@mysql.com's avatar
peter@mysql.com committed
3020
  if (counter == acl_users.elements)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3021
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3022 3023
    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
3024 3025 3026
    DBUG_RETURN(-1);
  }

3027
  Item_string *field=new Item_string("",0,&my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3028 3029 3030 3031 3032 3033
  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);
3034
  if (protocol->send_fields(&field_list,1))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3035 3036
    DBUG_RETURN(-1);

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3037
  rw_wrlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3038 3039 3040 3041
  VOID(pthread_mutex_lock(&acl_cache->lock));

  /* Add first global access grants */
  {
3042
    String global(buff,sizeof(buff),&my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3043 3044 3045
    global.length(0);
    global.append("GRANT ",6);

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3046
    want_access= acl_user->access;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3047 3048 3049 3050
    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
3051
    else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3052 3053
    {
      bool found=0;
3054
      ulong j,test_access= want_access & ~GRANT_ACL;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3055 3056
      for (counter=0, j = SELECT_ACL;j <= GLOBAL_ACLS;counter++,j <<= 1)
      {
peter@mysql.com's avatar
peter@mysql.com committed
3057
	if (test_access & j)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3058 3059 3060 3061 3062 3063 3064 3065 3066
	{
	  if (found)
	    global.append(", ",2);
	  found=1;
	  global.append(command_array[counter],command_lengths[counter]);
	}
      }
    }
    global.append (" ON *.* TO '",12);
peter@mysql.com's avatar
peter@mysql.com committed
3067
    global.append(lex_user->user.str,lex_user->user.length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3068 3069 3070
    global.append ("'@'",3);
    global.append(lex_user->host.str,lex_user->host.length);
    global.append ('\'');
3071
    if (acl_user->salt_len)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3072
    {
3073 3074 3075 3076 3077
      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
3078
      global.append(" IDENTIFIED BY PASSWORD '",25);
3079
      global.append(passwd_buff);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3080 3081
      global.append('\'');
    }
3082 3083
    /* "show grants" SSL related stuff */
    if (acl_user->ssl_type == SSL_TYPE_ANY)
3084
      global.append(" REQUIRE SSL",12);
3085
    else if (acl_user->ssl_type == SSL_TYPE_X509)
3086
      global.append(" REQUIRE X509",13);
3087
    else if (acl_user->ssl_type == SSL_TYPE_SPECIFIED)
3088
    {
3089
      int ssl_options = 0;
3090
      global.append(" REQUIRE ",9);
3091 3092
      if (acl_user->x509_issuer)
      {
3093 3094 3095
	ssl_options++;
	global.append("ISSUER \'",8);
	global.append(acl_user->x509_issuer,strlen(acl_user->x509_issuer));
3096
	global.append('\'');
3097
      }
3098 3099
      if (acl_user->x509_subject)
      {
3100 3101 3102 3103
	if (ssl_options++)
	  global.append(' ');
	global.append("SUBJECT \'",9);
	global.append(acl_user->x509_subject,strlen(acl_user->x509_subject));
3104
	global.append('\'');
tonu@x153.internalnet's avatar
tonu@x153.internalnet committed
3105
      }
3106 3107
      if (acl_user->ssl_cipher)
      {
3108 3109 3110 3111
	if (ssl_options++)
	  global.append(' ');
	global.append("CIPHER '",8);
	global.append(acl_user->ssl_cipher,strlen(acl_user->ssl_cipher));
3112
	global.append('\'');
3113 3114
      }
    }
3115 3116 3117
    if ((want_access & GRANT_ACL) ||
	(acl_user->user_resource.questions | acl_user->user_resource.updates |
	 acl_user->user_resource.connections))
3118
    {
peter@mysql.com's avatar
peter@mysql.com committed
3119
      global.append(" WITH",5);
3120
      if (want_access & GRANT_ACL)
peter@mysql.com's avatar
peter@mysql.com committed
3121
	global.append(" GRANT OPTION",13);
3122 3123 3124 3125 3126 3127
      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");
3128
    }
3129
    protocol->prepare_for_resend();
3130
    protocol->store(global.ptr(),global.length(),global.charset());
3131
    if (protocol->write())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3132
    {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3133
      error= -1;
3134
      goto end;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149
    }
  }

  /* Add database access */
  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))
      user="";
    if (!(host=acl_db->host.hostname))
      host="";

    if (!strcmp(lex_user->user.str,user) &&
3150
	!my_strcasecmp(&my_charset_latin1, lex_user->host.str, host))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3151 3152
    {
      want_access=acl_db->access;
peter@mysql.com's avatar
peter@mysql.com committed
3153
      if (want_access)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3154
      {
3155
	String db(buff,sizeof(buff),&my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3156 3157 3158 3159 3160
	db.length(0);
	db.append("GRANT ",6);

	if (test_all_bits(want_access,(DB_ACLS & ~GRANT_ACL)))
	  db.append("ALL PRIVILEGES",14);
3161
	else if (!(want_access & ~GRANT_ACL))
3162
	  db.append("USAGE",5);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3163 3164 3165
	else
	{
	  int found=0, cnt;
3166
	  ulong j,test_access= want_access & ~GRANT_ACL;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177
	  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]);
	    }
	  }
	}
3178 3179 3180
	db.append (" ON ",4);
	append_identifier(thd, &db, acl_db->db, strlen(acl_db->db));
	db.append (".* TO '",7);
peter@mysql.com's avatar
peter@mysql.com committed
3181
	db.append(lex_user->user.str,lex_user->user.length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3182 3183
	db.append ("'@'",3);
	db.append(lex_user->host.str, lex_user->host.length);
peter@mysql.com's avatar
peter@mysql.com committed
3184
	db.append ('\'');
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3185
	if (want_access & GRANT_ACL)
3186
	  db.append(" WITH GRANT OPTION",18);
3187
	protocol->prepare_for_resend();
3188
	protocol->store(db.ptr(),db.length(),db.charset());
3189
	if (protocol->write())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3190
	{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3191
	  error= -1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3192 3193 3194 3195 3196 3197 3198
	  goto end;
	}
      }
    }
  }

  /* Add column access */
3199
  for (index=0 ; index < column_priv_hash.records ; index++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3200 3201
  {
    const char *user,*host;
3202 3203
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  index);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3204 3205 3206 3207 3208 3209 3210

    if (!(user=grant_table->user))
      user="";
    if (!(host=grant_table->host))
      host="";

    if (!strcmp(lex_user->user.str,user) &&
3211
	!my_strcasecmp(&my_charset_latin1, lex_user->host.str, host))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3212
    {
3213 3214
      ulong table_access= grant_table->privs;
      if ((table_access | grant_table->cols) != 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3215
      {
3216
	String global(buff,sizeof(buff),&my_charset_latin1);
3217 3218
	ulong test_access= (table_access | grant_table->cols) & ~GRANT_ACL;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3219 3220 3221
	global.length(0);
	global.append("GRANT ",6);

3222
	if (test_all_bits(table_access, (TABLE_ACLS & ~GRANT_ACL)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3223
	  global.append("ALL PRIVILEGES",14);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3224
	else if (!test_access)
3225
 	  global.append("USAGE",5);
peter@mysql.com's avatar
peter@mysql.com committed
3226
	else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3227
	{
3228
	  int found= 0;
3229
	  ulong j;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3230

3231
	  for (counter= 0, j= SELECT_ACL; j <= TABLE_ACLS; counter++, j<<= 1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3232
	  {
peter@mysql.com's avatar
peter@mysql.com committed
3233
	    if (test_access & j)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3234 3235 3236
	    {
	      if (found)
		global.append(", ",2);
3237
	      found= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3238 3239
	      global.append(command_array[counter],command_lengths[counter]);

peter@mysql.com's avatar
peter@mysql.com committed
3240
	      if (grant_table->cols)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3241
	      {
3242
		uint found_col= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3243 3244 3245 3246 3247 3248
		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
3249
		  if (grant_column->rights & j)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3250
		  {
peter@mysql.com's avatar
peter@mysql.com committed
3251
		    if (!found_col)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3252
		    {
3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263
		      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
3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277
		      global.append(" (",2);
		    }
		    else
		      global.append(", ",2);
		    global.append(grant_column->column,
				  grant_column->key_length);
		  }
		}
		if (found_col)
		  global.append(')');
	      }
	    }
	  }
	}
3278 3279 3280 3281 3282 3283 3284
	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);
peter@mysql.com's avatar
peter@mysql.com committed
3285
	global.append(lex_user->user.str,lex_user->user.length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3286
	global.append("'@'",3);
peter@mysql.com's avatar
peter@mysql.com committed
3287
	global.append(lex_user->host.str,lex_user->host.length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3288
	global.append('\'');
3289
	if (table_access & GRANT_ACL)
peter@mysql.com's avatar
peter@mysql.com committed
3290
	  global.append(" WITH GRANT OPTION",18);
3291
	protocol->prepare_for_resend();
3292
	protocol->store(global.ptr(),global.length(),global.charset());
3293
	if (protocol->write())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3294
	{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3295
	  error= -1;
3296
	  break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3297 3298 3299 3300
	}
      }
    }
  }
3301
end:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3302
  VOID(pthread_mutex_unlock(&acl_cache->lock));
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3303
  rw_unlock(&LOCK_grant);
3304

3305
  send_eof(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3306 3307 3308 3309
  DBUG_RETURN(error);
}


3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337
/*
  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;
}


3338
void get_mqh(const char *user, const char *host, USER_CONN *uc)
3339 3340
{
  ACL_USER *acl_user;
3341 3342 3343 3344
  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));
3345 3346
}

3347 3348 3349 3350 3351 3352
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
3353
    net_printf(thd,ER_OPTION_PREVENTS_STATEMENT, "--skip-grant-tables");
3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374
    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.
  */
3375 3376
  if (thd->slave_thread && table_rules_on)
  {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3377 3378 3379
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
3380 3381 3382 3383 3384 3385
    */
    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;
  }
3386 3387
#endif

3388
  if (simple_open_n_lock_tables(thd, tables))
3389 3390 3391 3392 3393 3394 3395 3396 3397
  {						// 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
3398
			 uint *acl_acl_userdx)
3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417
{
  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))
      user="";
    if (!(host=acl_user->host.hostname))
      host="%";
    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
3418
  *acl_acl_userdx= counter;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3419
  return acl_user;
3420 3421
}

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

3423 3424
int mysql_drop_user(THD *thd, List <LEX_USER> &list)
{
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
3425
  uint counter, acl_userd;
3426 3427 3428 3429 3430 3431 3432 3433
  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)))
3434
    DBUG_RETURN(result == 1 ? 0 : 1);
3435 3436 3437 3438 3439 3440 3441 3442 3443 3444

  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
3445
      sql_print_error("DROP USER: Can't drop user: '%s'@'%s'; No such user",
3446 3447 3448 3449 3450 3451 3452
		      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
3453
      sql_print_error("DROP USER: Can't drop user: '%s'@'%s'; Global privileges exists",
3454 3455 3456 3457 3458
		      user_name->user.str,
		      user_name->host.str);
      result= -1;
      continue;
    }
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
3459
    acl_userd= counter;
3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475

    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))
	user="";
      if (!(host= acl_db->host.hostname))
	host="";

      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
3476
      sql_print_error("DROP USER: Can't drop user: '%s'@'%s'; Database privileges exists",
3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498
		      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))
	user="";
      if (!(host=grant_table->host))
	host="";

      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
3499
      sql_print_error("DROP USER: Can't drop user: '%s'@'%s';  Table privileges exists",
3500 3501 3502 3503 3504 3505
		      user_name->user.str,
		      user_name->host.str);
      result= -1;
      continue;
    }

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3506
    tables[0].table->field[0]->store(user_name->host.str,(uint)
3507 3508
				     user_name->host.length,
				     system_charset_info);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3509
    tables[0].table->field[1]->store(user_name->user.str,(uint)
3510 3511
				     user_name->user.length,
				     system_charset_info);
3512
    if (!tables[0].table->file->index_read_idx(tables[0].table->record[0],0,
3513 3514
					       (byte*) tables[0].table->
					       field[0]->ptr,0,
3515 3516 3517
					       HA_READ_KEY_EXACT))
    {
      int error;
3518 3519
      if ((error = tables[0].table->file->delete_row(tables[0].table->
						     record[0])))
3520 3521 3522 3523 3524
      {
	tables[0].table->file->print_error(error, MYF(0));
	tables[0].table->file->index_end();
	DBUG_RETURN(-1);
      }
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
3525
      delete_dynamic_element(&acl_users, acl_userd);
3526 3527 3528
    }
    tables[0].table->file->index_end();
  }
3529

3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541
  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)
{
  uint counter;
  int result;
3542
  ACL_DB *acl_db;
3543 3544 3545 3546
  TABLE_LIST tables[4];
  DBUG_ENTER("mysql_revoke_all");

  if ((result= open_grant_tables(thd, tables)))
3547
    DBUG_RETURN(result == 1 ? 0 : 1);
3548 3549 3550 3551 3552 3553 3554 3555

  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++))
  {
3556
    if (!check_acl_user(lex_user, &counter))
3557 3558 3559 3560 3561 3562 3563
    {
      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
3564

3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629
    if (replace_user_table(thd, tables[0].table,
			   *lex_user, ~0, 1, 0))
    {
      result= -1;
      continue;
    }

    /* Remove db access privileges */
    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))
	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))
      {
	if (replace_db_table(tables[1].table, acl_db->db, *lex_user, ~0, 1))
	  result= -1;
      }
    }

    /* Remove column access */
    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))
	user="";
      if (!(host=grant_table->host))
	host="";

      if (!strcmp(lex_user->user.str,user) &&
	  !my_strcasecmp(system_charset_info, lex_user->host.str, host))
      {
	if (replace_table_table(thd,grant_table,tables[2].table,*lex_user,
				grant_table->db,
				grant_table->tname,
				~0, 0, 1))
	{
	  result= -1;
	  continue;
	}
	if (grant_table->cols)
	{
	  List<LEX_COLUMN> columns;
	  if (replace_column_table(grant_table,tables[3].table, *lex_user,
				   columns,
				   grant_table->db,
				   grant_table->tname,
				   ~0, 1))
	    result= -1;
	}
      }
    }
  }

  VOID(pthread_mutex_unlock(&acl_cache->lock));
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
serg@serg.mylan's avatar
serg@serg.mylan committed
3630 3631 3632 3633 3634

  /* XXX this should not be necessary. The error message is already printed
     by replace_xxx_table. my_error() should be use above instead of
     sql_print_error(), and print ER_NONEXISTING_GRANT - as other grant
     commands do */
3635 3636
  /* when this code is deleted, the error slot (error 1268) can be reused,
     as this error code was not present in any MySQL release */
3637 3638
  if (result)
    my_error(ER_REVOKE_GRANTS, MYF(0));
serg@serg.mylan's avatar
serg@serg.mylan committed
3639

3640 3641
  DBUG_RETURN(result);
}
3642

3643

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3644
/*****************************************************************************
3645
  Instantiate used templates
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3646 3647 3648 3649 3650 3651 3652 3653
*****************************************************************************/

#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
3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700

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