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

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

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
13 14 15 16 17 18 19
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */


/*
  The privileges are saved in the following tables:
20 21
  mysql/user	 ; super user who are allowed to do almost anything
  mysql/host	 ; host privileges. This is used if host is empty in mysql/db.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
22 23 24 25 26 27 28 29 30
  mysql/db	 ; database privileges / user

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

#include "mysql_priv.h"
#include "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, uint *next_field=0);
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
  bool check_no_resolve= specialflag & SPECIAL_NO_RESOLVE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
143 144 145 146 147
  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
148
			    (hash_free_key) free, system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
149
  if (dont_read_acl_tables)
150
  {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
151
    DBUG_RETURN(0); /* purecov: tested */
peter@mysql.com's avatar
peter@mysql.com committed
152 153
  }

154
  priv_version++; /* Privileges updated */
155
  mysql_proc_table_exists= 1;			// Assume mysql.proc exists
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";
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
171 172
  tables[0].next_local= tables[0].next_global= tables+1;
  tables[1].next_local= tables[1].next_global= tables+2;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
173 174 175
  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))
    {
serg@serg.mylan's avatar
serg@serg.mylan committed
206
      sql_print_warning("'host' entry '%s|%s' "
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
207
		      "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
    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);
254 255 256
      sql_print_warning("mysql.user table is not updated to new password format; "
                        "Disabling new password usage until "
                        "mysql_fix_privilege_tables is run");
257 258 259 260
    }
    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))
    {
serg@serg.mylan's avatar
serg@serg.mylan committed
274 275
      sql_print_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 */
serg@serg.mylan's avatar
serg@serg.mylan committed
287 288 289 290 291
        sql_print_warning("Found 4.1 style password for user '%s@%s'. "
                          "Ignoring user. "
                          "You should change password for this user.",
                          user.user ? user.user : "",
                          user.host.hostname ? user.host.hostname : "");
292 293
        break;
      default:
serg@serg.mylan's avatar
serg@serg.mylan committed
294 295 296
        sql_print_warning("Found invalid password for user: '%s@%s'; "
                          "Ignoring user", user.user ? user.user : "",
                           user.host.hostname ? user.host.hostname : "");
297 298
        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
      uint next_field;
      user.access= get_access(table,3,&next_field) & GLOBAL_ACLS;
304 305 306 307 308 309
      /*
        if it is pre 5.0.1 privilege table then map CREATE privilege on
        CREATE VIEW & SHOW VIEW privileges
      */
      if (table->fields <= 31 && (user.access & CREATE_ACL))
        user.access|= (CREATE_VIEW_ACL | SHOW_VIEW_ACL);
310 311 312
      user.sort= get_sort(2,user.host.hostname,user.user);
      user.hostname_length= (user.host.hostname ?
                             (uint) strlen(user.host.hostname) : 0);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
313

314
      if (table->fields >= 31)	 /* Starting from 4.0.2 we have more fields */
315
      {
316
        char *ssl_type=get_field(&mem, table->field[next_field++]);
317 318 319 320 321 322 323 324 325
        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;

326 327 328
        user.ssl_cipher=   get_field(&mem, table->field[next_field++]);
        user.x509_issuer=  get_field(&mem, table->field[next_field++]);
        user.x509_subject= get_field(&mem, table->field[next_field++]);
329

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

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

end:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
413 414
  close_thread_tables(thd);
  delete thd;
415 416
  if (org_thd)
    org_thd->store_globals();			/* purecov: inspected */
417 418 419 420 421
  else
  {
    /* Remember that we don't have a THD */
    my_pthread_setspecific_ptr(THR_THD,  0);
  }
422
  DBUG_RETURN(return_val);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
423 424 425 426 427
}


void acl_free(bool end)
{
428
  free_root(&mem,MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
429 430 431 432 433 434 435 436 437 438 439 440 441 442
  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;
  }
}

443 444 445 446 447 448

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

  SYNOPSIS
    acl_reload()
monty@mysql.com's avatar
monty@mysql.com committed
449 450
    thd			Thread handle. Note that this may be NULL if we refresh
			because we got a signal    
451
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
452

453
void acl_reload(THD *thd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
454 455 456 457 458 459
{
  DYNAMIC_ARRAY old_acl_hosts,old_acl_users,old_acl_dbs;
  MEM_ROOT old_mem;
  bool old_initialized;
  DBUG_ENTER("acl_reload");

460
  if (thd && thd->locked_tables)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
461
  {					// Can't have locked tables here
462 463 464
    thd->lock=thd->locked_tables;
    thd->locked_tables=0;
    close_thread_tables(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
465 466 467 468 469 470 471 472 473 474 475
  }
  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);

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


499 500
/*
  Get all access bits from table after fieldnr
501 502

  IMPLEMENTATION
503 504
  We know that the access privileges ends when there is no more fields
  or the field is not an enum with two elements.
505 506 507 508 509 510 511 512 513 514 515

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

  RETURN VALUE
    privilege mask
516
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
517

518
static ulong get_access(TABLE *form, uint fieldnr, uint *next_field)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
519
{
520
  ulong access_bits=0,bit;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
521
  char buff[2];
522
  String res(buff,sizeof(buff),&my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
523 524
  Field **pos;

525 526 527
  for (pos=form->field+fieldnr, bit=1;
       *pos && (*pos)->real_type() == FIELD_TYPE_ENUM &&
	 ((Field_enum*) (*pos))->typelib->count == 2 ;
528
       pos++, fieldnr++, bit<<=1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
529
  {
530
    (*pos)->val_str(&res);
531
    if (my_toupper(&my_charset_latin1, res[0]) == 'Y')
532
      access_bits|= bit;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
533
  }
534 535
  if (next_field)
    *next_field=fieldnr;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
536 537 538 539 540
  return access_bits;
}


/*
541 542 543 544 545
  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
546 547 548 549 550 551 552

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

553 554 555
  /* Should not use this function with more than 4 arguments for compare. */
  DBUG_ASSERT(count <= 4);

bk@work.mysql.com's avatar
bk@work.mysql.com committed
556 557
  while (count--)
  {
558 559 560
    char *start, *str= va_arg(args,char*);
    uint chars= 0;
    uint wild_pos= 0;           /* first wildcard position */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
561

monty@mysql.com's avatar
monty@mysql.com committed
562
    if ((start= str))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
563 564 565 566
    {
      for (; *str ; str++)
      {
	if (*str == wild_many || *str == wild_one || *str == wild_prefix)
567
        {
monty@mysql.com's avatar
monty@mysql.com committed
568
          wild_pos= (uint) (str - start) + 1;
569 570
          break;
        }
monty@mysql.com's avatar
monty@mysql.com committed
571
        chars= 128;                             // Marker that chars existed
bk@work.mysql.com's avatar
bk@work.mysql.com committed
572 573
      }
    }
monty@mysql.com's avatar
monty@mysql.com committed
574
    sort= (sort << 8) + (wild_pos ? min(wild_pos, 127) : chars);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
  }
  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;
}

590

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

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
595 596 597 598
  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
599

600
  SYNOPSIS
601 602 603 604 605 606
    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
607
    passwd      scrambled & crypted password, received from client
608 609 610 611 612 613 614
                (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
615
  RETURN VALUE
616 617
    0  success: thd->priv_user, thd->priv_host, thd->master_access, mqh are
       updated
618
    1  user not found or authentication failure
619
    2  user found, has long (4.1.1) salt, but passwd is in old (3.23) format.
620
   -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
621 622
*/

623 624
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
625
{
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
626 627 628
  ulong user_access= NO_ACCESS;
  int res= 1;
  ACL_USER *acl_user= 0;
629
  DBUG_ENTER("acl_getroot");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
630 631

  if (!initialized)
632
  {
633 634 635 636 637 638
    /* 
      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
639
    bzero((char*) mqh, sizeof(*mqh));
640
    DBUG_RETURN(0);
641
  }
642

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
645
  /*
646 647 648
    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
649
  */
peter@mysql.com's avatar
peter@mysql.com committed
650

651
  for (uint i=0 ; i < acl_users.elements ; i++)
652
  {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
653 654
    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
655
    {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
656
      if (compare_hostname(&acl_user_tmp->host, thd->host, thd->ip))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
657
      {
658
        /* check password: it should be empty or valid */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
659
        if (passwd_len == acl_user_tmp->salt_len)
peter@mysql.com's avatar
peter@mysql.com committed
660
        {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
661
          if (acl_user_tmp->salt_len == 0 ||
serg@serg.mylan's avatar
serg@serg.mylan committed
662 663
              (acl_user_tmp->salt_len == SCRAMBLE_LENGTH ?
              check_scramble(passwd, thd->scramble, acl_user_tmp->salt) :
664
              check_scramble_323(passwd, thd->scramble,
serg@serg.mylan's avatar
serg@serg.mylan committed
665
                                 (ulong *) acl_user_tmp->salt)) == 0)
666
          {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
667
            acl_user= acl_user_tmp;
668 669
            res= 0;
          }
peter@mysql.com's avatar
peter@mysql.com committed
670
        }
671
        else if (passwd_len == SCRAMBLE_LENGTH &&
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
672
                 acl_user_tmp->salt_len == SCRAMBLE_LENGTH_323)
673
          res= -1;
674
        else if (passwd_len == SCRAMBLE_LENGTH_323 &&
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
675
                 acl_user_tmp->salt_len == SCRAMBLE_LENGTH)
676
          res= 2;
677 678
        /* linear search complete: */
        break;
peter@mysql.com's avatar
peter@mysql.com committed
679
      }
peter@mysql.com's avatar
peter@mysql.com committed
680
    }
681
  }
682 683 684 685
  /*
    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
686 687 688

  if (acl_user)
  {
689
    /* OK. User found and password checked continue validation */
690
#ifdef HAVE_OPENSSL
691
    Vio *vio=thd->net.vio;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
692
    SSL *ssl= (SSL*) vio->ssl_arg;
693
#endif
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
694

695
    /*
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
696
      At this point we know that user is allowed to connect
697 698 699 700 701 702
      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
703 704
    case SSL_TYPE_NONE:				// SSL is not required
      user_access= acl_user->access;
705
      break;
706
#ifdef HAVE_OPENSSL
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
707
    case SSL_TYPE_ANY:				// Any kind of SSL is ok
708
      if (vio_type(vio) == VIO_TYPE_SSL)
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
709
	user_access= acl_user->access;
710 711 712 713 714
      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
715

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
716 717
	We need to check for absence of SSL because without SSL
	we should reject connection.
718
      */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
719
      if (vio_type(vio) == VIO_TYPE_SSL &&
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
720 721
	  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
722
	user_access= acl_user->access;
723 724 725 726 727 728 729 730
      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
731
      X509 *cert;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
732
      if (vio_type(vio) != VIO_TYPE_SSL ||
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
733
	  SSL_get_verify_result(ssl) != X509_V_OK)
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
734
	break;
735
      if (acl_user->ssl_cipher)
peter@mysql.com's avatar
peter@mysql.com committed
736
      {
737
	DBUG_PRINT("info",("comparing ciphers: '%s' and '%s'",
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
738 739
			   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
740
	  user_access= acl_user->access;
741 742
	else
	{
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
743
	  if (global_system_variables.log_warnings)
serg@serg.mylan's avatar
serg@serg.mylan committed
744 745 746
	    sql_print_information("X509 ciphers mismatch: should be '%s' but is '%s'",
			      acl_user->ssl_cipher,
			      SSL_get_cipher(ssl));
747 748
	  break;
	}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
749
      }
750 751
      /* Prepare certificate (if exists) */
      DBUG_PRINT("info",("checkpoint 1"));
monty@mysql.com's avatar
monty@mysql.com committed
752 753 754 755 756
      if (!(cert= SSL_get_peer_certificate(ssl)))
      {
	user_access=NO_ACCESS;
	break;
      }
757
      DBUG_PRINT("info",("checkpoint 2"));
758
      /* If X509 issuer is specified, we check it... */
759
      if (acl_user->x509_issuer)
peter@mysql.com's avatar
peter@mysql.com committed
760
      {
kostja@oak.local's avatar
kostja@oak.local committed
761
        DBUG_PRINT("info",("checkpoint 3"));
762 763 764
	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
765
        if (strcmp(acl_user->x509_issuer, ptr))
766
        {
kostja@oak.local's avatar
kostja@oak.local committed
767
          if (global_system_variables.log_warnings)
serg@serg.mylan's avatar
serg@serg.mylan committed
768 769
            sql_print_information("X509 issuer mismatch: should be '%s' "
			      "but is '%s'", acl_user->x509_issuer, ptr);
770
          free(ptr);
kostja@oak.local's avatar
kostja@oak.local committed
771
          break;
772
        }
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
773
        user_access= acl_user->access;
kostja@oak.local's avatar
kostja@oak.local committed
774
        free(ptr);
peter@mysql.com's avatar
peter@mysql.com committed
775
      }
776 777 778 779
      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
780 781 782 783
        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))
784
        {
kostja@oak.local's avatar
kostja@oak.local committed
785
          if (global_system_variables.log_warnings)
serg@serg.mylan's avatar
serg@serg.mylan committed
786
            sql_print_information("X509 subject mismatch: '%s' vs '%s'",
kostja@oak.local's avatar
kostja@oak.local committed
787
                            acl_user->x509_subject, ptr);
788
        }
kostja@oak.local's avatar
kostja@oak.local committed
789
        else
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
790
          user_access= acl_user->access;
kostja@oak.local's avatar
kostja@oak.local committed
791
        free(ptr);
792 793
      }
      break;
peter@mysql.com's avatar
peter@mysql.com committed
794
#else  /* HAVE_OPENSSL */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
795
    default:
796
      /*
kostja@oak.local's avatar
kostja@oak.local committed
797 798 799
        If we don't have SSL but SSL is required for this user the 
        authentication should fail.
      */
800 801
      break;
#endif /* HAVE_OPENSSL */
peter@mysql.com's avatar
peter@mysql.com committed
802
    }
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
803
    thd->master_access= user_access;
804 805
    thd->priv_user= acl_user->user ? thd->user : (char *) "";
    *mqh= acl_user->user_resource;
806

807 808 809 810 811
    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
812
  VOID(pthread_mutex_unlock(&acl_cache->lock));
813
  DBUG_RETURN(res);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
814 815 816
}


817 818 819
/*
 * This is like acl_getroot() above, but it doesn't check password,
 * and we don't care about the user resources.
820
 * Used to get access rights for SQL SECURITY DEFINER invocation of
821 822 823 824 825 826
 * stored procedures.
 */
int acl_getroot_no_password(THD *thd)
{
  ulong user_access= NO_ACCESS;
  int res= 1;
827
  uint i;
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
  ACL_USER *acl_user= 0;
  DBUG_ENTER("acl_getroot_no_password");

  if (!initialized)
  {
    /* 
      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
    DBUG_RETURN(0);
  }

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

844 845 846
  thd->master_access= 0;
  thd->db_access= 0;

847 848 849 850 851 852
  /*
     Find acl entry in user database.
     This is specially tailored to suit the check we do for CALL of
     a stored procedure; thd->user is set to what is actually a
     priv_user, which can be ''.
  */
853
  for (i=0 ; i < acl_users.elements ; i++)
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
  {
    acl_user= dynamic_element(&acl_users,i,ACL_USER*);
    if ((!acl_user->user && (!thd->user || !thd->user[0])) ||
	(acl_user->user && strcmp(thd->user, acl_user->user) == 0))
    {
      if (compare_hostname(&acl_user->host, thd->host, thd->ip))
      {
	res= 0;
	break;
      }
    }
  }

  if (acl_user)
  {
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
    for (i=0 ; i < acl_dbs.elements ; i++)
    {
      ACL_DB *acl_db= dynamic_element(&acl_dbs, i, ACL_DB*);
      if (!acl_db->user ||
	  (thd->user && thd->user[0] && !strcmp(thd->user, acl_db->user)))
      {
	if (compare_hostname(&acl_db->host, thd->host, thd->ip))
	{
	  if (!acl_db->db || (thd->db && !strcmp(acl_db->db, thd->db)))
	  {
	    thd->db_access= acl_db->access;
	    break;
	  }
	}
      }
    }
885 886 887 888 889 890 891 892 893 894 895 896
    thd->master_access= acl_user->access;
    thd->priv_user= acl_user->user ? thd->user : (char *) "";

    if (acl_user->host.hostname)
      strmake(thd->priv_host, acl_user->host.hostname, MAX_HOSTNAME);
    else
      *thd->priv_host= 0;
  }
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  DBUG_RETURN(res);
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
897 898 899 900 901 902 903
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;
}

904

bk@work.mysql.com's avatar
bk@work.mysql.com committed
905
static void acl_update_user(const char *user, const char *host,
906
			    const char *password, uint password_len,
907 908 909 910
			    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
911
			    USER_RESOURCES  *mqh,
912
			    ulong privileges)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
913 914 915 916 917 918 919 920 921
{
  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] ||
922
	  acl_user->host.hostname &&
923
	  !my_strcasecmp(system_charset_info, host, acl_user->host.hostname))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
924 925
      {
	acl_user->access=privileges;
926
	if (mqh->bits & 1)
927
	  acl_user->user_resource.questions=mqh->questions;
928
	if (mqh->bits & 2)
929
	  acl_user->user_resource.updates=mqh->updates;
930
	if (mqh->bits & 4)
931
	  acl_user->user_resource.connections=mqh->connections;
932 933 934 935 936 937 938 939 940 941
	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);
	}
942 943
	if (password)
	  set_user_salt(acl_user, password, password_len);
944
        /* search complete: */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
945 946 947 948 949 950 951 952
	break;
      }
    }
  }
}


static void acl_insert_user(const char *user, const char *host,
953
			    const char *password, uint password_len,
954 955 956 957
			    enum SSL_type ssl_type,
			    const char *ssl_cipher,
			    const char *x509_issuer,
			    const char *x509_subject,
958
			    USER_RESOURCES *mqh,
959
			    ulong privileges)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
960 961
{
  ACL_USER acl_user;
962
  acl_user.user=*user ? strdup_root(&mem,user) : 0;
monty@mysql.com's avatar
monty@mysql.com committed
963
  update_hostname(&acl_user.host, *host ? strdup_root(&mem, host): 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
964
  acl_user.access=privileges;
965
  acl_user.user_resource = *mqh;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
966
  acl_user.sort=get_sort(2,acl_user.host.hostname,acl_user.user);
967
  acl_user.hostname_length=(uint) strlen(host);
968 969 970 971 972
  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;
973 974

  set_user_salt(&acl_user, password, password_len);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
975 976 977 978

  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
979
    allow_all_hosts=1;		// Anyone can connect /* purecov: tested */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
980 981 982 983 984 985 986 987 988 989 990
  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,
991
			  ulong privileges)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
992 993 994 995 996 997 998 999 1000
{
  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] ||
1001
	  acl_db->host.hostname &&
1002
	  !my_strcasecmp(system_charset_info, host, acl_db->host.hostname))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
      {
	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);
	}
      }
    }
  }
}


1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
/*
  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
1032
static void acl_insert_db(const char *user, const char *host, const char *db,
1033
			  ulong privileges)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1034 1035
{
  ACL_DB acl_db;
1036
  safe_mutex_assert_owner(&acl_cache->lock);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
  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);
}


1048 1049 1050 1051

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

1053
ulong acl_get(const char *host, const char *ip,
1054
              const char *user, const char *db, my_bool db_is_pattern)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1055
{
1056
  ulong host_access= ~0, db_access= 0;
1057
  uint i,key_length;
1058
  char key[ACL_KEY_LENGTH],*tmp_db,*end;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1059
  acl_entry *entry;
monty@mysql.com's avatar
monty@mysql.com committed
1060
  DBUG_ENTER("acl_get");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1061 1062

  VOID(pthread_mutex_lock(&acl_cache->lock));
1063
  end=strmov((tmp_db=strmov(strmov(key, ip ? ip : "")+1,user)+1),db);
1064 1065
  if (lower_case_table_names)
  {
1066
    my_casedn_str(files_charset_info, tmp_db);
1067 1068
    db=tmp_db;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1069 1070 1071 1072 1073
  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));
monty@mysql.com's avatar
monty@mysql.com committed
1074 1075
    DBUG_PRINT("exit", ("access: 0x%lx", db_access));
    DBUG_RETURN(db_access);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
  }

  /*
    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))
      {
1088
	if (!acl_db->db || !wild_compare(db,acl_db->db,db_is_pattern))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
	{
	  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))
    {
1110
      if (!acl_host->db || !wild_compare(db,acl_host->db,db_is_pattern))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
      {
	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));
monty@mysql.com's avatar
monty@mysql.com committed
1127 1128
  DBUG_PRINT("exit", ("access: 0x%lx", db_access & host_access));
  DBUG_RETURN(db_access & host_access);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1129 1130
}

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

static void init_check_host(void)
{
  DBUG_ENTER("init_check_host");
1142
  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
1143
			  acl_users.elements,1));
1144
  VOID(hash_init(&acl_check_hosts,system_charset_info,acl_users.elements,0,0,
1145
		 (hash_get_key) check_get_key,0,0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
  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 *);
1160
	  if (!my_strcasecmp(system_charset_info,
1161
                             acl_user->host.hostname, acl->hostname))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1162 1163 1164 1165 1166 1167
	    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,
1168
			    (uint) strlen(acl_user->host.hostname)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1169
      {
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1170
	if (my_hash_insert(&acl_check_hosts,(byte*) acl_user))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
	{					// 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));

1192 1193
  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
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
  {
    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
}


1212 1213 1214 1215 1216 1217 1218 1219
/*
  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
1220

1221
    RETURN VALUE
1222 1223
      0		OK
      1		ERROR  ; In this case the error is sent to the client.
1224 1225
*/

1226 1227
bool check_change_password(THD *thd, const char *host, const char *user,
                           char *new_password)
1228
{
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1229 1230
  if (!initialized)
  {
1231
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
1232
    return(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1233
  }
1234 1235
  if (!thd->slave_thread &&
      (strcmp(thd->user,user) ||
1236
       my_strcasecmp(system_charset_info, host, thd->host_or_ip)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1237
  {
hf@deer.(none)'s avatar
hf@deer.(none) committed
1238
    if (check_access(thd, UPDATE_ACL, "mysql",0,1,0))
1239
      return(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1240
  }
1241 1242
  if (!thd->slave_thread && !thd->user[0])
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1243 1244
    my_message(ER_PASSWORD_ANONYMOUS_USER, ER(ER_PASSWORD_ANONYMOUS_USER),
               MYF(0));
1245
    return(1);
1246
  }
1247
  uint len=strlen(new_password);
1248
  if (len && len != SCRAMBLED_PASSWORD_CHAR_LENGTH &&
1249 1250
      len != SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
  {
1251
    my_error(ER_PASSWD_LENGTH, MYF(0), SCRAMBLED_PASSWORD_CHAR_LENGTH);
1252 1253
    return -1;
  }
1254 1255 1256 1257
  return(0);
}


1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
/*
  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
1271
*/
1272

1273 1274 1275 1276 1277 1278 1279 1280
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

1281
  if (check_change_password(thd, host, user, new_password))
1282 1283
    DBUG_RETURN(1);

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1284 1285
  VOID(pthread_mutex_lock(&acl_cache->lock));
  ACL_USER *acl_user;
1286
  if (!(acl_user= find_acl_user(host, user)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1287 1288
  {
    VOID(pthread_mutex_unlock(&acl_cache->lock));
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1289
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH), MYF(0));
1290
    DBUG_RETURN(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1291
  }
1292 1293 1294 1295
  /* 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
1296 1297
  if (update_user_table(thd,
			acl_user->host.hostname ? acl_user->host.hostname : "",
1298
			acl_user->user ? acl_user->user : "",
1299
			new_password, new_password_len))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1300 1301
  {
    VOID(pthread_mutex_unlock(&acl_cache->lock)); /* purecov: deadcode */
1302
    DBUG_RETURN(1); /* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1303
  }
peter@mysql.com's avatar
peter@mysql.com committed
1304

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

1308
  char buff[512]; /* Extend with extended password length*/
1309
  ulong query_length=
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1310 1311
    my_sprintf(buff,
	       (buff,"SET PASSWORD FOR \"%-.120s\"@\"%-.120s\"=\"%-.120s\"",
1312
		acl_user->user ? acl_user->user : "",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1313 1314
		acl_user->host.hostname ? acl_user->host.hostname : "",
		new_password));
guilhem@mysql.com's avatar
guilhem@mysql.com committed
1315
  thd->clear_error();
1316
  Query_log_event qinfo(thd, buff, query_length, 0, FALSE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1317
  mysql_bin_log.write(&qinfo);
1318
  DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
}


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

static ACL_USER *
find_acl_user(const char *host, const char *user)
{
1329
  DBUG_ENTER("find_acl_user");
1330
  DBUG_PRINT("enter",("host: '%s'  user: '%s'",host,user));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1331 1332 1333
  for (uint i=0 ; i < acl_users.elements ; i++)
  {
    ACL_USER *acl_user=dynamic_element(&acl_users,i,ACL_USER*);
1334
    DBUG_PRINT("info",("strcmp('%s','%s'), compare_hostname('%s','%s'),",
1335 1336 1337 1338 1339
		       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
1340 1341 1342
    if (!acl_user->user && !user[0] ||
	acl_user->user && !strcmp(user,acl_user->user))
    {
1343
      if (compare_hostname(&acl_user->host,host,host))
1344 1345 1346
      {
	DBUG_RETURN(acl_user);
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1347 1348
    }
  }
1349
  DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1350 1351 1352
}


1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
/*
  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
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386

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!
1387
  if (!hostname ||
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1388 1389 1390
      (!(hostname=calc_ip(hostname,&host->ip,'/')) ||
       !(hostname=calc_ip(hostname+1,&host->ip_mask,'\0'))))
  {
1391
    host->ip= host->ip_mask=0;			// Not a masked ip
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
  }
}


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 ||
1405
	  (hostname && !wild_case_compare(system_charset_info,
1406
                                          hostname,host->hostname)) ||
1407
	  (ip && !wild_compare(ip,host->hostname,0)));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1408 1409
}

hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1410 1411 1412 1413
bool hostname_requires_resolving(const char *hostname)
{
  char cur;
  if (!hostname)
monty@mysql.com's avatar
monty@mysql.com committed
1414
    return FALSE;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1415 1416 1417
  int namelen= strlen(hostname);
  int lhlen= strlen(my_localhost);
  if ((namelen == lhlen) &&
1418
      !my_strnncoll(system_charset_info, (const uchar *)hostname,  namelen,
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1419
		    (const uchar *)my_localhost, strlen(my_localhost)))
monty@mysql.com's avatar
monty@mysql.com committed
1420
    return FALSE;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1421 1422 1423 1424
  for (; (cur=*hostname); hostname++)
  {
    if ((cur != '%') && (cur != '_') && (cur != '.') &&
	((cur < '0') || (cur > '9')))
monty@mysql.com's avatar
monty@mysql.com committed
1425
      return TRUE;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1426
  }
monty@mysql.com's avatar
monty@mysql.com committed
1427
  return FALSE;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1428
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1429

1430 1431 1432
/*
  Update grants in the user and database privilege tables
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1433 1434

static bool update_user_table(THD *thd, const char *host, const char *user,
1435
			      const char *new_password, uint new_password_len)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1436 1437 1438 1439
{
  TABLE_LIST tables;
  TABLE *table;
  bool error=1;
1440
  char user_key[MAX_KEY_LENGTH];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1441 1442 1443 1444
  DBUG_ENTER("update_user_table");
  DBUG_PRINT("enter",("user: %s  host: %s",user,host));

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

1448 1449 1450 1451 1452 1453 1454
#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
1455 1456 1457
    /*
      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.
1458
    */
1459
    tables.updating= 1;
1460 1461 1462 1463 1464 1465
    /* 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
1466 1467
  if (!(table=open_ltable(thd,&tables,TL_WRITE)))
    DBUG_RETURN(1); /* purecov: deadcode */
1468 1469
  table->field[0]->store(host,(uint) strlen(host), system_charset_info);
  table->field[1]->store(user,(uint) strlen(user), system_charset_info);
1470 1471
  key_copy(user_key, table->record[0], table->key_info,
           table->key_info->key_length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1472

1473
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
1474 1475
  if (table->file->index_read_idx(table->record[0], 0,
				  user_key, table->key_info->key_length,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1476 1477
				  HA_READ_KEY_EXACT))
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1478 1479
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH),
               MYF(0));	/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1480 1481
    DBUG_RETURN(1);				/* purecov: deadcode */
  }
1482
  store_record(table,record[1]);
1483
  table->field[2]->store(new_password, new_password_len, system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
  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
1496 1497 1498 1499 1500 1501 1502 1503 1504

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

1510
    db_access=acl_get(thd->host, thd->ip,
1511
		      thd->priv_user, tl.db, 0);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1512 1513
    if (!(db_access & INSERT_ACL))
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1514
      if (check_grant(thd, INSERT_ACL, &tl, 0, UINT_MAX, 1))
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1515 1516 1517 1518 1519 1520 1521
	create_new_users=0;
    }
  }
  return create_new_users;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
1522
/****************************************************************************
1523
  Handle GRANT commands
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1524 1525
****************************************************************************/

1526
static int replace_user_table(THD *thd, TABLE *table, const LEX_USER &combo,
1527 1528
			      ulong rights, bool revoke_grant,
			      bool create_user)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1529 1530
{
  int error = -1;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1531
  bool old_row_exists=0;
1532
  const char *password= "";
1533
  uint password_len= 0;
1534
  char what= (revoke_grant) ? 'N' : 'Y';
1535
  byte user_key[MAX_KEY_LENGTH];
1536
  LEX *lex= thd->lex;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1537
  DBUG_ENTER("replace_user_table");
1538

1539
  safe_mutex_assert_owner(&acl_cache->lock);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1540 1541

  if (combo.password.str && combo.password.str[0])
1542
  {
1543 1544
    if (combo.password.length != SCRAMBLED_PASSWORD_CHAR_LENGTH &&
        combo.password.length != SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
1545
    {
1546
      my_error(ER_PASSWD_LENGTH, MYF(0), SCRAMBLED_PASSWORD_CHAR_LENGTH);
1547
      DBUG_RETURN(-1);
1548
    }
1549
    password_len= combo.password.length;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1550
    password=combo.password.str;
1551
  }
peter@mysql.com's avatar
peter@mysql.com committed
1552

1553 1554
  table->field[0]->store(combo.host.str,combo.host.length, system_charset_info);
  table->field[1]->store(combo.user.str,combo.user.length, system_charset_info);
1555 1556 1557
  key_copy(user_key, table->record[0], table->key_info,
           table->key_info->key_length);

1558
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
1559
  if (table->file->index_read_idx(table->record[0], 0,
1560 1561
                                  user_key, table->key_info->key_length,
                                  HA_READ_KEY_EXACT))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1562
  {
1563 1564
    /* what == 'N' means revoke */
    if (what == 'N')
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1565
    {
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
      my_error(ER_NONEXISTING_GRANT, MYF(0), combo.user.str, combo.host.str);
      goto end;
    }
    /*
      There are four options which affect the process of creation of 
      a new user(mysqld option --safe-create-user, 'insert' privilege
      on 'mysql.user' table, using 'GRANT' with 'IDENTIFIED BY' and
      SQL_MODE flag NO_AUTO_CREATE_USER). Below is the simplified rule
      how it should work.
      if (safe-user-create && ! INSERT_priv) => reject
      else if (identified_by) => create
      else if (no_auto_create_user) => reject
      else create
    */
    else if (((thd->variables.sql_mode & MODE_NO_AUTO_CREATE_USER) &&
              !password_len) || !create_user)
    {
      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
1585 1586
      goto end;
    }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1587
    old_row_exists = 0;
1588 1589
    restore_record(table,default_values);       // cp empty row from default_values
    table->field[0]->store(combo.host.str,combo.host.length,
1590
                           system_charset_info);
1591
    table->field[1]->store(combo.user.str,combo.user.length,
1592
                           system_charset_info);
1593
    table->field[2]->store(password, password_len,
1594
                           system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1595 1596 1597
  }
  else
  {
1598 1599 1600 1601 1602 1603 1604
    /*
      Check that the user isn't trying to change a password for another
      user if he doesn't have UPDATE privilege to the MySQL database
    */
    DBUG_ASSERT(combo.host.str);
    if (thd->user && combo.password.str &&
        (strcmp(thd->user,combo.user.str) ||
1605
         my_strcasecmp(system_charset_info,
1606 1607 1608
                       combo.host.str, thd->host_or_ip)) &&
        check_access(thd, UPDATE_ACL, "mysql",0,1,0))
      goto end;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1609
    old_row_exists = 1;
1610
    store_record(table,record[1]);			// Save copy for update
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1611
    if (combo.password.str)			// If password given
1612
      table->field[2]->store(password, password_len, system_charset_info);
1613 1614
    else if (!rights && !revoke_grant &&
             lex->ssl_type == SSL_TYPE_NOT_SPECIFIED && !lex->mqh.bits)
1615 1616 1617
    {
      DBUG_RETURN(0);
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1618 1619
  }

1620 1621 1622 1623 1624 1625 1626 1627
  /* 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
1628
  {
1629
    if (priv & rights)				 // set requested privileges
1630
      (*tmp_field)->store(&what, 1, &my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1631 1632
  }
  rights=get_access(table,3);
1633
  DBUG_PRINT("info",("table->fields: %d",table->fields));
1634
  if (table->fields >= 31)		/* From 4.0.0 we have more fields */
1635
  {
1636
    /* We write down SSL related ACL stuff */
1637
    switch (lex->ssl_type) {
1638
    case SSL_TYPE_ANY:
1639 1640 1641 1642
      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);
1643 1644
      break;
    case SSL_TYPE_X509:
1645 1646 1647 1648
      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);
1649 1650
      break;
    case SSL_TYPE_SPECIFIED:
1651 1652 1653 1654
      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);
1655 1656
      if (lex->ssl_cipher)
	table->field[25]->store(lex->ssl_cipher,
1657
				strlen(lex->ssl_cipher), system_charset_info);
1658 1659
      if (lex->x509_issuer)
	table->field[26]->store(lex->x509_issuer,
1660
				strlen(lex->x509_issuer), system_charset_info);
1661 1662
      if (lex->x509_subject)
	table->field[27]->store(lex->x509_subject,
1663
				strlen(lex->x509_subject), system_charset_info);
1664
      break;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1665
    case SSL_TYPE_NOT_SPECIFIED:
gluh@gluh.(none)'s avatar
gluh@gluh.(none) committed
1666 1667
      break;
    case SSL_TYPE_NONE:
1668 1669 1670 1671
      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
1672
      break;
1673
    }
1674

1675
    USER_RESOURCES mqh= lex->mqh;
1676
    if (mqh.bits & 1)
1677
      table->field[28]->store((longlong) mqh.questions);
1678
    if (mqh.bits & 2)
1679
      table->field[29]->store((longlong) mqh.updates);
1680
    if (mqh.bits & 4)
1681
      table->field[30]->store((longlong) mqh.connections);
1682
    mqh_used = mqh_used || mqh.questions || mqh.updates || mqh.connections;
1683
  }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1684
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1685 1686 1687 1688 1689
  {
    /*
      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!
    */
1690
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
1691
    if (cmp_record(table,record[1]) &&
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
	(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

1711
end:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1712 1713 1714
  if (!error)
  {
    acl_cache->clear(1);			// Clear privilege cache
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1715
    if (old_row_exists)
1716 1717
      acl_update_user(combo.user.str, combo.host.str,
                      combo.password.str, password_len,
1718 1719 1720 1721 1722
		      lex->ssl_type,
		      lex->ssl_cipher,
		      lex->x509_issuer,
		      lex->x509_subject,
		      &lex->mqh,
1723
		      rights);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1724
    else
1725
      acl_insert_user(combo.user.str, combo.host.str, password, password_len,
1726 1727 1728 1729 1730
		      lex->ssl_type,
		      lex->ssl_cipher,
		      lex->x509_issuer,
		      lex->x509_subject,
		      &lex->mqh,
1731
		      rights);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1732 1733 1734 1735 1736 1737
  }
  DBUG_RETURN(error);
}


/*
1738
  change grants in the mysql.db table
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1739 1740 1741 1742
*/

static int replace_db_table(TABLE *table, const char *db,
			    const LEX_USER &combo,
1743
			    ulong rights, bool revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1744
{
1745 1746
  uint i;
  ulong priv,store_rights;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1747
  bool old_row_exists=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1748
  int error;
1749
  char what= (revoke_grant) ? 'N' : 'Y';
1750
  byte user_key[MAX_KEY_LENGTH];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1751 1752
  DBUG_ENTER("replace_db_table");

1753 1754
  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
1755
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
1756 1757 1758
    DBUG_RETURN(-1);
  }

1759
  /* Check if there is such a user in user table in memory? */
1760
  if (!find_acl_user(combo.host.str,combo.user.str))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1761
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1762
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH), MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1763 1764 1765
    DBUG_RETURN(-1);
  }

1766 1767 1768
  table->field[0]->store(combo.host.str,combo.host.length, system_charset_info);
  table->field[1]->store(db,(uint) strlen(db), system_charset_info);
  table->field[2]->store(combo.user.str,combo.user.length, system_charset_info);
1769 1770 1771
  key_copy(user_key, table->record[0], table->key_info,
           table->key_info->key_length);

1772 1773
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
  if (table->file->index_read_idx(table->record[0],0,
1774 1775
                                  user_key, table->key_info->key_length,
                                  HA_READ_KEY_EXACT))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1776 1777 1778
  {
    if (what == 'N')
    { // no row, no revoke
guilhem@mysql.com's avatar
guilhem@mysql.com committed
1779
      my_error(ER_NONEXISTING_GRANT, MYF(0), combo.user.str, combo.host.str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1780 1781
      goto abort;
    }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1782
    old_row_exists = 0;
1783
    restore_record(table,default_values);			// cp empty row from default_values
1784 1785 1786
    table->field[0]->store(combo.host.str,combo.host.length, system_charset_info);
    table->field[1]->store(db,(uint) strlen(db), system_charset_info);
    table->field[2]->store(combo.user.str,combo.user.length, system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1787 1788 1789
  }
  else
  {
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1790
    old_row_exists = 1;
1791
    store_record(table,record[1]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1792 1793 1794
  }

  store_rights=get_rights_for_db(rights);
1795
  for (i= 3, priv= 1; i < table->fields; i++, priv <<= 1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1796
  {
1797
    if (priv & store_rights)			// do it if priv is chosen
1798
      table->field [i]->store(&what,1, &my_charset_latin1);// set requested privileges
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1799 1800 1801 1802
  }
  rights=get_access(table,3);
  rights=fix_rights_for_db(rights);

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1803
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1804
  {
1805
    /* update old existing row */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1806 1807
    if (rights)
    {
1808
      table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1809 1810 1811 1812 1813 1814 1815 1816 1817
      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 */
    }
  }
1818
  else if (rights && (error=table->file->write_row(table->record[0])))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1819 1820 1821 1822 1823 1824
  {
    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
1825
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1826 1827
    acl_update_db(combo.user.str,combo.host.str,db,rights);
  else
1828
  if (rights)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1829 1830 1831 1832
    acl_insert_db(combo.user.str,combo.host.str,db,rights);
  DBUG_RETURN(0);

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

1836
abort:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1837 1838 1839 1840 1841 1842 1843 1844
  DBUG_RETURN(-1);
}


class GRANT_COLUMN :public Sql_alloc
{
public:
  char *column;
1845 1846 1847
  ulong rights;
  uint key_length;
  GRANT_COLUMN(String &c,  ulong y) :rights (y)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1848
  {
1849
    column= memdup_root(&memex,c.ptr(), key_length=c.length());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1850 1851 1852
  }
};

1853

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1854 1855 1856 1857 1858 1859 1860
static byte* get_key_column(GRANT_COLUMN *buff,uint *length,
			    my_bool not_used __attribute__((unused)))
{
  *length=buff->key_length;
  return (byte*) buff->column;
}

1861

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1862 1863 1864
class GRANT_TABLE :public Sql_alloc
{
public:
monty@mysql.com's avatar
monty@mysql.com committed
1865
  char *host,*db, *user, *tname, *hash_key, *orig_host;
1866
  ulong privs, cols;
1867
  ulong sort;
1868
  uint key_length;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1869
  HASH hash_columns;
monty@mysql.com's avatar
monty@mysql.com committed
1870 1871 1872 1873

  GRANT_TABLE(const char *h, const char *d,const char *u,
              const char *t, ulong p, ulong c);
  GRANT_TABLE (TABLE *form, TABLE *col_privs);
1874
  ~GRANT_TABLE();
1875 1876
  bool ok() { return privs != 0 || cols != 0; }
};
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1877

1878

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

1880 1881 1882 1883 1884 1885
GRANT_TABLE::GRANT_TABLE(const char *h, const char *d,const char *u,
                         const char *t, ulong p, ulong c)
  :privs(p), cols(c)
{
  /* Host given by user */
  orig_host=  strdup_root(&memex,h);
1886
  /* Convert empty hostname to '%' for easy comparison */
1887 1888 1889 1890 1891 1892
  host=  orig_host[0] ? orig_host : (char*) "%";
  db =   strdup_root(&memex,d);
  user = strdup_root(&memex,u);
  sort=  get_sort(3,host,db,user);
  tname= strdup_root(&memex,t);
  if (lower_case_table_names)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1893
  {
1894 1895
    my_casedn_str(files_charset_info, db);
    my_casedn_str(files_charset_info, tname);
1896 1897 1898 1899
  }
  key_length =(uint) strlen(d)+(uint) strlen(u)+(uint) strlen(t)+3;
  hash_key = (char*) alloc_root(&memex,key_length);
  strmov(strmov(strmov(hash_key,user)+1,db)+1,tname);
1900
  (void) hash_init(&hash_columns,system_charset_info,
monty@mysql.com's avatar
monty@mysql.com committed
1901
                   0,0,0, (hash_get_key) get_key_column,0,0);
1902
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1903

1904 1905 1906 1907 1908

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

monty@mysql.com's avatar
monty@mysql.com committed
1909 1910 1911
  orig_host= host= get_field(&memex, form->field[0]);
  db=    get_field(&memex,form->field[1]);
  user=  get_field(&memex,form->field[2]);
1912 1913 1914 1915 1916 1917 1918
  if (!user)
    user= (char*) "";
  if (!orig_host)
  {
    orig_host= (char*) "";
    host= (char*) "%";
  }
monty@mysql.com's avatar
monty@mysql.com committed
1919 1920
  sort=  get_sort(3, orig_host, db, user);
  tname= get_field(&memex,form->field[3]);
1921 1922 1923
  if (!db || !tname)
  {
    /* Wrong table row; Ignore it */
1924 1925
    hash_clear(&hash_columns);                  /* allow for destruction */
    privs= cols= 0;				/* purecov: inspected */
1926 1927 1928 1929
    return;					/* purecov: inspected */
  }
  if (lower_case_table_names)
  {
1930 1931
    my_casedn_str(files_charset_info, db);
    my_casedn_str(files_charset_info, tname);
1932 1933 1934 1935 1936 1937 1938 1939 1940 1941
  }
  key_length = ((uint) strlen(db) + (uint) strlen(user) +
                (uint) strlen(tname) + 3);
  hash_key = (char*) alloc_root(&memex,key_length);
  strmov(strmov(strmov(hash_key,user)+1,db)+1,tname);
  privs = (ulong) form->field[6]->val_int();
  cols  = (ulong) form->field[7]->val_int();
  privs = fix_rights_for_table(privs);
  cols =  fix_rights_for_column(cols);

1942
  (void) hash_init(&hash_columns,system_charset_info,
monty@mysql.com's avatar
monty@mysql.com committed
1943
                   0,0,0, (hash_get_key) get_key_column,0,0);
1944 1945
  if (cols)
  {
1946 1947
    uint key_prefix_len;
    KEY_PART_INFO *key_part= col_privs->key_info->key_part;
monty@mysql.com's avatar
monty@mysql.com committed
1948
    col_privs->field[0]->store(orig_host,(uint) strlen(orig_host),
1949 1950 1951 1952
                               system_charset_info);
    col_privs->field[1]->store(db,(uint) strlen(db), system_charset_info);
    col_privs->field[2]->store(user,(uint) strlen(user), system_charset_info);
    col_privs->field[3]->store(tname,(uint) strlen(tname), system_charset_info);
1953 1954 1955 1956 1957 1958

    key_prefix_len= (key_part[0].store_length +
                     key_part[1].store_length +
                     key_part[2].store_length +
                     key_part[3].store_length);
    key_copy(key, col_privs->record[0], col_privs->key_info, key_prefix_len);
monty@mysql.com's avatar
monty@mysql.com committed
1959
    col_privs->field[4]->store("",0, &my_charset_latin1);
1960

1961 1962
    col_privs->file->ha_index_init(0);
    if (col_privs->file->index_read(col_privs->record[0],
1963 1964
                                    (byte*) key,
                                    key_prefix_len, HA_READ_KEY_EXACT))
1965
    {
1966
      cols = 0; /* purecov: deadcode */
1967
      col_privs->file->ha_index_end();
1968
      return;
1969
    }
1970
    do
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1971
    {
1972 1973 1974
      String *res,column_name;
      GRANT_COLUMN *mem_check;
      /* As column name is a string, we don't have to supply a buffer */
monty@mysql.com's avatar
monty@mysql.com committed
1975
      res=col_privs->field[4]->val_str(&column_name);
1976 1977 1978
      ulong priv= (ulong) col_privs->field[6]->val_int();
      if (!(mem_check = new GRANT_COLUMN(*res,
                                         fix_rights_for_column(priv))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1979
      {
1980 1981 1982
        /* Don't use this entry */
        privs = cols = 0;			/* purecov: deadcode */
        return;				/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1983
      }
monty@mysql.com's avatar
monty@mysql.com committed
1984
      my_hash_insert(&hash_columns, (byte *) mem_check);
1985
    } while (!col_privs->file->index_next(col_privs->record[0]) &&
1986
             !key_cmp_if_same(col_privs,key,0,key_prefix_len));
1987
    col_privs->file->ha_index_end();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1988
  }
1989
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1990

1991

1992 1993 1994 1995 1996 1997
GRANT_TABLE::~GRANT_TABLE()
{
  hash_free(&hash_columns);
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
1998 1999 2000 2001 2002 2003 2004
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;
}

2005

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2006 2007 2008 2009 2010
void free_grant_table(GRANT_TABLE *grant_table)
{
  hash_free(&grant_table->hash_columns);
}

2011

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023
/* 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;
2024 2025
  for (grant_table=(GRANT_TABLE*) hash_search(&column_priv_hash,
					      (byte*) helping,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2026 2027
					      len) ;
       grant_table ;
2028 2029
       grant_table= (GRANT_TABLE*) hash_next(&column_priv_hash,(byte*) helping,
					     len))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2030 2031 2032
  {
    if (exact)
    {
2033
      if ((host &&
2034
	   !my_strcasecmp(system_charset_info, host, grant_table->host)) ||
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2035 2036 2037 2038 2039
	  (ip && !strcmp(ip,grant_table->host)))
	return grant_table;
    }
    else
    {
2040
      if (((host && !wild_case_compare(system_charset_info,
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2041
				       host,grant_table->host)) ||
2042
	   (ip && !wild_case_compare(system_charset_info,
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2043
				     ip,grant_table->host))) &&
2044
          (!found || found->sort < grant_table->sort))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2045 2046 2047 2048 2049 2050 2051 2052
	found=grant_table;					// Host ok
    }
  }
  return found;
}



2053
inline GRANT_COLUMN *
2054
column_hash_search(GRANT_TABLE *t, const char *cname, uint length)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2055 2056 2057 2058 2059 2060 2061 2062 2063
{
  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,
2064
				ulong rights, bool revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2065 2066 2067
{
  int error=0,result=0;
  byte key[MAX_KEY_LENGTH];
2068 2069
  uint key_prefix_length;
  KEY_PART_INFO *key_part= table->key_info->key_part;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2070 2071
  DBUG_ENTER("replace_column_table");

2072 2073 2074 2075
  table->field[0]->store(combo.host.str,combo.host.length, system_charset_info);
  table->field[1]->store(db,(uint) strlen(db), system_charset_info);
  table->field[2]->store(combo.user.str,combo.user.length, system_charset_info);
  table->field[3]->store(table_name,(uint) strlen(table_name), system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2076

2077 2078 2079 2080
  /* Get length of 3 first key parts */
  key_prefix_length= (key_part[0].store_length + key_part[1].store_length +
                      key_part[2].store_length + key_part[3].store_length);
  key_copy(key, table->record[0], table->key_info, key_prefix_length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2081

2082
  rights&= COL_ACLS;				// Only ACL for columns
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2083 2084 2085 2086 2087

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

  List_iterator <LEX_COLUMN> iter(columns);
  class LEX_COLUMN *xx;
2088
  table->file->ha_index_init(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2089 2090
  while ((xx=iter++))
  {
2091
    ulong privileges = xx->rights;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2092
    bool old_row_exists=0;
2093 2094 2095 2096
    byte user_key[MAX_KEY_LENGTH];

    key_restore(table->record[0],key,table->key_info,
                key_prefix_length);
2097
    table->field[4]->store(xx->column.ptr(),xx->column.length(),
2098
                           system_charset_info);
2099 2100 2101
    /* Get key for the first 4 columns */
    key_copy(user_key, table->record[0], table->key_info,
             table->key_info->key_length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2102

2103
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
2104 2105 2106
    if (table->file->index_read(table->record[0], user_key,
				table->key_info->key_length,
                                HA_READ_KEY_EXACT))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2107 2108 2109
    {
      if (revoke_grant)
      {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2110
	my_error(ER_NONEXISTING_TABLE_GRANT, MYF(0),
2111 2112
                 combo.user.str, combo.host.str,
                 table_name); /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2113 2114 2115
	result= -1; /* purecov: inspected */
	continue; /* purecov: inspected */
      }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2116
      old_row_exists = 0;
2117
      restore_record(table,default_values);		// Get empty record
2118 2119
      key_restore(table->record[0],key,table->key_info,
                  key_prefix_length);
2120
      table->field[4]->store(xx->column.ptr(),xx->column.length(),
2121
                             system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2122 2123 2124
    }
    else
    {
2125
      ulong tmp= (ulong) table->field[6]->val_int();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2126 2127 2128 2129 2130 2131
      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
2132
      old_row_exists = 1;
2133
      store_record(table,record[1]);			// copy original row
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2134 2135 2136 2137
    }

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

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2138
    if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164
    {
      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
2165
      my_hash_insert(&g_t->hash_columns,(byte*) grant_column);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2166 2167 2168 2169 2170 2171 2172 2173 2174 2175
    }
  }

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

  if (revoke_grant)
  {
2176 2177
    byte user_key[MAX_KEY_LENGTH];
    key_copy(user_key, table->record[0], table->key_info,
2178 2179
             key_prefix_length);

2180
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
2181
    if (table->file->index_read(table->record[0], user_key,
2182
				key_prefix_length,
2183
                                HA_READ_KEY_EXACT))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2184 2185
      goto end;

2186
    /* Scan through all rows with the same host,db,user and table */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2187 2188
    do
    {
2189
      ulong privileges = (ulong) table->field[6]->val_int();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2190
      privileges=fix_rights_for_column(privileges);
2191
      store_record(table,record[1]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2192 2193 2194 2195 2196

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

	privileges&= ~rights;
	table->field[6]->store((longlong)
			       get_rights_for_column(privileges));
2203
	table->field[4]->val_str(&column_name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233
	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]) &&
2234
	     !key_cmp_if_same(table, key, 0, key_prefix_length));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2235 2236
  }

2237
end:
2238
  table->file->ha_index_end();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2239 2240 2241 2242 2243 2244 2245
  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,
2246 2247
			       ulong rights, ulong col_rights,
			       bool revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2248
{
2249
  char grantor[HOSTNAME_LENGTH+USERNAME_LENGTH+2];
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2250
  int old_row_exists = 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2251
  int error=0;
2252
  ulong store_table_rights, store_col_rights;
2253
  byte user_key[MAX_KEY_LENGTH];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2254 2255
  DBUG_ENTER("replace_table_table");

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

2258 2259 2260 2261
  /*
    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
2262 2263
  if (!find_acl_user(combo.host.str,combo.user.str))
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2264 2265
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH),
               MYF(0));	/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2266 2267 2268
    DBUG_RETURN(-1);				/* purecov: deadcode */
  }

2269
  restore_record(table,default_values);			// Get empty record
2270 2271 2272 2273
  table->field[0]->store(combo.host.str,combo.host.length, system_charset_info);
  table->field[1]->store(db,(uint) strlen(db), system_charset_info);
  table->field[2]->store(combo.user.str,combo.user.length, system_charset_info);
  table->field[3]->store(table_name,(uint) strlen(table_name), system_charset_info);
2274
  store_record(table,record[1]);			// store at pos 1
2275 2276
  key_copy(user_key, table->record[0], table->key_info,
           table->key_info->key_length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2277

2278
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
2279 2280
  if (table->file->index_read_idx(table->record[0], 0,
                                  user_key, table->key_info->key_length,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2281 2282 2283 2284 2285 2286 2287 2288 2289
				  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
2290 2291
      my_error(ER_NONEXISTING_TABLE_GRANT, MYF(0),
               combo.user.str, combo.host.str,
2292
               table_name);		        /* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2293 2294
      DBUG_RETURN(-1);				/* purecov: deadcode */
    }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2295
    old_row_exists = 0;
2296
    restore_record(table,record[1]);			// Get saved record
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2297 2298
  }

2299 2300
  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
2301
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2302
  {
2303
    ulong j,k;
2304
    store_record(table,record[1]);
2305 2306
    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
2307 2308 2309

    if (revoke_grant)
    {
2310
      /* column rights are already fixed in mysql_table_grant */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2311 2312 2313 2314
      store_table_rights=j & ~store_table_rights;
    }
    else
    {
2315 2316
      store_table_rights|= j;
      store_col_rights|=   k;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2317 2318 2319
    }
  }

2320
  table->field[4]->store(grantor,(uint) strlen(grantor), system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2321 2322 2323
  table->field[6]->store((longlong) store_table_rights);
  table->field[7]->store((longlong) store_col_rights);
  rights=fix_rights_for_table(store_table_rights);
2324
  col_rights=fix_rights_for_column(store_col_rights);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2325

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2326
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342
  {
    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 */
  }

2343
  if (rights | col_rights)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2344
  {
2345
    grant_table->privs= rights;
2346
    grant_table->cols=	col_rights;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2347 2348 2349
  }
  else
  {
2350
    hash_delete(&column_priv_hash,(byte*) grant_table);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2351 2352 2353
  }
  DBUG_RETURN(0);

2354 2355
  /* This should never happen */
table_error:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2356 2357 2358 2359 2360
  table->file->print_error(error,MYF(0)); /* purecov: deadcode */
  DBUG_RETURN(-1); /* purecov: deadcode */
}


2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373
/*
  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
2374 2375
    FALSE ok
    TRUE  error
2376 2377
*/

2378
bool mysql_table_grant(THD *thd, TABLE_LIST *table_list,
2379 2380 2381
		      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
2382
{
2383
  ulong column_priv= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2384 2385 2386
  List_iterator <LEX_USER> str_list (user_list);
  LEX_USER *Str;
  TABLE_LIST tables[3];
2387
  bool create_new_users=0;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2388
  char *db_name, *real_name;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2389 2390 2391 2392
  DBUG_ENTER("mysql_table_grant");

  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2393 2394
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0),
             "--skip-grant-tables");	/* purecov: inspected */
2395
    DBUG_RETURN(TRUE);				/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2396 2397 2398
  }
  if (rights & ~TABLE_ACLS)
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2399 2400
    my_message(ER_ILLEGAL_GRANT_FOR_TABLE, ER(ER_ILLEGAL_GRANT_FOR_TABLE),
               MYF(0));
2401
    DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2402 2403 2404 2405
  }

  if (columns.elements && !revoke_grant)
  {
2406 2407
    class LEX_COLUMN *column;
    List_iterator <LEX_COLUMN> column_iter(columns);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2408
    int res;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2409

2410 2411
    if (open_and_lock_tables(thd, table_list))
      DBUG_RETURN(TRUE);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2412
    
2413
    while ((column = column_iter++))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2414
    {
2415
      uint unused_field_idx= NO_CACHED_FIELD_INDEX;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2416
      if (!find_field_in_table(thd, table_list, column->column.ptr(),
2417
                               column->column.ptr(),
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2418
                               column->column.length(), 0, 0, 0, 0,
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2419
                               &unused_field_idx, FALSE))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2420
      {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2421 2422
	my_error(ER_BAD_FIELD_ERROR, MYF(0),
                 column->column.c_ptr(), table_list->alias);
2423
	DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2424
      }
2425
      column_priv|= column->rights;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2426 2427 2428 2429 2430 2431
    }
    close_thread_tables(thd);
  }
  else if (!(rights & CREATE_ACL) && !revoke_grant)
  {
    char buf[FN_REFLEN];
2432 2433
    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
2434 2435 2436
    fn_format(buf,buf,"","",4+16+32);
    if (access(buf,F_OK))
    {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2437
      my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->alias);
2438
      DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2439 2440 2441 2442 2443 2444
    }
  }

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

  bzero((char*) &tables,sizeof(tables));
2445 2446 2447
  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";
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2448
  tables[0].next_local= tables[0].next_global= tables+1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2449
  /* Don't open column table if we don't need it ! */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2450 2451 2452 2453 2454
  tables[1].next_local=
    tables[1].next_global= ((column_priv ||
			     (revoke_grant &&
			      ((rights & COL_ACLS) || columns.elements)))
			    ? tables+2 : 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2455 2456 2457
  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";

2458 2459 2460 2461 2462
#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
2463 2464
  if (thd->slave_thread && table_rules_on)
  {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2465 2466 2467
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
2468
    */
2469
    tables[0].updating= tables[1].updating= tables[2].updating= 1;
2470
    if (!tables_ok(0, tables))
2471
      DBUG_RETURN(FALSE);
2472
  }
2473 2474
#endif

2475
  if (simple_open_n_lock_tables(thd,tables))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2476 2477
  {						// Should never happen
    close_thread_tables(thd);			/* purecov: deadcode */
2478
    DBUG_RETURN(TRUE);				/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2479 2480
  }

2481 2482
  if (!revoke_grant)
    create_new_users= test_if_create_new_users(thd);
2483
  bool result= FALSE;
2484
  rw_wrlock(&LOCK_grant);
2485 2486
  MEM_ROOT *old_root= thd->mem_root;
  thd->mem_root= &memex;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2487 2488 2489

  while ((Str = str_list++))
  {
2490
    int error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2491 2492 2493 2494
    GRANT_TABLE *grant_table;
    if (Str->host.length > HOSTNAME_LENGTH ||
	Str->user.length > USERNAME_LENGTH)
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2495 2496
      my_message(ER_GRANT_WRONG_HOST_OR_USER, ER(ER_GRANT_WRONG_HOST_OR_USER),
                 MYF(0));
2497
      result= TRUE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2498 2499 2500
      continue;
    }
    /* Create user if needed */
2501
    pthread_mutex_lock(&acl_cache->lock);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2502 2503
    error=replace_user_table(thd, tables[0].table, *Str,
			     0, revoke_grant, create_new_users);
2504 2505
    pthread_mutex_unlock(&acl_cache->lock);
    if (error)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2506
    {
2507
      result= TRUE;				// Remember error
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2508 2509 2510
      continue;					// Add next user
    }

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2511 2512 2513 2514 2515 2516 2517
    db_name= (table_list->view_db.length ?
	      table_list->view_db.str :
	      table_list->db);
    real_name= (table_list->view_name.length ?
		table_list->view_name.str :
		table_list->real_name);

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2518
    /* Find/create cached table grant */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2519 2520
    grant_table= table_hash_search(Str->host.str, NullS, db_name,
				   Str->user.str, real_name, 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2521 2522 2523 2524
    if (!grant_table)
    {
      if (revoke_grant)
      {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2525 2526
	my_error(ER_NONEXISTING_TABLE_GRANT, MYF(0),
                 Str->user.str, Str->host.str, table_list->real_name);
2527
	result= TRUE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2528 2529
	continue;
      }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2530 2531
      grant_table = new GRANT_TABLE (Str->host.str, db_name,
				     Str->user.str, real_name,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2532 2533 2534 2535
				     rights,
				     column_priv);
      if (!grant_table)				// end of memory
      {
2536
	result= TRUE;				/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2537 2538
	continue;				/* purecov: deadcode */
      }
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2539
      my_hash_insert(&column_priv_hash,(byte*) grant_table);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2540 2541 2542 2543 2544
    }

    /* If revoke_grant, calculate the new column privilege for tables_priv */
    if (revoke_grant)
    {
2545 2546
      class LEX_COLUMN *column;
      List_iterator <LEX_COLUMN> column_iter(columns);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2547 2548 2549
      GRANT_COLUMN *grant_column;

      /* Fix old grants */
2550
      while ((column = column_iter++))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2551 2552
      {
	grant_column = column_hash_search(grant_table,
2553 2554
					  column->column.ptr(),
					  column->column.length());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2555
	if (grant_column)
2556
	  grant_column->rights&= ~(column->rights | rights);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2557 2558
      }
      /* scan trough all columns to get new column grant */
2559
      column_priv= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575
      for (uint idx=0 ; idx < grant_table->hash_columns.records ; idx++)
      {
	grant_column= (GRANT_COLUMN*) hash_element(&grant_table->hash_columns,
						   idx);
	grant_column->rights&= ~rights;		// Fix other columns
	column_priv|= grant_column->rights;
      }
    }
    else
    {
      column_priv|= grant_table->cols;
    }


    /* update table and columns */

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2576 2577
    if (replace_table_table(thd, grant_table, tables[1].table, *Str,
			    db_name, real_name,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2578
			    rights, column_priv, revoke_grant))
2579 2580
    {
      /* Should only happen if table is crashed */
2581
      result= TRUE;			       /* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2582 2583 2584
    }
    else if (tables[2].table)
    {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2585
      if ((replace_column_table(grant_table, tables[2].table, *Str,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2586
				columns,
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2587
				db_name, real_name,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2588 2589
				rights, revoke_grant)))
      {
2590
	result= TRUE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2591 2592 2593 2594
      }
    }
  }
  grant_option=TRUE;
2595
  thd->mem_root= old_root;
2596
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2597
  if (!result)
2598
    send_ok(thd);
2599
  /* Tables are automatically closed */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2600 2601 2602 2603
  DBUG_RETURN(result);
}


2604 2605
bool mysql_grant(THD *thd, const char *db, List <LEX_USER> &list,
                 ulong rights, bool revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2606 2607 2608
{
  List_iterator <LEX_USER> str_list (list);
  LEX_USER *Str;
2609
  char tmp_db[NAME_LEN+1];
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2610
  bool create_new_users=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2611 2612 2613 2614
  TABLE_LIST tables[2];
  DBUG_ENTER("mysql_grant");
  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2615 2616
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0),
             "--skip-grant-tables");	/* purecov: tested */
2617
    DBUG_RETURN(TRUE);				/* purecov: tested */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2618 2619
  }

2620 2621 2622
  if (lower_case_table_names && db)
  {
    strmov(tmp_db,db);
2623
    my_casedn_str(files_charset_info, tmp_db);
2624 2625
    db=tmp_db;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2626 2627

  /* open the mysql.user and mysql.db tables */
2628
  bzero((char*) &tables,sizeof(tables));
2629 2630
  tables[0].alias=tables[0].real_name=(char*) "user";
  tables[1].alias=tables[1].real_name=(char*) "db";
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2631
  tables[0].next_local= tables[0].next_global= tables+1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2632 2633
  tables[0].lock_type=tables[1].lock_type=TL_WRITE;
  tables[0].db=tables[1].db=(char*) "mysql";
2634 2635 2636 2637 2638 2639

#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
2640 2641
  if (thd->slave_thread && table_rules_on)
  {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2642 2643 2644
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
2645
    */
2646
    tables[0].updating= tables[1].updating= 1;
2647
    if (!tables_ok(0, tables))
2648
      DBUG_RETURN(FALSE);
2649
  }
2650 2651
#endif

2652
  if (simple_open_n_lock_tables(thd,tables))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2653 2654
  {						// This should never happen
    close_thread_tables(thd);			/* purecov: deadcode */
2655
    DBUG_RETURN(TRUE);				/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2656 2657
  }

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2658 2659
  if (!revoke_grant)
    create_new_users= test_if_create_new_users(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2660

2661
  /* go through users in user_list */
2662
  rw_wrlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2663 2664 2665 2666 2667 2668 2669 2670 2671
  VOID(pthread_mutex_lock(&acl_cache->lock));
  grant_version++;

  int result=0;
  while ((Str = str_list++))
  {
    if (Str->host.length > HOSTNAME_LENGTH ||
	Str->user.length > USERNAME_LENGTH)
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2672 2673
      my_message(ER_GRANT_WRONG_HOST_OR_USER, ER(ER_GRANT_WRONG_HOST_OR_USER),
                 MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2674 2675 2676
      result= -1;
      continue;
    }
2677
    if ((replace_user_table(thd,
2678
			    tables[0].table,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2679
			    *Str,
2680 2681
			    (!db ? rights : 0), revoke_grant,
			    create_new_users)))
2682
      result= -1;
2683
    else if (db)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2684
    {
2685 2686 2687 2688 2689 2690 2691 2692 2693
      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
2694
	my_error(ER_WRONG_USAGE, MYF(0), "DB GRANT", "GLOBAL PRIVILEGES");
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2695
	result= -1;
2696
      }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2697
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2698 2699
  }
  VOID(pthread_mutex_unlock(&acl_cache->lock));
2700
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2701 2702 2703
  close_thread_tables(thd);

  if (!result)
2704
    send_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2705 2706 2707
  DBUG_RETURN(result);
}

2708 2709

/* Free grant array if possible */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2710 2711 2712 2713 2714

void  grant_free(void)
{
  DBUG_ENTER("grant_free");
  grant_option = FALSE;
2715
  hash_free(&column_priv_hash);
2716
  free_root(&memex,MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2717 2718 2719 2720 2721 2722
  DBUG_VOID_RETURN;
}


/* Init grant array if possible */

2723
my_bool grant_init(THD *org_thd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2724
{
2725
  THD  *thd;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2726
  TABLE_LIST tables[2];
2727
  MYSQL_LOCK *lock;
2728
  MEM_ROOT *memex_ptr;
2729
  my_bool return_val= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2730
  TABLE *t_table, *c_table;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2731
  bool check_no_resolve= specialflag & SPECIAL_NO_RESOLVE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2732 2733 2734
  DBUG_ENTER("grant_init");

  grant_option = FALSE;
2735
  (void) hash_init(&column_priv_hash,system_charset_info,
2736
		   0,0,0, (hash_get_key) get_grant_table,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2737
		   (hash_free_key) free_grant_table,0);
2738
  init_sql_alloc(&memex, ACL_ALLOC_BLOCK_SIZE, 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2739

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2744 2745
  if (!(thd=new THD))
    DBUG_RETURN(1);				/* purecov: deadcode */
2746
  thd->store_globals();
2747 2748
  thd->db= my_strdup("mysql",MYF(0));
  thd->db_length=5;				// Safety
2749
  bzero((char*) &tables, sizeof(tables));
2750 2751
  tables[0].alias=tables[0].real_name= (char*) "tables_priv";
  tables[1].alias=tables[1].real_name= (char*) "columns_priv";
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2752
  tables[0].next_local= tables[0].next_global= tables+1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2753 2754 2755
  tables[0].lock_type=tables[1].lock_type=TL_READ;
  tables[0].db=tables[1].db=thd->db;

2756 2757
  uint counter;
  if (open_tables(thd, tables, &counter))
2758 2759
    goto end;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2760 2761 2762
  TABLE *ptr[2];				// Lock tables for quick update
  ptr[0]= tables[0].table;
  ptr[1]= tables[1].table;
2763 2764
  if (!(lock=mysql_lock_tables(thd,ptr,2)))
    goto end;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2765 2766

  t_table = tables[0].table; c_table = tables[1].table;
2767
  t_table->file->ha_index_init(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2768 2769
  if (t_table->file->index_first(t_table->record[0]))
  {
2770
    return_val= 0;
2771
    goto end_unlock;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2772
  }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2773
  grant_option= TRUE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2774

2775
  /* Will be restored by org_thd->store_globals() */
2776 2777
  memex_ptr= &memex;
  my_pthread_setspecific_ptr(THR_MALLOC, &memex_ptr);
2778
  do
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2779 2780
  {
    GRANT_TABLE *mem_check;
Sinisa@sinisa.nasamreza.org's avatar
Sinisa@sinisa.nasamreza.org committed
2781
    if (!(mem_check=new GRANT_TABLE(t_table,c_table)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2782 2783
    {
      /* This could only happen if we are out memory */
2784
      grant_option= FALSE;			/* purecov: deadcode */
2785
      goto end_unlock;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2786
    }
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2787 2788 2789 2790 2791

    if (check_no_resolve)
    {
      if (hostname_requires_resolving(mem_check->host))
      {
serg@serg.mylan's avatar
serg@serg.mylan committed
2792 2793 2794 2795
        sql_print_warning("'tables_priv' entry '%s %s@%s' "
                          "ignored in --skip-name-resolve mode.",
                          mem_check->tname, mem_check->user,
                          mem_check->host, mem_check->host);
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2796 2797 2798 2799
	continue;
      }
    }

2800 2801 2802
    if (! mem_check->ok())
      delete mem_check;
    else if (my_hash_insert(&column_priv_hash,(byte*) mem_check))
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2803
    {
2804
      delete mem_check;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2805 2806 2807
      grant_option= FALSE;
      goto end_unlock;
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2808
  }
2809 2810 2811 2812 2813
  while (!t_table->file->index_next(t_table->record[0]));

  return_val=0;					// Return ok

end_unlock:
2814
  t_table->file->ha_index_end();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2815 2816
  mysql_unlock_tables(thd, lock);
  thd->version--;				// Force close to free memory
2817 2818

end:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2819 2820
  close_thread_tables(thd);
  delete thd;
2821 2822
  if (org_thd)
    org_thd->store_globals();
2823 2824 2825 2826 2827
  else
  {
    /* Remember that we don't have a THD */
    my_pthread_setspecific_ptr(THR_THD,  0);
  }
2828
  DBUG_RETURN(return_val);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2829 2830 2831
}


2832
/*
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2833
 Reload grant array (table and column privileges) if possible
2834 2835 2836 2837 2838 2839 2840 2841

  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
2842

2843
void grant_reload(THD *thd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2844
{
2845 2846
  HASH old_column_priv_hash;
  bool old_grant_option;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2847 2848 2849
  MEM_ROOT old_mem;
  DBUG_ENTER("grant_reload");

2850
  rw_wrlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2851
  grant_version++;
2852
  old_column_priv_hash= column_priv_hash;
2853
  old_grant_option= grant_option;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2854
  old_mem= memex;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2855

2856
  if (grant_init(thd))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2857
  {						// Error. Revert to old hash
2858
    DBUG_PRINT("error",("Reverting to old privileges"));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2859
    grant_free();				/* purecov: deadcode */
2860
    column_priv_hash= old_column_priv_hash;	/* purecov: deadcode */
2861
    grant_option= old_grant_option;		/* purecov: deadcode */
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2862
    memex= old_mem;				/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2863 2864 2865
  }
  else
  {
2866
    hash_free(&old_column_priv_hash);
2867
    free_root(&old_mem,MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2868
  }
2869
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2870 2871 2872 2873 2874
  DBUG_VOID_RETURN;
}


/****************************************************************************
2875
  Check table level grants
2876

2877
  SYNOPSIS
2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890
   bool check_grant()
   thd		Thread handler
   want_access  Bits of privileges user needs to have
   tables	List of tables to check. The user should have 'want_access'
		to all tables in list.
   show_table	<> 0 if we are in show table. In this case it's enough to have
	        any privilege for the table
   number	Check at most this number of tables.
   no_errors	If 0 then we write an error. The error is sent directly to
		the client

   RETURN
     0  ok
2891
     1  Error: User did not have the requested privileges
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2892 2893
****************************************************************************/

2894
bool check_grant(THD *thd, ulong want_access, TABLE_LIST *tables,
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2895
		 uint show_table, uint number, bool no_errors)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2896 2897 2898
{
  TABLE_LIST *table;
  char *user = thd->priv_user;
2899 2900
  DBUG_ENTER("check_grant");
  DBUG_ASSERT(number > 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2901

2902
  want_access&= ~thd->master_access;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2903
  if (!want_access)
2904
    DBUG_RETURN(0);                             // ok
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2905

2906
  rw_rdlock(&LOCK_grant);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2907
  for (table= tables; table && number--; table= table->next_global)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2908
  {
2909
    GRANT_TABLE *grant_table;
2910 2911
    if (!(~table->grant.privilege & want_access) || 
        table->derived || table->schema_table)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2912
    {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2913 2914 2915 2916 2917
      /*
        It is subquery in the FROM clause. VIEW set table->derived after
        table opening, but this function always called before table opening.
      */
      table->grant.want_privilege= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2918 2919
      continue;					// Already checked
    }
2920 2921
    if (!(grant_table= table_hash_search(thd->host,thd->ip,
                                         table->db,user, table->real_name,0)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2922 2923 2924 2925
    {
      want_access &= ~table->grant.privilege;
      goto err;					// No grants
    }
monty@tramp.mysql.fi's avatar
monty@tramp.mysql.fi committed
2926 2927
    if (show_table)
      continue;					// We have some priv on this
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943

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

2947
err:
2948
  rw_unlock(&LOCK_grant);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2949
  if (!no_errors)				// Not a silent skip of table
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2950 2951 2952
  {
    const char *command="";
    if (want_access & SELECT_ACL)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2953
      command= "select";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2954
    else if (want_access & INSERT_ACL)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2955
      command= "insert";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2956
    else if (want_access & UPDATE_ACL)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2957
      command= "update";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2958
    else if (want_access & DELETE_ACL)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2959
      command= "delete";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2960
    else if (want_access & DROP_ACL)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2961
      command= "drop";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2962
    else if (want_access & CREATE_ACL)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2963
      command= "create";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2964
    else if (want_access & ALTER_ACL)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2965
      command= "alter";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2966
    else if (want_access & INDEX_ACL)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2967
      command= "index";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2968
    else if (want_access & GRANT_ACL)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2969
      command= "grant";
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2970 2971 2972
    else if (want_access & CREATE_VIEW_ACL)
      command= "create view";
    else if (want_access & SHOW_VIEW_ACL)
2973
      command= "show create view";
2974 2975 2976 2977 2978
    my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0),
             command,
             thd->priv_user,
             thd->host_or_ip,
             table ? table->real_name : "unknown");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2979
  }
2980
  DBUG_RETURN(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2981 2982 2983
}


bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2984 2985 2986
bool check_grant_column(THD *thd, GRANT_INFO *grant,
			char*db_name, char *table_name,
			const char *name, uint length, uint show_tables)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2987 2988 2989 2990
{
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2991
  ulong want_access= grant->want_privilege & ~grant->privilege;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2992 2993 2994
  if (!want_access)
    return 0;					// Already checked

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

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

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2999
  if (grant->version != grant_version)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3000
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3001 3002
    grant->grant_table=
      table_hash_search(thd->host, thd->ip, db_name,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3003
			thd->priv_user,
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3004 3005
			table_name, 0);	/* purecov: inspected */
    grant->version= grant_version;		/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3006
  }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3007
  if (!(grant_table= grant->grant_table))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3008 3009 3010 3011 3012
    goto err;					/* purecov: deadcode */

  grant_column=column_hash_search(grant_table, name, length);
  if (grant_column && !(~grant_column->rights & want_access))
  {
3013
    rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3014 3015 3016
    return 0;
  }
#ifdef NOT_USED
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3017
  if (show_tables && (grant_column || grant->privilege & COL_ACLS))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3018
  {
3019
    rw_unlock(&LOCK_grant);			/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3020 3021 3022 3023
    return 0;					/* purecov: deadcode */
  }
#endif

3024
err:
3025
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3026 3027
  if (!show_tables)
  {
3028 3029
    char command[128];
    get_privilege_desc(command, sizeof(command), want_access);
3030 3031 3032 3033 3034 3035
    my_error(ER_COLUMNACCESS_DENIED_ERROR, MYF(0),
             command,
             thd->priv_user,
             thd->host_or_ip,
             name,
             table_name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3036 3037 3038 3039 3040
  }
  return 1;
}


bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3041 3042 3043
bool check_grant_all_columns(THD *thd, ulong want_access, GRANT_INFO *grant,
                             char* db_name, char *table_name,
                             Field_iterator *fields)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3044 3045 3046
{
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;
3047
  Field *field=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3048

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3049
  want_access &= ~grant->privilege;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3050
  if (!want_access)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3051
    return 0;				// Already checked
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3052 3053
  if (!grant_option)
    goto err2;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3054

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

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

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3059
  if (grant->version != grant_version)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3060
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3061 3062
    grant->grant_table=
      table_hash_search(thd->host, thd->ip, db_name,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3063
			thd->priv_user,
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3064 3065
			table_name, 0);	/* purecov: inspected */
    grant->version= grant_version;		/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3066
  }
3067
  /* The following should always be true */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3068
  if (!(grant_table= grant->grant_table))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3069 3070
    goto err;					/* purecov: inspected */

3071
  for (; !fields->end_of_fields(); fields->next())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3072
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3073 3074 3075
    const char *field_name= fields->name();
    grant_column= column_hash_search(grant_table, field_name,
				    (uint) strlen(field_name));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3076 3077 3078
    if (!grant_column || (~grant_column->rights & want_access))
      goto err;
  }
3079
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3080 3081
  return 0;

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3082
err:
3083
  rw_unlock(&LOCK_grant);
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3084
err2:
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3085
  const char *command= "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3086
  if (want_access & SELECT_ACL)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3087
    command= "select";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3088
  else if (want_access & INSERT_ACL)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3089
    command= "insert";
3090 3091 3092 3093 3094 3095
  my_error(ER_COLUMNACCESS_DENIED_ERROR, MYF(0),
           command,
           thd->priv_user,
           thd->host_or_ip,
           fields->name(),
           table_name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3096 3097 3098 3099
  return 1;
}


3100
/*
3101 3102 3103
  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
3104
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3105 3106 3107 3108 3109 3110 3111 3112

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

3115
  for (uint idx=0 ; idx < column_priv_hash.records ; idx++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3116
  {
3117 3118
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  idx);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3119 3120
    if (len < grant_table->key_length &&
	!memcmp(grant_table->hash_key,helping,len) &&
3121
	(thd->host && !wild_case_compare(system_charset_info,
3122
                                         thd->host,grant_table->host) ||
3123
	 (thd->ip && !wild_case_compare(system_charset_info,
3124
                                        thd->ip,grant_table->host))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3125 3126 3127 3128 3129
    {
      error=0;					// Found match
      break;
    }
  }
3130
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3131 3132 3133 3134
  return error;
}

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

3138
ulong get_table_grant(THD *thd, TABLE_LIST *table)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3139
{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3140
  ulong privilege;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3141 3142 3143 3144
  char *user = thd->priv_user;
  const char *db = table->db ? table->db : thd->db;
  GRANT_TABLE *grant_table;

3145
  rw_rdlock(&LOCK_grant);
3146 3147 3148
#ifdef EMBEDDED_LIBRARY
  grant_table= NULL;
#else
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3149 3150
  grant_table= table_hash_search(thd->host, thd->ip, db, user,
				 table->real_name, 0);
3151
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3152 3153 3154 3155
  table->grant.grant_table=grant_table; // Remember for column test
  table->grant.version=grant_version;
  if (grant_table)
    table->grant.privilege|= grant_table->privs;
3156
  privilege= table->grant.privilege;
3157
  rw_unlock(&LOCK_grant);
3158
  return privilege;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3159 3160 3161
}


bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3162 3163 3164
ulong get_column_grant(THD *thd, GRANT_INFO *grant,
                       const char *db_name, const char *table_name,
                       const char *field_name)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3165 3166 3167
{
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;
3168
  ulong priv;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3169

3170
  rw_rdlock(&LOCK_grant);
3171
  /* reload table if someone has modified any grants */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3172
  if (grant->version != grant_version)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3173
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3174 3175
    grant->grant_table=
      table_hash_search(thd->host, thd->ip, db_name,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3176
			thd->priv_user,
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3177 3178
			table_name, 0);	        /* purecov: inspected */
    grant->version= grant_version;              /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3179 3180
  }

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3181 3182
  if (!(grant_table= grant->grant_table))
    priv= grant->privilege;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3183 3184
  else
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3185 3186
    grant_column= column_hash_search(grant_table, field_name,
                                     (uint) strlen(field_name));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3187
    if (!grant_column)
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3188
      priv= grant->privilege;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3189
    else
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3190
      priv= grant->privilege | grant_column->rights;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3191
  }
3192
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3193 3194 3195
  return priv;
}

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

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

3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210
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
3211 3212

static const char *command_array[]=
3213
{
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3214 3215 3216 3217 3218
  "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",
  "CREATE VIEW", "SHOW VIEW"
3219
};
3220

3221 3222
static uint command_lengths[]=
{
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3223
  6, 6, 6, 6, 6, 4, 6, 8, 7, 4, 5, 10, 5, 5, 14, 5, 23, 11, 7, 17, 18, 11, 9
3224 3225
};

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

3227 3228 3229 3230 3231 3232 3233
/*
  SHOW GRANTS;  Send grants for a user to the client

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

3234
bool mysql_show_grants(THD *thd,LEX_USER *lex_user)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3235
{
3236 3237
  ulong want_access;
  uint counter,index;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3238
  int  error = 0;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3239 3240
  ACL_USER *acl_user;
  ACL_DB *acl_db;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3241
  char buff[1024];
3242
  Protocol *protocol= thd->protocol;
tonu@x153.internalnet's avatar
tonu@x153.internalnet committed
3243
  DBUG_ENTER("mysql_show_grants");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3244 3245 3246 3247

  LINT_INIT(acl_user);
  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3248
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
3249
    DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3250
  }
monty@mysql.com's avatar
monty@mysql.com committed
3251 3252 3253 3254 3255 3256

  if (!lex_user->host.str)
  {
    lex_user->host.str= (char*) "%";
    lex_user->host.length=1;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3257 3258 3259
  if (lex_user->host.length > HOSTNAME_LENGTH ||
      lex_user->user.length > USERNAME_LENGTH)
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3260 3261
    my_message(ER_GRANT_WRONG_HOST_OR_USER, ER(ER_GRANT_WRONG_HOST_OR_USER),
               MYF(0));
3262
    DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3263 3264 3265 3266 3267 3268 3269
  }

  for (counter=0 ; counter < acl_users.elements ; counter++)
  {
    const char *user,*host;
    acl_user=dynamic_element(&acl_users,counter,ACL_USER*);
    if (!(user=acl_user->user))
monty@mysql.com's avatar
monty@mysql.com committed
3270
      user= "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3271
    if (!(host=acl_user->host.hostname))
monty@mysql.com's avatar
monty@mysql.com committed
3272
      host= "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3273
    if (!strcmp(lex_user->user.str,user) &&
3274
	!my_strcasecmp(system_charset_info, lex_user->host.str, host))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3275 3276
      break;
  }
peter@mysql.com's avatar
peter@mysql.com committed
3277
  if (counter == acl_users.elements)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3278
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3279 3280
    my_error(ER_NONEXISTING_GRANT, MYF(0),
             lex_user->user.str, lex_user->host.str);
3281
    DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3282 3283
  }

3284
  Item_string *field=new Item_string("",0,&my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3285 3286 3287 3288 3289 3290
  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);
3291 3292
  if (protocol->send_fields(&field_list,
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
3293
    DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3294

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3295
  rw_wrlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3296 3297 3298 3299
  VOID(pthread_mutex_lock(&acl_cache->lock));

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

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3304
    want_access= acl_user->access;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3305 3306 3307 3308
    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
3309
    else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3310 3311
    {
      bool found=0;
3312
      ulong j,test_access= want_access & ~GRANT_ACL;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3313 3314
      for (counter=0, j = SELECT_ACL;j <= GLOBAL_ACLS;counter++,j <<= 1)
      {
peter@mysql.com's avatar
peter@mysql.com committed
3315
	if (test_access & j)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3316 3317 3318 3319 3320 3321 3322 3323 3324
	{
	  if (found)
	    global.append(", ",2);
	  found=1;
	  global.append(command_array[counter],command_lengths[counter]);
	}
      }
    }
    global.append (" ON *.* TO '",12);
3325 3326
    global.append(lex_user->user.str, lex_user->user.length,
		  system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3327
    global.append ("'@'",3);
3328 3329
    global.append(lex_user->host.str,lex_user->host.length,
		  system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3330
    global.append ('\'');
3331
    if (acl_user->salt_len)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3332
    {
3333 3334 3335 3336 3337
      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
3338
      global.append(" IDENTIFIED BY PASSWORD '",25);
3339
      global.append(passwd_buff);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3340 3341
      global.append('\'');
    }
3342 3343
    /* "show grants" SSL related stuff */
    if (acl_user->ssl_type == SSL_TYPE_ANY)
3344
      global.append(" REQUIRE SSL",12);
3345
    else if (acl_user->ssl_type == SSL_TYPE_X509)
3346
      global.append(" REQUIRE X509",13);
3347
    else if (acl_user->ssl_type == SSL_TYPE_SPECIFIED)
3348
    {
3349
      int ssl_options = 0;
3350
      global.append(" REQUIRE ",9);
3351 3352
      if (acl_user->x509_issuer)
      {
3353 3354 3355
	ssl_options++;
	global.append("ISSUER \'",8);
	global.append(acl_user->x509_issuer,strlen(acl_user->x509_issuer));
3356
	global.append('\'');
3357
      }
3358 3359
      if (acl_user->x509_subject)
      {
3360 3361 3362
	if (ssl_options++)
	  global.append(' ');
	global.append("SUBJECT \'",9);
3363 3364
	global.append(acl_user->x509_subject,strlen(acl_user->x509_subject),
                      system_charset_info);
3365
	global.append('\'');
tonu@x153.internalnet's avatar
tonu@x153.internalnet committed
3366
      }
3367 3368
      if (acl_user->ssl_cipher)
      {
3369 3370 3371
	if (ssl_options++)
	  global.append(' ');
	global.append("CIPHER '",8);
3372 3373
	global.append(acl_user->ssl_cipher,strlen(acl_user->ssl_cipher),
                      system_charset_info);
3374
	global.append('\'');
3375 3376
      }
    }
3377 3378 3379
    if ((want_access & GRANT_ACL) ||
	(acl_user->user_resource.questions | acl_user->user_resource.updates |
	 acl_user->user_resource.connections))
3380
    {
peter@mysql.com's avatar
peter@mysql.com committed
3381
      global.append(" WITH",5);
3382
      if (want_access & GRANT_ACL)
peter@mysql.com's avatar
peter@mysql.com committed
3383
	global.append(" GRANT OPTION",13);
3384 3385 3386 3387 3388 3389
      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");
3390
    }
3391
    protocol->prepare_for_resend();
3392
    protocol->store(global.ptr(),global.length(),global.charset());
3393
    if (protocol->write())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3394
    {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3395
      error= -1;
3396
      goto end;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3397 3398 3399 3400 3401 3402
    }
  }

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

    acl_db=dynamic_element(&acl_dbs,counter,ACL_DB*);
    if (!(user=acl_db->user))
monty@mysql.com's avatar
monty@mysql.com committed
3407
      user= "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3408
    if (!(host=acl_db->host.hostname))
monty@mysql.com's avatar
monty@mysql.com committed
3409
      host= "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3410 3411

    if (!strcmp(lex_user->user.str,user) &&
3412
	!my_strcasecmp(system_charset_info, lex_user->host.str, host))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3413 3414
    {
      want_access=acl_db->access;
peter@mysql.com's avatar
peter@mysql.com committed
3415
      if (want_access)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3416
      {
3417
	String db(buff,sizeof(buff),system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3418 3419 3420 3421 3422
	db.length(0);
	db.append("GRANT ",6);

	if (test_all_bits(want_access,(DB_ACLS & ~GRANT_ACL)))
	  db.append("ALL PRIVILEGES",14);
3423
	else if (!(want_access & ~GRANT_ACL))
3424
	  db.append("USAGE",5);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3425 3426 3427
	else
	{
	  int found=0, cnt;
3428
	  ulong j,test_access= want_access & ~GRANT_ACL;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439
	  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]);
	    }
	  }
	}
3440 3441 3442
	db.append (" ON ",4);
	append_identifier(thd, &db, acl_db->db, strlen(acl_db->db));
	db.append (".* TO '",7);
3443 3444
	db.append(lex_user->user.str, lex_user->user.length,
		  system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3445
	db.append ("'@'",3);
3446 3447
	db.append(lex_user->host.str, lex_user->host.length,
                  system_charset_info);
peter@mysql.com's avatar
peter@mysql.com committed
3448
	db.append ('\'');
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3449
	if (want_access & GRANT_ACL)
3450
	  db.append(" WITH GRANT OPTION",18);
3451
	protocol->prepare_for_resend();
3452
	protocol->store(db.ptr(),db.length(),db.charset());
3453
	if (protocol->write())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3454
	{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3455
	  error= -1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3456 3457 3458 3459 3460 3461
	  goto end;
	}
      }
    }
  }

3462
  /* Add table & column access */
3463
  for (index=0 ; index < column_priv_hash.records ; index++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3464
  {
monty@mysql.com's avatar
monty@mysql.com committed
3465
    const char *user;
3466 3467
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  index);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3468 3469

    if (!(user=grant_table->user))
3470
      user= "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3471 3472

    if (!strcmp(lex_user->user.str,user) &&
3473
	!my_strcasecmp(system_charset_info, lex_user->host.str,
monty@mysql.com's avatar
monty@mysql.com committed
3474
                       grant_table->orig_host))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3475
    {
3476 3477
      ulong table_access= grant_table->privs;
      if ((table_access | grant_table->cols) != 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3478
      {
3479
	String global(buff, sizeof(buff), system_charset_info);
3480 3481
	ulong test_access= (table_access | grant_table->cols) & ~GRANT_ACL;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3482 3483 3484
	global.length(0);
	global.append("GRANT ",6);

3485
	if (test_all_bits(table_access, (TABLE_ACLS & ~GRANT_ACL)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3486
	  global.append("ALL PRIVILEGES",14);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3487
	else if (!test_access)
3488
 	  global.append("USAGE",5);
peter@mysql.com's avatar
peter@mysql.com committed
3489
	else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3490
	{
3491
          /* Add specific column access */
3492
	  int found= 0;
3493
	  ulong j;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3494

3495
	  for (counter= 0, j= SELECT_ACL; j <= TABLE_ACLS; counter++, j<<= 1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3496
	  {
peter@mysql.com's avatar
peter@mysql.com committed
3497
	    if (test_access & j)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3498 3499 3500
	    {
	      if (found)
		global.append(", ",2);
3501
	      found= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3502 3503
	      global.append(command_array[counter],command_lengths[counter]);

peter@mysql.com's avatar
peter@mysql.com committed
3504
	      if (grant_table->cols)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3505
	      {
3506
		uint found_col= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3507 3508 3509 3510 3511 3512
		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
3513
		  if (grant_column->rights & j)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3514
		  {
peter@mysql.com's avatar
peter@mysql.com committed
3515
		    if (!found_col)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3516
		    {
3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527
		      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
3528 3529 3530 3531 3532
		      global.append(" (",2);
		    }
		    else
		      global.append(", ",2);
		    global.append(grant_column->column,
3533 3534
				  grant_column->key_length,
				  system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3535 3536 3537 3538 3539 3540 3541 3542
		  }
		}
		if (found_col)
		  global.append(')');
	      }
	    }
	  }
	}
3543 3544 3545 3546 3547 3548 3549
	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);
3550 3551
	global.append(lex_user->user.str, lex_user->user.length,
		      system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3552
	global.append("'@'",3);
3553 3554
	global.append(lex_user->host.str,lex_user->host.length,
		      system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3555
	global.append('\'');
3556
	if (table_access & GRANT_ACL)
peter@mysql.com's avatar
peter@mysql.com committed
3557
	  global.append(" WITH GRANT OPTION",18);
3558
	protocol->prepare_for_resend();
3559
	protocol->store(global.ptr(),global.length(),global.charset());
3560
	if (protocol->write())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3561
	{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3562
	  error= -1;
3563
	  break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3564 3565 3566 3567
	}
      }
    }
  }
3568
end:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3569
  VOID(pthread_mutex_unlock(&acl_cache->lock));
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3570
  rw_unlock(&LOCK_grant);
3571

3572
  send_eof(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3573 3574 3575 3576
  DBUG_RETURN(error);
}


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


3605
void get_mqh(const char *user, const char *host, USER_CONN *uc)
3606 3607
{
  ACL_USER *acl_user;
3608 3609 3610 3611
  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));
3612 3613
}

3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634
/*
  Open the grant tables.

  SYNOPSIS
    open_grant_tables()
    thd                         The current thread.
    tables (out)                The 4 elements array for the opened tables.

  DESCRIPTION
    Tables are numbered as follows:
    0 user
    1 db
    2 tables_priv
    3 columns_priv

  RETURN
    1           Skip GRANT handling during replication.
    0           OK.
    < 0         Error.
*/

3635 3636 3637 3638 3639 3640
int open_grant_tables(THD *thd, TABLE_LIST *tables)
{
  DBUG_ENTER("open_grant_tables");

  if (!initialized)
  {
3641
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
3642 3643 3644 3645 3646 3647 3648 3649
    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";
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3650 3651 3652
  tables->next_local= tables->next_global= tables+1;
  (tables+1)->next_local= (tables+1)->next_global= tables+2;
  (tables+2)->next_local= (tables+2)->next_global= tables+3;
3653 3654 3655 3656 3657 3658 3659 3660 3661
  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.
  */
3662 3663
  if (thd->slave_thread && table_rules_on)
  {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3664 3665 3666
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
3667 3668 3669 3670 3671 3672
    */
    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;
  }
3673 3674
#endif

3675
  if (simple_open_n_lock_tables(thd, tables))
3676 3677 3678 3679 3680 3681 3682 3683 3684
  {						// 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
3685
			 uint *acl_acl_userdx)
3686 3687 3688 3689 3690 3691 3692 3693 3694
{
  ACL_USER *acl_user= 0;
  uint counter;

  for (counter= 0 ; counter < acl_users.elements ; counter++)
  {
    const char *user,*host;
    acl_user= dynamic_element(&acl_users, counter, ACL_USER*);
    if (!(user=acl_user->user))
monty@mysql.com's avatar
monty@mysql.com committed
3695
      user= "";
3696
    if (!(host=acl_user->host.hostname))
monty@mysql.com's avatar
monty@mysql.com committed
3697
      host= "%";
3698 3699 3700 3701 3702 3703 3704
    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
3705
  *acl_acl_userdx= counter;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3706
  return acl_user;
3707 3708
}

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

3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731
/*
  Modify a privilege table.

  SYNOPSIS
    modify_grant_table()
    table                       The table to modify.
    host_field                  The host name field.
    user_field                  The user name field.
    user_to                     The new name for the user if to be renamed,
                                NULL otherwise.

  DESCRIPTION
  Update user/host in the current record if user_to is not NULL.
  Delete the current record if user_to is NULL.

  RETURN
    0           OK.
    != 0        Error.
*/

static int modify_grant_table(TABLE *table, Field *host_field,
                              Field *user_field, LEX_USER *user_to)
3732
{
3733 3734
  int error;
  DBUG_ENTER("modify_grant_table");
3735

3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752
  if (user_to)
  {
    /* rename */
    store_record(table, record[1]);
    host_field->store(user_to->host.str, user_to->host.length,
                      system_charset_info);
    user_field->store(user_to->user.str, user_to->user.length,
                      system_charset_info);
    if ((error= table->file->update_row(table->record[1], table->record[0])))
      table->file->print_error(error, MYF(0));
  }
  else
  {
    /* delete */
    if ((error=table->file->delete_row(table->record[0])))
      table->file->print_error(error, MYF(0));
  }
3753

3754 3755
  DBUG_RETURN(error);
}
3756 3757


3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800
/*
  Handle a privilege table.

  SYNOPSIS
    handle_grant_table()
    tables                      The array with the four open tables.
    table_no                    The number of the table to handle (0..3).
    drop                        If user_from is to be dropped.
    user_from                   The the user to be searched/dropped/renamed.
    user_to                     The new name for the user if to be renamed,
                                NULL otherwise.

  DESCRIPTION
    Scan through all records in a grant table and apply the requested
    operation. For the "user" table, a single index access is sufficient,
    since there is an unique index on (host, user).
    Delete from grant table if drop is true.
    Update in grant table if drop is false and user_to is not NULL.
    Search in grant table if drop is false and user_to is NULL.
    Tables are numbered as follows:
    0 user
    1 db
    2 tables_priv
    3 columns_priv

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

static int handle_grant_table(TABLE_LIST *tables, uint table_no, bool drop,
                              LEX_USER *user_from, LEX_USER *user_to)
{
  int result= 0;
  int error;
  TABLE *table= tables[table_no].table;
  Field *host_field= table->field[0];
  Field *user_field= table->field[table_no ? 2 : 1];
  char *host_str= user_from->host.str;
  char *user_str= user_from->user.str;
  const char *host;
  const char *user;
3801
  byte user_key[MAX_KEY_LENGTH];
3802
  uint key_prefix_length;
3803 3804
  DBUG_ENTER("handle_grant_table");

3805
  if (! table_no) // mysql.user table
3806
  {
3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819
    /*
      The 'user' table has an unique index on (host, user).
      Thus, we can handle everything with a single index access.
      The host- and user fields are consecutive in the user table records.
      So we set host- and user fields of table->record[0] and use the
      pointer to the host field as key.
      index_read_idx() will replace table->record[0] (its first argument)
      by the searched record, if it exists.
    */
    DBUG_PRINT("info",("read table: '%s'  search: '%s'@'%s'",
                       table->real_name, user_str, host_str));
    host_field->store(host_str, user_from->host.length, system_charset_info);
    user_field->store(user_str, user_from->user.length, system_charset_info);
3820 3821 3822 3823 3824

    key_prefix_length= (table->key_info->key_part[0].store_length +
                        table->key_info->key_part[1].store_length);
    key_copy(user_key, table->record[0], table->key_info, key_prefix_length);

3825
    if ((error= table->file->index_read_idx(table->record[0], 0,
3826
                                            user_key, key_prefix_length,
3827
                                            HA_READ_KEY_EXACT)))
3828
    {
3829 3830 3831 3832 3833
      if (error != HA_ERR_KEY_NOT_FOUND)
      {
        table->file->print_error(error, MYF(0));
        result= -1;
      }
3834
    }
3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851
    else
    {
      /* If requested, delete or update the record. */
      result= ((drop || user_to) &&
               modify_grant_table(table, host_field, user_field, user_to)) ?
        -1 : 1; /* Error or found. */
    }
    DBUG_PRINT("info",("read result: %d", result));
  }
  else
  {
    /*
      The non-'user' table do not have indexes on (host, user).
      And their host- and user fields are not consecutive.
      Thus, we need to do a table scan to find all matching records.
    */
    if ((error= table->file->ha_rnd_init(1)))
3852
    {
3853
      table->file->print_error(error, MYF(0));
3854
      result= -1;
3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002
    }
    else
    {
#ifdef EXTRA_DEBUG
      DBUG_PRINT("info",("scan table: '%s'  search: '%s'@'%s'",
                         table->real_name, user_str, host_str));
#endif
      while ((error= table->file->rnd_next(table->record[0])) != 
             HA_ERR_END_OF_FILE)
      {
        if (error)
        {
          /* Most probable 'deleted record'. */
          DBUG_PRINT("info",("scan error: %d", error));
          continue;
        }
        if (! (host= get_field(&mem, host_field)))
          host= "";
        if (! (user= get_field(&mem, user_field)))
          user= "";

#ifdef EXTRA_DEBUG
        DBUG_PRINT("loop",("scan fields: '%s'@'%s' '%s' '%s' '%s'",
                           user, host,
                           get_field(&mem, table->field[1]) /*db*/,
                           get_field(&mem, table->field[3]) /*table*/,
                           get_field(&mem, table->field[4]) /*column*/));
#endif
        if (strcmp(user_str, user) ||
            my_strcasecmp(system_charset_info, host_str, host))
          continue;

        /* If requested, delete or update the record. */
        result= ((drop || user_to) &&
                 modify_grant_table(table, host_field, user_field, user_to)) ?
          -1 : result ? result : 1; /* Error or keep result or found. */
        /* If search is requested, we do not need to search further. */
        if (! drop && ! user_to)
          break ;
      }
      (void) table->file->ha_rnd_end();
      DBUG_PRINT("info",("scan result: %d", result));
    }
  }

  DBUG_RETURN(result);
}


/*
  Handle an in-memory privilege structure.

  SYNOPSIS
    handle_grant_struct()
    struct_no                   The number of the structure to handle (0..2).
    drop                        If user_from is to be dropped.
    user_from                   The the user to be searched/dropped/renamed.
    user_to                     The new name for the user if to be renamed,
                                NULL otherwise.

  DESCRIPTION
    Scan through all elements in an in-memory grant structure and apply
    the requested operation.
    Delete from grant structure if drop is true.
    Update in grant structure if drop is false and user_to is not NULL.
    Search in grant structure if drop is false and user_to is NULL.
    Structures are numbered as follows:
    0 acl_users
    1 acl_dbs
    2 column_priv_hash

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

static int handle_grant_struct(uint struct_no, bool drop,
                               LEX_USER *user_from, LEX_USER *user_to)
{
  int result= 0;
  uint idx;
  uint elements;
  const char *user;
  const char *host;
  ACL_USER *acl_user;
  ACL_DB *acl_db;
  GRANT_TABLE *grant_table;
  DBUG_ENTER("handle_grant_struct");
  LINT_INIT(acl_user);
  LINT_INIT(acl_db);
  LINT_INIT(grant_table);
  DBUG_PRINT("info",("scan struct: %u  search: '%s'@'%s'",
                     struct_no, user_from->user.str, user_from->host.str));

  /* Get the number of elements in the in-memory structure. */
  switch (struct_no)
  {
  case 0:
    elements= acl_users.elements;
    break;
  case 1:
    elements= acl_dbs.elements;
    break;
  default:
    elements= column_priv_hash.records;
  }

#ifdef EXTRA_DEBUG
    DBUG_PRINT("loop",("scan struct: %u  search    user: '%s'  host: '%s'",
                       struct_no, user_from->user.str, user_from->host.str));
#endif
  /* Loop over all elements. */
  for (idx= 0; idx < elements; idx++)
  {
    /*
      Get a pointer to the element.
      Unfortunaltely, the host default differs for the structures.
    */
    switch (struct_no)
    {
    case 0:
      acl_user= dynamic_element(&acl_users, idx, ACL_USER*);
      user= acl_user->user;
      if (!(host= acl_user->host.hostname))
        host= "%";
      break;

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

    default:
      grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash, idx);
      user= grant_table->user;
      host= grant_table->host;
    }
    if (! user)
        user= "";
    if (! host)
        host= "";
#ifdef EXTRA_DEBUG
    DBUG_PRINT("loop",("scan struct: %u  index: %u  user: '%s'  host: '%s'",
                       struct_no, idx, user, host));
#endif
    if (strcmp(user_from->user.str, user) ||
        my_strcasecmp(system_charset_info, user_from->host.str, host))
4003
      continue;
4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022

    result= 1; /* At least one element found. */
    if ( drop )
    {
      switch ( struct_no )
      {
      case 0:
        delete_dynamic_element(&acl_users, idx);
        break;

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

      default:
        hash_delete(&column_priv_hash, (byte*) grant_table);
      }
      elements--;
      idx--;
4023
    }
4024 4025 4026 4027 4028 4029 4030 4031
    else if ( user_to )
    {
      switch ( struct_no )
      {
      case 0:
        acl_user->user= strdup_root(&mem, user_to->user.str);
        acl_user->host.hostname= strdup_root(&mem, user_to->host.str);
        break;
4032

4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043
      case 1:
        acl_db->user= strdup_root(&mem, user_to->user.str);
        acl_db->host.hostname= strdup_root(&mem, user_to->host.str);
        break;

      default:
        grant_table->user= strdup_root(&mem, user_to->user.str);
        grant_table->host= strdup_root(&mem, user_to->host.str);
      }
    }
    else
4044
    {
4045 4046 4047 4048 4049 4050 4051
      /* If search is requested, we do not need to search further. */
      break;
    }
  }
#ifdef EXTRA_DEBUG
  DBUG_PRINT("loop",("scan struct: %u  result %d", struct_no, result));
#endif
4052

4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096
  DBUG_RETURN(result);
}


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

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

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

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

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

  /* Handle user table. */
  if ((found= handle_grant_table(tables, 0, drop, user_from, user_to)) < 0)
  {
    /* Handle of table failed, don't touch the in-memory array. */
    result= -1;
  }
  else
  {
    /* Handle user array. */
4097 4098
    if ((handle_grant_struct(0, drop, user_from, user_to) && ! result) ||
        found)
4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139
    {
      result= 1; /* At least one record/element found. */
      /* If search is requested, we do not need to search further. */
      if (! drop && ! user_to)
        goto end;
    }
  }

  /* Handle db table. */
  if ((found= handle_grant_table(tables, 1, drop, user_from, user_to)) < 0)
  {
    /* Handle of table failed, don't touch the in-memory array. */
    result= -1;
  }
  else
  {
    /* Handle db array. */
    if (((handle_grant_struct(1, drop, user_from, user_to) && ! result) ||
         found) && ! result)
    {
      result= 1; /* At least one record/element found. */
      /* If search is requested, we do not need to search further. */
      if (! drop && ! user_to)
        goto end;
    }
  }

  /* Handle tables table. */
  if ((found= handle_grant_table(tables, 2, drop, user_from, user_to)) < 0)
  {
    /* Handle of table failed, don't touch columns and in-memory array. */
    result= -1;
  }
  else
  {
    if (found && ! result)
    {
      result= 1; /* At least one record found. */
      /* If search is requested, we do not need to search further. */
      if (! drop && ! user_to)
        goto end;
4140
    }
4141 4142 4143

    /* Handle columns table. */
    if ((found= handle_grant_table(tables, 3, drop, user_from, user_to)) < 0)
4144
    {
4145
      /* Handle of table failed, don't touch the in-memory array. */
4146 4147
      result= -1;
    }
4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159
    else
    {
      /* Handle columns hash. */
      if (((handle_grant_struct(2, drop, user_from, user_to) && ! result) ||
           found) && ! result)
        result= 1; /* At least one record/element found. */
    }
  }
 end:
  DBUG_RETURN(result);
}

4160

4161 4162 4163 4164 4165 4166 4167 4168 4169 4170
static void append_user(String *str, LEX_USER *user)
{
  if (str->length())
    str->append(',');
  str->append('\'');
  str->append(user->user.str);
  str->append("'@'");
  str->append(user->host.str);
  str->append('\'');
}
4171

4172

4173 4174 4175 4176 4177 4178 4179
/*
  Create a list of users.

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

4181 4182 4183 4184 4185 4186 4187 4188 4189
  RETURN
    FALSE       OK.
    TRUE        Error.
*/

bool mysql_create_user(THD *thd, List <LEX_USER> &list)
{
  int result;
  int found;
4190
  String wrong_users;
4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210
  ulong sql_mode;
  LEX_USER *user_name;
  List_iterator <LEX_USER> user_list(list);
  TABLE_LIST tables[4];
  DBUG_ENTER("mysql_create_user");

  /* CREATE USER may be skipped on replication client. */
  if ((result= open_grant_tables(thd, tables)))
    DBUG_RETURN(result != 1);

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

  while ((user_name= user_list++))
  {
    /*
      Search all in-memory structures and grant tables
      for a mention of the new user name.
    */
    if ((found= handle_grant_data(tables, 0, user_name, NULL)))
4211
    {
4212
      append_user(&wrong_users, user_name);
4213
      result= TRUE;
4214
      continue;
4215
    }
4216

4217 4218 4219 4220
    sql_mode= thd->variables.sql_mode;
    thd->variables.sql_mode&= ~MODE_NO_AUTO_CREATE_USER;
    if (replace_user_table(thd, tables[0].table, *user_name, 0, 0, 1))
    {
4221
      append_user(&wrong_users, user_name);
4222 4223 4224 4225 4226 4227 4228 4229 4230
      result= TRUE;
    }
    thd->variables.sql_mode= sql_mode;
  }

  VOID(pthread_mutex_unlock(&acl_cache->lock));
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
  if (result)
4231
    my_error(ER_CANNOT_USER, MYF(0), "CREATE USER", wrong_users.c_ptr());
4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252
  DBUG_RETURN(result);
}


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

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

  RETURN
    FALSE       OK.
    TRUE        Error.
*/

bool mysql_drop_user(THD *thd, List <LEX_USER> &list)
{
  int result;
  int found;
4253
  String wrong_users;
4254 4255 4256 4257 4258
  LEX_USER *user_name;
  List_iterator <LEX_USER> user_list(list);
  TABLE_LIST tables[4];
  DBUG_ENTER("mysql_drop_user");

4259
  /* DROP USER may be skipped on replication client. */
4260 4261 4262 4263 4264 4265 4266 4267
  if ((result= open_grant_tables(thd, tables)))
    DBUG_RETURN(result != 1);

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

  while ((user_name= user_list++))
  {
4268
    if ((found= handle_grant_data(tables, 1, user_name, NULL)) <= 0)
4269
    {
4270
      append_user(&wrong_users, user_name);
4271
      result= TRUE;
4272
    }
4273
  }
4274

4275 4276 4277 4278
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
  if (result)
4279
    my_error(ER_CANNOT_USER, MYF(0), "DROP USER", wrong_users.c_ptr());
4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300
  DBUG_RETURN(result);
}


/*
  Rename a user.

  SYNOPSIS
    mysql_rename_user()
    thd                         The current thread.
    list                        The user name pairs: (from, to).

  RETURN
    FALSE       OK.
    TRUE        Error.
*/

bool mysql_rename_user(THD *thd, List <LEX_USER> &list)
{
  int result= 0;
  int found;
4301
  String wrong_users;
4302 4303 4304 4305 4306 4307
  LEX_USER *user_from;
  LEX_USER *user_to;
  List_iterator <LEX_USER> user_list(list);
  TABLE_LIST tables[4];
  DBUG_ENTER("mysql_rename_user");

4308
  /* RENAME USER may be skipped on replication client. */
4309 4310 4311 4312 4313 4314 4315 4316 4317
  if ((result= open_grant_tables(thd, tables)))
    DBUG_RETURN(result != 1);

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

  while ((user_from= user_list++))
  {
    user_to= user_list++;
4318
    DBUG_ASSERT(user_to); /* Syntax enforces pairs of users. */
4319 4320 4321 4322 4323

    /*
      Search all in-memory structures and grant tables
      for a mention of the new user name.
    */
4324 4325
    if (handle_grant_data(tables, 0, user_to, NULL) ||
        handle_grant_data(tables, 0, user_from, user_to) <= 0)
4326
    {
4327
      append_user(&wrong_users, user_from);
4328 4329
      result= TRUE;
    }
4330
  }
4331

4332 4333 4334 4335
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
  if (result)
4336
    my_error(ER_CANNOT_USER, MYF(0), "RENAME USER", wrong_users.c_ptr());
4337 4338 4339
  DBUG_RETURN(result);
}

4340

4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354
/*
  Revoke all privileges from a list of users.

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

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

4355
bool mysql_revoke_all(THD *thd,  List <LEX_USER> &list)
4356
{
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4357
  uint counter, revoked;
4358
  int result;
4359
  ACL_DB *acl_db;
4360 4361 4362 4363
  TABLE_LIST tables[4];
  DBUG_ENTER("mysql_revoke_all");

  if ((result= open_grant_tables(thd, tables)))
4364
    DBUG_RETURN(result != 1);
4365 4366 4367 4368 4369 4370 4371 4372

  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++))
  {
4373
    if (!check_acl_user(lex_user, &counter))
4374
    {
4375 4376
      sql_print_error("REVOKE ALL PRIVILEGES, GRANT: User '%s'@'%s' does not "
                      "exists", lex_user->user.str, lex_user->host.str);
4377 4378 4379
      result= -1;
      continue;
    }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4380

4381 4382 4383 4384 4385 4386 4387 4388
    if (replace_user_table(thd, tables[0].table,
			   *lex_user, ~0, 1, 0))
    {
      result= -1;
      continue;
    }

    /* Remove db access privileges */
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4389 4390 4391 4392 4393
    /*
      Because acl_dbs and column_priv_hash shrink and may re-order
      as privileges are removed, removal occurs in a repeated loop
      until no more privileges are revoked.
     */
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4394
    do
4395
    {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4396
      for (counter= 0, revoked= 0 ; counter < acl_dbs.elements ; )
4397
      {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4398
	const char *user,*host;
4399

dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4400 4401 4402 4403 4404
	acl_db=dynamic_element(&acl_dbs,counter,ACL_DB*);
	if (!(user=acl_db->user))
	  user= "";
	if (!(host=acl_db->host.hostname))
	  host= "";
4405

dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4406 4407 4408
	if (!strcmp(lex_user->user.str,user) &&
	    !my_strcasecmp(system_charset_info, lex_user->host.str, host))
	{
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4409
	  if (!replace_db_table(tables[1].table, acl_db->db, *lex_user, ~0, 1))
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4410
	  {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4411 4412 4413 4414 4415
	    /*
	      Don't increment counter as replace_db_table deleted the
	      current element in acl_dbs.
	     */
	    revoked= 1;
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4416 4417
	    continue;
	  }
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4418
	  result= -1; // Something went wrong
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4419
	}
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4420
	counter++;
4421
      }
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4422
    } while (revoked);
4423 4424

    /* Remove column access */
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4425
    do
4426
    {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4427
      for (counter= 0, revoked= 0 ; counter < column_priv_hash.records ; )
4428
      {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4429 4430 4431 4432 4433 4434 4435
	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= "";
4436

dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4437 4438
	if (!strcmp(lex_user->user.str,user) &&
	    !my_strcasecmp(system_charset_info, lex_user->host.str, host))
4439
	{
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4440 4441 4442 4443
	  if (replace_table_table(thd,grant_table,tables[2].table,*lex_user,
				  grant_table->db,
				  grant_table->tname,
				  ~0, 0, 1))
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4444
	  {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4445
	    result= -1;
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4446
	  }
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4447
	  else
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4448
	  {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4449
	    if (!grant_table->cols)
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4450
	    {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4451 4452
	      revoked= 1;
	      continue;
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4453
	    }
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4454 4455
	    List<LEX_COLUMN> columns;
	    if (!replace_column_table(grant_table,tables[3].table, *lex_user,
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4456 4457 4458 4459
				      columns,
				      grant_table->db,
				      grant_table->tname,
				      ~0, 1))
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4460
	    {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4461
	      revoked= 1;
4462
	      continue;
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4463
	    }
4464
	    result= -1;
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4465
	  }
4466
	}
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4467
	counter++;
4468
      }
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
4469
    } while (revoked);
4470
  }
4471

4472 4473 4474
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
4475

4476
  if (result)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4477
    my_message(ER_REVOKE_GRANTS, ER(ER_REVOKE_GRANTS), MYF(0));
4478

4479 4480
  DBUG_RETURN(result);
}
4481

4482

bk@work.mysql.com's avatar
bk@work.mysql.com committed
4483
/*****************************************************************************
4484
  Instantiate used templates
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4485 4486 4487 4488 4489 4490 4491 4492
*****************************************************************************/

#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
4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539

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

4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600

void update_schema_privilege(TABLE *table, char *buff, const char* db,
                             const char* t_name, const char* column,
                             uint col_length, const char *priv, 
                             uint priv_length, const char* is_grantable)
{
  int i= 2;
  CHARSET_INFO *cs= system_charset_info;
  restore_record(table, default_values);
  table->field[0]->store(buff, strlen(buff), cs);
  if (db)
    table->field[i++]->store(db, strlen(db), cs);
  if (t_name)
    table->field[i++]->store(t_name, strlen(t_name), cs);
  if (column)
    table->field[i++]->store(column, col_length, cs);
  table->field[i++]->store(priv, priv_length, cs);
  table->field[i]->store(is_grantable, strlen(is_grantable), cs);
  table->file->write_row(table->record[0]);
}


int fill_schema_user_privileges(THD *thd, TABLE_LIST *tables, COND *cond)
{
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  uint counter;
  ACL_USER *acl_user;
  ulong want_access;

  char buff[100];
  TABLE *table= tables->table;
  DBUG_ENTER("fill_schema_user_privileges");
  for (counter=0 ; counter < acl_users.elements ; counter++)
  {
    const char *user,*host, *is_grantable="YES";
    acl_user=dynamic_element(&acl_users,counter,ACL_USER*);
    if (!(user=acl_user->user))
      user= "";
    if (!(host=acl_user->host.hostname))
      host= "";
    want_access= acl_user->access;
    if (!(want_access & GRANT_ACL))
      is_grantable= "NO";

    strxmov(buff,"'",user,"'@'",host,"'",NullS);
    if (!(want_access & ~GRANT_ACL))
      update_schema_privilege(table, buff, 0, 0, 0, 0, "USAGE", 5, is_grantable);
    else
    {
      uint priv_id;
      ulong j,test_access= want_access & ~GRANT_ACL;
      for (priv_id=0, j = SELECT_ACL;j <= GLOBAL_ACLS; priv_id++,j <<= 1)
      {
	if (test_access & j)
          update_schema_privilege(table, buff, 0, 0, 0, 0, 
                                  command_array[priv_id],
                                  command_lengths[priv_id], is_grantable);
      }
    }
  }
  DBUG_RETURN(0);
4601 4602 4603
#else
  return(0);
#endif
4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650
}


int fill_schema_schema_privileges(THD *thd, TABLE_LIST *tables, COND *cond)
{
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  uint counter;
  ACL_DB *acl_db;
  ulong want_access;
  char buff[100];
  TABLE *table= tables->table;
  DBUG_ENTER("fill_schema_schema_privileges");

  for (counter=0 ; counter < acl_dbs.elements ; counter++)
  {
    const char *user, *host, *is_grantable="YES";

    acl_db=dynamic_element(&acl_dbs,counter,ACL_DB*);
    if (!(user=acl_db->user))
      user= "";
    if (!(host=acl_db->host.hostname))
      host= "";

    want_access=acl_db->access;
    if (want_access)
    {
      if (!(want_access & GRANT_ACL))
      {
        is_grantable= "NO";
      }
      strxmov(buff,"'",user,"'@'",host,"'",NullS);
      if (!(want_access & ~GRANT_ACL))
        update_schema_privilege(table, buff, acl_db->db, 0, 0,
                                0, "USAGE", 5, is_grantable);
      else
      {
        int cnt;
        ulong j,test_access= want_access & ~GRANT_ACL;
        for (cnt=0, j = SELECT_ACL; j <= DB_ACLS; cnt++,j <<= 1)
          if (test_access & j)
            update_schema_privilege(table, buff, acl_db->db, 0, 0, 0,
                                    command_array[cnt], command_lengths[cnt],
                                    is_grantable);
      }
    }
  }
  DBUG_RETURN(0);
4651 4652 4653
#else
  return (0);
#endif
4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672
}


int fill_schema_table_privileges(THD *thd, TABLE_LIST *tables, COND *cond)
{
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  uint index;
  char buff[100];
  TABLE *table= tables->table;
  DBUG_ENTER("fill_schema_table_privileges");

  for (index=0 ; index < column_priv_hash.records ; index++)
  {
    const char *user, *is_grantable= "YES";
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  index);
    if (!(user=grant_table->user))
      user= "";
    ulong table_access= grant_table->privs;
4673
    if (table_access)
4674 4675
    {
      ulong test_access= table_access & ~GRANT_ACL;
4676 4677 4678 4679
      /*
        We should skip 'usage' privilege on table if
        we have any privileges on column(s) of this table
      */
4680 4681
      if (!test_access && grant_table->cols)
        continue;
4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703
      if (!(table_access & GRANT_ACL))
        is_grantable= "NO";

      strxmov(buff,"'",user,"'@'",grant_table->orig_host,"'",NullS);
      if (!test_access)
        update_schema_privilege(table, buff, grant_table->db, grant_table->tname,
                                0, 0, "USAGE", 5, is_grantable);
      else
      {
        ulong j;
        int cnt;
        for (cnt= 0, j= SELECT_ACL; j <= TABLE_ACLS; cnt++, j<<= 1)
        {
          if (test_access & j)
            update_schema_privilege(table, buff, grant_table->db, 
                                    grant_table->tname, 0, 0, command_array[cnt],
                                    command_lengths[cnt], is_grantable);
        }
      }
    }
  }
  DBUG_RETURN(0);
4704 4705 4706
#else
  return (0);
#endif
4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727
}


int fill_schema_column_privileges(THD *thd, TABLE_LIST *tables, COND *cond)
{
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  uint index;
  char buff[100];
  TABLE *table= tables->table;
  DBUG_ENTER("fill_schema_table_privileges");

  for (index=0 ; index < column_priv_hash.records ; index++)
  {
    const char *user, *is_grantable= "YES";
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  index);
    if (!(user=grant_table->user))
      user= "";
    ulong table_access= grant_table->cols;
    if (table_access != 0)
    {
4728
      if (!(grant_table->privs & GRANT_ACL))
4729 4730
        is_grantable= "NO";

4731
      ulong test_access= table_access & ~GRANT_ACL;
4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762
      strxmov(buff,"'",user,"'@'",grant_table->orig_host,"'",NullS);
      if (!test_access)
        continue;
      else
      {
        ulong j;
        int cnt;
        for (cnt= 0, j= SELECT_ACL; j <= TABLE_ACLS; cnt++, j<<= 1)
        {
          if (test_access & j)
          {
            for (uint col_index=0 ;
                 col_index < grant_table->hash_columns.records ;
                 col_index++)
            {
              GRANT_COLUMN *grant_column = (GRANT_COLUMN*)
                hash_element(&grant_table->hash_columns,col_index);
              if ((grant_column->rights & j) && (table_access & j))
                  update_schema_privilege(table, buff, grant_table->db,
                                          grant_table->tname,
                                          grant_column->column,
                                          grant_column->key_length,
                                          command_array[cnt],
                                          command_lengths[cnt], is_grantable);
            }
          }
        }
      }
    }
  }
  DBUG_RETURN(0);
4763 4764 4765
#else
  return (0);
#endif
4766 4767 4768
}


bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4769 4770 4771 4772 4773
#ifndef NO_EMBEDDED_ACCESS_CHECKS
/*
  fill effective privileges for table

  SYNOPSIS
4774 4775
    fill_effective_table_privileges()
    thd     thread handler
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4776 4777 4778 4779 4780 4781 4782 4783
    grant   grants table descriptor
    db      db name
    table   table name
*/

void fill_effective_table_privileges(THD *thd, GRANT_INFO *grant,
                                     const char *db, const char *table)
{
4784 4785 4786 4787 4788 4789 4790
  /* --skip-grants */
  if (!initialized)
  {
    grant->privilege= ~NO_ACCESS;             // everything is allowed
    return;
  }

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4791 4792
  /* global privileges */
  grant->privilege= thd->master_access;
4793

4794 4795 4796
  /* db privileges */
  grant->privilege|= acl_get(thd->host, thd->ip, thd->priv_user, db, 0);

4797 4798 4799
  if (!grant_option)
    return;

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4800 4801 4802
  /* table privileges */
  if (grant->version != grant_version)
  {
4803
    rw_rdlock(&LOCK_grant);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4804 4805 4806 4807 4808
    grant->grant_table=
      table_hash_search(thd->host, thd->ip, db,
			thd->priv_user,
			table, 0);              /* purecov: inspected */
    grant->version= grant_version;              /* purecov: inspected */
4809
    rw_unlock(&LOCK_grant);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4810 4811 4812 4813 4814 4815 4816
  }
  if (grant->grant_table != 0)
  {
    grant->privilege|= grant->grant_table->privs;
  }
}
#endif