コード例 #1
0
int main()
{
	for (size_t n = 0; n <= 20; ++n)
	{
		for (int i = 0; i < 1000; ++i)
		{
			std::string str = random_string(n);

			suffix_tree S(str);

			for (const std::string& substr : substrings(str))
			{
				assert(S.find(substr) == find_occurrences(substr, str));
			}

			/* search for random strings in str */
			for (size_t m = 0; m <= n; ++m)
			{
				std::string rnd_str = random_string(m);
				assert(S.find(rnd_str) == find_occurrences(rnd_str, str));
			}
		}

		std::cout << "passed random tests for strings of length " << n << std::endl;
	}

	return 0;
}
コード例 #2
0
int main()
{
	std::random_device device;
	std::mt19937 generator(device());

	for (size_t n = 0; n <= 100; ++n)
	{
		for (int i = 0; i < 1000; ++i)
		{
			std::string str1 = random_string(n);
			std::string str2 = random_string(n);

			assert(is_anagram_1(str1, str2) == is_anagram_2(str1, str2));

			std::string str1_shuf = str1;
			std::shuffle(str1_shuf.begin(), str1_shuf.end(), generator);

			assert(is_anagram_1(str1, str1_shuf) == true);
			assert(is_anagram_2(str1, str1_shuf) == true);
		}

		std::cout << "passed random tests for strings of length " << n << std::endl;
	}

	return 0;
}
コード例 #3
0
ファイル: zhash_test.c プロジェクト: zfletch/zhash-c
static void zhash_set_test()
{
  size_t size, ii;
  char **keys, **vals;
  struct ZHashTable *hash_table;

  size = 100;
  hash_table = zcreate_hash_table();
  keys = malloc(size * sizeof(char *));
  vals = malloc(size * sizeof(char *));

  for (ii = 0; ii < size; ii++) {
    keys[ii] = random_string();
    vals[ii] = random_string();
    zhash_set(hash_table, keys[ii], (void *) vals[ii]);
  }

  assert(hash_table->size_index == 2);
  assert(hash_table->entry_count == size);

  for (ii = 0; ii < size; ii++) {
    assert(strcmp(zhash_get(hash_table, keys[ii]), vals[ii]) == 0);
  }

  for (ii = 0; ii < size; ii++) {
    free(keys[ii]);
    free(vals[ii]);
  }

  free(keys);
  free(vals);
  zfree_hash_table(hash_table);
}
コード例 #4
0
void test() {
  /* Field testing: Kattis stringmultimatching, Codeforces 366C */

  int ts = 100,
    ts2 = 10;

  for (int t = 0; t < ts; t++) {
    int n = rand() % 1000;

    vector<string> kws;
    for (int i = 0; i < n; i++) {
      kws.push_back(random_string(rand() % 10 + 1, rand() % 5 + 1));
    }

    aho_corasick ac(kws);
    aho_corasick_slow ac2(kws);

    for (int p = 0; p < ts2; p++) {
      string s = random_string(rand() % 100, rand() % 5 + 1);
      vector<string> res = ac.search(s);
      vector<string> res2 = ac2.search(s);
      sort(res.begin(), res.end());
      sort(res2.begin(), res2.end());

      assert_equal(size(res2), size(res));

      for (int i = 0; i < size(res); i++) {
        assert_equal(res2[i], res[i]);
      }
    }
  }
}
コード例 #5
0
ファイル: ice.c プロジェクト: Zodiac-Evil/rtpengine
static void __new_stun_transaction(struct ice_candidate_pair *pair) {
	struct ice_agent *ag = pair->agent;

	g_hash_table_remove(ag->transaction_hash, pair->stun_transaction);
	random_string((void *) pair->stun_transaction, sizeof(pair->stun_transaction));
	g_hash_table_insert(ag->transaction_hash, pair->stun_transaction, pair);
}
コード例 #6
0
int TestConcurrentReadWrite(STORAGE::Filesystem *fs) {

	for (int i = 0; i < numWriters; ++i) {
		std::srand((unsigned int)std::time(NULL) + i);
		data[i] = random_string(dataSize);
	}

	THREADING::ThreadPool pool(numThreads);

	std::thread writeThread([&pool, fs] {
		for (int i = 0; i < numWriters; ++i) {
			pool.enqueue([fs, i] {startWriter(fs, i); });
		}
	});

	std::thread readThread([&pool, fs] {
		for (int i = 0; i < numReaders; ++i) {
			std::future<bool> ret = pool.enqueue([fs] {return startReader(fs); });
			if (!ret.get()) {
				failure = true;
				break;
			}
		}
	});

	readThread.join();
	writeThread.join();

	return failure;
}
コード例 #7
0
void generate_random_strings(std::size_t n, OutIt it)
{
	static const std::vector<char> ch_set = {
		'0','1','2','3','4',
		'5','6','7','8','9',
		'A','B','C','D','E','F',
		'G','H','I','J','K',
		'L','M','N','O','P',
		'Q','R','S','T','U',
		'V','W','X','Y','Z',
		'a','b','c','d','e','f',
		'g','h','i','j','k',
		'l','m','n','o','p',
		'q','r','s','t','u',
		'v','w','x','y','z',
		'_'
	};
	std::uniform_int_distribution<std::size_t> dist(0, ch_set.size() - 1);
	std::uniform_int_distribution<std::size_t> lengthdist(4, 10);
	auto genchar = [&dist]() { return ch_set[dist(benchmark_rng_engine())]; };
	for (std::size_t i = 0; i < n; ++i) {
		auto len = lengthdist(benchmark_rng_engine());
		*it = std::pair<std::string, std::size_t>(random_string(len, genchar), i);
		++it;
	}
}
コード例 #8
0
ファイル: main.c プロジェクト: iamscottmoyers/hashmap
static void random_insertions( void )
{
	int res;
	hashmap_t hashmap;
	unsigned int i;

	res = hashmap_init_with_buckets( &hashmap, 8192 /* pow 2 */ );
	assert( 0 == res );

	for( i = 0; i < 100000; ++i )
	{
		char str[10];
		hashmap_value_t val = rand();
		hashmap_value_t retrieved;

		random_string( str, sizeof(str) );

		res = hashmap_insert( &hashmap, str, val );
		assert( 0 == res );

		res = hashmap_find( &hashmap, str, &retrieved );
		assert( 1 == res );
		assert( retrieved == val );
	}

	hashmap_term( &hashmap );
}
コード例 #9
0
ファイル: performance.cpp プロジェクト: noeljt/DataStructures
// Load the data either from a file, or generate random data
void load_data(const std::string &input, std::string*& input_data, int& input_count, int string_length) {

  if (input == "random") {
    // seed the random number generator
    // using a fixed seed for repeatable tests for debugging
    srand(37);
    // using the time as a seed
    //srand(time(0));
    input_data = new std::string[input_count];
    for (int i = 0; i < input_count; i++) 
      input_data[i] = random_string(string_length);

  } else {
    // load the file once to get the count
    std::ifstream istr(input.c_str());
    if (!istr) {
      std::cerr << "Error: Can't open input file: " << input << std::endl;
      exit(0);
    }
    std::string s;
    input_count = 0;
    while (istr >> s) {
      input_count++;
    }
    // make an array exactly the right size
    input_data = new std::string[input_count];
    // close & reopen & reread the file to store the data
    istr.close();
    istr.open(input.c_str());
    for (int i = 0; i < input_count; i++) {
      istr >> s;
      input_data[i] = s;
    }
  }
}
コード例 #10
0
ファイル: profiler_test.cpp プロジェクト: jbrezmorf/flow123d
void ProfilerTest::test_str_hash() {
    EXPECT_EQ(0, str_hash("", PROFILER_HASH_DEFAULT));
    EXPECT_EQ(65, str_hash("A", PROFILER_HASH_DEFAULT));
    EXPECT_EQ(6597, str_hash(" A", PROFILER_HASH_DEFAULT));

    srand ( time(NULL) );
    char a[16];
    char b[16];

    // random test for hash collision
    unsigned int n_pairs=100;
    for(unsigned int i=0; i<n_pairs; i++) {
        random_string(a);
        random_string(b);
        if (string(a) != string(b) )
            EXPECT_NE( str_hash(a, PROFILER_HASH_DEFAULT) , str_hash(b, PROFILER_HASH_DEFAULT) );
    }
}
コード例 #11
0
ファイル: profiler_test.cpp プロジェクト: jstebel/flow123d
TEST(Profiler, str_hash) {
    EXPECT_EQ(0, str_hash(""));
    EXPECT_EQ(65, str_hash("A"));
    EXPECT_EQ(6597, str_hash(" A"));

    srand ( time(NULL) );
    char a[16];
    char b[16];

// random test for hash collision
    unsigned int n_pairs=100;
    for(unsigned int i=0; i<n_pairs; i++) {
        random_string(a);
        random_string(b);
        if (string(a) != string(b) )
            EXPECT_NE( str_hash(a) , str_hash(b) );
    }
}
コード例 #12
0
ファイル: random.c プロジェクト: 50wu/gpdb
Datum
dbms_random_string(PG_FUNCTION_ARGS)
{
	char *option;
	int	len;
	const char *charset;
	int chrset_size;

	const char *alpha_mixed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	const char *lower_only = "abcdefghijklmnopqrstuvwxyz";
	const char *upper_only = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	const char *upper_alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	const char *printable = "`1234567890-=qwertyuiop[]asdfghjkl;'zxcvbnm,./!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:\"ZXCVVBNM<>? ";
	
	option = text_to_cstring(PG_GETARG_TEXT_P(0));
	len = PG_GETARG_INT32(1);
	
	switch (option[0])
	{
		case 'a':
		case 'A':
			charset = alpha_mixed;
			chrset_size = strlen(alpha_mixed);
			break;
		case 'l':
		case 'L':
			charset = lower_only;
			chrset_size = strlen(lower_only);
			break;
		case 'u':
		case 'U':
			charset = upper_only;
			chrset_size = strlen(upper_only);
			break;
		case 'x':
		case 'X':
			charset = upper_alphanum;
			chrset_size = strlen(upper_alphanum);
			break;
		case 'p':
		case 'P':
			charset = printable;
			chrset_size = strlen(printable);
			break;
			
		default:
			ereport(ERROR, 
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE), 
				 errmsg("unknown option '%s'", option),
				 errhint("available option \"aAlLuUxXpP\"")));
			/* be compiler a quiete */
			charset = NULL;
			chrset_size = 0;
	}
	
	PG_RETURN_TEXT_P(random_string(charset, chrset_size, len));
}
コード例 #13
0
int main(int argc, char *argv[])
{
   int num_objects;
   int num_names;
   int i;
   bool uh, nuh;

   if (argc != 1 && argc < 5) {
      usage(argv[0]);
   }

   /* initialize globals */
   lInit(my_nmv);
   clk_tck = sysconf(_SC_CLK_TCK); /* JG: TODO: sge_sysconf? */
   prof_mt_init();

   /* we need random numbers */
   srand(time(0));

   if (argc == 1) {
      num_objects = 1000;
      num_names   = 10;
      uh          = true;
      nuh         = true;
   } else {
      /* parse commandline options */
      num_objects = atoi(argv[1]);
      num_names   = atoi(argv[2]);
      uh          = atoi(argv[3]) == 0 ? false : true;
      nuh         = atoi(argv[4]) == 0 ? false : true;
   }

   /* create name array */
   names = sge_malloc (num_names * sizeof(const char *));

   /* build random names */
   for (i = 0; i < num_names; i++) {
      const char *name = random_string(10);
      names[i] = name;
   }

   /* output header */
   printf(HEADER_FORMAT, "uh ", "nuh", 
          "create", "copy", "rau", "inu", "curo", "cnuro", 
          "dru", "(objs)", "dinu", "(objs)", "mem(kB)");

   /* do tests */
   do_test(uh, nuh, num_objects, num_names);
   
   /* free names */
   for (i = 0; i < num_names; i++) {
      sge_free(&(names[i]));
   }

   return EXIT_SUCCESS;
}
コード例 #14
0
ファイル: ClapTrap.cpp プロジェクト: Elytum/PISCINE_CPP
std::string			talk_fn ( std::string const & kind ) {
	static const char			*character_selection[] = CHARACTER_SELECTION_QUOTES;
	static const char			*melee[] = MELEE_QUOTES;
	static const char			*ranged[] = RANGED_QUOTES;
	static const char			*healing[] = HEALING_QUOTES;
	static const char			*death[] = DEATH_QUOTES;

	if (kind == "creation")
		return (random_string(character_selection, ARRAY_SIZE(character_selection)));
	else if (kind == "melee")
		return (random_string(melee, ARRAY_SIZE(melee)));
	else if (kind == "ranged")
		return (random_string(ranged, ARRAY_SIZE(ranged)));
	else if (kind == "healing")
		return (random_string(healing, ARRAY_SIZE(ranged)));
	else if (kind == "death")
		return (random_string(death, ARRAY_SIZE(death)));
	return ("");
}
コード例 #15
0
ファイル: sort_tests.hpp プロジェクト: ShmuelLevine/hpx
// --------------------------------------------------------------------
// fill a vector with random strings
void rnd_strings(std::vector<std::string> &V)
{
    const std::size_t test_size = HPX_SORT_TEST_SIZE_STRINGS;
    // Fill vector with random strings
    V.clear();
    V.reserve(test_size);
    // random strings up to 128 chars long
    for (std::size_t i=0; i<test_size; i++) {
        V.push_back(random_string( std::rand() % 128)); //-V106
    }
}
コード例 #16
0
ファイル: TableGenerator.cpp プロジェクト: martinfaust/hyrise
atable_ptr_t TableGenerator::string_random_delta(size_t rows, size_t cols, int string_length) {
  start(rows, cols, rows * cols);
  srand(clock());


  atable_ptr_t new_table = create_empty_table(rows, cols);


  for (size_t col = 0; col < cols; ++col) {
    std::set<std::string> values;

    for (size_t row = 0; row < rows; ++row) {
      values.insert(random_string(string_length));
      increment();
    }

    // shuffle the dict (its a delta)
    std::vector<std::string> values_vector(values.begin(), values.end());
    random_shuffle(values_vector.begin(), values_vector.end());

    OrderIndifferentDictionary<std::string> *dict = new OrderIndifferentDictionary<std::string>();
for (const auto & i: values_vector) {
      dict->addValue(i);
    }
    new_table->setDictionaryAt(AbstractTable::SharedDictionaryPtr(dict), col);

  }

  new_table->resize(rows);

  for (size_t col = 0; col < cols; ++col) {
    // shuffle the values
    std::vector<value_id_t> attribute_vector;

    for (size_t row = 0; row < rows; ++row) {
      attribute_vector.push_back(row % new_table->dictionaryAt(col)->size());
    }

    random_shuffle(attribute_vector.begin(), attribute_vector.end());

    for (size_t row = 0; row < rows; ++row) {
      ValueId v;
      v.valueId = attribute_vector[row];
      v.table = 0;
      new_table->setValueId(col, row, v);
    }
  }

  if (!_quiet) {
    std::cout << std::endl;
  }

  return new_table;
}
コード例 #17
0
ファイル: TestUnlink.cpp プロジェクト: RapidStash/RapidStash
int TestUnlink(STORAGE::Filesystem *fs) {
	File &first = fs->select("FirstFile");
	File &second = fs->select("SecondFile");

	std::string f1Data = random_string(128);
	auto f1Writer = fs->getSafeWriter(first);
	f1Writer.write(f1Data.c_str(), f1Data.size());

	std::string f2Data = random_string(32);
	auto f2Writer = fs->getSafeWriter(second);
	f2Writer.write(f2Data.c_str(), f2Data.size());

	STORAGE::FileHeader h1 = fs->getHeader(first);
	STORAGE::FileHeader h2 = fs->getHeader(second);
	FileSize sizeBefore = h2.virtualSize;
	bool merged = fs->unlink(first);
	h2 = fs->getHeader(second);
	if (merged && h2.virtualSize != sizeBefore + STORAGE::FileHeader::SIZE + h1.virtualSize) {
		return 1;
	}
	return 0;
}
コード例 #18
0
ファイル: env.cpp プロジェクト: hiwang123/winjudge
restricted_env::restricted_env(const std::shared_ptr<judge::pool> &pool,
	const string &username, const string &password)
	: env(pool)
	, username_(username)
	, session_(username, password)
	, desktop_(random_string(desktop_name_length))
{
	vector<char> sid = session_.sid();
	window_station_.remove_ace_by_sid(sid);
	window_station_.add_allowed_ace(sid, user_object::allowed_ace(0,
		GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE));
	desktop_.add_allowed_ace(sid, user_object::allowed_ace(0,
		GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE));
}
コード例 #19
0
ファイル: string_helper.cpp プロジェクト: mrkeng/ardb
 std::string random_between_string(const std::string& min, const std::string& max)
 {
     if (min == max)
     {
         return min;
     }
     std::string random_key;
     for (uint32 i = 0; i < min.size() && i < max.size(); i++)
     {
         if (min[i] < max[i])
         {
             if (min[i] == max[i] - 1)
             {
                 random_key.push_back(min[i]);
                 for (uint32 j = i + 1; j < min.size(); j++)
                 {
                     if (min[j] == 127)
                     {
                         random_key.push_back(min[j]);
                     }
                     else
                     {
                         char c = (char) random_between_int32(min[j], 127);
                         random_key.push_back(c);
                         if (c > min[j])
                         {
                             break;
                         }
                     }
                 }
             }
             else
             {
                 char c = (char) random_between_int32(min[i], max[i]);
                 while (c == min[i] || c == max[i])
                 {
                     c = (char) random_between_int32(min[i], max[i]);
                 }
                 random_key.push_back(c);
             }
             break;
         }
         else
         {
             random_key.push_back(min[i]);
         }
     }
     random_key.append(random_string(5));
     return random_key;
 }
コード例 #20
0
  std::string ValueGenerator::generate_random_string( int min, int max )
  {
    std::string random_string( "\"" );

    int size = rand() % ( max-min ) + min;

    for( int i = 0; i < size; i++ )
    {
      random_string += alphanum[ rand() % ( alphanum.size()-1 ) ];
    }

    random_string.insert( random_string.end(), '\"' );

    return random_string;
  }
コード例 #21
0
int TestReadWrite(STORAGE::Filesystem *fs) {
    static unsigned int test;

    File &file = fs->select("TestFile");
    STORAGE::IO::SafeWriter writer = fs->getSafeWriter(file);
    STORAGE::IO::SafeReader reader = fs->getSafeReader(file);

    std::srand(test++);
    std::string data = random_string(dataSize);

    writer.write(data.c_str(), data.size());
    std::string res = reader.readString();
    if (res.compare(data) != 0) {
        return -1;
    }

    return 0;
}
コード例 #22
0
/*
 * No params
 * 
 * Returns:
 * A valid name for the file (String)
 * 
 * Returns a valid name of a file
 */
char* Disk_File::getValidPeer() {
    int i = 1;
    char random_str[Peer_SIZE + 1];

    srand((unsigned) time(NULL));

    random_str[Peer_SIZE] = '\0';

    random_string(Peer_SIZE, random_str);

    string nameToCheck = string(random_str) + ".bin";
    char* nametoCheckChar = strdup(nameToCheck.c_str());
    if (exists((char*) nametoCheckChar)) {
        nameToCheck = getValidPeer();
    }
    nameToCheck = string(random_str);
    return strdup(nameToCheck.c_str());
}
コード例 #23
0
int main()
{
    for (size_t n = 0; n <= 100; ++n)
    {
        for (int i = 0; i < 1000; ++i)
        {
            std::string str = random_string(n);

            bool result = has_duplicates_3(str);

            assert(has_duplicates_1(str) == result);
            assert(has_duplicates_2(str) == result);
        }

        std::cout << "passed random tests for strings of length " << n << std::endl;
    }

    return 0;
}
コード例 #24
0
char* test_random()
{
  const size_t str_len = 5000;
  char* str = malloc(str_len * sizeof(char));
  unsigned int i = 0;
  for(i = 0; i < 25; i++) {
    random_string(str, str_len);
    SuffixTree_T stree = SuffixTree_create(str, str_len);
    EulerTour_T euler_tour = EulerTour_create(stree);
    
    int ret = EulerTour_verify(euler_tour, stree);
    mu_assert(ret == 0, "Euler tour verification failed.");

    SuffixTree_delete(&stree);
    EulerTour_delete(&euler_tour);
  }
  free(str);
  return NULL;
}
コード例 #25
0
int main()
{
	for (size_t n = 0; n <= 100; ++n)
	{
		for (int i = 0; i < 1000; ++i)
		{
			std::string str = random_string(n);
			std::string str_copy(str);

			remove_duplicates_1(str);
			remove_duplicates_2(str_copy);

			assert(str == str_copy);
		}

		std::cout << "passed random tests for strings of length " << n << std::endl;
	}

	return 0;
}
コード例 #26
0
int main(int argc, char *argv[])
{
	int i;

	i = 0;
	for (;;) {
		char string[10];

		printf("%u/%u = %.2f\n", nitems, nhash, (double) nitems / nhash);
		if (i >= INSERT_NUM)
			break;
		random_string(string, sizeof(string));
		lookup(strdup(string), 1, i);
		i++;
		if (count() != i) {
			eprintf("error growing hash: expected %d entries, found %d.\n",
				i, count());
		}
	}

	return 0;
}
コード例 #27
0
ファイル: lua-ext.c プロジェクト: cofyc/alilua
int lua_f_random_string(lua_State *L)
{
    int size = 32;

    if(lua_gettop(L) == 1 && lua_isnumber(L, 1)) {
        size = lua_tonumber(L, 1);
    }

    if(size < 1) {
        size = 32;
    }

    if(size > 4096) {
        return 0;
    }

    random_string(temp_buf, size, 0);

    lua_pushlstring(L, temp_buf, size);

    return 1;
}
コード例 #28
0
ファイル: base.c プロジェクト: macrofengye/cweb
//产生随机字符串
char *random_string(char *dest) {
	size_t len = 0;
	char *p = dest;
	int three_in_a_row = 0;
	int arr[128] = { 0x0 };
	if (!srand_called) {
		srandom(time(NULL));
		srand_called = 1;
	}
	for (len = 6 + rand() % 3; len; len--, p++) {
		char *q = dest;
		*p = (rand() % 2) ? rand() % 26 + 97 : rand() % 10 + 48;
		p[1] = 0x0;
		arr[*p]++;
		if (arr[*p] == 3) {
			for (q = dest; q[2] > 0 && !three_in_a_row; q++)
				if (*q == q[1] && q[1] == q[2])
					three_in_a_row = 1;
		}
		if (three_in_a_row || arr[*p] > 3)
			return random_string(dest);
	}
	return dest;
}
コード例 #29
0
ファイル: sendpass.c プロジェクト: Gryllida/atheme
static void ns_cmd_sendpass(sourceinfo_t *si, int parc, char *parv[])
{
	myuser_t *mu;
	char *name = parv[0];
	char *newpass = NULL;
	char *key;
	metadata_t *md;
	enum specialoperation op = op_none;
	bool ismarked = false;
	char cmdtext[NICKLEN + 20];
	hook_user_needforce_t needforce_hdata;

	if (!name)
	{
		command_fail(si, fault_needmoreparams, STR_INSUFFICIENT_PARAMS, "SENDPASS");
		command_fail(si, fault_needmoreparams, _("Syntax: SENDPASS <account>"));
		return;
	}

	if (parc > 1)
	{
		if (!strcasecmp(parv[1], "FORCE"))
			op = op_force;
		else if (!strcasecmp(parv[1], "CLEAR"))
			op = op_clear;
		else
		{
			command_fail(si, fault_badparams, STR_INVALID_PARAMS, "SENDPASS");
			command_fail(si, fault_badparams, _("Syntax: SENDPASS <account> [FORCE|CLEAR]"));
			return;
		}
	}

	if (!(mu = myuser_find_by_nick(name)))
	{
		command_fail(si, fault_nosuch_target, _("\2%s\2 is not registered."), name);
		return;
	}

	if (is_soper(mu) && !has_priv(si, PRIV_ADMIN))
	{
		logcommand(si, CMDLOG_ADMIN, "failed SENDPASS \2%s\2 (is SOPER)", name);
		command_fail(si, fault_badparams, _("\2%s\2 belongs to a services operator; you need %s privilege to send the password."), name, PRIV_ADMIN);
		return;
	}

	if (mu->flags & MU_WAITAUTH)
	{
		command_fail(si, fault_badparams, _("\2%s\2 is not verified."), entity(mu)->name);
		return;
	}

	if ((md = metadata_find(mu, "private:mark:setter")))
	{
		ismarked = true;
		if (op == op_none)
		{
			logcommand(si, CMDLOG_ADMIN, "failed SENDPASS \2%s\2 (marked by \2%s\2)", entity(mu)->name, md->value);
			command_fail(si, fault_badparams, _("This operation cannot be performed on %s, because the account has been marked by %s."), entity(mu)->name, md->value);
			if (has_priv(si, PRIV_MARK))
			{
				snprintf(cmdtext, sizeof cmdtext, "SENDPASS %s FORCE", entity(mu)->name);
				command_fail(si, fault_badparams, _("Use %s to override this restriction."), cmdtext);
			}
			return;
		}
		else if (!has_priv(si, PRIV_MARK))
		{
			logcommand(si, CMDLOG_ADMIN, "failed SENDPASS \2%s\2 (marked by \2%s\2)", entity(mu)->name, md->value);
			command_fail(si, fault_noprivs, STR_NO_PRIVILEGE, PRIV_MARK);
			return;
		}
	}

	needforce_hdata.si = si;
	needforce_hdata.mu = mu;
	needforce_hdata.allowed = 1;

	hook_call_user_needforce(&needforce_hdata);

	if (!needforce_hdata.allowed)
	{
		ismarked = true;
		if (op == op_none)
		{
			logcommand(si, CMDLOG_ADMIN, "failed SENDPASS \2%s\2 (marked)", entity(mu)->name);
			command_fail(si, fault_badparams, _("This operation cannot be performed on %s, because the account has been marked."), entity(mu)->name);
			if (has_priv(si, PRIV_MARK))
			{
				snprintf(cmdtext, sizeof cmdtext, "SENDPASS %s FORCE", entity(mu)->name);
				command_fail(si, fault_badparams, _("Use %s to override this restriction."), cmdtext);
			}
			return;
		}
		else if (!has_priv(si, PRIV_MARK))
		{
			logcommand(si, CMDLOG_ADMIN, "failed SENDPASS \2%s\2 (marked)", entity(mu)->name);
			command_fail(si, fault_noprivs, STR_NO_PRIVILEGE, PRIV_MARK);
			return;
		}
	}

	if (op == op_clear)
	{
		if (metadata_find(mu, "private:setpass:key"))
		{
			metadata_delete(mu, "private:setpass:key");
			metadata_delete(mu, "private:sendpass:sender");
			metadata_delete(mu, "private:sendpass:timestamp");
			logcommand(si, CMDLOG_ADMIN, "SENDPASS:CLEAR: \2%s\2", entity(mu)->name);
			command_success_nodata(si, _("The password change key for \2%s\2 has been cleared."), entity(mu)->name);
		}
		else
			command_fail(si, fault_nochange, _("\2%s\2 did not have a password change key outstanding."), entity(mu)->name);
		return;
	}

	if (MOWGLI_LIST_LENGTH(&mu->logins) > 0)
	{
		command_fail(si, fault_noprivs, _("This operation cannot be performed on %s, because someone is logged in to it."), entity(mu)->name);
		return;
	}

	if (metadata_find(mu, "private:freeze:freezer"))
	{
		command_fail(si, fault_noprivs, _("%s has been frozen by the %s administration."), entity(mu)->name, me.netname);
		return;
	}

	if (command_find(si->service->commands, "SETPASS"))
	{
		if (metadata_find(mu, "private:setpass:key"))
		{
			command_fail(si, fault_alreadyexists, _("\2%s\2 already has a password change key outstanding."), entity(mu)->name);
			command_fail(si, fault_alreadyexists, _("Use SENDPASS %s CLEAR to clear it so that a new one can be sent."), entity(mu)->name);
			return;
		}

		if (ismarked)
		{
			wallops("%s sent the password for the \2MARKED\2 account %s.", get_oper_name(si), entity(mu)->name);
			if (md)
				command_success_nodata(si, _("Overriding MARK placed by %s on the account %s."), md->value, entity(mu)->name);
			else
				command_success_nodata(si, _("Overriding MARK on the account %s."), entity(mu)->name);
		}
		logcommand(si, CMDLOG_ADMIN, "SENDPASS: \2%s\2 (change key)", name);

		key = random_string(12);
		metadata_add(mu, "private:sendpass:sender", get_oper_name(si));
		metadata_add(mu, "private:sendpass:timestamp", number_to_string(time(NULL)));

		if (!sendemail(si->su != NULL ? si->su : si->service->me, mu, EMAIL_SETPASS, mu->email, key))
		{
			command_fail(si, fault_emailfail, _("Email send failed."));
			free(key);
			return;
		}

		metadata_add(mu, "private:setpass:key", crypt_string(key, gen_salt()));
		free(key);

		command_success_nodata(si, _("The password change key for \2%s\2 has been sent to \2%s\2."), entity(mu)->name, mu->email);
	}
	else {
		if (ismarked)
		{
			wallops("%s sent the password for the \2MARKED\2 account %s.", get_oper_name(si), entity(mu)->name);
			if (md)
				command_success_nodata(si, _("Overriding MARK placed by %s on the account %s."), md->value, entity(mu)->name);
			else
				command_success_nodata(si, _("Overriding MARK on the account %s."), entity(mu)->name);
		}
		logcommand(si, CMDLOG_ADMIN, "SENDPASS: \2%s\2", name);

		newpass = random_string(12);
		metadata_add(mu, "private:sendpass:sender", get_oper_name(si));
		metadata_add(mu, "private:sendpass:timestamp", number_to_string(time(NULL)));

		if (!sendemail(si->su != NULL ? si->su : si->service->me, mu, EMAIL_SENDPASS, mu->email, newpass))
		{
			command_fail(si, fault_emailfail, _("Email send failed."));
			free(newpass);
			return;
		}

		set_password(mu, newpass);
		free(newpass);

		command_success_nodata(si, _("The password for \2%s\2 has been sent to \2%s\2."), entity(mu)->name, mu->email);

		if (mu->flags & MU_NOPASSWORD)
		{
			mu->flags &= ~MU_NOPASSWORD;
			command_success_nodata(si, _("The \2%s\2 flag has been removed for account \2%s\2."), "NOPASSWORD", entity(mu)->name);
		}
	}
}
コード例 #30
0
ファイル: ice.c プロジェクト: Zodiac-Evil/rtpengine
void ice_init(void) {
	random_string((void *) &tie_breaker, sizeof(tie_breaker));
	ice_agents_timers = g_tree_new(__ice_agent_timer_cmp);
}