1 /*=========================================================================
2 
3   Program: GDCM (Grassroots DICOM). A DICOM library
4 
5   Copyright (c) 2006-2011 Mathieu Malaterre
6   All rights reserved.
7   See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html for details.
8 
9      This software is distributed WITHOUT ANY WARRANTY; without even
10      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
11      PURPOSE.  See the above copyright notice for more information.
12 
13 =========================================================================*/
14 #include "gdcmUUIDGenerator.h"
15 #include "gdcmTrace.h"
16 #include "gdcmSystem.h"
17 
18 #include <cstring> // memcpy
19 
20 // FIXME...
21 #if defined(_WIN32) || defined(__CYGWIN__)
22 #define HAVE_UUIDCREATE
23 #else
24 #define HAVE_UUID_GENERATE
25 #endif
26 
27 #ifdef HAVE_UUID_GENERATE
28 #include "gdcm_uuid.h"
29 #endif
30 
31 #ifdef GDCM_HAVE_RPC_H
32 #include <rpc.h>
33 #endif
34 
35 namespace gdcm
36 {
37 
Generate()38 const char* UUIDGenerator::Generate()
39 {
40   Unique.resize( 36 );
41   char *uuid_data = &Unique[0];
42 #if defined(HAVE_UUID_GENERATE)
43   assert( sizeof(uuid_t) == 16 );
44   uuid_t g;
45   uuid_generate(g);
46   uuid_unparse(g, uuid_data);
47 #elif defined(HAVE_UUID_CREATE)
48   uint32_t rv;
49   uuid_t g;
50   uuid_create(&g, &rv);
51   if (rv != uuid_s_ok) return NULL;
52   uuid_to_string(&g, &uuid_data, &rv);
53   if (rv != uuid_s_ok) return NULL;
54 #elif defined(HAVE_UUIDCREATE)
55   UUID uuid;
56   UuidCreate(&uuid);
57   unsigned char * str = 0;
58   UuidToString(&uuid, &str);
59   Unique = (char*)str;
60   RpcStringFree(&str);
61 #else
62 #error should not happen
63 #endif
64   assert( IsValid( Unique.c_str() ) );
65 
66   return Unique.c_str();
67 }
68 
IsValid(const char * suid)69 bool UUIDGenerator::IsValid(const char *suid)
70 {
71   if( !suid ) return false;
72 #if defined(HAVE_UUID_GENERATE)
73   uuid_t uu;
74   // technically the specification wants char* input not const char*:
75   // this makes compilation fails otherwise on OpenIndiana:
76   int res = uuid_parse((const char*)suid, uu);
77   if( res ) return false;
78 #elif defined(HAVE_UUID_CREATE)
79   // http://www.freebsd.org/cgi/man.cgi?query=uuid_create
80   uint32_t status;
81   uuid_t uuid;
82   uuid_from_string(suid, &uuid, &status);
83   if( status != uuid_s_ok	) return false;
84 #elif defined(HAVE_UUIDCREATE)
85   // http://msdn.microsoft.com/en-us/library/windows/desktop/aa379336(v=vs.85).aspx
86   UUID uuid;
87   if (FAILED(UuidFromString((unsigned char*)suid, &uuid)))
88     {
89     return false;
90     }
91 #else
92 #error should not happen
93 #endif
94   // no error found !
95   return true;
96 }
97 
98 
99 } // end namespace gdcm
100