su_uniqueid.c 5.86 KB
Newer Older
Pekka Pessi's avatar
Pekka Pessi committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
/*
 * This file is part of the Sofia-SIP package
 *
 * Copyright (C) 2005 Nokia Corporation.
 *
 * Contact: Pekka Pessi <pekka.pessi@nokia.com>
 *
 * * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

/**@defgroup su_uniqueid GloballyUniqueIDs
 *
 * Globally unique IDs and random integers.
 *
 * GloballyUniqueID or #su_guid_t is a 128-bit identifier based on current
 * time and MAC address of the node generating the ID. A new ID is generated
 * each time su_guid_generate() is called. Please note that such IDs are @b
 * not unique if multiple processes are run on the same node.
 *
 * Use su_guid_sprintf() to convert #su_guid_t to printable format.
 * 
 * The random integers can be generated with functions
 * - su_randint(),
 * - su_randmem(), or
 * - su_random().
 */

/**@ingroup su_uniqueid
 *
 * @CFILE su_uniqueid.c Construct a GloballyUniqueID as per H.225.0 v2.
 *
 * @author Pekka Pessi <pessi@research.nokia.com>
 * 
 * @date Created: Tue Apr 15 06:31:41 1997 pessi
 * $Date: 2005/07/20 20:35:59 $
 */

#include "config.h"

const char su_uniqueid_c_id[] = 
"$Id: su_uniqueid.c,v 1.1.1.1 2005/07/20 20:35:59 kaiv Exp $";

#if defined(_WIN32)
int _getpid(void);
#define getpid _getpid
#endif

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#if HAVE_UNISTD_H
#include <sys/types.h>
#include <unistd.h>
#endif

#include "su.h"
#include "su_time.h"
#include "su_uniqueid.h"

char su_uniqueid_h_id[] = SU_UNIQUEID_H;

/* For random number generator */
static int initialized = 0;

static void init(void);

/* Constants */
static const unsigned version = 1;	/* Current version */
static const unsigned reserved = 128;	/* DCE variant */
#define granularity (10000000UL)
static const uint64_t mask60 = SU_U64_C(0xfffFFFFffffFFFF);
#define MAGIC (16384)

/* 100-nanosecond intervals between 15 October 1582 and 1 January 1900 */
static const uint64_t ntp_epoch = 
(uint64_t)(141427) * (24 * 60 * 60L) * granularity;

/* State */
static uint64_t timestamp0 = 0;
static unsigned clock_sequence = MAGIC;
static unsigned char node[6];

/*
 * Get current timestamp
 */
static uint64_t timestamp(void)
{
  uint64_t tl = su_ntp_now();
  uint64_t hi = su_ntp_hi(tl), lo = su_ntp_lo(tl);
  
  lo *= granularity;
  hi *= granularity;

  tl = hi + (lo >> 32) + ntp_epoch;

#ifdef TESTING
  printf("timestamp %08x-%08x\n", (unsigned)(tl >>32), (unsigned)tl);
#endif

  tl &= mask60;

  if (tl <= timestamp0) {
    clock_sequence++;
    clock_sequence &= MAGIC - 1;
  }

  timestamp0 = tl;

  return tl;
}

#if !HAVE_RANDOM
#define random() rand()
#define srandom(x) srand(x)
#endif

/*
 * Initialize clock_sequence and timestamp0
 */
static void init(void)
{
  int i;

  static uint32_t seed[32] = { 0 };
  su_time_t now;

  initialized = 1;

  /* Initialize our random number generator */
  for (i = 0; i < 16; i++) {
#if HAVE_CLOCK_GETTIME
    struct timespec ts;
    (void)clock_gettime(CLOCK_REALTIME, &ts);
    seed[2*i] ^= ts.tv_sec; seed[2*i+1] ^= ts.tv_nsec; 
#endif
    su_time(&now);
    seed[2*i] ^= now.tv_sec; seed[2*i+1] ^= now.tv_sec;     
  }

  seed[30] ^= getuid(); 
  seed[31] ^= getpid();

#if HAVE_INITSTATE
  initstate(seed[0] ^ seed[1], (char *)&seed, sizeof(seed));
#else
  srand(seed[0] ^ seed[1]);
#endif

  clock_sequence = su_randint(0, MAGIC - 1);

  (void)timestamp();

  for (i = 0; i < sizeof(node); i++) {
    unsigned r = random();
    node[i] = (r >> 24) ^ (r >> 16) ^ (r >> 8) ^ r;
  }

  node[0] |= 1;			/* "multicast" address */
}

void su_guid_generate(su_guid_t *v)
{
  uint64_t time;
  unsigned clock;

  if (!initialized) init(); 

  time = timestamp();
  clock = clock_sequence;

  v->s.time_high_and_version = 
    htons((unsigned short)(((time >> 48) & 0x0fff) | (version << 12)));
  v->s.time_mid = htons((unsigned short)((time >> 32) & 0xffff));
  v->s.time_low = htonl((unsigned long)(time & 0xffffffffUL));
  v->s.clock_seq_low = clock & 0xff;
  v->s.clock_seq_hi_and_reserved = (clock >> 8) | reserved;
  memcpy(v->s.node, node, sizeof(v->s.node));
}

/*
 * Human-readable form of GloballyUniqueID
 */
int su_guid_sprintf(char* buf, size_t len, su_guid_t const *v) {
  char mybuf[su_guid_strlen + 1];
  sprintf(mybuf, "%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
	  (unsigned long)ntohl(v->s.time_low),
	  ntohs(v->s.time_mid),
	  ntohs(v->s.time_high_and_version),
	  v->s.clock_seq_low,
	  v->s.clock_seq_hi_and_reserved,
	  v->s.node[0], v->s.node[1], v->s.node[2], 
	  v->s.node[3], v->s.node[4], v->s.node[5]);
  memcpy(buf, mybuf, len > sizeof(mybuf) ? sizeof(mybuf) : len);
  return su_guid_strlen;
}

/* 
 * Generate random integer in range [lb, ub] (inclusive) 
 */
int su_randint(int lb, int ub)
{
  unsigned rnd = 0;

  if (!initialized) init(); 

  rnd = random();

  if (ub - lb + 1 != 0)
    rnd %= (ub - lb + 1);

  return rnd + lb;
}

void *su_randmem(void *mem, size_t siz)
{
  size_t i;

  if (!initialized) init(); 

  for (i = 0; i < siz; i++) {
    unsigned r = random();
    ((char *)mem)[i] = (r >> 24) ^ (r >> 16) ^ (r >> 8) ^ r;
  }

  return mem;
}

/** Get random number for RTP timestamps. 
 *
 * This function returns a 32-bit random integer. It also initializes the
 * random number generator, if needed.
 */
uint32_t su_random(void)
{
  if (!initialized) init(); 

  return (uint32_t)random();
}