uuid.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  1. /** BEGIN COPYRIGHT BLOCK
  2. * This Program is free software; you can redistribute it and/or modify it under
  3. * the terms of the GNU General Public License as published by the Free Software
  4. * Foundation; version 2 of the License.
  5. *
  6. * This Program is distributed in the hope that it will be useful, but WITHOUT
  7. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  8. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  9. *
  10. * You should have received a copy of the GNU General Public License along with
  11. * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple
  12. * Place, Suite 330, Boston, MA 02111-1307 USA.
  13. *
  14. * In addition, as a special exception, Red Hat, Inc. gives You the additional
  15. * right to link the code of this Program with code not covered under the GNU
  16. * General Public License ("Non-GPL Code") and to distribute linked combinations
  17. * including the two, subject to the limitations in this paragraph. Non-GPL Code
  18. * permitted under this exception must only link to the code of this Program
  19. * through those well defined interfaces identified in the file named EXCEPTION
  20. * found in the source code files (the "Approved Interfaces"). The files of
  21. * Non-GPL Code may instantiate templates or use macros or inline functions from
  22. * the Approved Interfaces without causing the resulting work to be covered by
  23. * the GNU General Public License. Only Red Hat, Inc. may make changes or
  24. * additions to the list of Approved Interfaces. You must obey the GNU General
  25. * Public License in all respects for all of the Program code and other code used
  26. * in conjunction with the Program except the Non-GPL Code covered by this
  27. * exception. If you modify this file, you may extend this exception to your
  28. * version of the file, but you are not obligated to do so. If you do not wish to
  29. * provide this exception without modification, you must delete this exception
  30. * statement from your version and license this file solely under the GPL without
  31. * exception.
  32. *
  33. *
  34. * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission.
  35. * Copyright (C) 2005 Red Hat, Inc.
  36. * All rights reserved.
  37. * END COPYRIGHT BLOCK **/
  38. /* uuid.c */
  39. /*
  40. ** Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc.
  41. ** Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. &
  42. ** Digital Equipment Corporation, Maynard, Mass.
  43. ** Copyright (c) 1998 Microsoft.
  44. ** To anyone who acknowledges that this file is provided "AS IS"
  45. ** without any express or implied warranty: permission to use, copy,
  46. ** modify, and distribute this file for any purpose is hereby
  47. ** granted without fee, provided that the above copyright notices and
  48. ** this notice appears in all source code copies, and that none of
  49. ** the names of Open Software Foundation, Inc., Hewlett-Packard
  50. ** Company, or Digital Equipment Corporation be used in advertising
  51. ** or publicity pertaining to distribution of the software without
  52. ** specific, written prior permission. Neither Open Software
  53. ** Foundation, Inc., Hewlett-Packard Company, Microsoft, nor Digital Equipment
  54. * Corporation makes any representations about the suitability of
  55. ** this software for any purpose.
  56. */
  57. #include <string.h>
  58. #include <stdio.h>
  59. #include <stdlib.h>
  60. #include <time.h>
  61. #include <pk11func.h>
  62. #ifdef _WIN32
  63. #include <sys/stat.h> /* for S_IREAD and S_IWRITE */
  64. #else
  65. #include <sys/types.h>
  66. #include <sys/time.h>
  67. #include <sys/sysinfo.h>
  68. #include <sys/utsname.h>
  69. #include <unistd.h> /* gethostname() */
  70. #endif
  71. #include "slap.h"
  72. #include "uuid.h"
  73. #include "sechash.h"
  74. #define SEQ_PER_SEC 10000000 /* number of 100ns intervals in a sec */
  75. #define STATE_FILE "state" /* file that contains generator's state */
  76. #define STATE_ATTR "nsState" /* attribute that stores state info */
  77. #define MODULE "uuid" /* for logging */
  78. #define UPDATE_INTERVAL 60000 /* 1 minute */
  79. #define NEED_TIME_UPDATE -1
  80. /* generates uuid in singlethreaded environment */
  81. static int uuid_create_st(guid_t *uuid);
  82. /* generates uuid in multithreaded environment */
  83. static int uuid_create_mt(guid_t *uuid);
  84. /* periodically called to update generator's state - mt case only */
  85. static void uuid_update_state (time_t when, void *arg);
  86. /* creates uuid in v1 format using current state info */
  87. static void format_uuid_v1(guid_t *uuid, uuid_time_t timestamp, unsigned16 clock_seq);
  88. /* generates uuid in v3 format */
  89. static void format_uuid_v3(guid_t *uuid, unsigned char hash[16]);
  90. /* reads state from a file or DIT entry */
  91. static int read_state (const char *configDir, const Slapi_DN *configDN, PRBool *newState);
  92. /* reads state from a file */
  93. static int read_state_from_file (const char *configDir);
  94. /* read state information from DIT */
  95. static int read_state_from_entry (const Slapi_DN *configDN);
  96. /* writes state to persistent store: file or dit */
  97. static int write_state(PRBool newState);
  98. /* writes state to a file */
  99. static int write_state_to_file();
  100. /* writes state to dit */
  101. static int write_state_to_entry(PRBool newState);
  102. /* add state entry to the dit */
  103. static int add_state_entry ();
  104. /* modify state entry in the dit */
  105. static int modify_state_entry ();
  106. /* generates timestamp for the next uuid - single threaded */
  107. static uuid_time_t update_time();
  108. /* generates timestamp for the next uuid - multithreaded threaded */
  109. static int update_time_mt(uuid_time_t *timestamp, unsigned16 *clock_seq);
  110. /* retrieves or generates nodeid */
  111. static int get_node_identifier(uuid_node_t *node);
  112. /* returns current time in the UTC format */
  113. static void get_system_time(uuid_time_t *uuid_time);
  114. /* generates random value - used to set clock sequence */
  115. static unsigned16 true_random(void);
  116. /* generate random info buffer to generate nodeid */
  117. static void get_random_info(unsigned char seed[16]);
  118. /* UUID generator state stored persistently */
  119. typedef struct
  120. {
  121. uuid_time_t timestamp; /* saved timestamp */
  122. uuid_node_t node; /* saved node ID */
  123. unsigned16 clockseq; /* saved clock sequence */
  124. unsigned8 last_update;/* flags the update made during server sutdown */
  125. } uuid_gen_state;
  126. /* generator state plus data to support it */
  127. typedef struct
  128. {
  129. uuid_gen_state genstate; /* generator state */
  130. int time_seq; /* sequence number to account for clock
  131. granularity; not written to disk */
  132. PRBool initialized; /* uniqueid successfully initialized */
  133. PRBool mtGen; /* multithreaded generation */
  134. PRLock *lock; /* lock to protect state */
  135. PRFileDesc *fd; /* fd for the state file */
  136. Slapi_DN *configDN; /* db entry that contains state info */
  137. } uuid_state;
  138. static unsigned int uuid_seed = 0; /* seed for the random generator */
  139. uuid_state _state; /* generator's state */
  140. /* uuid_init -- initializes uuid layer */
  141. int uuid_init (const char *configDir, const Slapi_DN *configDN, PRBool mtGen)
  142. {
  143. int rt;
  144. PRBool newState = PR_FALSE;
  145. if (_state.initialized)
  146. {
  147. slapi_log_error (SLAPI_LOG_FATAL, MODULE,
  148. "uuid_init: generator is already initialized\n");
  149. return UUID_SUCCESS;
  150. }
  151. memset (&_state, 0, sizeof (_state));
  152. /* get saved state */
  153. rt = read_state(configDir, configDN, &newState);
  154. if (rt != UUID_SUCCESS)
  155. {
  156. slapi_log_error (SLAPI_LOG_FATAL, MODULE,
  157. "uuid_init: failed to get generator's state\n");
  158. uuid_cleanup ();
  159. return rt;
  160. }
  161. _state.mtGen = mtGen;
  162. /* this is multithreaded generation - create lock */
  163. if (_state.mtGen)
  164. {
  165. _state.lock = PR_NewLock();
  166. if (!_state.lock)
  167. {
  168. PRErrorCode prerr = PR_GetError();
  169. slapi_log_error (SLAPI_LOG_FATAL, MODULE, "uuid_init: "
  170. "failed to create state lock; " SLAPI_COMPONENT_NAME_NSPR " error %d (%s).\n",
  171. prerr, slapd_pr_strerror(prerr));
  172. uuid_cleanup ();
  173. return UUID_LOCK_ERROR;
  174. }
  175. }
  176. /* save the state */
  177. rt = write_state(newState);
  178. /* can't proceede if the state can't be written */
  179. if (rt != UUID_SUCCESS)
  180. {
  181. if (slapi_config_get_readonly() &&
  182. (rt == UUID_LDAP_ERROR)) {
  183. /*
  184. * If server is readonly and error is UUID_LDAP_ERROR
  185. * we can continue.
  186. */
  187. slapi_log_error (SLAPI_LOG_FATAL, MODULE, "Warning: "
  188. "The server is in read-only mode, therefore the unique ID generator cannot be used. "
  189. "Do not use this server in any replication agreement\n");
  190. }
  191. else {
  192. slapi_log_error (SLAPI_LOG_FATAL, MODULE, "uuid_init: "
  193. "failed to save generator's state.\n");
  194. uuid_cleanup ();
  195. return rt;
  196. }
  197. }
  198. /* schedule update task for multithreaded generation */
  199. if (_state.mtGen)
  200. slapi_eq_repeat(uuid_update_state, NULL, (time_t)0, UPDATE_INTERVAL);
  201. _state.initialized = PR_TRUE;
  202. return UUID_SUCCESS;
  203. }
  204. /* uuid_cleanup -- saves state, destroys generator data */
  205. void uuid_cleanup ()
  206. {
  207. if (_state.initialized)
  208. {
  209. _state.genstate.last_update = 1;
  210. write_state (PR_FALSE);
  211. }
  212. if (_state.lock)
  213. PR_DestroyLock (_state.lock);
  214. if (_state.fd)
  215. PR_Close (_state.fd);
  216. if (_state.configDN)
  217. slapi_sdn_free(&_state.configDN);
  218. memset (&_state, 0, sizeof (_state));
  219. }
  220. /* uuid_create - main generating function */
  221. int uuid_create(guid_t *uuid)
  222. {
  223. if (_state.mtGen)
  224. return uuid_create_mt(uuid);
  225. else
  226. return uuid_create_st(uuid);
  227. }
  228. /* uuid_compare -- Compare two UUID's "lexically" and return
  229. -1 u1 is lexically before u2
  230. 0 u1 is equal to u2
  231. 1 u1 is lexically after u2
  232. Note: lexical ordering is not temporal ordering!
  233. */
  234. #define CHECK(f1, f2) if (f1 != f2) return f1 < f2 ? -1 : 1;
  235. int uuid_compare(const guid_t *u1, const guid_t *u2)
  236. {
  237. int i;
  238. CHECK(u1->time_low, u2->time_low);
  239. CHECK(u1->time_mid, u2->time_mid);
  240. CHECK(u1->time_hi_and_version, u2->time_hi_and_version);
  241. CHECK(u1->clock_seq_hi_and_reserved, u2->clock_seq_hi_and_reserved);
  242. CHECK(u1->clock_seq_low, u2->clock_seq_low)
  243. for (i = 0; i < 6; i++)
  244. {
  245. if (u1->node[i] < u2->node[i])
  246. return -1;
  247. if (u1->node[i] > u2->node[i])
  248. return 1;
  249. }
  250. return 0;
  251. }
  252. /* uuid_format -- converts UUID to its string representation
  253. buffer should be at list 40 bytes long
  254. */
  255. void uuid_format(const guid_t *u, char *buff)
  256. {
  257. sprintf(buff, "%8.8lx-%4.4x-%4.4x-%2.2x%2.2x-%2.2x%2.2x%2.2x%2.2x%2.2x%2.2x",
  258. u->time_low, u->time_mid, u->time_hi_and_version,
  259. u->clock_seq_hi_and_reserved, u->clock_seq_low, u->node[0],
  260. u->node[1], u->node[2], u->node[3], u->node[4], u->node[5]);
  261. }
  262. /* uuid_create_from_name -- create a UUID using a "name" from a "name space"
  263. */
  264. void uuid_create_from_name(guid_t * uuid, /* resulting UUID */
  265. const guid_t nsid, /* UUID to serve as context, so identical
  266. names from different name spaces generate
  267. different UUIDs */
  268. const void * name, /* the name from which to generate a UUID */
  269. int namelen) /* the length of the name */
  270. {
  271. PK11Context *c = NULL;
  272. unsigned char hash[16];
  273. unsigned int hashLen;
  274. guid_t net_nsid; /* context UUID in network byte order */
  275. memset(hash, 0, 16);
  276. /* put name space ID in network byte order so it hashes the same
  277. no matter what endian machine we're on */
  278. memset(&net_nsid, 0, sizeof(guid_t));
  279. net_nsid.time_low = PR_htonl(nsid.time_low);
  280. net_nsid.time_mid = PR_htons(nsid.time_mid);
  281. net_nsid.time_hi_and_version = PR_htons(nsid.time_hi_and_version);
  282. net_nsid.clock_seq_hi_and_reserved=nsid.clock_seq_hi_and_reserved;
  283. net_nsid.clock_seq_low=nsid.clock_seq_low;
  284. strncpy((char *)net_nsid.node, (char *)nsid.node, 6);
  285. c = PK11_CreateDigestContext(SEC_OID_MD5);
  286. if (c != NULL) {
  287. PK11_DigestBegin(c);
  288. PK11_DigestOp(c, (unsigned char *)&net_nsid, sizeof(net_nsid));
  289. PK11_DigestOp(c, (unsigned char *)name, namelen);
  290. PK11_DigestFinal(c, hash, &hashLen, 16);
  291. /* the hash is in network byte order at this point */
  292. format_uuid_v3(uuid, hash);
  293. PK11_DestroyContext(c, PR_TRUE);
  294. }
  295. else { /* Probably desesperate but at least deterministic... */
  296. memset(&uuid, 0, sizeof(uuid));
  297. }
  298. }
  299. /* Helper Functions */
  300. /* uuid_create_st -- singlethreaded generation */
  301. static int uuid_create_st(guid_t *uuid)
  302. {
  303. uuid_time_t timestamp;
  304. /* generate new time and save it in the state */
  305. timestamp = update_time ();
  306. /* stuff fields into the UUID */
  307. format_uuid_v1(uuid, timestamp, _state.genstate.clockseq);
  308. return UUID_SUCCESS;
  309. }
  310. /* uuid_create -- multithreaded generation */
  311. static int uuid_create_mt(guid_t *uuid)
  312. {
  313. uuid_time_t timestamp;
  314. unsigned16 clock_seq;
  315. /* just bumps time sequence number. the actual
  316. time calls are made by a uuid_update_state */
  317. update_time_mt (&timestamp, &clock_seq);
  318. if (timestamp == NEED_TIME_UPDATE)
  319. {
  320. slapi_log_error (SLAPI_LOG_FATAL, MODULE, "uuid_create_mt: generator ran "
  321. "out of sequence numbers.\n");
  322. return UUID_TIME_ERROR;
  323. }
  324. /* stuff fields into UUID */
  325. format_uuid_v1(uuid, timestamp, clock_seq);
  326. return UUID_SUCCESS;
  327. }
  328. /* uuid_update_state -- called periodically to update generator's state
  329. (multithreaded case only)
  330. */
  331. static void uuid_update_state (time_t when, void *arg)
  332. {
  333. uuid_time_t timestamp;
  334. get_system_time (&timestamp);
  335. /* time has not changed since last call - return */
  336. if (timestamp == _state.genstate.timestamp)
  337. return;
  338. PR_Lock (_state.lock);
  339. /* clock was set backward - insure uuid uniquness by incrementing clock sequence */
  340. if (timestamp < _state.genstate.timestamp)
  341. _state.genstate.clockseq ++;
  342. _state.genstate.timestamp = timestamp;
  343. _state.time_seq = 0;
  344. PR_Unlock (_state.lock);
  345. }
  346. /* read_state -- read UUID generator state from non-volatile store.
  347. */
  348. static int read_state(const char *configDir, const Slapi_DN *configDN, PRBool *newState)
  349. {
  350. uuid_time_t timestamp;
  351. int rt;
  352. if (configDN)
  353. rt = read_state_from_entry (configDN);
  354. else
  355. rt = read_state_from_file (configDir);
  356. if (rt == UUID_NOTFOUND)
  357. *newState = PR_TRUE;
  358. else
  359. *newState = PR_FALSE;
  360. if (rt != UUID_SUCCESS && rt != UUID_NOTFOUND) /* fatal error - bail out */
  361. {
  362. slapi_log_error (SLAPI_LOG_FATAL, MODULE,
  363. "read_state: failed to get generator's state\n");
  364. return rt;
  365. }
  366. /* get current time and nodeid */
  367. get_system_time(&timestamp);
  368. if (*newState) /* state info is missing - generate */
  369. {
  370. get_node_identifier (&_state.genstate.node);
  371. _state.genstate.clockseq = true_random();
  372. }
  373. else if(_state.genstate.last_update != 1)
  374. {
  375. /* clock sequence should be randomized and not just incremented
  376. because server's clock could have been set back before the
  377. server crashed in which case clock sequence was incremented */
  378. _state.genstate.clockseq = true_random();
  379. }
  380. else if (timestamp <= _state.genstate.timestamp)
  381. {
  382. _state.genstate.clockseq ++;
  383. }
  384. _state.genstate.timestamp = timestamp;
  385. _state.time_seq = 0;
  386. /* need to clear this field so that we know if the state information
  387. is written during shutdown (in which case this flag is set to 1 */
  388. _state.genstate.last_update = 0;
  389. return UUID_SUCCESS;
  390. }
  391. /* read_state_from_file -- read generator state from file.
  392. */
  393. static int read_state_from_file (const char *configDir)
  394. {
  395. char *path;
  396. int rt;
  397. if (configDir == NULL || configDir[0] == '\0')
  398. { /* this directory */
  399. path = (char*)slapi_ch_malloc(strlen (STATE_FILE) + 1);
  400. if (path == NULL)
  401. {
  402. slapi_log_error (SLAPI_LOG_FATAL, MODULE, "read_state: "
  403. "memory allocation failed.\n");
  404. return (UUID_MEMORY_ERROR);
  405. }
  406. strcpy (path, STATE_FILE);
  407. }
  408. else
  409. {
  410. path = slapi_ch_smprintf("%s/%s", configDir, STATE_FILE);
  411. if (path == NULL)
  412. {
  413. slapi_log_error (SLAPI_LOG_FATAL, MODULE, "read_state: "
  414. "memory allocation failed.\n");
  415. return (UUID_MEMORY_ERROR);
  416. }
  417. }
  418. /* open or create state file for read/write and keep it in sync */
  419. _state.fd = PR_Open(path, PR_RDWR | PR_CREATE_FILE | PR_SYNC,
  420. SLAPD_DEFAULT_FILE_MODE);
  421. slapi_ch_free ((void**)&path);
  422. if (!_state.fd)
  423. {
  424. PRErrorCode prerr = PR_GetError();
  425. slapi_log_error (SLAPI_LOG_FATAL, MODULE, "read_state: "
  426. "failed to open state file - %s; " SLAPI_COMPONENT_NAME_NSPR " error %d (%s).\n",
  427. path, prerr, slapd_pr_strerror(prerr));
  428. return (UUID_IO_ERROR);
  429. }
  430. rt = PR_Read (_state.fd, &_state.genstate, sizeof(uuid_gen_state));
  431. if (rt == 0) /* new state */
  432. {
  433. return UUID_NOTFOUND;
  434. }
  435. if (rt == -1)
  436. {
  437. PRErrorCode prerr = PR_GetError();
  438. slapi_log_error (SLAPI_LOG_FATAL, MODULE, "read_state: "
  439. "failed to read state information; " SLAPI_COMPONENT_NAME_NSPR " error %d (%s).\n",
  440. prerr, slapd_pr_strerror(prerr));
  441. return (UUID_IO_ERROR);
  442. }
  443. return(UUID_SUCCESS);
  444. }
  445. /* read_state_from_entry -- read generator state from DIT.
  446. */
  447. static int read_state_from_entry (const Slapi_DN *configDN)
  448. {
  449. Slapi_PBlock *pb;
  450. int res, rt;
  451. Slapi_Entry **entries;
  452. Slapi_Attr *attr;
  453. Slapi_Value *value;
  454. const struct berval *bv;
  455. _state.configDN = slapi_sdn_dup (configDN);
  456. pb = slapi_search_internal(slapi_sdn_get_ndn (configDN), LDAP_SCOPE_BASE,
  457. "objectclass=*", NULL, NULL, 0);
  458. if (pb == NULL)
  459. {
  460. /* the only time NULL pb is returned is when memory allocation fails */
  461. slapi_log_error (SLAPI_LOG_FATAL, MODULE, "read_state_from_entry: "
  462. "NULL pblock returned from search\n");
  463. return UUID_MEMORY_ERROR;
  464. }
  465. slapi_pblock_get(pb, SLAPI_PLUGIN_INTOP_RESULT, &res);
  466. if (res == LDAP_NO_SUCH_OBJECT)
  467. {
  468. rt = UUID_NOTFOUND;
  469. goto done;
  470. }
  471. if (res != LDAP_SUCCESS)
  472. {
  473. slapi_log_error (SLAPI_LOG_FATAL, MODULE, "read_state_from_entry: "
  474. "search operation failed; LDAP error - %d\n", res);
  475. rt = UUID_LDAP_ERROR;
  476. goto done;
  477. }
  478. slapi_pblock_get(pb, SLAPI_PLUGIN_INTOP_SEARCH_ENTRIES, &entries);
  479. if (entries == NULL || entries[0] == NULL)
  480. {
  481. rt = UUID_UNKNOWN_ERROR;
  482. goto done;
  483. }
  484. /* get state info */
  485. rt = slapi_entry_attr_find (entries[0], STATE_ATTR, &attr);
  486. if (rt != LDAP_SUCCESS)
  487. {
  488. rt = UUID_FORMAT_ERROR;
  489. goto done;
  490. }
  491. slapi_attr_first_value(attr,&value);
  492. if (value == NULL)
  493. {
  494. rt = UUID_FORMAT_ERROR;
  495. goto done;
  496. }
  497. bv = slapi_value_get_berval(value);
  498. if (bv == NULL || bv->bv_val == NULL || bv->bv_len != sizeof (_state.genstate))
  499. {
  500. rt = UUID_FORMAT_ERROR;
  501. goto done;
  502. }
  503. memcpy (&(_state.genstate), bv->bv_val, bv->bv_len);
  504. done:;
  505. if (pb)
  506. {
  507. slapi_free_search_results_internal(pb);
  508. slapi_pblock_destroy(pb);
  509. }
  510. return rt;
  511. }
  512. /* write_state -- save UUID generator state back to non-volatile
  513. storage. Writes immediately to the disk
  514. */
  515. static int write_state (PRBool newState)
  516. {
  517. if (_state.configDN) /* write to DIT */
  518. return write_state_to_entry (newState);
  519. else /* write to a file */
  520. return write_state_to_file ();
  521. }
  522. /* write_state_to_file -- stores state to state file
  523. */
  524. static int write_state_to_file()
  525. {
  526. int rt;
  527. rt = PR_Seek (_state.fd, 0, PR_SEEK_SET);
  528. if (rt == -1)
  529. {
  530. PRErrorCode prerr = PR_GetError();
  531. slapi_log_error (SLAPI_LOG_FATAL, MODULE, "write_state: "
  532. "failed to rewind state file; " SLAPI_COMPONENT_NAME_NSPR " error %d (%s).\n",
  533. prerr, slapd_pr_strerror(prerr));
  534. return UUID_IO_ERROR;
  535. }
  536. rt = PR_Write (_state.fd, &_state.genstate, sizeof (uuid_gen_state));
  537. if (rt == -1)
  538. {
  539. PRErrorCode prerr = PR_GetError();
  540. slapi_log_error (SLAPI_LOG_FATAL, MODULE, "write_state: "
  541. "failed to update state file; " SLAPI_COMPONENT_NAME_NSPR " error %d (%s).\n",
  542. prerr, slapd_pr_strerror(prerr));
  543. return (UUID_IO_ERROR);
  544. }
  545. return (UUID_SUCCESS);
  546. }
  547. /* write_state_to_entry -- stores state to state file
  548. */
  549. static int write_state_to_entry(PRBool newState) {
  550. if (newState)
  551. return add_state_entry ();
  552. else
  553. return modify_state_entry ();
  554. }
  555. /* add_state_entry -- add state entry to the dit */
  556. static int add_state_entry ()
  557. {
  558. struct berval *vals[2];
  559. struct berval val;
  560. Slapi_Entry *e;
  561. Slapi_PBlock *pb = NULL;
  562. const char *dn = slapi_sdn_get_ndn (_state.configDN);
  563. int rt;
  564. vals[0] = &val;
  565. vals[1] = NULL;
  566. e = slapi_entry_alloc();
  567. slapi_entry_set_dn(e, slapi_ch_strdup(dn));
  568. /* Set the objectclass attribute */
  569. val.bv_val = "top";
  570. val.bv_len = strlen (val.bv_val);
  571. slapi_entry_add_values(e, "objectclass", vals);
  572. val.bv_val = "extensibleObject";
  573. val.bv_len = strlen (val.bv_val);
  574. slapi_entry_add_values(e, "objectclass", vals);
  575. /* Set state attribute */
  576. val.bv_val = (char*)&(_state.genstate);
  577. val.bv_len = sizeof (_state.genstate);
  578. slapi_entry_add_values(e, STATE_ATTR, vals);
  579. /* this operation frees the entry */
  580. pb = slapi_add_entry_internal(e, 0, 0 /* log_change */);
  581. if (pb == NULL)
  582. {
  583. /* the only time NULL pb is returned is when memory allocation fails */
  584. slapi_log_error (SLAPI_LOG_FATAL, MODULE, "add_state_entry: "
  585. "NULL pblock returned from search\n");
  586. return UUID_MEMORY_ERROR;
  587. }
  588. else
  589. {
  590. slapi_pblock_get( pb, SLAPI_PLUGIN_INTOP_RESULT, &rt);
  591. slapi_ch_free((void **) &pb);
  592. }
  593. if (rt != LDAP_SUCCESS)
  594. {
  595. slapi_log_error (SLAPI_LOG_FATAL, MODULE, "add_state_entry: "
  596. "add operation failed; LDAP error - %d.\n", rt);
  597. return UUID_LDAP_ERROR;
  598. }
  599. slapi_log_error (SLAPI_LOG_HOUSE, MODULE, "add_state_entry: "
  600. "successfully added generator's state entry");
  601. return UUID_SUCCESS;
  602. }
  603. /* modify_state_entry -- modify state entry in the dit */
  604. static int modify_state_entry ()
  605. {
  606. int res;
  607. Slapi_Mods mods;
  608. struct berval *vals[2];
  609. struct berval val;
  610. Slapi_PBlock *pb;
  611. val.bv_val = (char*)&(_state.genstate);
  612. val.bv_len = sizeof (_state.genstate);
  613. vals[0] = &val;
  614. vals[1] = NULL;
  615. slapi_mods_init (&mods, 1);
  616. slapi_mods_add_modbvps(&mods, LDAP_MOD_REPLACE | LDAP_MOD_BVALUES, STATE_ATTR, vals);
  617. pb = slapi_modify_internal(slapi_sdn_get_ndn (_state.configDN),
  618. slapi_mods_get_ldapmods_byref(&mods), NULL, 0);
  619. slapi_mods_done(&mods);
  620. if (pb == NULL)
  621. {
  622. /* the only time NULL pb is returned is when memory allocation fails */
  623. slapi_log_error (SLAPI_LOG_FATAL, MODULE, "modify_state_entry: "
  624. "NULL pblock returned from search\n");
  625. return UUID_MEMORY_ERROR;
  626. }
  627. slapi_pblock_get(pb, SLAPI_PLUGIN_INTOP_RESULT, &res);
  628. slapi_pblock_destroy(pb);
  629. if (res != LDAP_SUCCESS)
  630. {
  631. slapi_log_error (SLAPI_LOG_FATAL, MODULE, "modify_state_entry: "
  632. "update operation failed; LDAP error - %d.\n", res);
  633. return UUID_LDAP_ERROR;
  634. }
  635. slapi_log_error (SLAPI_LOG_HOUSE, MODULE, "modify_state_entry: "
  636. "successfully updated generator's state entry");
  637. return UUID_SUCCESS;
  638. }
  639. /* update_time -- updates time portion of the generators state
  640. for singlethreaded generation
  641. */
  642. static uuid_time_t update_time()
  643. {
  644. uuid_time_t time_now;
  645. get_system_time(&time_now);
  646. /* time was turned back - need to change clocksequence */
  647. if (time_now < _state.genstate.timestamp)
  648. {
  649. _state.genstate.clockseq ++;
  650. _state.genstate.timestamp = time_now;
  651. _state.time_seq = 0;
  652. return _state.genstate.timestamp;
  653. }
  654. /* go into loop if the time has not changed since last call */
  655. while (time_now == _state.genstate.timestamp)
  656. {
  657. /* if we still have sequence numbers to give to the
  658. timestamp, use it and get out of the loop */
  659. if (_state.time_seq < SEQ_PER_SEC - 1)
  660. {
  661. _state.time_seq ++;
  662. break;
  663. }
  664. /* this should never happen because we don't generate more that 10 mln ids/sec */
  665. DS_Sleep (PR_MillisecondsToInterval(500));
  666. get_system_time(&time_now);
  667. }
  668. /* system time has changed - clear sequence number and
  669. update last time */
  670. if (time_now > _state.genstate.timestamp)
  671. {
  672. _state.time_seq = 0;
  673. _state.genstate.timestamp = time_now;
  674. }
  675. return _state.genstate.timestamp + _state.time_seq;
  676. }
  677. /* update_time_mt -- this function updates time sequence part of generators state.
  678. This function should be used in the multithreaded environment
  679. only.
  680. */
  681. static int update_time_mt (uuid_time_t *timestamp, unsigned16 *clock_seq)
  682. {
  683. PR_Lock (_state.lock);
  684. /* we ran out time sequence numbers because
  685. uuid_update_state function is not called
  686. frequently enough */
  687. if (_state.time_seq >= SEQ_PER_SEC - 1)
  688. {
  689. _state.time_seq = NEED_TIME_UPDATE;
  690. slapi_log_error (SLAPI_LOG_FATAL, MODULE, "update_time_mt: "
  691. "ran out of time sequence numbers; "
  692. "uuid_update_state must be called\n");
  693. PR_Unlock (_state.lock);
  694. return (UUID_TIME_ERROR);
  695. }
  696. _state.time_seq++;
  697. *timestamp = _state.genstate.timestamp + _state.time_seq;
  698. *clock_seq = _state.genstate.clockseq;
  699. PR_Unlock (_state.lock);
  700. return UUID_SUCCESS;
  701. }
  702. /* format_uuid_v1 -- make a UUID from the timestamp, clockseq,
  703. and node ID
  704. */
  705. static void format_uuid_v1(guid_t * uuid, uuid_time_t timestamp, unsigned16 clock_seq)
  706. {
  707. /* Construct a version 1 uuid with the information we've gathered
  708. * plus a few constants. */
  709. uuid->time_low = (unsigned32)(timestamp & 0xFFFFFFFF);
  710. uuid->time_mid = (unsigned16)((timestamp >> 32) & 0xFFFF);
  711. uuid->time_hi_and_version = (unsigned16)
  712. ((timestamp >> 48) & 0x0FFF);
  713. uuid->time_hi_and_version |= (1 << 12);
  714. uuid->clock_seq_low = clock_seq & 0xFF;
  715. uuid->clock_seq_hi_and_reserved = (unsigned8)(clock_seq & 0x3F00) >> 8;
  716. uuid->clock_seq_hi_and_reserved |= 0x80;
  717. memcpy(&uuid->node, &_state.genstate.node, sizeof (uuid->node));
  718. }
  719. /* format_uuid_v3 -- make a UUID from a (pseudo)random 128 bit number
  720. */
  721. static void format_uuid_v3(guid_t * uuid, unsigned char hash[16])
  722. {
  723. /* Construct a version 3 uuid with the (pseudo-)random number
  724. * plus a few constants. */
  725. memcpy(uuid, hash, sizeof(guid_t));
  726. /* convert UUID to local byte order */
  727. ntohl(uuid->time_low);
  728. ntohs(uuid->time_mid);
  729. ntohs(uuid->time_hi_and_version);
  730. /* put in the variant and version bits */
  731. uuid->time_hi_and_version &= 0x0FFF;
  732. uuid->time_hi_and_version |= (3 << 12);
  733. uuid->clock_seq_hi_and_reserved &= 0x3F;
  734. uuid->clock_seq_hi_and_reserved |= 0x80;
  735. }
  736. /* system dependent call to get IEEE node ID.
  737. This sample implementation generates a random node ID
  738. Assumes that configDir was tested for validity by
  739. the higher layer
  740. */
  741. static int get_node_identifier (uuid_node_t *node)
  742. {
  743. unsigned char seed[16]= {0};
  744. #ifdef USE_NIC
  745. /* ONREPL - code to use NIC address would go here; Currently, we use
  746. cryptographic random number to avoid state sharing among
  747. servers running on the same host. See UniqueID Generator
  748. docs for more info.
  749. */
  750. #endif
  751. get_random_info(seed);
  752. seed[0] |= 0x80;
  753. memcpy (node, seed, sizeof (uuid_node_t));
  754. return UUID_SUCCESS;
  755. }
  756. /* call to get the current system time. Returned as 100ns ticks
  757. since Oct 15, 1582, but resolution may be less than 100ns.
  758. */
  759. static void get_system_time(uuid_time_t *uuid_time)
  760. {
  761. time_t cur_time;
  762. cur_time = current_time ();
  763. /* Offset between UUID formatted times and time() formatted times.
  764. UUID UTC base time is October 15, 1582. time() base time is January 1, 1970.*/
  765. *uuid_time = cur_time * SEQ_PER_SEC + I64(0x01B21DD213814000);
  766. }
  767. /* ONREPL */
  768. /* true_random -- generate a crypto-quality random number.
  769. */
  770. static unsigned16 true_random(void)
  771. {
  772. static int inited = 0;
  773. if (!inited)
  774. {
  775. uuid_seed = slapi_rand();
  776. inited = 1;
  777. }
  778. return (slapi_rand_r(&uuid_seed));
  779. }
  780. static void get_random_info(unsigned char seed[16])
  781. {
  782. slapi_rand_array(seed, sizeof(seed));
  783. }