xref: /PHP-8.0/ext/standard/uniqid.c (revision 2b5de6f8)
1 /*
2    +----------------------------------------------------------------------+
3    | Copyright (c) The PHP Group                                          |
4    +----------------------------------------------------------------------+
5    | This source file is subject to version 3.01 of the PHP license,      |
6    | that is bundled with this package in the file LICENSE, and is        |
7    | available through the world-wide-web at the following url:           |
8    | http://www.php.net/license/3_01.txt                                  |
9    | If you did not receive a copy of the PHP license and are unable to   |
10    | obtain it through the world-wide-web, please send a note to          |
11    | license@php.net so we can mail you a copy immediately.               |
12    +----------------------------------------------------------------------+
13    | Author: Stig Sæther Bakken <ssb@php.net>                             |
14    +----------------------------------------------------------------------+
15  */
16 
17 #include "php.h"
18 
19 #include <stdlib.h>
20 #if HAVE_UNISTD_H
21 #include <unistd.h>
22 #endif
23 
24 #include <string.h>
25 #include <errno.h>
26 
27 #include <stdio.h>
28 #ifdef PHP_WIN32
29 #include "win32/time.h"
30 #else
31 #include <sys/time.h>
32 #endif
33 
34 #include "php_lcg.h"
35 
36 #ifdef HAVE_GETTIMEOFDAY
37 ZEND_TLS struct timeval prev_tv = { 0, 0 };
38 
39 /* {{{ Generates a unique ID */
PHP_FUNCTION(uniqid)40 PHP_FUNCTION(uniqid)
41 {
42 	char *prefix = "";
43 	zend_bool more_entropy = 0;
44 	zend_string *uniqid;
45 	int sec, usec;
46 	size_t prefix_len = 0;
47 	struct timeval tv;
48 
49 	ZEND_PARSE_PARAMETERS_START(0, 2)
50 		Z_PARAM_OPTIONAL
51 		Z_PARAM_STRING(prefix, prefix_len)
52 		Z_PARAM_BOOL(more_entropy)
53 	ZEND_PARSE_PARAMETERS_END();
54 
55 	/* This implementation needs current microsecond to change,
56 	 * hence we poll time until it does. This is much faster than
57 	 * calling usleep(1) which may cause the kernel to schedule
58 	 * another process, causing a pause of around 10ms.
59 	 */
60 	do {
61 		(void)gettimeofday((struct timeval *) &tv, (struct timezone *) NULL);
62 	} while (tv.tv_sec == prev_tv.tv_sec && tv.tv_usec == prev_tv.tv_usec);
63 
64 	prev_tv.tv_sec = tv.tv_sec;
65 	prev_tv.tv_usec = tv.tv_usec;
66 
67 	sec = (int) tv.tv_sec;
68 	usec = (int) (tv.tv_usec % 0x100000);
69 
70 	/* The max value usec can have is 0xF423F, so we use only five hex
71 	 * digits for usecs.
72 	 */
73 	if (more_entropy) {
74 		uniqid = strpprintf(0, "%s%08x%05x%.8F", prefix, sec, usec, php_combined_lcg() * 10);
75 	} else {
76 		uniqid = strpprintf(0, "%s%08x%05x", prefix, sec, usec);
77 	}
78 
79 	RETURN_STR(uniqid);
80 }
81 #endif
82 /* }}} */
83