sql_acl.cc 163 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
  mysql/db	 ; database privileges / user

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

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

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

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

48

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

static DYNAMIC_ARRAY acl_hosts,acl_users,acl_dbs;
static MEM_ROOT mem, memex;
static bool initialized=0;
static bool allow_all_hosts=1;
63
static HASH acl_check_hosts, column_priv_hash, proc_priv_hash, func_priv_hash;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
64 65
static DYNAMIC_ARRAY acl_wild_hosts;
static hash_filo *acl_cache;
66
static uint grant_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
  my_bool return_val=1;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
141
  bool check_no_resolve= specialflag & SPECIAL_NO_RESOLVE;
142
  char tmp_name[NAME_LEN+1];
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
143

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

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

155
  grant_version++; /* Privileges updated */
156
  mysql_proc_table_exists= 1;			// Assume mysql.proc exists
peter@mysql.com's avatar
peter@mysql.com committed
157

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
165
  acl_cache->clear(1);				// Clear locked hostname cache
166 167
  thd->db= my_strdup("mysql",MYF(0));
  thd->db_length=5;				// Safety
bk@work.mysql.com's avatar
bk@work.mysql.com committed
168
  bzero((char*) &tables,sizeof(tables));
169 170 171
  tables[0].alias=tables[0].table_name=(char*) "host";
  tables[1].alias=tables[1].table_name=(char*) "user";
  tables[2].alias=tables[2].table_name=(char*) "db";
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
172 173
  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
174 175 176
  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;

177
  if (simple_open_n_lock_tables(thd, tables))
178
  {
179
    sql_print_error("Fatal error: Can't open and lock privilege tables: %s",
180
		    thd->net.last_error);
181
    goto end;
182
  }
183
  init_sql_alloc(&mem, ACL_ALLOC_BLOCK_SIZE, 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
184
  init_read_record(&read_record_info,thd,table= tables[0].table,NULL,1,0);
185
  VOID(my_init_dynamic_array(&acl_hosts,sizeof(ACL_HOST),20,50));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
186 187 188
  while (!(read_record_info.read_record(&read_record_info)))
  {
    ACL_HOST host;
189 190
    update_hostname(&host.host,get_field(&mem, table->field[0]));
    host.db=	 get_field(&mem, table->field[1]);
191
    if (lower_case_table_names && host.db)
192 193
    {
      /*
194 195
        convert db to lower case and give a warning if the db wasn't
        already in lower case
196
      */
197 198
      (void) strmov(tmp_name, host.db);
      my_casedn_str(files_charset_info, host.db);
199 200 201
      if (strcmp(host.db, tmp_name) != 0)
        sql_print_warning("'host' entry '%s|%s' had database in mixed "
                          "case that has been forced to lowercase because "
202 203
                          "lower_case_table_names is set. It will not be "
                          "possible to remove this privilege using REVOKE.",
204 205
                          host.host.hostname, host.db);
    }
206 207
    host.access= get_access(table,2);
    host.access= fix_rights_for_db(host.access);
208
    host.sort=	 get_sort(2,host.host.hostname,host.db);
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
209 210
    if (check_no_resolve && hostname_requires_resolving(host.host.hostname))
    {
serg@serg.mylan's avatar
serg@serg.mylan committed
211
      sql_print_warning("'host' entry '%s|%s' "
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
212
		      "ignored in --skip-name-resolve mode.",
213
		      host.host.hostname, host.db?host.db:"");
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
214 215
      continue;
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
216
#ifndef TO_BE_REMOVED
217
    if (table->s->fields == 8)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
218 219
    {						// Without grant
      if (host.access & CREATE_ACL)
220
	host.access|=REFERENCES_ACL | INDEX_ACL | ALTER_ACL | CREATE_TMP_ACL;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
221 222 223 224 225 226 227 228 229 230
    }
#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);
231
  VOID(my_init_dynamic_array(&acl_users,sizeof(ACL_USER),50,100));
232
  if (table->field[2]->field_length < SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
233
  {
234 235 236
    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
237 238
  }

239
  DBUG_PRINT("info",("user table fields: %d, password length: %d",
240
		     table->s->fields, table->field[2]->field_length));
241

242 243
  pthread_mutex_lock(&LOCK_global_system_variables);
  if (table->field[2]->field_length < SCRAMBLED_PASSWORD_CHAR_LENGTH)
244
  {
245 246 247 248 249 250 251 252 253 254 255 256 257 258
    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);
259 260 261
      sql_print_warning("mysql.user table is not updated to new password format; "
                        "Disabling new password usage until "
                        "mysql_fix_privilege_tables is run");
262 263 264 265
    }
    thd->variables.old_passwords= 1;
  }
  else
266
  {
267 268
    sys_old_passwords.after_update= 0;
    pthread_mutex_unlock(&LOCK_global_system_variables);
269 270
  }

bk@work.mysql.com's avatar
bk@work.mysql.com committed
271 272 273 274
  allow_all_hosts=0;
  while (!(read_record_info.read_record(&read_record_info)))
  {
    ACL_USER user;
275 276
    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
277 278
    if (check_no_resolve && hostname_requires_resolving(user.host.hostname))
    {
serg@serg.mylan's avatar
serg@serg.mylan committed
279 280
      sql_print_warning("'user' entry '%s@%s' "
                        "ignored in --skip-name-resolve mode.",
281
		      user.user, user.host.hostname);
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
282 283 284
      continue;
    }

285 286 287 288
    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
289
    {
290 291
      switch (password_len) {
      case 45: /* 4.1: to be removed */
serg@serg.mylan's avatar
serg@serg.mylan committed
292 293 294 295 296
        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 : "");
297 298
        break;
      default:
serg@serg.mylan's avatar
serg@serg.mylan committed
299 300 301
        sql_print_warning("Found invalid password for user: '%s@%s'; "
                          "Ignoring user", user.user ? user.user : "",
                           user.host.hostname ? user.host.hostname : "");
302 303
        break;
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
304
    }
305
    else                                        // password is correct
bk@work.mysql.com's avatar
bk@work.mysql.com committed
306
    {
307 308
      uint next_field;
      user.access= get_access(table,3,&next_field) & GLOBAL_ACLS;
309 310 311 312
      /*
        if it is pre 5.0.1 privilege table then map CREATE privilege on
        CREATE VIEW & SHOW VIEW privileges
      */
313
      if (table->s->fields <= 31 && (user.access & CREATE_ACL))
314
        user.access|= (CREATE_VIEW_ACL | SHOW_VIEW_ACL);
315 316 317 318 319

      /*
        if it is pre 5.0.2 privilege table then map CREATE/ALTER privilege on
        CREATE PROCEDURE & ALTER PROCEDURE privileges
      */
320
      if (table->s->fields <= 33 && (user.access & CREATE_ACL))
321
        user.access|= CREATE_PROC_ACL;
322
      if (table->s->fields <= 33 && (user.access & ALTER_ACL))
323 324
        user.access|= ALTER_PROC_ACL;

325 326 327 328 329 330
      /*
        pre 5.0.3 did not have CREATE_USER_ACL
      */
      if (table->s->fields <= 36 && (user.access & GRANT_ACL))
        user.access|= CREATE_USER_ACL;

331 332 333
      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
334

335 336
      /* Starting from 4.0.2 we have more fields */
      if (table->s->fields >= 31)
337
      {
338
        char *ssl_type=get_field(&mem, table->field[next_field++]);
339 340 341 342 343 344 345 346 347
        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;

348 349 350
        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++]);
351

352 353 354 355 356
        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++]);
357
        user.user_resource.conn_per_hour= ptr ? atoi(ptr) : 0;
358
        if (user.user_resource.questions || user.user_resource.updates ||
359
            user.user_resource.conn_per_hour)
360
          mqh_used=1;
361

362
        if (table->s->fields >= 36)
363 364 365 366 367 368 369
        {
          /* Starting from 5.0.3 we have max_user_connections field */
          ptr= get_field(&mem, table->field[next_field++]);
          user.user_resource.user_conn= ptr ? atoi(ptr) : 0;
        }
        else
          user.user_resource.user_conn= 0;
370
      }
371 372 373
      else
      {
        user.ssl_type=SSL_TYPE_NONE;
374
        bzero((char *)&(user.user_resource),sizeof(user.user_resource));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
375
#ifndef TO_BE_REMOVED
376
        if (table->s->fields <= 13)
377 378 379 380 381 382 383 384 385 386
        {						// 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
387
#endif
388 389 390 391 392
      }
      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
393
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
394 395 396 397 398
  }
  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
399

bk@work.mysql.com's avatar
bk@work.mysql.com committed
400
  init_read_record(&read_record_info,thd,table=tables[2].table,NULL,1,0);
401
  VOID(my_init_dynamic_array(&acl_dbs,sizeof(ACL_DB),50,100));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
402 403 404
  while (!(read_record_info.read_record(&read_record_info)))
  {
    ACL_DB db;
405 406
    update_hostname(&db.host,get_field(&mem, table->field[0]));
    db.db=get_field(&mem, table->field[1]);
407 408
    if (!db.db)
    {
serg@serg.mylan's avatar
serg@serg.mylan committed
409
      sql_print_warning("Found an entry in the 'db' table with empty database name; Skipped");
410
      continue;
411
    }
412
    db.user=get_field(&mem, table->field[2]);
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
413 414
    if (check_no_resolve && hostname_requires_resolving(db.host.hostname))
    {
serg@serg.mylan's avatar
serg@serg.mylan committed
415 416
      sql_print_warning("'db' entry '%s %s@%s' "
		        "ignored in --skip-name-resolve mode.",
417
		        db.db, db.user, db.host.hostname);
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
418 419
      continue;
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
420 421
    db.access=get_access(table,3);
    db.access=fix_rights_for_db(db.access);
422 423 424
    if (lower_case_table_names)
    {
      /*
425 426
        convert db to lower case and give a warning if the db wasn't
        already in lower case
427 428
      */
      (void)strmov(tmp_name, db.db);
429
      my_casedn_str(files_charset_info, db.db);
430 431 432 433
      if (strcmp(db.db, tmp_name) != 0)
      {
        sql_print_warning("'db' entry '%s %s@%s' had database in mixed "
                          "case that has been forced to lowercase because "
434 435
                          "lower_case_table_names is set. It will not be "
                          "possible to remove this privilege using REVOKE.",
436 437 438
		          db.db, db.user, db.host.hostname, db.host.hostname);
      }
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
439 440
    db.sort=get_sort(3,db.host.hostname,db.db,db.user);
#ifndef TO_BE_REMOVED
441
    if (table->s->fields <=  9)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
442 443 444 445 446 447 448 449 450 451 452 453 454
    {						// 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();

455
  initialized=1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
456
  thd->version--;				// Force close to free memory
457 458 459
  return_val=0;

end:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
460 461
  close_thread_tables(thd);
  delete thd;
462 463
  if (org_thd)
    org_thd->store_globals();			/* purecov: inspected */
464 465 466 467 468
  else
  {
    /* Remember that we don't have a THD */
    my_pthread_setspecific_ptr(THR_THD,  0);
  }
469
  DBUG_RETURN(return_val);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
470 471 472 473 474
}


void acl_free(bool end)
{
475
  free_root(&mem,MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
476 477 478 479 480 481 482 483 484 485 486 487 488 489
  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;
  }
}

490 491 492 493 494 495

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

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

500
void acl_reload(THD *thd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
501 502 503 504 505 506
{
  DYNAMIC_ARRAY old_acl_hosts,old_acl_users,old_acl_dbs;
  MEM_ROOT old_mem;
  bool old_initialized;
  DBUG_ENTER("acl_reload");

507
  if (thd && thd->locked_tables)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
508
  {					// Can't have locked tables here
509 510 511
    thd->lock=thd->locked_tables;
    thd->locked_tables=0;
    close_thread_tables(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
512 513 514 515 516 517 518 519 520 521 522
  }
  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);

523
  if (acl_init(thd, 0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
524
  {					// Error. Revert to old list
525
    DBUG_PRINT("error",("Reverting to old privileges"));
526
    acl_free();				/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
527 528 529 530 531 532 533 534
    acl_hosts=old_acl_hosts;
    acl_users=old_acl_users;
    acl_dbs=old_acl_dbs;
    mem=old_mem;
    init_check_host();
  }
  else
  {
535
    free_root(&old_mem,MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
536 537 538 539 540 541 542 543 544 545
    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;
}


546 547
/*
  Get all access bits from table after fieldnr
548 549

  IMPLEMENTATION
550 551
  We know that the access privileges ends when there is no more fields
  or the field is not an enum with two elements.
552 553 554 555 556 557 558 559 560 561 562

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

565
static ulong get_access(TABLE *form, uint fieldnr, uint *next_field)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
566
{
567
  ulong access_bits=0,bit;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
568
  char buff[2];
569
  String res(buff,sizeof(buff),&my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
570 571
  Field **pos;

572 573 574
  for (pos=form->field+fieldnr, bit=1;
       *pos && (*pos)->real_type() == FIELD_TYPE_ENUM &&
	 ((Field_enum*) (*pos))->typelib->count == 2 ;
575
       pos++, fieldnr++, bit<<=1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
576
  {
577
    (*pos)->val_str(&res);
578
    if (my_toupper(&my_charset_latin1, res[0]) == 'Y')
579
      access_bits|= bit;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
580
  }
581 582
  if (next_field)
    *next_field=fieldnr;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
583 584 585 586 587
  return access_bits;
}


/*
588 589 590 591 592
  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
593 594 595 596 597 598 599

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

600 601 602
  /* 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
603 604
  while (count--)
  {
605 606 607
    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
608

monty@mysql.com's avatar
monty@mysql.com committed
609
    if ((start= str))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
610 611 612 613
    {
      for (; *str ; str++)
      {
	if (*str == wild_many || *str == wild_one || *str == wild_prefix)
614
        {
monty@mysql.com's avatar
monty@mysql.com committed
615
          wild_pos= (uint) (str - start) + 1;
616 617
          break;
        }
monty@mysql.com's avatar
monty@mysql.com committed
618
        chars= 128;                             // Marker that chars existed
bk@work.mysql.com's avatar
bk@work.mysql.com committed
619 620
      }
    }
monty@mysql.com's avatar
monty@mysql.com committed
621
    sort= (sort << 8) + (wild_pos ? min(wild_pos, 127) : chars);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
  }
  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;
}

637

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

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
642 643 644 645
  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
646

647
  SYNOPSIS
648 649 650 651 652 653
    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
654
    passwd      scrambled & crypted password, received from client
655 656 657 658 659 660 661
                (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
662
  RETURN VALUE
663 664
    0  success: thd->priv_user, thd->priv_host, thd->master_access, mqh are
       updated
665
    1  user not found or authentication failure
666
    2  user found, has long (4.1.1) salt, but passwd is in old (3.23) format.
667
   -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
668 669
*/

670 671
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
672
{
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
673 674 675
  ulong user_access= NO_ACCESS;
  int res= 1;
  ACL_USER *acl_user= 0;
676
  DBUG_ENTER("acl_getroot");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
677 678

  if (!initialized)
679
  {
680 681 682 683 684 685
    /* 
      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
686
    bzero((char*) mqh, sizeof(*mqh));
687
    DBUG_RETURN(0);
688
  }
689

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
692
  /*
693 694 695
    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
696
  */
peter@mysql.com's avatar
peter@mysql.com committed
697

698
  for (uint i=0 ; i < acl_users.elements ; i++)
699
  {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
700 701
    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
702
    {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
703
      if (compare_hostname(&acl_user_tmp->host, thd->host, thd->ip))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
704
      {
705
        /* check password: it should be empty or valid */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
706
        if (passwd_len == acl_user_tmp->salt_len)
peter@mysql.com's avatar
peter@mysql.com committed
707
        {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
708
          if (acl_user_tmp->salt_len == 0 ||
serg@serg.mylan's avatar
serg@serg.mylan committed
709 710
              (acl_user_tmp->salt_len == SCRAMBLE_LENGTH ?
              check_scramble(passwd, thd->scramble, acl_user_tmp->salt) :
711
              check_scramble_323(passwd, thd->scramble,
serg@serg.mylan's avatar
serg@serg.mylan committed
712
                                 (ulong *) acl_user_tmp->salt)) == 0)
713
          {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
714
            acl_user= acl_user_tmp;
715 716
            res= 0;
          }
peter@mysql.com's avatar
peter@mysql.com committed
717
        }
718
        else if (passwd_len == SCRAMBLE_LENGTH &&
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
719
                 acl_user_tmp->salt_len == SCRAMBLE_LENGTH_323)
720
          res= -1;
721
        else if (passwd_len == SCRAMBLE_LENGTH_323 &&
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
722
                 acl_user_tmp->salt_len == SCRAMBLE_LENGTH)
723
          res= 2;
724 725
        /* linear search complete: */
        break;
peter@mysql.com's avatar
peter@mysql.com committed
726
      }
peter@mysql.com's avatar
peter@mysql.com committed
727
    }
728
  }
729 730 731 732
  /*
    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
733 734 735

  if (acl_user)
  {
736
    /* OK. User found and password checked continue validation */
737
#ifdef HAVE_OPENSSL
738
    Vio *vio=thd->net.vio;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
739
    SSL *ssl= (SSL*) vio->ssl_arg;
740
#endif
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
741

742
    /*
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
743
      At this point we know that user is allowed to connect
744 745 746 747 748 749
      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
750 751
    case SSL_TYPE_NONE:				// SSL is not required
      user_access= acl_user->access;
752
      break;
753
#ifdef HAVE_OPENSSL
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
754
    case SSL_TYPE_ANY:				// Any kind of SSL is ok
755
      if (vio_type(vio) == VIO_TYPE_SSL)
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
756
	user_access= acl_user->access;
757 758 759 760 761
      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
762

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
763 764
	We need to check for absence of SSL because without SSL
	we should reject connection.
765
      */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
766
      if (vio_type(vio) == VIO_TYPE_SSL &&
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
767 768
	  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
769
	user_access= acl_user->access;
770 771 772 773 774 775 776 777
      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
778
      X509 *cert;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
779
      if (vio_type(vio) != VIO_TYPE_SSL ||
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
780
	  SSL_get_verify_result(ssl) != X509_V_OK)
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
781
	break;
782
      if (acl_user->ssl_cipher)
peter@mysql.com's avatar
peter@mysql.com committed
783
      {
784
	DBUG_PRINT("info",("comparing ciphers: '%s' and '%s'",
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
785 786
			   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
787
	  user_access= acl_user->access;
788 789
	else
	{
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
790
	  if (global_system_variables.log_warnings)
serg@serg.mylan's avatar
serg@serg.mylan committed
791 792 793
	    sql_print_information("X509 ciphers mismatch: should be '%s' but is '%s'",
			      acl_user->ssl_cipher,
			      SSL_get_cipher(ssl));
794 795
	  break;
	}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
796
      }
797 798
      /* Prepare certificate (if exists) */
      DBUG_PRINT("info",("checkpoint 1"));
monty@mysql.com's avatar
monty@mysql.com committed
799 800 801 802 803
      if (!(cert= SSL_get_peer_certificate(ssl)))
      {
	user_access=NO_ACCESS;
	break;
      }
804
      DBUG_PRINT("info",("checkpoint 2"));
805
      /* If X509 issuer is specified, we check it... */
806
      if (acl_user->x509_issuer)
peter@mysql.com's avatar
peter@mysql.com committed
807
      {
kostja@oak.local's avatar
kostja@oak.local committed
808
        DBUG_PRINT("info",("checkpoint 3"));
809 810 811
	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
812
        if (strcmp(acl_user->x509_issuer, ptr))
813
        {
kostja@oak.local's avatar
kostja@oak.local committed
814
          if (global_system_variables.log_warnings)
serg@serg.mylan's avatar
serg@serg.mylan committed
815 816
            sql_print_information("X509 issuer mismatch: should be '%s' "
			      "but is '%s'", acl_user->x509_issuer, ptr);
817
          free(ptr);
kostja@oak.local's avatar
kostja@oak.local committed
818
          break;
819
        }
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
820
        user_access= acl_user->access;
kostja@oak.local's avatar
kostja@oak.local committed
821
        free(ptr);
peter@mysql.com's avatar
peter@mysql.com committed
822
      }
823 824 825 826
      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
827 828 829 830
        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))
831
        {
kostja@oak.local's avatar
kostja@oak.local committed
832
          if (global_system_variables.log_warnings)
serg@serg.mylan's avatar
serg@serg.mylan committed
833
            sql_print_information("X509 subject mismatch: '%s' vs '%s'",
kostja@oak.local's avatar
kostja@oak.local committed
834
                            acl_user->x509_subject, ptr);
835
        }
kostja@oak.local's avatar
kostja@oak.local committed
836
        else
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
837
          user_access= acl_user->access;
kostja@oak.local's avatar
kostja@oak.local committed
838
        free(ptr);
839 840
      }
      break;
peter@mysql.com's avatar
peter@mysql.com committed
841
#else  /* HAVE_OPENSSL */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
842
    default:
843
      /*
kostja@oak.local's avatar
kostja@oak.local committed
844 845 846
        If we don't have SSL but SSL is required for this user the 
        authentication should fail.
      */
847 848
      break;
#endif /* HAVE_OPENSSL */
peter@mysql.com's avatar
peter@mysql.com committed
849
    }
monty@narttu.mysql.fi's avatar
merge  
monty@narttu.mysql.fi committed
850
    thd->master_access= user_access;
851 852
    thd->priv_user= acl_user->user ? thd->user : (char *) "";
    *mqh= acl_user->user_resource;
853

854 855 856 857 858
    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
859
  VOID(pthread_mutex_unlock(&acl_cache->lock));
860
  DBUG_RETURN(res);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
861 862 863
}


864 865 866
/*
 * This is like acl_getroot() above, but it doesn't check password,
 * and we don't care about the user resources.
867
 * Used to get access rights for SQL SECURITY DEFINER invocation of
868 869 870 871 872
 * stored procedures.
 */
int acl_getroot_no_password(THD *thd)
{
  int res= 1;
873
  uint i;
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
  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));

890 891 892
  thd->master_access= 0;
  thd->db_access= 0;

893 894 895 896 897 898
  /*
     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 ''.
  */
899
  for (i=0 ; i < acl_users.elements ; i++)
900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
  {
    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)
  {
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
    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;
	  }
	}
      }
    }
931 932 933 934 935 936 937 938 939 940 941 942
    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
943 944 945 946 947 948 949
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;
}

950

bk@work.mysql.com's avatar
bk@work.mysql.com committed
951
static void acl_update_user(const char *user, const char *host,
952
			    const char *password, uint password_len,
953 954 955 956
			    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
957
			    USER_RESOURCES  *mqh,
958
			    ulong privileges)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
959 960 961 962 963 964 965 966 967
{
  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] ||
968
	  acl_user->host.hostname &&
969
	  !my_strcasecmp(system_charset_info, host, acl_user->host.hostname))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
970 971
      {
	acl_user->access=privileges;
972
	if (mqh->specified_limits & USER_RESOURCES::QUERIES_PER_HOUR)
973
	  acl_user->user_resource.questions=mqh->questions;
974
	if (mqh->specified_limits & USER_RESOURCES::UPDATES_PER_HOUR)
975
	  acl_user->user_resource.updates=mqh->updates;
976 977 978 979
	if (mqh->specified_limits & USER_RESOURCES::CONNECTIONS_PER_HOUR)
	  acl_user->user_resource.conn_per_hour= mqh->conn_per_hour;
	if (mqh->specified_limits & USER_RESOURCES::USER_CONNECTIONS)
	  acl_user->user_resource.user_conn= mqh->user_conn;
980 981 982 983 984 985 986 987 988 989
	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);
	}
990 991
	if (password)
	  set_user_salt(acl_user, password, password_len);
992
        /* search complete: */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
993 994 995 996 997 998 999 1000
	break;
      }
    }
  }
}


static void acl_insert_user(const char *user, const char *host,
1001
			    const char *password, uint password_len,
1002 1003 1004 1005
			    enum SSL_type ssl_type,
			    const char *ssl_cipher,
			    const char *x509_issuer,
			    const char *x509_subject,
1006
			    USER_RESOURCES *mqh,
1007
			    ulong privileges)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1008 1009
{
  ACL_USER acl_user;
1010
  acl_user.user=*user ? strdup_root(&mem,user) : 0;
monty@mysql.com's avatar
monty@mysql.com committed
1011
  update_hostname(&acl_user.host, *host ? strdup_root(&mem, host): 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1012
  acl_user.access=privileges;
1013
  acl_user.user_resource = *mqh;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1014
  acl_user.sort=get_sort(2,acl_user.host.hostname,acl_user.user);
1015
  acl_user.hostname_length=(uint) strlen(host);
1016 1017 1018 1019 1020
  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;
1021 1022

  set_user_salt(&acl_user, password, password_len);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1023 1024 1025 1026

  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
1027
    allow_all_hosts=1;		// Anyone can connect /* purecov: tested */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
  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,
1039
			  ulong privileges)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1040 1041 1042 1043 1044 1045 1046 1047 1048
{
  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] ||
1049
	  acl_db->host.hostname &&
1050
	  !my_strcasecmp(system_charset_info, host, acl_db->host.hostname))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
      {
	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);
	}
      }
    }
  }
}


1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
/*
  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
1080
static void acl_insert_db(const char *user, const char *host, const char *db,
1081
			  ulong privileges)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1082 1083
{
  ACL_DB acl_db;
1084
  safe_mutex_assert_owner(&acl_cache->lock);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
  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);
}


1096 1097 1098

/*
  Get privilege for a host, user and db combination
1099 1100 1101

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

1104
ulong acl_get(const char *host, const char *ip,
1105
              const char *user, const char *db, my_bool db_is_pattern)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1106
{
1107
  ulong host_access= ~(ulong)0, db_access= 0;
1108
  uint i,key_length;
1109
  char key[ACL_KEY_LENGTH],*tmp_db,*end;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1110
  acl_entry *entry;
monty@mysql.com's avatar
monty@mysql.com committed
1111
  DBUG_ENTER("acl_get");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1112 1113

  VOID(pthread_mutex_lock(&acl_cache->lock));
1114
  end=strmov((tmp_db=strmov(strmov(key, ip ? ip : "")+1,user)+1),db);
1115 1116
  if (lower_case_table_names)
  {
1117
    my_casedn_str(files_charset_info, tmp_db);
1118 1119
    db=tmp_db;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1120
  key_length=(uint) (end-key);
1121
  if (!db_is_pattern && (entry=(acl_entry*) acl_cache->search(key,key_length)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1122 1123 1124
  {
    db_access=entry->access;
    VOID(pthread_mutex_unlock(&acl_cache->lock));
monty@mysql.com's avatar
monty@mysql.com committed
1125 1126
    DBUG_PRINT("exit", ("access: 0x%lx", db_access));
    DBUG_RETURN(db_access);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
  }

  /*
    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))
      {
1139
	if (!acl_db->db || !wild_compare(db,acl_db->db,db_is_pattern))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
	{
	  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))
    {
1161
      if (!acl_host->db || !wild_compare(db,acl_host->db,db_is_pattern))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1162 1163 1164 1165 1166 1167 1168 1169
      {
	host_access=acl_host->access;		// Fully specified. Take it
	break;
      }
    }
  }
exit:
  /* Save entry in cache for quick retrieval */
1170 1171
  if (!db_is_pattern &&
      (entry= (acl_entry*) malloc(sizeof(acl_entry)+key_length)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1172 1173 1174 1175 1176 1177 1178
  {
    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
1179 1180
  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
1181 1182
}

1183 1184 1185 1186 1187 1188 1189
/*
  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
1190 1191 1192 1193

static void init_check_host(void)
{
  DBUG_ENTER("init_check_host");
1194
  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
1195
			  acl_users.elements,1));
1196
  VOID(hash_init(&acl_check_hosts,system_charset_info,acl_users.elements,0,0,
1197
		 (hash_get_key) check_get_key,0,0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
  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 *);
1212
	  if (!my_strcasecmp(system_charset_info,
1213
                             acl_user->host.hostname, acl->hostname))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1214 1215 1216 1217 1218 1219
	    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,
1220
			    (uint) strlen(acl_user->host.hostname)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1221
      {
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1222
	if (my_hash_insert(&acl_check_hosts,(byte*) acl_user))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
	{					// 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));

1244 1245
  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
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
  {
    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
}


1264 1265 1266 1267 1268 1269 1270 1271
/*
  Check if the user is allowed to change password

  SYNOPSIS:
    check_change_password()
    thd		THD
    host	hostname for the user
    user	user name
1272 1273 1274 1275
    new_password new password

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

1277
    RETURN VALUE
1278 1279
      0		OK
      1		ERROR  ; In this case the error is sent to the client.
1280 1281
*/

1282
bool check_change_password(THD *thd, const char *host, const char *user,
1283
                           char *new_password, uint new_password_len)
1284
{
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1285 1286
  if (!initialized)
  {
1287
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
1288
    return(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1289
  }
1290 1291
  if (!thd->slave_thread &&
      (strcmp(thd->user,user) ||
1292
       my_strcasecmp(system_charset_info, host, thd->host_or_ip)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1293
  {
hf@deer.(none)'s avatar
hf@deer.(none) committed
1294
    if (check_access(thd, UPDATE_ACL, "mysql",0,1,0))
1295
      return(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1296
  }
1297 1298
  if (!thd->slave_thread && !thd->user[0])
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1299 1300
    my_message(ER_PASSWORD_ANONYMOUS_USER, ER(ER_PASSWORD_ANONYMOUS_USER),
               MYF(0));
1301
    return(1);
1302
  }
1303
  uint len=strlen(new_password);
1304
  if (len && len != SCRAMBLED_PASSWORD_CHAR_LENGTH &&
1305 1306
      len != SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
  {
1307
    my_error(ER_PASSWD_LENGTH, MYF(0), SCRAMBLED_PASSWORD_CHAR_LENGTH);
1308 1309
    return -1;
  }
1310 1311 1312 1313
  return(0);
}


1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
/*
  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
1327
*/
1328

1329 1330 1331
bool change_password(THD *thd, const char *host, const char *user,
		     char *new_password)
{
1332
  uint new_password_len= strlen(new_password);
1333 1334 1335 1336 1337
  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

1338
  if (check_change_password(thd, host, user, new_password, new_password_len))
1339 1340
    DBUG_RETURN(1);

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1341 1342
  VOID(pthread_mutex_lock(&acl_cache->lock));
  ACL_USER *acl_user;
1343
  if (!(acl_user= find_acl_user(host, user)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1344 1345
  {
    VOID(pthread_mutex_unlock(&acl_cache->lock));
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1346
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH), MYF(0));
1347
    DBUG_RETURN(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1348
  }
1349 1350 1351
  /* update loaded acl entry: */
  set_user_salt(acl_user, new_password, new_password_len);

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1352 1353
  if (update_user_table(thd,
			acl_user->host.hostname ? acl_user->host.hostname : "",
1354
			acl_user->user ? acl_user->user : "",
1355
			new_password, new_password_len))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1356 1357
  {
    VOID(pthread_mutex_unlock(&acl_cache->lock)); /* purecov: deadcode */
1358
    DBUG_RETURN(1); /* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1359
  }
peter@mysql.com's avatar
peter@mysql.com committed
1360

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

1364
  char buff[512]; /* Extend with extended password length*/
1365
  ulong query_length=
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1366 1367
    my_sprintf(buff,
	       (buff,"SET PASSWORD FOR \"%-.120s\"@\"%-.120s\"=\"%-.120s\"",
1368
		acl_user->user ? acl_user->user : "",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1369 1370
		acl_user->host.hostname ? acl_user->host.hostname : "",
		new_password));
guilhem@mysql.com's avatar
guilhem@mysql.com committed
1371
  thd->clear_error();
1372
  Query_log_event qinfo(thd, buff, query_length, 0, FALSE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1373
  mysql_bin_log.write(&qinfo);
1374
  DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
}


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

static ACL_USER *
find_acl_user(const char *host, const char *user)
{
1385
  DBUG_ENTER("find_acl_user");
1386
  DBUG_PRINT("enter",("host: '%s'  user: '%s'",host,user));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1387 1388 1389
  for (uint i=0 ; i < acl_users.elements ; i++)
  {
    ACL_USER *acl_user=dynamic_element(&acl_users,i,ACL_USER*);
1390
    DBUG_PRINT("info",("strcmp('%s','%s'), compare_hostname('%s','%s'),",
1391 1392 1393 1394 1395
		       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
1396 1397 1398
    if (!acl_user->user && !user[0] ||
	acl_user->user && !strcmp(user,acl_user->user))
    {
1399
      if (compare_hostname(&acl_user->host,host,host))
1400 1401 1402
      {
	DBUG_RETURN(acl_user);
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1403 1404
    }
  }
1405
  DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1406 1407 1408
}


1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
/*
  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
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442

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!
1443
  if (!hostname ||
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1444 1445 1446
      (!(hostname=calc_ip(hostname,&host->ip,'/')) ||
       !(hostname=calc_ip(hostname+1,&host->ip_mask,'\0'))))
  {
1447
    host->ip= host->ip_mask=0;			// Not a masked ip
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
  }
}


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 ||
1461
	  (hostname && !wild_case_compare(system_charset_info,
1462
                                          hostname,host->hostname)) ||
1463
	  (ip && !wild_compare(ip,host->hostname,0)));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1464 1465
}

hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1466 1467 1468 1469
bool hostname_requires_resolving(const char *hostname)
{
  char cur;
  if (!hostname)
monty@mysql.com's avatar
monty@mysql.com committed
1470
    return FALSE;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1471 1472 1473
  int namelen= strlen(hostname);
  int lhlen= strlen(my_localhost);
  if ((namelen == lhlen) &&
1474
      !my_strnncoll(system_charset_info, (const uchar *)hostname,  namelen,
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1475
		    (const uchar *)my_localhost, strlen(my_localhost)))
monty@mysql.com's avatar
monty@mysql.com committed
1476
    return FALSE;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1477 1478
  for (; (cur=*hostname); hostname++)
  {
1479
    if ((cur != '%') && (cur != '_') && (cur != '.') && (cur != '/') &&
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1480
	((cur < '0') || (cur > '9')))
monty@mysql.com's avatar
monty@mysql.com committed
1481
      return TRUE;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1482
  }
monty@mysql.com's avatar
monty@mysql.com committed
1483
  return FALSE;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1484
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1485

1486 1487 1488
/*
  Update grants in the user and database privilege tables
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1489 1490

static bool update_user_table(THD *thd, const char *host, const char *user,
1491
			      const char *new_password, uint new_password_len)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1492 1493 1494 1495
{
  TABLE_LIST tables;
  TABLE *table;
  bool error=1;
1496
  char user_key[MAX_KEY_LENGTH];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1497 1498 1499 1500
  DBUG_ENTER("update_user_table");
  DBUG_PRINT("enter",("user: %s  host: %s",user,host));

  bzero((char*) &tables,sizeof(tables));
1501
  tables.alias=tables.table_name=(char*) "user";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1502
  tables.db=(char*) "mysql";
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1503

1504 1505 1506 1507 1508 1509 1510
#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
1511 1512 1513
    /*
      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.
1514
    */
1515
    tables.updating= 1;
1516
    /* Thanks to bzero, tables.next==0 */
1517
    if (!tables_ok(thd, &tables))
1518 1519 1520 1521
      DBUG_RETURN(0);
  }
#endif

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1522 1523
  if (!(table=open_ltable(thd,&tables,TL_WRITE)))
    DBUG_RETURN(1); /* purecov: deadcode */
1524 1525
  table->field[0]->store(host,(uint) strlen(host), system_charset_info);
  table->field[1]->store(user,(uint) strlen(user), system_charset_info);
1526
  key_copy((byte *) user_key, table->record[0], table->key_info,
1527
           table->key_info->key_length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1528

1529
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
1530
  if (table->file->index_read_idx(table->record[0], 0,
1531
				  (byte *) user_key, table->key_info->key_length,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1532 1533
				  HA_READ_KEY_EXACT))
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1534 1535
    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
1536 1537
    DBUG_RETURN(1);				/* purecov: deadcode */
  }
1538
  store_record(table,record[1]);
1539
  table->field[2]->store(new_password, new_password_len, system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
  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
1552

1553 1554 1555 1556 1557 1558
/*
  Return 1 if we are allowed to create new users
  the logic here is: INSERT_ACL is sufficient.
  It's also a requirement in opt_safe_user_create,
  otherwise CREATE_USER_ACL is enough.
*/
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1559 1560 1561

static bool test_if_create_new_users(THD *thd)
{
1562 1563 1564 1565
  bool create_new_users= test(thd->master_access & INSERT_ACL) ||
                         (!opt_safe_user_create &&
                          test(thd->master_access & CREATE_USER_ACL));
  if (!create_new_users)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1566 1567
  {
    TABLE_LIST tl;
1568
    ulong db_access;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1569 1570
    bzero((char*) &tl,sizeof(tl));
    tl.db=	   (char*) "mysql";
1571
    tl.table_name=  (char*) "user";
1572
    create_new_users= 1;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1573

1574
    db_access=acl_get(thd->host, thd->ip,
1575
		      thd->priv_user, tl.db, 0);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1576 1577
    if (!(db_access & INSERT_ACL))
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1578
      if (check_grant(thd, INSERT_ACL, &tl, 0, UINT_MAX, 1))
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1579 1580 1581 1582 1583 1584 1585
	create_new_users=0;
    }
  }
  return create_new_users;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
1586
/****************************************************************************
1587
  Handle GRANT commands
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1588 1589
****************************************************************************/

1590
static int replace_user_table(THD *thd, TABLE *table, const LEX_USER &combo,
1591
			      ulong rights, bool revoke_grant,
serg@serg.mylan's avatar
serg@serg.mylan committed
1592
			      bool can_create_user, bool no_auto_create)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1593 1594
{
  int error = -1;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1595
  bool old_row_exists=0;
1596
  const char *password= "";
1597
  uint password_len= 0;
1598
  char what= (revoke_grant) ? 'N' : 'Y';
1599
  byte user_key[MAX_KEY_LENGTH];
1600
  LEX *lex= thd->lex;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1601
  DBUG_ENTER("replace_user_table");
1602

1603
  safe_mutex_assert_owner(&acl_cache->lock);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1604 1605

  if (combo.password.str && combo.password.str[0])
1606
  {
1607 1608
    if (combo.password.length != SCRAMBLED_PASSWORD_CHAR_LENGTH &&
        combo.password.length != SCRAMBLED_PASSWORD_CHAR_LENGTH_323)
1609
    {
1610
      my_error(ER_PASSWD_LENGTH, MYF(0), SCRAMBLED_PASSWORD_CHAR_LENGTH);
1611
      DBUG_RETURN(-1);
1612
    }
1613
    password_len= combo.password.length;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1614
    password=combo.password.str;
1615
  }
peter@mysql.com's avatar
peter@mysql.com committed
1616

1617 1618
  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);
1619 1620 1621
  key_copy(user_key, table->record[0], table->key_info,
           table->key_info->key_length);

1622
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
1623
  if (table->file->index_read_idx(table->record[0], 0,
1624 1625
                                  user_key, table->key_info->key_length,
                                  HA_READ_KEY_EXACT))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1626
  {
1627 1628
    /* what == 'N' means revoke */
    if (what == 'N')
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1629
    {
1630 1631 1632 1633
      my_error(ER_NONEXISTING_GRANT, MYF(0), combo.user.str, combo.host.str);
      goto end;
    }
    /*
1634 1635
      There are four options which affect the process of creation of
      a new user (mysqld option --safe-create-user, 'insert' privilege
1636 1637 1638 1639 1640 1641 1642
      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
1643 1644

      see also test_if_create_new_users()
1645
    */
serg@serg.mylan's avatar
serg@serg.mylan committed
1646 1647 1648 1649 1650 1651
    else if (!password_len && no_auto_create)
    {
      my_error(ER_PASSWORD_NO_MATCH, MYF(0), combo.user.str, combo.host.str);
      goto end;
    }
    else if (!can_create_user)
1652
    {
1653
      my_error(ER_CANT_CREATE_USER_WITH_GRANT, MYF(0),
1654
               thd->user, thd->host_or_ip);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1655 1656
      goto end;
    }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1657
    old_row_exists = 0;
1658
    restore_record(table,s->default_values);
1659
    table->field[0]->store(combo.host.str,combo.host.length,
1660
                           system_charset_info);
1661
    table->field[1]->store(combo.user.str,combo.user.length,
1662
                           system_charset_info);
1663
    table->field[2]->store(password, password_len,
1664
                           system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1665 1666 1667
  }
  else
  {
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1668
    old_row_exists = 1;
1669
    store_record(table,record[1]);			// Save copy for update
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1670
    if (combo.password.str)			// If password given
1671
      table->field[2]->store(password, password_len, system_charset_info);
1672
    else if (!rights && !revoke_grant &&
1673 1674
             lex->ssl_type == SSL_TYPE_NOT_SPECIFIED &&
             !lex->mqh.specified_limits)
1675 1676 1677
    {
      DBUG_RETURN(0);
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1678 1679
  }

1680 1681 1682 1683
  /* Update table columns with new privileges */

  Field **tmp_field;
  ulong priv;
1684
  uint next_field;
1685 1686 1687 1688
  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
1689
  {
1690
    if (priv & rights)				 // set requested privileges
1691
      (*tmp_field)->store(&what, 1, &my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1692
  }
1693
  rights= get_access(table, 3, &next_field);
1694 1695
  DBUG_PRINT("info",("table fields: %d",table->s->fields));
  if (table->s->fields >= 31)		/* From 4.0.0 we have more fields */
1696
  {
1697
    /* We write down SSL related ACL stuff */
1698
    switch (lex->ssl_type) {
1699
    case SSL_TYPE_ANY:
1700 1701 1702 1703
      table->field[next_field]->store("ANY", 3, &my_charset_latin1);
      table->field[next_field+1]->store("", 0, &my_charset_latin1);
      table->field[next_field+2]->store("", 0, &my_charset_latin1);
      table->field[next_field+3]->store("", 0, &my_charset_latin1);
1704 1705
      break;
    case SSL_TYPE_X509:
1706 1707 1708 1709
      table->field[next_field]->store("X509", 4, &my_charset_latin1);
      table->field[next_field+1]->store("", 0, &my_charset_latin1);
      table->field[next_field+2]->store("", 0, &my_charset_latin1);
      table->field[next_field+3]->store("", 0, &my_charset_latin1);
1710 1711
      break;
    case SSL_TYPE_SPECIFIED:
1712 1713 1714 1715
      table->field[next_field]->store("SPECIFIED", 9, &my_charset_latin1);
      table->field[next_field+1]->store("", 0, &my_charset_latin1);
      table->field[next_field+2]->store("", 0, &my_charset_latin1);
      table->field[next_field+3]->store("", 0, &my_charset_latin1);
1716
      if (lex->ssl_cipher)
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
1717 1718
        table->field[next_field+1]->store(lex->ssl_cipher,
                                strlen(lex->ssl_cipher), system_charset_info);
1719
      if (lex->x509_issuer)
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
1720 1721
        table->field[next_field+2]->store(lex->x509_issuer,
                                strlen(lex->x509_issuer), system_charset_info);
1722
      if (lex->x509_subject)
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
1723 1724
        table->field[next_field+3]->store(lex->x509_subject,
                                strlen(lex->x509_subject), system_charset_info);
1725
      break;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1726
    case SSL_TYPE_NOT_SPECIFIED:
gluh@gluh.(none)'s avatar
gluh@gluh.(none) committed
1727 1728
      break;
    case SSL_TYPE_NONE:
1729 1730 1731 1732
      table->field[next_field]->store("", 0, &my_charset_latin1);
      table->field[next_field+1]->store("", 0, &my_charset_latin1);
      table->field[next_field+2]->store("", 0, &my_charset_latin1);
      table->field[next_field+3]->store("", 0, &my_charset_latin1);
gluh@gluh.(none)'s avatar
gluh@gluh.(none) committed
1733
      break;
1734
    }
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
1735
    next_field+=4;
1736

1737
    USER_RESOURCES mqh= lex->mqh;
1738
    if (mqh.specified_limits & USER_RESOURCES::QUERIES_PER_HOUR)
1739
      table->field[next_field]->store((longlong) mqh.questions);
1740
    if (mqh.specified_limits & USER_RESOURCES::UPDATES_PER_HOUR)
1741
      table->field[next_field+1]->store((longlong) mqh.updates);
1742
    if (mqh.specified_limits & USER_RESOURCES::CONNECTIONS_PER_HOUR)
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
1743
      table->field[next_field+2]->store((longlong) mqh.conn_per_hour);
1744
    if (table->s->fields >= 36 &&
1745
        (mqh.specified_limits & USER_RESOURCES::USER_CONNECTIONS))
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
1746
      table->field[next_field+3]->store((longlong) mqh.user_conn);
1747
    mqh_used= mqh_used || mqh.questions || mqh.updates || mqh.conn_per_hour;
1748
  }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1749
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1750 1751 1752 1753 1754
  {
    /*
      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!
    */
1755
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
1756
    if (cmp_record(table,record[1]) &&
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
	(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

1776
end:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1777 1778 1779
  if (!error)
  {
    acl_cache->clear(1);			// Clear privilege cache
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1780
    if (old_row_exists)
1781 1782
      acl_update_user(combo.user.str, combo.host.str,
                      combo.password.str, password_len,
1783 1784 1785 1786 1787
		      lex->ssl_type,
		      lex->ssl_cipher,
		      lex->x509_issuer,
		      lex->x509_subject,
		      &lex->mqh,
1788
		      rights);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1789
    else
1790
      acl_insert_user(combo.user.str, combo.host.str, password, password_len,
1791 1792 1793 1794 1795
		      lex->ssl_type,
		      lex->ssl_cipher,
		      lex->x509_issuer,
		      lex->x509_subject,
		      &lex->mqh,
1796
		      rights);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1797 1798 1799 1800 1801 1802
  }
  DBUG_RETURN(error);
}


/*
1803
  change grants in the mysql.db table
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1804 1805 1806 1807
*/

static int replace_db_table(TABLE *table, const char *db,
			    const LEX_USER &combo,
1808
			    ulong rights, bool revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1809
{
1810 1811
  uint i;
  ulong priv,store_rights;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1812
  bool old_row_exists=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1813
  int error;
1814
  char what= (revoke_grant) ? 'N' : 'Y';
1815
  byte user_key[MAX_KEY_LENGTH];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1816 1817
  DBUG_ENTER("replace_db_table");

1818 1819
  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
1820
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
1821 1822 1823
    DBUG_RETURN(-1);
  }

1824
  /* Check if there is such a user in user table in memory? */
1825
  if (!find_acl_user(combo.host.str,combo.user.str))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1826
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1827
    my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH), MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1828 1829 1830
    DBUG_RETURN(-1);
  }

1831 1832 1833
  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);
1834 1835 1836
  key_copy(user_key, table->record[0], table->key_info,
           table->key_info->key_length);

1837 1838
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
  if (table->file->index_read_idx(table->record[0],0,
1839 1840
                                  user_key, table->key_info->key_length,
                                  HA_READ_KEY_EXACT))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1841 1842 1843
  {
    if (what == 'N')
    { // no row, no revoke
guilhem@mysql.com's avatar
guilhem@mysql.com committed
1844
      my_error(ER_NONEXISTING_GRANT, MYF(0), combo.user.str, combo.host.str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1845 1846
      goto abort;
    }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1847
    old_row_exists = 0;
1848
    restore_record(table, s->default_values);
1849 1850 1851
    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
1852 1853 1854
  }
  else
  {
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1855
    old_row_exists = 1;
1856
    store_record(table,record[1]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1857 1858 1859
  }

  store_rights=get_rights_for_db(rights);
1860
  for (i= 3, priv= 1; i < table->s->fields; i++, priv <<= 1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1861
  {
1862
    if (priv & store_rights)			// do it if priv is chosen
1863
      table->field [i]->store(&what,1, &my_charset_latin1);// set requested privileges
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1864 1865 1866 1867
  }
  rights=get_access(table,3);
  rights=fix_rights_for_db(rights);

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1868
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1869
  {
1870
    /* update old existing row */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1871 1872
    if (rights)
    {
1873
      table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1874 1875 1876 1877 1878 1879 1880 1881 1882
      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 */
    }
  }
1883
  else if (rights && (error=table->file->write_row(table->record[0])))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1884 1885 1886 1887 1888 1889
  {
    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
1890
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1891 1892
    acl_update_db(combo.user.str,combo.host.str,db,rights);
  else
1893
  if (rights)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1894 1895 1896 1897
    acl_insert_db(combo.user.str,combo.host.str,db,rights);
  DBUG_RETURN(0);

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

1901
abort:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1902 1903 1904 1905 1906 1907 1908 1909
  DBUG_RETURN(-1);
}


class GRANT_COLUMN :public Sql_alloc
{
public:
  char *column;
1910 1911 1912
  ulong rights;
  uint key_length;
  GRANT_COLUMN(String &c,  ulong y) :rights (y)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1913
  {
1914
    column= memdup_root(&memex,c.ptr(), key_length=c.length());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1915 1916 1917
  }
};

1918

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1919 1920 1921 1922 1923 1924 1925
static byte* get_key_column(GRANT_COLUMN *buff,uint *length,
			    my_bool not_used __attribute__((unused)))
{
  *length=buff->key_length;
  return (byte*) buff->column;
}

1926

1927
class GRANT_NAME :public Sql_alloc
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1928 1929
{
public:
1930 1931
  acl_host_and_ip host;
  char *db, *user, *tname, *hash_key;
1932
  ulong privs;
1933
  ulong sort;
1934
  uint key_length;
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
  GRANT_NAME(const char *h, const char *d,const char *u,
             const char *t, ulong p);
  GRANT_NAME (TABLE *form);
  virtual ~GRANT_NAME() {};
  virtual bool ok() { return privs != 0; }
};


class GRANT_TABLE :public GRANT_NAME
{
public:
  ulong cols;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1947
  HASH hash_columns;
monty@mysql.com's avatar
monty@mysql.com committed
1948 1949 1950 1951

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

1956

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

1958 1959 1960
GRANT_NAME::GRANT_NAME(const char *h, const char *d,const char *u,
                       const char *t, ulong p)
  :privs(p)
1961 1962
{
  /* Host given by user */
1963
  update_hostname(&host, strdup_root(&memex, h));
1964 1965
  db =   strdup_root(&memex,d);
  user = strdup_root(&memex,u);
1966
  sort=  get_sort(3,host.hostname,db,user);
1967 1968
  tname= strdup_root(&memex,t);
  if (lower_case_table_names)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1969
  {
1970 1971
    my_casedn_str(files_charset_info, db);
    my_casedn_str(files_charset_info, tname);
1972 1973 1974 1975
  }
  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);
1976 1977 1978 1979 1980 1981 1982
}


GRANT_TABLE::GRANT_TABLE(const char *h, const char *d,const char *u,
                	 const char *t, ulong p, ulong c)
  :GRANT_NAME(h,d,u,t,p), cols(c)
{
1983
  (void) hash_init(&hash_columns,system_charset_info,
monty@mysql.com's avatar
monty@mysql.com committed
1984
                   0,0,0, (hash_get_key) get_key_column,0,0);
1985
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1986

1987

1988
GRANT_NAME::GRANT_NAME(TABLE *form)
1989
{
1990
  update_hostname(&host, get_field(&memex, form->field[0]));
monty@mysql.com's avatar
monty@mysql.com committed
1991 1992
  db=    get_field(&memex,form->field[1]);
  user=  get_field(&memex,form->field[2]);
1993 1994
  if (!user)
    user= (char*) "";
1995
  sort=  get_sort(3, host.hostname, db, user);
monty@mysql.com's avatar
monty@mysql.com committed
1996
  tname= get_field(&memex,form->field[3]);
1997 1998 1999
  if (!db || !tname)
  {
    /* Wrong table row; Ignore it */
2000
    privs= 0;
2001 2002 2003 2004
    return;					/* purecov: inspected */
  }
  if (lower_case_table_names)
  {
2005 2006
    my_casedn_str(files_charset_info, db);
    my_casedn_str(files_charset_info, tname);
2007 2008 2009 2010 2011 2012 2013
  }
  key_length = ((uint) strlen(db) + (uint) strlen(user) +
                (uint) strlen(tname) + 3);
  hash_key = (char*) alloc_root(&memex,key_length);
  strmov(strmov(strmov(hash_key,user)+1,db)+1,tname);
  privs = (ulong) form->field[6]->val_int();
  privs = fix_rights_for_table(privs);
2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
}


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

  if (!db || !tname)
  {
    /* Wrong table row; Ignore it */
    hash_clear(&hash_columns);                  /* allow for destruction */
    cols= 0;
    return;
  }
  cols= (ulong) form->field[7]->val_int();
2030 2031
  cols =  fix_rights_for_column(cols);

2032
  (void) hash_init(&hash_columns,system_charset_info,
monty@mysql.com's avatar
monty@mysql.com committed
2033
                   0,0,0, (hash_get_key) get_key_column,0,0);
2034 2035
  if (cols)
  {
2036 2037
    uint key_prefix_len;
    KEY_PART_INFO *key_part= col_privs->key_info->key_part;
2038
    col_privs->field[0]->store(host.hostname,(uint) strlen(host.hostname),
2039 2040 2041 2042
                               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);
2043 2044 2045 2046 2047 2048

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

2051 2052
    col_privs->file->ha_index_init(0);
    if (col_privs->file->index_read(col_privs->record[0],
2053 2054
                                    (byte*) key,
                                    key_prefix_len, HA_READ_KEY_EXACT))
2055
    {
2056
      cols = 0; /* purecov: deadcode */
2057
      col_privs->file->ha_index_end();
2058
      return;
2059
    }
2060
    do
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2061
    {
2062 2063 2064
      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
2065
      res=col_privs->field[4]->val_str(&column_name);
2066 2067 2068
      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
2069
      {
2070 2071 2072
        /* Don't use this entry */
        privs = cols = 0;			/* purecov: deadcode */
        return;				/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2073
      }
monty@mysql.com's avatar
monty@mysql.com committed
2074
      my_hash_insert(&hash_columns, (byte *) mem_check);
2075
    } while (!col_privs->file->index_next(col_privs->record[0]) &&
2076
             !key_cmp_if_same(col_privs,key,0,key_prefix_len));
2077
    col_privs->file->ha_index_end();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2078
  }
2079
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2080

2081

2082 2083 2084 2085 2086 2087
GRANT_TABLE::~GRANT_TABLE()
{
  hash_free(&hash_columns);
}


2088
static byte* get_grant_table(GRANT_NAME *buff,uint *length,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2089 2090 2091 2092 2093 2094
			     my_bool not_used __attribute__((unused)))
{
  *length=buff->key_length;
  return (byte*) buff->hash_key;
}

2095

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2096 2097 2098 2099 2100
void free_grant_table(GRANT_TABLE *grant_table)
{
  hash_free(&grant_table->hash_columns);
}

2101

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

2104 2105
static GRANT_NAME *name_hash_search(HASH *name_hash,
				      const char *host,const char* ip,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2106 2107 2108 2109 2110 2111
				      const char *db,
				      const char *user, const char *tname,
				      bool exact)
{
  char helping [NAME_LEN*2+USERNAME_LENGTH+3];
  uint len;
2112
  GRANT_NAME *grant_name,*found=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2113 2114

  len  = (uint) (strmov(strmov(strmov(helping,user)+1,db)+1,tname)-helping)+ 1;
2115
  for (grant_name=(GRANT_NAME*) hash_search(name_hash,
2116
					      (byte*) helping,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2117
					      len) ;
2118 2119
       grant_name ;
       grant_name= (GRANT_NAME*) hash_next(name_hash,(byte*) helping,
2120
					     len))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2121 2122 2123
  {
    if (exact)
    {
2124
      if (compare_hostname(&grant_name->host, host, ip))
2125
	return grant_name;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2126 2127 2128
    }
    else
    {
2129
      if (compare_hostname(&grant_name->host, host, ip) &&
2130 2131
          (!found || found->sort < grant_name->sort))
	found=grant_name;					// Host ok
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2132 2133 2134 2135 2136 2137
    }
  }
  return found;
}


2138
inline GRANT_NAME *
2139 2140
routine_hash_search(const char *host, const char *ip, const char *db,
                 const char *user, const char *tname, bool proc, bool exact)
2141
{
2142 2143 2144
  return (GRANT_TABLE*)
    name_hash_search(proc ? &proc_priv_hash : &func_priv_hash,
		     host, ip, db, user, tname, exact);
2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
}


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

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

2157
inline GRANT_COLUMN *
2158
column_hash_search(GRANT_TABLE *t, const char *cname, uint length)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2159 2160 2161 2162 2163 2164 2165 2166 2167
{
  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,
2168
				ulong rights, bool revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2169 2170 2171
{
  int error=0,result=0;
  byte key[MAX_KEY_LENGTH];
2172 2173
  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
2174 2175
  DBUG_ENTER("replace_column_table");

2176 2177 2178 2179 2180 2181 2182 2183
  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
2184

2185 2186 2187 2188
  /* 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
2189

2190
  rights&= COL_ACLS;				// Only ACL for columns
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2191 2192 2193 2194

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

  List_iterator <LEX_COLUMN> iter(columns);
2195
  class LEX_COLUMN *column;
2196
  table->file->ha_index_init(0);
2197
  while ((column= iter++))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2198
  {
2199
    ulong privileges= column->rights;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2200
    bool old_row_exists=0;
2201 2202 2203 2204
    byte user_key[MAX_KEY_LENGTH];

    key_restore(table->record[0],key,table->key_info,
                key_prefix_length);
2205
    table->field[4]->store(column->column.ptr(), column->column.length(),
2206
                           system_charset_info);
2207 2208 2209
    /* 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
2210

2211
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
2212 2213 2214
    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
2215 2216 2217
    {
      if (revoke_grant)
      {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2218
	my_error(ER_NONEXISTING_TABLE_GRANT, MYF(0),
2219
                 combo.user.str, combo.host.str,
2220 2221 2222
                 table_name);                   /* purecov: inspected */
	result= -1;                             /* purecov: inspected */
	continue;                               /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2223
      }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2224
      old_row_exists = 0;
2225
      restore_record(table, s->default_values);		// Get empty record
2226 2227
      key_restore(table->record[0],key,table->key_info,
                  key_prefix_length);
2228
      table->field[4]->store(column->column.ptr(),column->column.length(),
2229
                             system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2230 2231 2232
    }
    else
    {
2233
      ulong tmp= (ulong) table->field[6]->val_int();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2234 2235 2236 2237 2238 2239
      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
2240
      old_row_exists = 1;
2241
      store_record(table,record[1]);			// copy original row
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2242 2243 2244 2245
    }

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

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2246
    if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2247
    {
2248
      GRANT_COLUMN *grant_column;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2249 2250 2251 2252 2253 2254 2255 2256 2257 2258
      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 */
      }
2259 2260
      grant_column= column_hash_search(g_t, column->column.ptr(),
                                       column->column.length());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2261
      if (grant_column)				// Should always be true
2262
	grant_column->rights= privileges;	// Update hash
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2263 2264 2265
    }
    else					// new grant
    {
2266
      GRANT_COLUMN *grant_column;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2267 2268 2269 2270 2271 2272
      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 */
      }
2273
      grant_column= new GRANT_COLUMN(column->column,privileges);
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2274
      my_hash_insert(&g_t->hash_columns,(byte*) grant_column);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2275 2276 2277 2278 2279 2280 2281 2282 2283 2284
    }
  }

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

  if (revoke_grant)
  {
2285 2286
    byte user_key[MAX_KEY_LENGTH];
    key_copy(user_key, table->record[0], table->key_info,
2287 2288
             key_prefix_length);

2289
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
2290
    if (table->file->index_read(table->record[0], user_key,
2291
				key_prefix_length,
2292
                                HA_READ_KEY_EXACT))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2293 2294
      goto end;

2295
    /* Scan through all rows with the same host,db,user and table */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2296 2297
    do
    {
2298
      ulong privileges = (ulong) table->field[6]->val_int();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2299
      privileges=fix_rights_for_column(privileges);
2300
      store_record(table,record[1]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2301 2302 2303 2304 2305

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

	privileges&= ~rights;
	table->field[6]->store((longlong)
			       get_rights_for_column(privileges));
2312
	table->field[4]->val_str(&column_name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342
	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]) &&
2343
	     !key_cmp_if_same(table, key, 0, key_prefix_length));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2344 2345
  }

2346
end:
2347
  table->file->ha_index_end();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2348 2349 2350 2351 2352 2353 2354
  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,
2355 2356
			       ulong rights, ulong col_rights,
			       bool revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2357
{
2358
  char grantor[HOSTNAME_LENGTH+USERNAME_LENGTH+2];
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2359
  int old_row_exists = 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2360
  int error=0;
2361
  ulong store_table_rights, store_col_rights;
2362
  byte user_key[MAX_KEY_LENGTH];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2363 2364
  DBUG_ENTER("replace_table_table");

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

2367 2368 2369 2370
  /*
    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
2371 2372
  if (!find_acl_user(combo.host.str,combo.user.str))
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2373 2374
    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
2375 2376 2377
    DBUG_RETURN(-1);				/* purecov: deadcode */
  }

2378
  restore_record(table, s->default_values);     // Get empty record
2379 2380 2381 2382
  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);
2383
  store_record(table,record[1]);			// store at pos 1
2384 2385
  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
2386

2387
  table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
2388 2389
  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
2390 2391 2392 2393 2394 2395 2396 2397 2398
				  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
2399 2400
      my_error(ER_NONEXISTING_TABLE_GRANT, MYF(0),
               combo.user.str, combo.host.str,
2401
               table_name);		        /* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2402 2403
      DBUG_RETURN(-1);				/* purecov: deadcode */
    }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2404
    old_row_exists = 0;
2405
    restore_record(table,record[1]);			// Get saved record
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2406 2407
  }

2408 2409
  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
2410
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2411
  {
2412
    ulong j,k;
2413
    store_record(table,record[1]);
2414 2415
    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
2416 2417 2418

    if (revoke_grant)
    {
2419
      /* column rights are already fixed in mysql_table_grant */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2420 2421 2422 2423
      store_table_rights=j & ~store_table_rights;
    }
    else
    {
2424 2425
      store_table_rights|= j;
      store_col_rights|=   k;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2426 2427 2428
    }
  }

2429
  table->field[4]->store(grantor,(uint) strlen(grantor), system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2430 2431 2432
  table->field[6]->store((longlong) store_table_rights);
  table->field[7]->store((longlong) store_col_rights);
  rights=fix_rights_for_table(store_table_rights);
2433
  col_rights=fix_rights_for_column(store_col_rights);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2434

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2435
  if (old_row_exists)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451
  {
    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 */
  }

2452
  if (rights | col_rights)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2453
  {
2454
    grant_table->privs= rights;
2455
    grant_table->cols=	col_rights;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2456 2457 2458
  }
  else
  {
2459
    hash_delete(&column_priv_hash,(byte*) grant_table);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2460 2461 2462
  }
  DBUG_RETURN(0);

2463 2464
  /* This should never happen */
table_error:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2465 2466 2467 2468 2469
  table->file->print_error(error,MYF(0)); /* purecov: deadcode */
  DBUG_RETURN(-1); /* purecov: deadcode */
}


2470
static int replace_routine_table(THD *thd, GRANT_NAME *grant_name,
2471
			      TABLE *table, const LEX_USER &combo,
2472 2473
			      const char *db, const char *routine_name,
			      bool is_proc, ulong rights, bool revoke_grant)
2474 2475 2476 2477 2478
{
  char grantor[HOSTNAME_LENGTH+USERNAME_LENGTH+2];
  int old_row_exists= 1;
  int error=0;
  ulong store_proc_rights;
2479 2480
  byte *key;
  DBUG_ENTER("replace_routine_table");
2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499

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

  strxmov(grantor, thd->user, "@", thd->host_or_ip, NullS);

  /*
    The following should always succeed as new users are created before
    this function is called!
  */
  if (!find_acl_user(combo.host.str,combo.user.str))
  {
    my_error(ER_PASSWORD_NO_MATCH,MYF(0));
    DBUG_RETURN(-1);
  }

2500
  restore_record(table, s->default_values);		// Get empty record
2501 2502 2503
  table->field[0]->store(combo.host.str,combo.host.length, &my_charset_latin1);
  table->field[1]->store(db,(uint) strlen(db), &my_charset_latin1);
  table->field[2]->store(combo.user.str,combo.user.length, &my_charset_latin1);
2504 2505 2506 2507
  table->field[3]->store(routine_name,(uint) strlen(routine_name),
                         &my_charset_latin1);
  table->field[4]->store((longlong)(is_proc ? 
                         TYPE_ENUM_PROCEDURE : TYPE_ENUM_FUNCTION));
2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521
  store_record(table,record[1]);			// store at pos 1

  if (table->file->index_read_idx(table->record[0],0,
				  (byte*) table->field[0]->ptr,0,
				  HA_READ_KEY_EXACT))
  {
    /*
      The following should never happen as we first check the in memory
      grant tables for the user.  There is however always a small change that
      the user has modified the grant tables directly.
    */
    if (revoke_grant)
    { // no row, no revoke
      my_error(ER_NONEXISTING_PROC_GRANT, MYF(0),
2522
               combo.user.str, combo.host.str, routine_name);
2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546
      DBUG_RETURN(-1);
    }
    old_row_exists= 0;
    restore_record(table,record[1]);			// Get saved record
  }

  store_proc_rights= get_rights_for_procedure(rights);
  if (old_row_exists)
  {
    ulong j;
    store_record(table,record[1]);
    j= (ulong) table->field[6]->val_int();

    if (revoke_grant)
    {
      /* column rights are already fixed in mysql_table_grant */
      store_proc_rights=j & ~store_proc_rights;
    }
    else
    {
      store_proc_rights|= j;
    }
  }

2547
  table->field[5]->store(grantor,(uint) strlen(grantor), &my_charset_latin1);
2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573
  table->field[6]->store((longlong) store_proc_rights);
  rights=fix_rights_for_procedure(store_proc_rights);

  if (old_row_exists)
  {
    if (store_proc_rights)
    {
      if ((error=table->file->update_row(table->record[1],table->record[0])))
	goto table_error;
    }
    else if ((error= table->file->delete_row(table->record[1])))
      goto table_error;
  }
  else
  {
    error=table->file->write_row(table->record[0]);
    if (error && error != HA_ERR_FOUND_DUPP_KEY)
      goto table_error;
  }

  if (rights)
  {
    grant_name->privs= rights;
  }
  else
  {
2574
    hash_delete(is_proc ? &proc_priv_hash : &func_priv_hash,(byte*) grant_name);
2575 2576 2577 2578 2579 2580 2581 2582 2583 2584
  }
  DBUG_RETURN(0);

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


2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597
/*
  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
2598 2599
    FALSE ok
    TRUE  error
2600 2601
*/

2602
bool mysql_table_grant(THD *thd, TABLE_LIST *table_list,
2603 2604 2605
		      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
2606
{
2607
  ulong column_priv= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2608 2609 2610
  List_iterator <LEX_USER> str_list (user_list);
  LEX_USER *Str;
  TABLE_LIST tables[3];
2611
  bool create_new_users=0;
2612
  char *db_name, *table_name;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2613 2614 2615 2616
  DBUG_ENTER("mysql_table_grant");

  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2617 2618
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0),
             "--skip-grant-tables");	/* purecov: inspected */
2619
    DBUG_RETURN(TRUE);				/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2620 2621 2622
  }
  if (rights & ~TABLE_ACLS)
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2623 2624
    my_message(ER_ILLEGAL_GRANT_FOR_TABLE, ER(ER_ILLEGAL_GRANT_FOR_TABLE),
               MYF(0));
2625
    DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2626 2627
  }

2628
  if (!revoke_grant)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2629
  {
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
2630
    if (columns.elements)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2631
    {
2632 2633
      class LEX_COLUMN *column;
      List_iterator <LEX_COLUMN> column_iter(columns);
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
2634 2635 2636

      if (open_and_lock_tables(thd, table_list))
        DBUG_RETURN(TRUE);
2637 2638

      while ((column = column_iter++))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2639
      {
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
2640
        uint unused_field_idx= NO_CACHED_FIELD_INDEX;
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
2641 2642
        Field *f=find_field_in_table(thd, table_list, column->column.ptr(),
                                     column->column.ptr(),
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
2643
                                     column->column.length(), 0, 1, 1, 0,
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
2644 2645
                                     &unused_field_idx, FALSE);
        if (f == (Field*)0)
2646
        {
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
2647 2648
          my_error(ER_BAD_FIELD_ERROR, MYF(0),
                   column->column.c_ptr(), table_list->alias);
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
2649
          DBUG_RETURN(TRUE);
2650
        }
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
2651 2652
        if (f == (Field *)-1)
          DBUG_RETURN(TRUE);
2653
        column_priv|= column->rights;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2654
      }
2655
      close_thread_tables(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2656
    }
2657
    else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2658
    {
2659 2660 2661 2662
      if (!(rights & CREATE_ACL))
      {
        char buf[FN_REFLEN];
        sprintf(buf,"%s/%s/%s.frm",mysql_data_home, table_list->db,
2663
                table_list->table_name);
2664 2665 2666
        fn_format(buf,buf,"","",4+16+32);
        if (access(buf,F_OK))
        {
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
2667
          my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->alias);
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
2668
          DBUG_RETURN(TRUE);
2669 2670 2671 2672 2673 2674 2675 2676
        }
      }
      if (table_list->grant.want_privilege)
      {
        char command[128];
        get_privilege_desc(command, sizeof(command),
                           table_list->grant.want_privilege);
        my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0),
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
2677
                 command, thd->priv_user, thd->host_or_ip, table_list->alias);
2678 2679
        DBUG_RETURN(-1);
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2680 2681 2682 2683 2684 2685
    }
  }

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

  bzero((char*) &tables,sizeof(tables));
2686 2687 2688
  tables[0].alias=tables[0].table_name= (char*) "user";
  tables[1].alias=tables[1].table_name= (char*) "tables_priv";
  tables[2].alias=tables[2].table_name= (char*) "columns_priv";
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2689
  tables[0].next_local= tables[0].next_global= tables+1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2690
  /* 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
2691 2692 2693 2694 2695
  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
2696 2697 2698
  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";

2699 2700 2701 2702 2703
#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
2704 2705
  if (thd->slave_thread && table_rules_on)
  {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2706 2707 2708
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
2709
    */
2710
    tables[0].updating= tables[1].updating= tables[2].updating= 1;
2711
    if (!tables_ok(thd, tables))
2712
      DBUG_RETURN(FALSE);
2713
  }
2714 2715
#endif

2716
  if (simple_open_n_lock_tables(thd,tables))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2717 2718
  {						// Should never happen
    close_thread_tables(thd);			/* purecov: deadcode */
2719
    DBUG_RETURN(TRUE);				/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2720 2721
  }

2722 2723
  if (!revoke_grant)
    create_new_users= test_if_create_new_users(thd);
2724
  bool result= FALSE;
2725
  rw_wrlock(&LOCK_grant);
2726 2727
  MEM_ROOT *old_root= thd->mem_root;
  thd->mem_root= &memex;
2728
  grant_version++;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2729 2730 2731

  while ((Str = str_list++))
  {
2732
    int error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2733 2734 2735 2736
    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
2737 2738
      my_message(ER_GRANT_WRONG_HOST_OR_USER, ER(ER_GRANT_WRONG_HOST_OR_USER),
                 MYF(0));
2739
      result= TRUE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2740 2741 2742
      continue;
    }
    /* Create user if needed */
2743
    pthread_mutex_lock(&acl_cache->lock);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2744
    error=replace_user_table(thd, tables[0].table, *Str,
serg@serg.mylan's avatar
serg@serg.mylan committed
2745
			     0, revoke_grant, create_new_users,
monty@mysql.com's avatar
monty@mysql.com committed
2746 2747
                             test(thd->variables.sql_mode &
                                  MODE_NO_AUTO_CREATE_USER));
2748 2749
    pthread_mutex_unlock(&acl_cache->lock);
    if (error)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2750
    {
2751
      result= TRUE;				// Remember error
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2752 2753 2754
      continue;					// Add next user
    }

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2755 2756 2757
    db_name= (table_list->view_db.length ?
	      table_list->view_db.str :
	      table_list->db);
2758
    table_name= (table_list->view_name.length ?
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2759
		table_list->view_name.str :
2760
		table_list->table_name);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2761

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2762
    /* Find/create cached table grant */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2763
    grant_table= table_hash_search(Str->host.str, NullS, db_name,
2764
				   Str->user.str, table_name, 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2765 2766 2767 2768
    if (!grant_table)
    {
      if (revoke_grant)
      {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2769
	my_error(ER_NONEXISTING_TABLE_GRANT, MYF(0),
2770
                 Str->user.str, Str->host.str, table_list->table_name);
2771
	result= TRUE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2772 2773
	continue;
      }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2774
      grant_table = new GRANT_TABLE (Str->host.str, db_name,
2775
				     Str->user.str, table_name,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2776 2777 2778 2779
				     rights,
				     column_priv);
      if (!grant_table)				// end of memory
      {
2780
	result= TRUE;				/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2781 2782
	continue;				/* purecov: deadcode */
      }
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2783
      my_hash_insert(&column_priv_hash,(byte*) grant_table);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2784 2785 2786 2787 2788
    }

    /* If revoke_grant, calculate the new column privilege for tables_priv */
    if (revoke_grant)
    {
2789 2790
      class LEX_COLUMN *column;
      List_iterator <LEX_COLUMN> column_iter(columns);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2791 2792 2793
      GRANT_COLUMN *grant_column;

      /* Fix old grants */
2794
      while ((column = column_iter++))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2795 2796
      {
	grant_column = column_hash_search(grant_table,
2797 2798
					  column->column.ptr(),
					  column->column.length());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2799
	if (grant_column)
2800
	  grant_column->rights&= ~(column->rights | rights);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2801 2802
      }
      /* scan trough all columns to get new column grant */
2803
      column_priv= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819
      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
2820
    if (replace_table_table(thd, grant_table, tables[1].table, *Str,
2821
			    db_name, table_name,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2822
			    rights, column_priv, revoke_grant))
2823 2824
    {
      /* Should only happen if table is crashed */
2825
      result= TRUE;			       /* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2826 2827 2828
    }
    else if (tables[2].table)
    {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2829
      if ((replace_column_table(grant_table, tables[2].table, *Str,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2830
				columns,
2831
				db_name, table_name,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2832 2833
				rights, revoke_grant)))
      {
2834
	result= TRUE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2835 2836 2837 2838
      }
    }
  }
  grant_option=TRUE;
2839
  thd->mem_root= old_root;
2840
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2841
  if (!result)
2842
    send_ok(thd);
2843
  /* Tables are automatically closed */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2844 2845 2846 2847
  DBUG_RETURN(result);
}


2848
/*
2849
  Store routine level grants in the privilege tables
2850 2851

  SYNOPSIS
2852
    mysql_routine_grant()
2853
    thd			Thread handle
2854 2855
    table_list		List of routines to give grant
    is_proc             true indicates routine list are procedures
2856 2857 2858 2859 2860 2861 2862 2863 2864
    user_list		List of users to give grant
    rights		Table level grant
    revoke_grant	Set to 1 if this is a REVOKE command

  RETURN
    0	ok
    1	error
*/

2865 2866 2867
bool mysql_routine_grant(THD *thd, TABLE_LIST *table_list, bool is_proc,
			 List <LEX_USER> &user_list, ulong rights,
			 bool revoke_grant, bool no_error)
2868 2869 2870 2871 2872
{
  List_iterator <LEX_USER> str_list (user_list);
  LEX_USER *Str;
  TABLE_LIST tables[2];
  bool create_new_users=0, result=0;
2873
  char *db_name, *table_name;
2874
  DBUG_ENTER("mysql_routine_grant");
2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892

  if (!initialized)
  {
    if (!no_error)
      my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0),
               "--skip-grant-tables");
    DBUG_RETURN(TRUE);
  }
  if (rights & ~PROC_ACLS)
  {
    if (!no_error)
      my_message(ER_ILLEGAL_GRANT_FOR_TABLE, ER(ER_ILLEGAL_GRANT_FOR_TABLE),
        	 MYF(0));
    DBUG_RETURN(TRUE);
  }

  if (!revoke_grant)
  {
2893
    if (sp_exists_routine(thd, table_list, is_proc, no_error)<0)
2894 2895 2896 2897 2898 2899
      DBUG_RETURN(TRUE);
  }

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

  bzero((char*) &tables,sizeof(tables));
2900 2901
  tables[0].alias=tables[0].table_name= (char*) "user";
  tables[1].alias=tables[1].table_name= (char*) "procs_priv";
2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917
  tables[0].next_local= tables[0].next_global= tables+1;
  tables[0].lock_type=tables[1].lock_type=TL_WRITE;
  tables[0].db=tables[1].db=(char*) "mysql";

#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
  if (thd->slave_thread && table_rules_on)
  {
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
    */
    tables[0].updating= tables[1].updating= 1;
2918
    if (!tables_ok(thd, tables))
2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952
      DBUG_RETURN(FALSE);
  }
#endif

  if (simple_open_n_lock_tables(thd,tables))
  {						// Should never happen
    close_thread_tables(thd);
    DBUG_RETURN(TRUE);
  }

  if (!revoke_grant)
    create_new_users= test_if_create_new_users(thd);
  rw_wrlock(&LOCK_grant);
  MEM_ROOT *old_root= thd->mem_root;
  thd->mem_root= &memex;

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

  while ((Str= str_list++))
  {
    int error;
    GRANT_NAME *grant_name;
    if (Str->host.length > HOSTNAME_LENGTH ||
	Str->user.length > USERNAME_LENGTH)
    {
      if (!no_error)
	my_message(ER_GRANT_WRONG_HOST_OR_USER, ER(ER_GRANT_WRONG_HOST_OR_USER),
                   MYF(0));
      result= TRUE;
      continue;
    }
    /* Create user if needed */
    pthread_mutex_lock(&acl_cache->lock);
    error=replace_user_table(thd, tables[0].table, *Str,
serg@serg.mylan's avatar
serg@serg.mylan committed
2953
			     0, revoke_grant, create_new_users,
monty@mysql.com's avatar
monty@mysql.com committed
2954 2955
                             test(thd->variables.sql_mode &
                                  MODE_NO_AUTO_CREATE_USER));
2956 2957 2958 2959 2960 2961 2962 2963
    pthread_mutex_unlock(&acl_cache->lock);
    if (error)
    {
      result= TRUE;				// Remember error
      continue;					// Add next user
    }

    db_name= table_list->db;
2964
    table_name= table_list->table_name;
2965

2966 2967
    grant_name= routine_hash_search(Str->host.str, NullS, db_name,
                                    Str->user.str, table_name, is_proc, 1);
2968 2969 2970 2971 2972 2973
    if (!grant_name)
    {
      if (revoke_grant)
      {
        if (!no_error)
          my_error(ER_NONEXISTING_PROC_GRANT, MYF(0),
2974
		   Str->user.str, Str->host.str, table_name);
2975 2976 2977 2978
	result= TRUE;
	continue;
      }
      grant_name= new GRANT_NAME(Str->host.str, db_name,
2979
				 Str->user.str, table_name,
2980 2981 2982 2983 2984 2985
				 rights);
      if (!grant_name)
      {
        result= TRUE;
	continue;
      }
2986
      my_hash_insert(is_proc ? &proc_priv_hash : &func_priv_hash,(byte*) grant_name);
2987
    }
2988

2989 2990
    if (replace_routine_table(thd, grant_name, tables[1].table, *Str,
			   db_name, table_name, is_proc, rights, revoke_grant))
2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005
    {
      result= TRUE;
      continue;
    }
  }
  grant_option=TRUE;
  thd->mem_root= old_root;
  rw_unlock(&LOCK_grant);
  if (!result && !no_error)
    send_ok(thd);
  /* Tables are automatically closed */
  DBUG_RETURN(result);
}


3006 3007
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
3008 3009 3010
{
  List_iterator <LEX_USER> str_list (list);
  LEX_USER *Str;
3011
  char tmp_db[NAME_LEN+1];
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
3012
  bool create_new_users=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3013 3014 3015 3016
  TABLE_LIST tables[2];
  DBUG_ENTER("mysql_grant");
  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3017 3018
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0),
             "--skip-grant-tables");	/* purecov: tested */
3019
    DBUG_RETURN(TRUE);				/* purecov: tested */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3020 3021
  }

3022 3023 3024
  if (lower_case_table_names && db)
  {
    strmov(tmp_db,db);
3025
    my_casedn_str(files_charset_info, tmp_db);
3026 3027
    db=tmp_db;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3028 3029

  /* open the mysql.user and mysql.db tables */
3030
  bzero((char*) &tables,sizeof(tables));
3031 3032
  tables[0].alias=tables[0].table_name=(char*) "user";
  tables[1].alias=tables[1].table_name=(char*) "db";
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3033
  tables[0].next_local= tables[0].next_global= tables+1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3034 3035
  tables[0].lock_type=tables[1].lock_type=TL_WRITE;
  tables[0].db=tables[1].db=(char*) "mysql";
3036 3037 3038 3039 3040 3041

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

3054
  if (simple_open_n_lock_tables(thd,tables))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3055 3056
  {						// This should never happen
    close_thread_tables(thd);			/* purecov: deadcode */
3057
    DBUG_RETURN(TRUE);				/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3058 3059
  }

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
3060 3061
  if (!revoke_grant)
    create_new_users= test_if_create_new_users(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3062

3063
  /* go through users in user_list */
3064
  rw_wrlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3065 3066 3067 3068 3069 3070 3071 3072 3073
  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
3074 3075
      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
3076 3077 3078
      result= -1;
      continue;
    }
serg@serg.mylan's avatar
serg@serg.mylan committed
3079 3080
    if (replace_user_table(thd, tables[0].table, *Str,
                           (!db ? rights : 0), revoke_grant, create_new_users,
monty@mysql.com's avatar
monty@mysql.com committed
3081 3082
                           test(thd->variables.sql_mode &
                                MODE_NO_AUTO_CREATE_USER)))
3083
      result= -1;
3084
    else if (db)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
3085
    {
3086 3087 3088 3089 3090 3091 3092 3093 3094
      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
3095
	my_error(ER_WRONG_USAGE, MYF(0), "DB GRANT", "GLOBAL PRIVILEGES");
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3096
	result= -1;
3097
      }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
3098
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3099 3100
  }
  VOID(pthread_mutex_unlock(&acl_cache->lock));
3101
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3102 3103 3104
  close_thread_tables(thd);

  if (!result)
3105
    send_ok(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3106 3107 3108
  DBUG_RETURN(result);
}

3109 3110

/* Free grant array if possible */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3111 3112 3113 3114 3115

void  grant_free(void)
{
  DBUG_ENTER("grant_free");
  grant_option = FALSE;
3116
  hash_free(&column_priv_hash);
3117
  hash_free(&proc_priv_hash);
monty@mysql.com's avatar
monty@mysql.com committed
3118
  hash_free(&func_priv_hash);
3119
  free_root(&memex,MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3120 3121 3122 3123 3124 3125
  DBUG_VOID_RETURN;
}


/* Init grant array if possible */

3126
my_bool grant_init(THD *org_thd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3127
{
3128
  THD  *thd;
3129
  TABLE_LIST tables[3];
3130
  MEM_ROOT *memex_ptr;
3131
  my_bool return_val= 1;
3132
  TABLE *t_table, *c_table, *p_table;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
3133
  bool check_no_resolve= specialflag & SPECIAL_NO_RESOLVE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3134 3135 3136
  DBUG_ENTER("grant_init");

  grant_option = FALSE;
3137
  (void) hash_init(&column_priv_hash,system_charset_info,
3138
		   0,0,0, (hash_get_key) get_grant_table,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3139
		   (hash_free_key) free_grant_table,0);
3140 3141 3142
  (void) hash_init(&proc_priv_hash,system_charset_info,
		   0,0,0, (hash_get_key) get_grant_table,
		   0,0);
3143 3144 3145
  (void) hash_init(&func_priv_hash,system_charset_info,
		   0,0,0, (hash_get_key) get_grant_table,
		   0,0);
3146
  init_sql_alloc(&memex, ACL_ALLOC_BLOCK_SIZE, 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3147

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3152 3153
  if (!(thd=new THD))
    DBUG_RETURN(1);				/* purecov: deadcode */
3154
  thd->store_globals();
3155 3156
  thd->db= my_strdup("mysql",MYF(0));
  thd->db_length=5;				// Safety
3157
  bzero((char*) &tables, sizeof(tables));
3158 3159 3160
  tables[0].alias=tables[0].table_name= (char*) "tables_priv";
  tables[1].alias=tables[1].table_name= (char*) "columns_priv";
  tables[2].alias=tables[2].table_name= (char*) "procs_priv";
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3161
  tables[0].next_local= tables[0].next_global= tables+1;
3162 3163 3164
  tables[1].next_local= tables[1].next_global= tables+2;
  tables[0].lock_type=tables[1].lock_type=tables[2].lock_type=TL_READ;
  tables[0].db=tables[1].db=tables[2].db=thd->db;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3165

3166
  if (simple_open_n_lock_tables(thd, tables))
3167
    goto end;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3168 3169

  t_table = tables[0].table; c_table = tables[1].table;
3170
  p_table= tables[2].table;
3171
  t_table->file->ha_index_init(0);
3172 3173
  p_table->file->ha_index_init(0);
  if (!t_table->file->index_first(t_table->record[0]))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3174
  {
3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186
    /* Will be restored by org_thd->store_globals() */
    memex_ptr= &memex;
    my_pthread_setspecific_ptr(THR_MALLOC, &memex_ptr);
    do
    {
      GRANT_TABLE *mem_check;
      if (!(mem_check=new GRANT_TABLE(t_table,c_table)))
      {
	/* This could only happen if we are out memory */
	grant_option= FALSE;
	goto end_unlock;
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3187

3188 3189
      if (check_no_resolve)
      {
3190
	if (hostname_requires_resolving(mem_check->host.hostname))
3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211
	{
          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);
	  continue;
	}
      }

      if (! mem_check->ok())
	delete mem_check;
      else if (my_hash_insert(&column_priv_hash,(byte*) mem_check))
      {
	delete mem_check;
	grant_option= FALSE;
	goto end_unlock;
      }
    }
    while (!t_table->file->index_next(t_table->record[0]));
  }
  if (!p_table->file->index_first(p_table->record[0]))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3212
  {
3213 3214 3215 3216
    /* Will be restored by org_thd->store_globals() */
    memex_ptr= &memex;
    my_pthread_setspecific_ptr(THR_MALLOC, &memex_ptr);
    do
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3217
    {
3218
      GRANT_NAME *mem_check;
3219 3220
      longlong proc_type;
      HASH *hash;
3221 3222 3223 3224 3225 3226
      if (!(mem_check=new GRANT_NAME(p_table)))
      {
	/* This could only happen if we are out memory */
	grant_option= FALSE;
	goto end_unlock;
      }
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
3227

3228
      if (check_no_resolve)
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
3229
      {
jimw@mysql.com's avatar
jimw@mysql.com committed
3230
	if (hostname_requires_resolving(mem_check->host.hostname))
3231 3232 3233 3234
	{
          sql_print_warning("'procs_priv' entry '%s %s@%s' "
                            "ignored in --skip-name-resolve mode.",
                            mem_check->tname, mem_check->user,
acurtis@xiphis.org's avatar
Merge  
acurtis@xiphis.org committed
3235
                            mem_check->host);
3236 3237
	  continue;
	}
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
3238
      }
3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254
      if (p_table->field[4]->val_int() == TYPE_ENUM_PROCEDURE)
      {
        hash= &proc_priv_hash;
      }
      else
      if (p_table->field[4]->val_int() == TYPE_ENUM_FUNCTION)
      {
        hash= &func_priv_hash;
      }
      else
      {
        sql_print_warning("'procs_priv' entry '%s' "
                          "ignored, bad routine type",
                          mem_check->tname);
	continue;
      }
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
3255

3256 3257 3258
      mem_check->privs= fix_rights_for_procedure(mem_check->privs);
      if (! mem_check->ok())
	delete mem_check;
3259
      else if (my_hash_insert(hash, (byte*) mem_check))
3260 3261 3262 3263 3264
      {
	delete mem_check;
	grant_option= FALSE;
	goto end_unlock;
      }
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
3265
    }
3266
    while (!p_table->file->index_next(p_table->record[0]));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3267
  }
3268
  grant_option= TRUE;
3269 3270 3271
  return_val=0;					// Return ok

end_unlock:
3272
  t_table->file->ha_index_end();
3273
  p_table->file->ha_index_end();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3274
  thd->version--;				// Force close to free memory
3275 3276

end:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3277 3278
  close_thread_tables(thd);
  delete thd;
3279 3280
  if (org_thd)
    org_thd->store_globals();
3281 3282 3283 3284 3285
  else
  {
    /* Remember that we don't have a THD */
    my_pthread_setspecific_ptr(THR_THD,  0);
  }
3286
  DBUG_RETURN(return_val);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3287 3288 3289
}


3290
/*
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3291
 Reload grant array (table and column privileges) if possible
3292 3293 3294

  SYNOPSIS
    grant_reload()
3295
    thd			Thread handler (can be NULL)
3296 3297 3298 3299

  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
3300

3301
void grant_reload(THD *thd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3302
{
3303
  HASH old_column_priv_hash, old_proc_priv_hash, old_func_priv_hash;
3304
  bool old_grant_option;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3305 3306 3307
  MEM_ROOT old_mem;
  DBUG_ENTER("grant_reload");

3308
  rw_wrlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3309
  grant_version++;
3310
  old_column_priv_hash= column_priv_hash;
3311
  old_proc_priv_hash= proc_priv_hash;
3312
  old_func_priv_hash= func_priv_hash;
3313
  old_grant_option= grant_option;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3314
  old_mem= memex;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3315

3316
  if (grant_init(thd))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3317
  {						// Error. Revert to old hash
3318
    DBUG_PRINT("error",("Reverting to old privileges"));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3319
    grant_free();				/* purecov: deadcode */
3320
    column_priv_hash= old_column_priv_hash;	/* purecov: deadcode */
3321
    proc_priv_hash= old_proc_priv_hash;
3322
    func_priv_hash= old_func_priv_hash;
3323
    grant_option= old_grant_option;		/* purecov: deadcode */
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3324
    memex= old_mem;				/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3325 3326 3327
  }
  else
  {
3328
    hash_free(&old_column_priv_hash);
3329
    hash_free(&old_proc_priv_hash);
3330
    hash_free(&old_func_priv_hash);
3331
    free_root(&old_mem,MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3332
  }
3333
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3334 3335 3336 3337 3338
  DBUG_VOID_RETURN;
}


/****************************************************************************
3339
  Check table level grants
3340

3341
  SYNOPSIS
3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354
   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
3355
     1  Error: User did not have the requested privileges
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3356 3357
****************************************************************************/

3358
bool check_grant(THD *thd, ulong want_access, TABLE_LIST *tables,
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3359
		 uint show_table, uint number, bool no_errors)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3360 3361 3362
{
  TABLE_LIST *table;
  char *user = thd->priv_user;
3363 3364
  DBUG_ENTER("check_grant");
  DBUG_ASSERT(number > 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3365

3366
  want_access&= ~thd->master_access;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3367
  if (!want_access)
3368
    DBUG_RETURN(0);                             // ok
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3369

3370
  rw_rdlock(&LOCK_grant);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3371
  for (table= tables; table && number--; table= table->next_global)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3372
  {
3373
    GRANT_TABLE *grant_table;
3374
    if (!(~table->grant.privilege & want_access) || 
3375
        table->derived || table->schema_table || table->belong_to_view)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3376
    {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3377 3378 3379 3380 3381
      /*
        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
3382 3383
      continue;					// Already checked
    }
3384
    if (!(grant_table= table_hash_search(thd->host,thd->ip,
3385
                                         table->db,user, table->table_name,0)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3386 3387 3388 3389
    {
      want_access &= ~table->grant.privilege;
      goto err;					// No grants
    }
monty@tramp.mysql.fi's avatar
monty@tramp.mysql.fi committed
3390 3391
    if (show_table)
      continue;					// We have some priv on this
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407

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

3411
err:
3412
  rw_unlock(&LOCK_grant);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
3413
  if (!no_errors)				// Not a silent skip of table
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3414
  {
3415 3416
    char command[128];
    get_privilege_desc(command, sizeof(command), want_access);
3417 3418 3419 3420
    my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0),
             command,
             thd->priv_user,
             thd->host_or_ip,
3421
             table ? table->table_name : "unknown");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3422
  }
3423
  DBUG_RETURN(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3424 3425 3426
}


bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3427
bool check_grant_column(THD *thd, GRANT_INFO *grant,
3428
			const char *db_name, const char *table_name,
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3429
			const char *name, uint length, uint show_tables)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3430 3431 3432
{
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3433
  ulong want_access= grant->want_privilege & ~grant->privilege;
monty@mysql.com's avatar
monty@mysql.com committed
3434 3435 3436
  DBUG_ENTER("check_grant_column");
  DBUG_PRINT("enter", ("table: %s  want_access: %u", table_name, want_access));

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3437
  if (!want_access)
monty@mysql.com's avatar
monty@mysql.com committed
3438
    DBUG_RETURN(0);				// Already checked
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3439

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

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

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3444
  if (grant->version != grant_version)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3445
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3446 3447
    grant->grant_table=
      table_hash_search(thd->host, thd->ip, db_name,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3448
			thd->priv_user,
monty@mysql.com's avatar
monty@mysql.com committed
3449
			table_name, 0);         /* purecov: inspected */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3450
    grant->version= grant_version;		/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3451
  }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3452
  if (!(grant_table= grant->grant_table))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3453 3454 3455 3456 3457
    goto err;					/* purecov: deadcode */

  grant_column=column_hash_search(grant_table, name, length);
  if (grant_column && !(~grant_column->rights & want_access))
  {
3458
    rw_unlock(&LOCK_grant);
monty@mysql.com's avatar
monty@mysql.com committed
3459
    DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3460 3461
  }
#ifdef NOT_USED
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3462
  if (show_tables && (grant_column || grant->privilege & COL_ACLS))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3463
  {
3464
    rw_unlock(&LOCK_grant);			/* purecov: deadcode */
monty@mysql.com's avatar
monty@mysql.com committed
3465
    DBUG_RETURN(0);				/* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3466 3467 3468
  }
#endif

3469
err:
3470
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3471 3472
  if (!show_tables)
  {
3473 3474
    char command[128];
    get_privilege_desc(command, sizeof(command), want_access);
3475 3476 3477 3478 3479 3480
    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
3481
  }
monty@mysql.com's avatar
monty@mysql.com committed
3482
  DBUG_RETURN(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3483 3484 3485
}


bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3486
bool check_grant_all_columns(THD *thd, ulong want_access, GRANT_INFO *grant,
3487
                             const char* db_name, const char *table_name,
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3488
                             Field_iterator *fields)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3489 3490 3491 3492
{
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3493
  want_access &= ~grant->privilege;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3494
  if (!want_access)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3495
    return 0;				// Already checked
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3496 3497
  if (!grant_option)
    goto err2;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3498

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

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

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3503
  if (grant->version != grant_version)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3504
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3505 3506
    grant->grant_table=
      table_hash_search(thd->host, thd->ip, db_name,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3507
			thd->priv_user,
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3508 3509
			table_name, 0);	/* purecov: inspected */
    grant->version= grant_version;		/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3510
  }
3511
  /* The following should always be true */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3512
  if (!(grant_table= grant->grant_table))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3513 3514
    goto err;					/* purecov: inspected */

3515
  for (; !fields->end_of_fields(); fields->next())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3516
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3517 3518 3519
    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
3520 3521 3522
    if (!grant_column || (~grant_column->rights & want_access))
      goto err;
  }
3523
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3524 3525
  return 0;

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3526
err:
3527
  rw_unlock(&LOCK_grant);
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3528
err2:
3529 3530
  char command[128];
  get_privilege_desc(command, sizeof(command), want_access);
3531 3532 3533 3534 3535 3536
  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
3537 3538 3539 3540
  return 1;
}


3541
/*
3542
  Check if a user has the right to access a database
3543
  Access is accepted if he has a grant for any table/routine in the database
3544
  Return 1 if access is denied
3545
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3546 3547 3548 3549 3550 3551 3552 3553

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

3556
  for (uint idx=0 ; idx < column_priv_hash.records ; idx++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3557
  {
3558 3559
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  idx);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3560 3561
    if (len < grant_table->key_length &&
	!memcmp(grant_table->hash_key,helping,len) &&
3562
        compare_hostname(&grant_table->host, thd->host, thd->ip))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3563 3564 3565 3566 3567
    {
      error=0;					// Found match
      break;
    }
  }
3568
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3569 3570 3571
  return error;
}

3572 3573

/****************************************************************************
3574
  Check routine level grants
3575 3576

  SYNPOSIS
3577
   bool check_grant_routine()
3578 3579
   thd		Thread handler
   want_access  Bits of privileges user needs to have
3580 3581
   procs	List of routines to check. The user should have 'want_access'
   is_proc	True if the list is all procedures, else functions
3582 3583 3584 3585 3586 3587 3588 3589
   no_errors	If 0 then we write an error. The error is sent directly to
		the client

   RETURN
     0  ok
     1  Error: User did not have the requested privielges
****************************************************************************/

3590 3591
bool check_grant_routine(THD *thd, ulong want_access, 
			 TABLE_LIST *procs, bool is_proc, bool no_errors)
3592 3593 3594 3595
{
  TABLE_LIST *table;
  char *user= thd->priv_user;
  char *host= thd->priv_host;
3596
  DBUG_ENTER("check_grant_routine");
3597 3598 3599 3600 3601 3602 3603 3604 3605

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

  rw_rdlock(&LOCK_grant);
  for (table= procs; table; table= table->next_global)
  {
    GRANT_NAME *grant_proc;
3606 3607
    if ((grant_proc= routine_hash_search(host,thd->ip, table->db, user,
					 table->table_name, is_proc, 0)))
3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624
      table->grant.privilege|= grant_proc->privs;

    if (want_access & ~table->grant.privilege)
    {
      want_access &= ~table->grant.privilege;
      goto err;
    }
  }
  rw_unlock(&LOCK_grant);
  DBUG_RETURN(0);
err:
  rw_unlock(&LOCK_grant);
  if (!no_errors)
  {
    char buff[1024];
    const char *command="";
    if (table)
3625
      strxmov(buff, table->db, ".", table->table_name, NullS);
3626 3627 3628
    if (want_access & EXECUTE_ACL)
      command= "execute";
    else if (want_access & ALTER_PROC_ACL)
3629
      command= "alter routine";
3630 3631 3632 3633 3634 3635 3636 3637 3638
    else if (want_access & GRANT_ACL)
      command= "grant";
    my_error(ER_PROCACCESS_DENIED_ERROR, MYF(0),
             command, user, host, table ? buff : "unknown");
  }
  DBUG_RETURN(1);
}


3639 3640
/*
  Check if routine has any of the 
3641
  routine level grants
3642 3643 3644 3645 3646 3647 3648 3649 3650
  
  SYNPOSIS
   bool    check_routine_level_acl()
   thd	        Thread handler
   db           Database name
   name         Routine name

  RETURN
   0            Ok 
3651
   1            error
3652 3653
*/

acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
3654 3655
bool check_routine_level_acl(THD *thd, const char *db, const char *name, 
                             bool is_proc)
3656 3657 3658 3659 3660 3661
{
  bool no_routine_acl= 1;
  if (grant_option)
  {
    GRANT_NAME *grant_proc;
    rw_rdlock(&LOCK_grant);
3662 3663
    if ((grant_proc= routine_hash_search(thd->priv_host, thd->ip, db,
                                         thd->priv_user, name, is_proc, 0)))
3664 3665 3666 3667 3668 3669 3670
      no_routine_acl= !(grant_proc->privs & SHOW_PROC_ACLS);
    rw_unlock(&LOCK_grant);
  }
  return no_routine_acl;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
3671
/*****************************************************************************
3672
  Functions to retrieve the grant for a table/column  (for SHOW functions)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3673 3674
*****************************************************************************/

3675
ulong get_table_grant(THD *thd, TABLE_LIST *table)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3676
{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3677
  ulong privilege;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3678 3679 3680 3681
  char *user = thd->priv_user;
  const char *db = table->db ? table->db : thd->db;
  GRANT_TABLE *grant_table;

3682
  rw_rdlock(&LOCK_grant);
3683 3684 3685
#ifdef EMBEDDED_LIBRARY
  grant_table= NULL;
#else
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3686
  grant_table= table_hash_search(thd->host, thd->ip, db, user,
3687
				 table->table_name, 0);
3688
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3689 3690 3691 3692
  table->grant.grant_table=grant_table; // Remember for column test
  table->grant.version=grant_version;
  if (grant_table)
    table->grant.privilege|= grant_table->privs;
3693
  privilege= table->grant.privilege;
3694
  rw_unlock(&LOCK_grant);
3695
  return privilege;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3696 3697 3698
}


bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3699 3700 3701
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
3702 3703 3704
{
  GRANT_TABLE *grant_table;
  GRANT_COLUMN *grant_column;
3705
  ulong priv;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3706

3707
  rw_rdlock(&LOCK_grant);
3708
  /* reload table if someone has modified any grants */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3709
  if (grant->version != grant_version)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3710
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3711 3712
    grant->grant_table=
      table_hash_search(thd->host, thd->ip, db_name,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3713
			thd->priv_user,
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3714 3715
			table_name, 0);	        /* purecov: inspected */
    grant->version= grant_version;              /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3716 3717
  }

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3718 3719
  if (!(grant_table= grant->grant_table))
    priv= grant->privilege;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3720 3721
  else
  {
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3722 3723
    grant_column= column_hash_search(grant_table, field_name,
                                     (uint) strlen(field_name));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3724
    if (!grant_column)
3725
      priv= (grant->privilege | grant_table->privs);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3726
    else
3727
      priv= (grant->privilege | grant_table->privs | grant_column->rights);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3728
  }
3729
  rw_unlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3730 3731 3732
  return priv;
}

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

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

3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747
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
3748 3749

static const char *command_array[]=
3750
{
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
3751 3752 3753 3754
  "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",
3755
  "CREATE VIEW", "SHOW VIEW", "CREATE ROUTINE", "ALTER ROUTINE",
3756
  "CREATE USER"
3757
};
3758

3759 3760
static uint command_lengths[]=
{
3761 3762
  6, 6, 6, 6, 6, 4, 6, 8, 7, 4, 5, 10, 5, 5, 14, 5, 23, 11, 7, 17, 18, 11, 9,
  14, 13, 11
3763 3764
};

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

3766 3767 3768 3769 3770
static int show_routine_grants(THD *thd, LEX_USER *lex_user, HASH *hash,
                               const char *type, int typelen,
                               char *buff, int buffsize);


3771 3772 3773 3774 3775 3776 3777
/*
  SHOW GRANTS;  Send grants for a user to the client

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

3778
bool mysql_show_grants(THD *thd,LEX_USER *lex_user)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3779
{
3780 3781
  ulong want_access;
  uint counter,index;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3782
  int  error = 0;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3783 3784
  ACL_USER *acl_user;
  ACL_DB *acl_db;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3785
  char buff[1024];
3786
  Protocol *protocol= thd->protocol;
tonu@x153.internalnet's avatar
tonu@x153.internalnet committed
3787
  DBUG_ENTER("mysql_show_grants");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3788 3789 3790 3791

  LINT_INIT(acl_user);
  if (!initialized)
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3792
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
3793
    DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3794
  }
monty@mysql.com's avatar
monty@mysql.com committed
3795 3796 3797 3798 3799 3800

  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
3801 3802 3803
  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
3804 3805
    my_message(ER_GRANT_WRONG_HOST_OR_USER, ER(ER_GRANT_WRONG_HOST_OR_USER),
               MYF(0));
3806
    DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3807 3808 3809 3810 3811 3812 3813
  }

  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
3814
      user= "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3815
    if (!(host=acl_user->host.hostname))
monty@mysql.com's avatar
monty@mysql.com committed
3816
      host= "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3817
    if (!strcmp(lex_user->user.str,user) &&
3818
	!my_strcasecmp(system_charset_info, lex_user->host.str, host))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3819 3820
      break;
  }
peter@mysql.com's avatar
peter@mysql.com committed
3821
  if (counter == acl_users.elements)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3822
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
3823 3824
    my_error(ER_NONEXISTING_GRANT, MYF(0),
             lex_user->user.str, lex_user->host.str);
3825
    DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3826 3827
  }

3828
  Item_string *field=new Item_string("",0,&my_charset_latin1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3829 3830 3831 3832 3833 3834
  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);
3835 3836
  if (protocol->send_fields(&field_list,
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
3837
    DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3838

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3839
  rw_wrlock(&LOCK_grant);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3840 3841 3842 3843
  VOID(pthread_mutex_lock(&acl_cache->lock));

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

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3848
    want_access= acl_user->access;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3849 3850 3851 3852
    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
3853
    else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3854 3855
    {
      bool found=0;
3856
      ulong j,test_access= want_access & ~GRANT_ACL;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3857 3858
      for (counter=0, j = SELECT_ACL;j <= GLOBAL_ACLS;counter++,j <<= 1)
      {
peter@mysql.com's avatar
peter@mysql.com committed
3859
	if (test_access & j)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3860 3861 3862 3863 3864 3865 3866 3867 3868
	{
	  if (found)
	    global.append(", ",2);
	  found=1;
	  global.append(command_array[counter],command_lengths[counter]);
	}
      }
    }
    global.append (" ON *.* TO '",12);
3869 3870
    global.append(lex_user->user.str, lex_user->user.length,
		  system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3871
    global.append ("'@'",3);
3872 3873
    global.append(lex_user->host.str,lex_user->host.length,
		  system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3874
    global.append ('\'');
3875
    if (acl_user->salt_len)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3876
    {
3877 3878 3879 3880 3881
      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
3882
      global.append(" IDENTIFIED BY PASSWORD '",25);
3883
      global.append(passwd_buff);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3884 3885
      global.append('\'');
    }
3886 3887
    /* "show grants" SSL related stuff */
    if (acl_user->ssl_type == SSL_TYPE_ANY)
3888
      global.append(" REQUIRE SSL",12);
3889
    else if (acl_user->ssl_type == SSL_TYPE_X509)
3890
      global.append(" REQUIRE X509",13);
3891
    else if (acl_user->ssl_type == SSL_TYPE_SPECIFIED)
3892
    {
3893
      int ssl_options = 0;
3894
      global.append(" REQUIRE ",9);
3895 3896
      if (acl_user->x509_issuer)
      {
3897 3898 3899
	ssl_options++;
	global.append("ISSUER \'",8);
	global.append(acl_user->x509_issuer,strlen(acl_user->x509_issuer));
3900
	global.append('\'');
3901
      }
3902 3903
      if (acl_user->x509_subject)
      {
3904 3905 3906
	if (ssl_options++)
	  global.append(' ');
	global.append("SUBJECT \'",9);
3907 3908
	global.append(acl_user->x509_subject,strlen(acl_user->x509_subject),
                      system_charset_info);
3909
	global.append('\'');
tonu@x153.internalnet's avatar
tonu@x153.internalnet committed
3910
      }
3911 3912
      if (acl_user->ssl_cipher)
      {
3913 3914 3915
	if (ssl_options++)
	  global.append(' ');
	global.append("CIPHER '",8);
3916 3917
	global.append(acl_user->ssl_cipher,strlen(acl_user->ssl_cipher),
                      system_charset_info);
3918
	global.append('\'');
3919 3920
      }
    }
3921
    if ((want_access & GRANT_ACL) ||
3922 3923 3924 3925
	(acl_user->user_resource.questions ||
         acl_user->user_resource.updates ||
         acl_user->user_resource.conn_per_hour ||
         acl_user->user_resource.user_conn))
3926
    {
peter@mysql.com's avatar
peter@mysql.com committed
3927
      global.append(" WITH",5);
3928
      if (want_access & GRANT_ACL)
peter@mysql.com's avatar
peter@mysql.com committed
3929
	global.append(" GRANT OPTION",13);
3930 3931 3932 3933
      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");
3934
      add_user_option(&global, acl_user->user_resource.conn_per_hour,
3935
		      "MAX_CONNECTIONS_PER_HOUR");
3936 3937
      add_user_option(&global, acl_user->user_resource.user_conn,
		      "MAX_USER_CONNECTIONS");
3938
    }
3939
    protocol->prepare_for_resend();
3940
    protocol->store(global.ptr(),global.length(),global.charset());
3941
    if (protocol->write())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3942
    {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3943
      error= -1;
3944
      goto end;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3945 3946 3947 3948 3949 3950
    }
  }

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

    acl_db=dynamic_element(&acl_dbs,counter,ACL_DB*);
    if (!(user=acl_db->user))
monty@mysql.com's avatar
monty@mysql.com committed
3955
      user= "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3956
    if (!(host=acl_db->host.hostname))
monty@mysql.com's avatar
monty@mysql.com committed
3957
      host= "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3958 3959

    if (!strcmp(lex_user->user.str,user) &&
3960
	!my_strcasecmp(system_charset_info, lex_user->host.str, host))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3961 3962
    {
      want_access=acl_db->access;
peter@mysql.com's avatar
peter@mysql.com committed
3963
      if (want_access)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3964
      {
3965
	String db(buff,sizeof(buff),system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3966 3967 3968 3969 3970
	db.length(0);
	db.append("GRANT ",6);

	if (test_all_bits(want_access,(DB_ACLS & ~GRANT_ACL)))
	  db.append("ALL PRIVILEGES",14);
3971
	else if (!(want_access & ~GRANT_ACL))
3972
	  db.append("USAGE",5);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3973 3974 3975
	else
	{
	  int found=0, cnt;
3976
	  ulong j,test_access= want_access & ~GRANT_ACL;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987
	  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]);
	    }
	  }
	}
3988 3989 3990
	db.append (" ON ",4);
	append_identifier(thd, &db, acl_db->db, strlen(acl_db->db));
	db.append (".* TO '",7);
3991 3992
	db.append(lex_user->user.str, lex_user->user.length,
		  system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3993
	db.append ("'@'",3);
3994 3995
	db.append(lex_user->host.str, lex_user->host.length,
                  system_charset_info);
peter@mysql.com's avatar
peter@mysql.com committed
3996
	db.append ('\'');
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3997
	if (want_access & GRANT_ACL)
3998
	  db.append(" WITH GRANT OPTION",18);
3999
	protocol->prepare_for_resend();
4000
	protocol->store(db.ptr(),db.length(),db.charset());
4001
	if (protocol->write())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4002
	{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4003
	  error= -1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4004 4005 4006 4007 4008 4009
	  goto end;
	}
      }
    }
  }

4010
  /* Add table & column access */
4011
  for (index=0 ; index < column_priv_hash.records ; index++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4012
  {
monty@mysql.com's avatar
monty@mysql.com committed
4013
    const char *user;
4014 4015
    GRANT_TABLE *grant_table= (GRANT_TABLE*) hash_element(&column_priv_hash,
							  index);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4016 4017

    if (!(user=grant_table->user))
4018
      user= "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4019 4020

    if (!strcmp(lex_user->user.str,user) &&
4021
	!my_strcasecmp(system_charset_info, lex_user->host.str,
4022
                       grant_table->host.hostname))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4023
    {
4024 4025
      ulong table_access= grant_table->privs;
      if ((table_access | grant_table->cols) != 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4026
      {
4027
	String global(buff, sizeof(buff), system_charset_info);
4028 4029
	ulong test_access= (table_access | grant_table->cols) & ~GRANT_ACL;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
4030 4031 4032
	global.length(0);
	global.append("GRANT ",6);

4033
	if (test_all_bits(table_access, (TABLE_ACLS & ~GRANT_ACL)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4034
	  global.append("ALL PRIVILEGES",14);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4035
	else if (!test_access)
4036
 	  global.append("USAGE",5);
peter@mysql.com's avatar
peter@mysql.com committed
4037
	else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4038
	{
4039
          /* Add specific column access */
4040
	  int found= 0;
4041
	  ulong j;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4042

4043
	  for (counter= 0, j= SELECT_ACL; j <= TABLE_ACLS; counter++, j<<= 1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4044
	  {
peter@mysql.com's avatar
peter@mysql.com committed
4045
	    if (test_access & j)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4046 4047 4048
	    {
	      if (found)
		global.append(", ",2);
4049
	      found= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4050 4051
	      global.append(command_array[counter],command_lengths[counter]);

peter@mysql.com's avatar
peter@mysql.com committed
4052
	      if (grant_table->cols)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4053
	      {
4054
		uint found_col= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4055 4056 4057 4058 4059 4060
		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
4061
		  if (grant_column->rights & j)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4062
		  {
peter@mysql.com's avatar
peter@mysql.com committed
4063
		    if (!found_col)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4064
		    {
4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075
		      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
4076 4077 4078 4079 4080
		      global.append(" (",2);
		    }
		    else
		      global.append(", ",2);
		    global.append(grant_column->column,
4081 4082
				  grant_column->key_length,
				  system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4083 4084 4085 4086 4087 4088 4089 4090
		  }
		}
		if (found_col)
		  global.append(')');
	      }
	    }
	  }
	}
4091 4092 4093 4094 4095 4096 4097
	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);
4098 4099
	global.append(lex_user->user.str, lex_user->user.length,
		      system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4100
	global.append("'@'",3);
4101 4102
	global.append(lex_user->host.str,lex_user->host.length,
		      system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4103
	global.append('\'');
4104
	if (table_access & GRANT_ACL)
peter@mysql.com's avatar
peter@mysql.com committed
4105
	  global.append(" WITH GRANT OPTION",18);
4106
	protocol->prepare_for_resend();
4107
	protocol->store(global.ptr(),global.length(),global.charset());
4108
	if (protocol->write())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4109
	{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4110
	  error= -1;
4111
	  break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
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 4140 4141 4142 4143 4144 4145 4146 4147
  if (show_routine_grants(thd, lex_user, &proc_priv_hash, 
                          "PROCEDURE", 9, buff, sizeof(buff)))
  {
    error= -1;
    goto end;
  }

  if (show_routine_grants(thd, lex_user, &func_priv_hash,
                          "FUNCTION", 8, buff, sizeof(buff)))
  {
    error= -1;
    goto end;
  }

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

  send_eof(thd);
  DBUG_RETURN(error);
}

static int show_routine_grants(THD* thd, LEX_USER *lex_user, HASH *hash,
                               const char *type, int typelen,
                               char *buff, int buffsize)
{
  uint counter, index;
  int error= 0;
  Protocol *protocol= thd->protocol;
  /* Add routine access */
  for (index=0 ; index < hash->records ; index++)
4148 4149
  {
    const char *user;
4150
    GRANT_NAME *grant_proc= (GRANT_NAME*) hash_element(hash, index);
4151 4152 4153 4154 4155 4156

    if (!(user=grant_proc->user))
      user= "";

    if (!strcmp(lex_user->user.str,user) &&
	!my_strcasecmp(system_charset_info, lex_user->host.str,
4157
                       grant_proc->host.hostname))
4158 4159 4160 4161
    {
      ulong proc_access= grant_proc->privs;
      if (proc_access != 0)
      {
4162
	String global(buff, buffsize, system_charset_info);
4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187
	ulong test_access= proc_access & ~GRANT_ACL;

	global.length(0);
	global.append("GRANT ",6);

	if (!test_access)
 	  global.append("USAGE",5);
	else
	{
          /* Add specific procedure access */
	  int found= 0;
	  ulong j;

	  for (counter= 0, j= SELECT_ACL; j <= PROC_ACLS; counter++, j<<= 1)
	  {
	    if (test_access & j)
	    {
	      if (found)
		global.append(", ",2);
	      found= 1;
	      global.append(command_array[counter],command_lengths[counter]);
	    }
	  }
	}
	global.append(" ON ",4);
4188 4189
        global.append(type,typelen);
        global.append(' ');
4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213
	append_identifier(thd, &global, grant_proc->db,
			  strlen(grant_proc->db));
	global.append('.');
	append_identifier(thd, &global, grant_proc->tname,
			  strlen(grant_proc->tname));
	global.append(" TO '",5);
	global.append(lex_user->user.str, lex_user->user.length,
		      system_charset_info);
	global.append("'@'",3);
	global.append(lex_user->host.str,lex_user->host.length,
		      system_charset_info);
	global.append('\'');
	if (proc_access & GRANT_ACL)
	  global.append(" WITH GRANT OPTION",18);
	protocol->prepare_for_resend();
	protocol->store(global.ptr(),global.length(),global.charset());
	if (protocol->write())
	{
	  error= -1;
	  break;
	}
      }
    }
  }
4214
  return error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4215 4216
}

4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244
/*
  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;
}


4245
void get_mqh(const char *user, const char *host, USER_CONN *uc)
4246 4247
{
  ACL_USER *acl_user;
4248 4249 4250 4251
  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));
4252 4253
}

4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274
/*
  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.
*/

4275
#define GRANT_TABLES 5
4276 4277 4278 4279 4280 4281
int open_grant_tables(THD *thd, TABLE_LIST *tables)
{
  DBUG_ENTER("open_grant_tables");

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

4286
  bzero((char*) tables, GRANT_TABLES*sizeof(*tables));
4287 4288 4289 4290 4291
  tables->alias= tables->table_name= (char*) "user";
  (tables+1)->alias= (tables+1)->table_name= (char*) "db";
  (tables+2)->alias= (tables+2)->table_name= (char*) "tables_priv";
  (tables+3)->alias= (tables+3)->table_name= (char*) "columns_priv";
  (tables+4)->alias= (tables+4)->table_name= (char*) "procs_priv";
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
4292 4293 4294
  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;
4295
  (tables+3)->next_local= (tables+3)->next_global= tables+4;
4296
  tables->lock_type= (tables+1)->lock_type=
4297 4298 4299 4300
    (tables+2)->lock_type= (tables+3)->lock_type= 
    (tables+4)->lock_type= TL_WRITE;
  tables->db= (tables+1)->db= (tables+2)->db= 
    (tables+3)->db= (tables+4)->db= (char*) "mysql";
4301 4302 4303 4304 4305 4306

#ifdef HAVE_REPLICATION
  /*
    GRANT and REVOKE are applied the slave in/exclusion rules as they are
    some kind of updates to the mysql.% tables.
  */
4307 4308
  if (thd->slave_thread && table_rules_on)
  {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4309 4310 4311
    /*
      The tables must be marked "updating" so that tables_ok() takes them into
      account in tests.
4312
    */
4313 4314
    tables[0].updating=tables[1].updating=tables[2].updating=
      tables[3].updating=tables[4].updating=1;
4315
    if (!tables_ok(thd, tables))
4316
      DBUG_RETURN(1);
4317 4318
    tables[0].updating=tables[1].updating=tables[2].updating=
      tables[3].updating=tables[4].updating=0;;
4319
  }
4320 4321
#endif

4322
  if (simple_open_n_lock_tables(thd, tables))
4323 4324 4325 4326 4327 4328 4329 4330 4331
  {						// 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
4332
			 uint *acl_acl_userdx)
4333 4334 4335 4336 4337 4338 4339 4340 4341
{
  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
4342
      user= "";
4343
    if (!(host=acl_user->host.hostname))
monty@mysql.com's avatar
monty@mysql.com committed
4344
      host= "%";
4345 4346 4347 4348 4349 4350 4351
    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
4352
  *acl_acl_userdx= counter;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4353
  return acl_user;
4354 4355
}

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

4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378
/*
  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)
4379
{
4380 4381
  int error;
  DBUG_ENTER("modify_grant_table");
4382

4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399
  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));
  }
4400

4401 4402
  DBUG_RETURN(error);
}
4403 4404


4405 4406 4407 4408 4409 4410
/*
  Handle a privilege table.

  SYNOPSIS
    handle_grant_table()
    tables                      The array with the four open tables.
4411
    table_no                    The number of the table to handle (0..4).
4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428
    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
4429
    4 procs_priv
4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448

  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;
4449
  byte user_key[MAX_KEY_LENGTH];
4450
  uint key_prefix_length;
4451 4452
  DBUG_ENTER("handle_grant_table");

4453
  if (! table_no) // mysql.user table
4454
  {
4455 4456 4457 4458 4459 4460 4461 4462 4463 4464
    /*
      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'",
4465
                       table->s->table_name, user_str, host_str));
4466 4467
    host_field->store(host_str, user_from->host.length, system_charset_info);
    user_field->store(user_str, user_from->user.length, system_charset_info);
4468 4469 4470 4471 4472

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

4473
    if ((error= table->file->index_read_idx(table->record[0], 0,
4474
                                            user_key, key_prefix_length,
4475
                                            HA_READ_KEY_EXACT)))
4476
    {
4477 4478 4479 4480 4481
      if (error != HA_ERR_KEY_NOT_FOUND)
      {
        table->file->print_error(error, MYF(0));
        result= -1;
      }
4482
    }
4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499
    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)))
4500
    {
4501
      table->file->print_error(error, MYF(0));
4502
      result= -1;
4503 4504 4505 4506 4507
    }
    else
    {
#ifdef EXTRA_DEBUG
      DBUG_PRINT("info",("scan table: '%s'  search: '%s'@'%s'",
4508
                         table->s->table_name, user_str, host_str));
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 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556
#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()
4557
    struct_no                   The number of the structure to handle (0..3).
4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572
    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
4573
    3 procs_priv_hash
4574 4575 4576 4577

  RETURN
    > 0         At least one element matched.
    0           OK, but no element matched.
4578
    -1		Wrong arguments to function
4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590
*/

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;
4591
  GRANT_NAME *grant_name;
4592 4593 4594
  DBUG_ENTER("handle_grant_struct");
  LINT_INIT(acl_user);
  LINT_INIT(acl_db);
4595
  LINT_INIT(grant_name);
4596 4597 4598 4599
  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. */
4600
  switch (struct_no) {
4601 4602 4603 4604 4605 4606
  case 0:
    elements= acl_users.elements;
    break;
  case 1:
    elements= acl_dbs.elements;
    break;
4607
  case 2:
4608
    elements= column_priv_hash.records;
4609 4610 4611 4612 4613 4614
    break;
  case 3:
    elements= proc_priv_hash.records;
    break;
  default:
    return -1;
4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627
  }

#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.
    */
4628
    switch (struct_no) {
4629 4630 4631 4632 4633 4634 4635 4636 4637 4638
    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;
4639 4640
      if (!(host= acl_db->host.hostname))
        host= "%";
4641 4642
      break;

4643 4644 4645
    case 2:
      grant_name= (GRANT_NAME*) hash_element(&column_priv_hash, idx);
      user= grant_name->user;
4646 4647
      if (!(host= grant_name->host.hostname))
        host= "%";
4648 4649 4650 4651 4652
      break;

    case 3:
      grant_name= (GRANT_NAME*) hash_element(&proc_priv_hash, idx);
      user= grant_name->user;
4653 4654
      if (!(host= grant_name->host.hostname))
        host= "%";
4655
      break;
4656 4657
    }
    if (! user)
4658
      user= "";
4659
    if (! host)
4660
      host= "";
4661 4662 4663 4664 4665 4666
#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))
4667
      continue;
4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681

    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;

4682 4683 4684 4685 4686 4687 4688
      case 2:
        hash_delete(&column_priv_hash, (byte*) grant_name);
	break;

      case 3:
        hash_delete(&proc_priv_hash, (byte*) grant_name);
	break;
4689 4690 4691
      }
      elements--;
      idx--;
4692
    }
4693 4694
    else if ( user_to )
    {
4695
      switch ( struct_no ) {
4696 4697 4698 4699
      case 0:
        acl_user->user= strdup_root(&mem, user_to->user.str);
        acl_user->host.hostname= strdup_root(&mem, user_to->host.str);
        break;
4700

4701 4702 4703 4704 4705
      case 1:
        acl_db->user= strdup_root(&mem, user_to->user.str);
        acl_db->host.hostname= strdup_root(&mem, user_to->host.str);
        break;

4706 4707 4708
      case 2:
      case 3:
        grant_name->user= strdup_root(&mem, user_to->user.str);
4709 4710
        update_hostname(&grant_name->host,
                        strdup_root(&mem, user_to->host.str));
4711
	break;
4712 4713 4714
      }
    }
    else
4715
    {
4716 4717 4718 4719 4720 4721 4722
      /* 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
4723

4724 4725 4726 4727 4728 4729 4730 4731 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 4763 4764 4765 4766 4767
  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. */
4768 4769
    if ((handle_grant_struct(0, drop, user_from, user_to) && ! result) ||
        found)
4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796
    {
      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;
    }
  }

4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815
  /* Handle procedures table. */
  if ((found= handle_grant_table(tables, 4, drop, user_from, user_to)) < 0)
  {
    /* Handle of table failed, don't touch in-memory array. */
    result= -1;
  }
  else
  {
    /* Handle procs array. */
    if (((handle_grant_struct(3, drop, user_from, user_to) && ! result) ||
         found) && ! result)
    {
      result= 1; /* At least one record/element found. */
      /* If search is requested, we do not need to search further. */
      if (! drop && ! user_to)
        goto end;
    }
  }

4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829
  /* 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;
4830
    }
4831 4832 4833

    /* Handle columns table. */
    if ((found= handle_grant_table(tables, 3, drop, user_from, user_to)) < 0)
4834
    {
4835
      /* Handle of table failed, don't touch the in-memory array. */
4836 4837
      result= -1;
    }
4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849
    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);
}

4850

4851 4852 4853 4854 4855 4856 4857 4858 4859 4860
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('\'');
}
4861

4862

4863 4864 4865 4866 4867 4868 4869
/*
  Create a list of users.

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

4871 4872 4873 4874 4875 4876 4877 4878
  RETURN
    FALSE       OK.
    TRUE        Error.
*/

bool mysql_create_user(THD *thd, List <LEX_USER> &list)
{
  int result;
4879
  String wrong_users;
4880 4881 4882
  ulong sql_mode;
  LEX_USER *user_name;
  List_iterator <LEX_USER> user_list(list);
4883
  TABLE_LIST tables[GRANT_TABLES];
4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898
  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.
    */
4899
    if (handle_grant_data(tables, 0, user_name, NULL))
4900
    {
4901
      append_user(&wrong_users, user_name);
4902
      result= TRUE;
4903
      continue;
4904
    }
4905

4906
    sql_mode= thd->variables.sql_mode;
serg@serg.mylan's avatar
serg@serg.mylan committed
4907
    if (replace_user_table(thd, tables[0].table, *user_name, 0, 0, 1, 0))
4908
    {
4909
      append_user(&wrong_users, user_name);
4910 4911 4912 4913 4914 4915 4916 4917
      result= TRUE;
    }
  }

  VOID(pthread_mutex_unlock(&acl_cache->lock));
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
  if (result)
4918
    my_error(ER_CANNOT_USER, MYF(0), "CREATE USER", wrong_users.c_ptr_safe());
4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938
  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;
4939
  String wrong_users;
4940 4941
  LEX_USER *user_name;
  List_iterator <LEX_USER> user_list(list);
4942
  TABLE_LIST tables[GRANT_TABLES];
4943 4944
  DBUG_ENTER("mysql_drop_user");

4945
  /* DROP USER may be skipped on replication client. */
4946 4947 4948 4949 4950 4951 4952 4953
  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++))
  {
4954
    if (handle_grant_data(tables, 1, user_name, NULL) <= 0)
4955
    {
4956
      append_user(&wrong_users, user_name);
4957
      result= TRUE;
4958
    }
4959
  }
4960

4961 4962 4963 4964
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
  if (result)
monty@mysql.com's avatar
monty@mysql.com committed
4965
    my_error(ER_CANNOT_USER, MYF(0), "DROP USER", wrong_users.c_ptr_safe());
4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985
  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;
4986
  String wrong_users;
4987 4988 4989
  LEX_USER *user_from;
  LEX_USER *user_to;
  List_iterator <LEX_USER> user_list(list);
4990
  TABLE_LIST tables[GRANT_TABLES];
4991 4992
  DBUG_ENTER("mysql_rename_user");

4993
  /* RENAME USER may be skipped on replication client. */
4994 4995 4996 4997 4998 4999 5000 5001 5002
  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++;
5003
    DBUG_ASSERT(user_to != 0); /* Syntax enforces pairs of users. */
5004 5005 5006 5007 5008

    /*
      Search all in-memory structures and grant tables
      for a mention of the new user name.
    */
5009 5010
    if (handle_grant_data(tables, 0, user_to, NULL) ||
        handle_grant_data(tables, 0, user_from, user_to) <= 0)
5011
    {
5012
      append_user(&wrong_users, user_from);
5013 5014
      result= TRUE;
    }
5015
  }
5016

5017 5018 5019 5020
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
  if (result)
5021
    my_error(ER_CANNOT_USER, MYF(0), "RENAME USER", wrong_users.c_ptr_safe());
5022 5023 5024
  DBUG_RETURN(result);
}

5025

5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039
/*
  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.
*/

5040
bool mysql_revoke_all(THD *thd,  List <LEX_USER> &list)
5041
{
5042
  uint counter, revoked, is_proc;
5043
  int result;
5044
  ACL_DB *acl_db;
5045
  TABLE_LIST tables[GRANT_TABLES];
5046 5047 5048
  DBUG_ENTER("mysql_revoke_all");

  if ((result= open_grant_tables(thd, tables)))
5049
    DBUG_RETURN(result != 1);
5050 5051 5052 5053 5054 5055 5056 5057

  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++))
  {
5058
    if (!check_acl_user(lex_user, &counter))
5059
    {
5060 5061
      sql_print_error("REVOKE ALL PRIVILEGES, GRANT: User '%s'@'%s' does not "
                      "exists", lex_user->user.str, lex_user->host.str);
5062 5063 5064
      result= -1;
      continue;
    }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
5065

5066
    if (replace_user_table(thd, tables[0].table,
5067
			   *lex_user, ~(ulong)0, 1, 0, 0))
5068 5069 5070 5071 5072 5073
    {
      result= -1;
      continue;
    }

    /* Remove db access privileges */
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5074 5075 5076 5077 5078
    /*
      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
5079
    do
5080
    {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5081
      for (counter= 0, revoked= 0 ; counter < acl_dbs.elements ; )
5082
      {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5083
	const char *user,*host;
5084

dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5085 5086 5087 5088 5089
	acl_db=dynamic_element(&acl_dbs,counter,ACL_DB*);
	if (!(user=acl_db->user))
	  user= "";
	if (!(host=acl_db->host.hostname))
	  host= "";
5090

dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5091 5092 5093
	if (!strcmp(lex_user->user.str,user) &&
	    !my_strcasecmp(system_charset_info, lex_user->host.str, host))
	{
5094
	  if (!replace_db_table(tables[1].table, acl_db->db, *lex_user, ~(ulong)0, 1))
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5095
	  {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5096 5097 5098 5099 5100
	    /*
	      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
5101 5102
	    continue;
	  }
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5103
	  result= -1; // Something went wrong
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5104
	}
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5105
	counter++;
5106
      }
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5107
    } while (revoked);
5108 5109

    /* Remove column access */
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5110
    do
5111
    {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5112
      for (counter= 0, revoked= 0 ; counter < column_priv_hash.records ; )
5113
      {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5114 5115 5116 5117 5118
	const char *user,*host;
	GRANT_TABLE *grant_table= (GRANT_TABLE*)hash_element(&column_priv_hash,
							     counter);
	if (!(user=grant_table->user))
	  user= "";
5119
	if (!(host=grant_table->host.hostname))
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5120
	  host= "";
5121

dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5122 5123
	if (!strcmp(lex_user->user.str,user) &&
	    !my_strcasecmp(system_charset_info, lex_user->host.str, host))
5124
	{
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5125 5126 5127
	  if (replace_table_table(thd,grant_table,tables[2].table,*lex_user,
				  grant_table->db,
				  grant_table->tname,
5128
				  ~(ulong)0, 0, 1))
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5129
	  {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5130
	    result= -1;
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5131
	  }
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5132
	  else
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5133
	  {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5134
	    if (!grant_table->cols)
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5135
	    {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5136 5137
	      revoked= 1;
	      continue;
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5138
	    }
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5139 5140
	    List<LEX_COLUMN> columns;
	    if (!replace_column_table(grant_table,tables[3].table, *lex_user,
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5141 5142 5143
				      columns,
				      grant_table->db,
				      grant_table->tname,
5144
				      ~(ulong)0, 1))
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5145
	    {
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5146
	      revoked= 1;
5147
	      continue;
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5148
	    }
5149
	    result= -1;
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5150
	  }
5151
	}
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5152
	counter++;
5153
      }
dellis@goetia.(none)'s avatar
dellis@goetia.(none) committed
5154
    } while (revoked);
5155 5156

    /* Remove procedure access */
5157 5158 5159
    for (is_proc=0; is_proc<2; is_proc++) do {
      HASH *hash= is_proc ? &proc_priv_hash : &func_priv_hash;
      for (counter= 0, revoked= 0 ; counter < hash->records ; )
5160 5161
      {
	const char *user,*host;
5162
	GRANT_NAME *grant_proc= (GRANT_NAME*) hash_element(hash, counter);
5163 5164
	if (!(user=grant_proc->user))
	  user= "";
5165
	if (!(host=grant_proc->host.hostname))
5166 5167 5168 5169 5170
	  host= "";

	if (!strcmp(lex_user->user.str,user) &&
	    !my_strcasecmp(system_charset_info, lex_user->host.str, host))
	{
5171
	  if (!replace_routine_table(thd,grant_proc,tables[4].table,*lex_user,
5172 5173
				  grant_proc->db,
				  grant_proc->tname,
5174
                                  is_proc,
5175 5176 5177 5178 5179 5180 5181 5182 5183 5184
				  ~0, 1))
	  {
	    revoked= 1;
	    continue;
	  }
	  result= -1;	// Something went wrong
	}
	counter++;
      }
    } while (revoked);
5185
  }
5186

5187 5188 5189
  VOID(pthread_mutex_unlock(&acl_cache->lock));
  rw_unlock(&LOCK_grant);
  close_thread_tables(thd);
5190

5191
  if (result)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5192
    my_message(ER_REVOKE_GRANTS, ER(ER_REVOKE_GRANTS), MYF(0));
5193

5194 5195
  DBUG_RETURN(result);
}
5196

5197

5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211
/*
  Revoke privileges for all users on a stored procedure

  SYNOPSIS
    sp_revoke_privileges()
    thd                         The current thread.
    db				DB of the stored procedure
    name			Name of the stored procedure

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

5212 5213
bool sp_revoke_privileges(THD *thd, const char *sp_db, const char *sp_name,
                          bool is_proc)
5214 5215 5216 5217
{
  uint counter, revoked;
  int result;
  TABLE_LIST tables[GRANT_TABLES];
5218
  HASH *hash= is_proc ? &proc_priv_hash : &func_priv_hash;
5219 5220 5221 5222 5223 5224 5225 5226 5227
  DBUG_ENTER("sp_revoke_privileges");

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

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

  /* Remove procedure access */
5228 5229
  do
  {
5230
    for (counter= 0, revoked= 0 ; counter < hash->records ; )
5231
    {
5232
      GRANT_NAME *grant_proc= (GRANT_NAME*) hash_element(hash, counter);
5233 5234 5235 5236 5237 5238
      if (!my_strcasecmp(system_charset_info, grant_proc->db, sp_db) &&
	  !my_strcasecmp(system_charset_info, grant_proc->tname, sp_name))
      {
        LEX_USER lex_user;
	lex_user.user.str= grant_proc->user;
	lex_user.user.length= strlen(grant_proc->user);
5239 5240
	lex_user.host.str= grant_proc->host.hostname;
	lex_user.host.length= strlen(grant_proc->host.hostname);
5241 5242 5243
	if (!replace_routine_table(thd,grant_proc,tables[4].table,lex_user,
				   grant_proc->db, grant_proc->tname,
                                   is_proc, ~0, 1))
5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278
	{
	  revoked= 1;
	  continue;
	}
	result= -1;	// Something went wrong
      }
      counter++;
    }
  } while (revoked);

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

  if (result)
    my_message(ER_REVOKE_GRANTS, ER(ER_REVOKE_GRANTS), MYF(0));

  DBUG_RETURN(result);
}


/*
  Grant EXECUTE,ALTER privilege for a stored procedure

  SYNOPSIS
    sp_grant_privileges()
    thd                         The current thread.
    db				DB of the stored procedure
    name			Name of the stored procedure

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

5279 5280
bool sp_grant_privileges(THD *thd, const char *sp_db, const char *sp_name,
                         bool is_proc)
5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302
{
  LEX_USER *combo;
  TABLE_LIST tables[1];
  List<LEX_USER> user_list;
  bool result;
  DBUG_ENTER("sp_grant_privileges");  

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

  combo->user.str= thd->user;
  
  if (!find_acl_user(combo->host.str=(char*)thd->host_or_ip, combo->user.str) &&
      !find_acl_user(combo->host.str=(char*)thd->host, combo->user.str) &&
      !find_acl_user(combo->host.str=(char*)thd->ip, combo->user.str) &&
      !find_acl_user(combo->host.str=(char*)"%", combo->user.str))
    DBUG_RETURN(TRUE);

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

  tables->db= (char*)sp_db;
5303
  tables->table_name= tables->alias= (char*)sp_name;
5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315
  
  combo->host.length= strlen(combo->host.str);
  combo->user.length= strlen(combo->user.str);
  combo->host.str= thd->strmake(combo->host.str,combo->host.length);
  combo->user.str= thd->strmake(combo->user.str,combo->user.length);
  combo->password.str= (char*)"";
  combo->password.length= 0;

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

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

5318
  result= mysql_routine_grant(thd, tables, is_proc, user_list,
5319 5320 5321 5322 5323
  				DEFAULT_CREATE_PROC_ACLS, 0, 1);
  DBUG_RETURN(result);
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
5324
/*****************************************************************************
5325
  Instantiate used templates
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5326 5327 5328 5329 5330 5331 5332 5333
*****************************************************************************/

#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
5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380

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

5381 5382 5383 5384 5385 5386 5387 5388

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;
5389
  restore_record(table, s->default_values);
5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410
  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;
5411 5412
  bool no_global_access= check_access(thd, SELECT_ACL, "mysql",0,1,1);
  char *curr_host= thd->priv_host ? thd->priv_host : (char *) "%";
5413
  DBUG_ENTER("fill_schema_user_privileges");
5414

5415 5416 5417 5418 5419 5420 5421 5422
  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= "";
5423 5424 5425 5426 5427 5428

    if (no_global_access &&
        (strcmp(thd->priv_user, user) ||
         my_strcasecmp(system_charset_info, curr_host, host)))
      continue;
      
5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449
    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);
5450 5451 5452
#else
  return(0);
#endif
5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463
}


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;
5464 5465
  bool no_global_access= check_access(thd, SELECT_ACL, "mysql",0,1,1);
  char *curr_host= thd->priv_host ? thd->priv_host : (char *) "%";
5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477
  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= "";

5478 5479 5480 5481 5482
    if (no_global_access &&
        (strcmp(thd->priv_user, user) ||
         my_strcasecmp(system_charset_info, curr_host, host)))
      continue;

5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506
    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);
5507 5508 5509
#else
  return (0);
#endif
5510 5511 5512 5513 5514 5515 5516 5517 5518
}


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;
5519 5520
  bool no_global_access= check_access(thd, SELECT_ACL, "mysql",0,1,1);
  char *curr_host= thd->priv_host ? thd->priv_host : (char *) "%";
5521 5522 5523 5524 5525 5526 5527 5528 5529
  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= "";
5530 5531 5532 5533 5534 5535 5536

    if (no_global_access &&
        (strcmp(thd->priv_user, user) ||
         my_strcasecmp(system_charset_info, curr_host,
                       grant_table->host.hostname)))
      continue;

5537
    ulong table_access= grant_table->privs;
5538
    if (table_access)
5539 5540
    {
      ulong test_access= table_access & ~GRANT_ACL;
5541 5542 5543 5544
      /*
        We should skip 'usage' privilege on table if
        we have any privileges on column(s) of this table
      */
5545 5546
      if (!test_access && grant_table->cols)
        continue;
5547 5548 5549
      if (!(table_access & GRANT_ACL))
        is_grantable= "NO";

5550
      strxmov(buff,"'",user,"'@'",grant_table->host.hostname,"'",NullS);
5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568
      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);
5569 5570 5571
#else
  return (0);
#endif
5572 5573 5574 5575 5576 5577 5578 5579 5580
}


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;
5581 5582
  bool no_global_access= check_access(thd, SELECT_ACL, "mysql",0,1,1);
  char *curr_host= thd->priv_host ? thd->priv_host : (char *) "%";
5583 5584 5585 5586 5587 5588 5589 5590 5591
  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= "";
5592 5593 5594 5595 5596 5597 5598

    if (no_global_access &&
        (strcmp(thd->priv_user, user) ||
         my_strcasecmp(system_charset_info, curr_host,
                       grant_table->host.hostname)))
      continue;

5599 5600 5601
    ulong table_access= grant_table->cols;
    if (table_access != 0)
    {
5602
      if (!(grant_table->privs & GRANT_ACL))
5603 5604
        is_grantable= "NO";

5605
      ulong test_access= table_access & ~GRANT_ACL;
5606
      strxmov(buff,"'",user,"'@'",grant_table->host.hostname,"'",NullS);
5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636
      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);
5637 5638 5639
#else
  return (0);
#endif
5640 5641 5642
}


bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
5643 5644 5645 5646 5647
#ifndef NO_EMBEDDED_ACCESS_CHECKS
/*
  fill effective privileges for table

  SYNOPSIS
5648 5649
    fill_effective_table_privileges()
    thd     thread handler
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
5650 5651 5652 5653 5654 5655 5656 5657
    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)
{
5658 5659 5660 5661 5662 5663 5664
  /* --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
5665 5666
  /* global privileges */
  grant->privilege= thd->master_access;
5667

5668 5669 5670
  if (!thd->priv_user)
    return;                                   // it is slave

5671 5672 5673
  /* db privileges */
  grant->privilege|= acl_get(thd->host, thd->ip, thd->priv_user, db, 0);

5674 5675 5676
  if (!grant_option)
    return;

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
5677 5678 5679
  /* table privileges */
  if (grant->version != grant_version)
  {
5680
    rw_rdlock(&LOCK_grant);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
5681 5682 5683 5684 5685
    grant->grant_table=
      table_hash_search(thd->host, thd->ip, db,
			thd->priv_user,
			table, 0);              /* purecov: inspected */
    grant->version= grant_version;              /* purecov: inspected */
5686
    rw_unlock(&LOCK_grant);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
5687 5688 5689 5690 5691 5692
  }
  if (grant->grant_table != 0)
  {
    grant->privilege|= grant->grant_table->privs;
  }
}
5693 5694 5695 5696 5697 5698 5699

#else /* NO_EMBEDDED_ACCESS_CHECKS */

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

acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
5700 5701
bool check_routine_level_acl(THD *thd, const char *db, const char *name,
                             bool is_proc)
5702 5703 5704 5705
{
  return FALSE;
}

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