1 /*=========================================================================
4 Module: $RCSfile: gdcmUtil.cxx,v $
6 Date: $Date: 2005/02/02 10:02:18 $
7 Version: $Revision: 1.129 $
9 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10 l'Image). All rights reserved. See Doc/License.txt or
11 http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
13 This software is distributed WITHOUT ANY WARRANTY; without even
14 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 PURPOSE. See the above copyright notices for more information.
17 =========================================================================*/
20 #include "gdcmDebug.h"
23 // For GetCurrentDate, GetCurrentTime
25 #include <sys/types.h>
28 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
29 #include <sys/timeb.h>
34 #include <stdarg.h> //only included in implementation file
35 #include <stdio.h> //only included in implementation file
37 #if defined(_MSC_VER) || defined(__MINGW32__)
38 #include <winsock.h> // for gethostname and gethostbyname
42 #include <unistd.h> // for gethostname
43 #include <netdb.h> // for gethostbyname
55 #include <sys/types.h>
58 #ifdef CMAKE_HAVE_SYS_IOCTL_H
59 #include <sys/ioctl.h> // For SIOCGIFCONF on Linux
61 #ifdef CMAKE_HAVE_SYS_SOCKET_H
62 #include <sys/socket.h>
64 #ifdef CMAKE_HAVE_SYS_SOCKIO_H
65 #include <sys/sockio.h> // For SIOCGIFCONF on SunOS
67 #ifdef CMAKE_HAVE_NET_IF_H
70 #ifdef CMAKE_HAVE_NETINET_IN_H
71 #include <netinet/in.h> //For IPPROTO_IP
73 #ifdef CMAKE_HAVE_NET_IF_DL_H
74 #include <net/if_dl.h>
76 #if defined(CMAKE_HAVE_NET_IF_ARP_H) && defined(__sun)
77 // This is absolutely necessary on SunOS
78 #include <net/if_arp.h>
81 // For GetCurrentThreadID()
83 #include <sys/types.h>
84 #include <linux/unistd.h>
92 //-------------------------------------------------------------------------
93 const std::string Util::GDCM_UID = "1.2.826.0.1.3680043.2.1143";
94 std::string Util::RootUID = GDCM_UID;
96 //-------------------------------------------------------------------------
98 * \brief Provide a better 'c++' approach for sprintf
99 * For example c code is:
100 * sprintf(trash, "%04x|%04x", group , elem);
103 * std::ostringstream buf;
104 * buf << std::right << std::setw(4) << std::setfill('0') << std::hex
105 * << group << "|" << std::right << std::setw(4) << std::setfill('0')
106 * << std::hex << elem;
110 * Format("%04x|%04x", group , elem);
112 std::string Util::Format(const char *format, ...)
116 va_start(args, format);
117 vsprintf(buffer, format, args); //might be a security flaw
118 va_end(args); // Each invocation of va_start should be matched
119 // by a corresponding invocation of va_end
120 // args is then 'undefined'
126 * \brief Because not available in C++ (?)
128 void Util::Tokenize (const std::string &str,
129 std::vector<std::string> &tokens,
130 const std::string &delimiters)
132 std::string::size_type lastPos = str.find_first_not_of(delimiters,0);
133 std::string::size_type pos = str.find_first_of (delimiters,lastPos);
134 while (std::string::npos != pos || std::string::npos != lastPos)
136 tokens.push_back(str.substr(lastPos, pos - lastPos));
137 lastPos = str.find_first_not_of(delimiters, pos);
138 pos = str.find_first_of (delimiters, lastPos);
143 * \brief Because not available in C++ (?)
144 * Counts the number of occurences of a substring within a string
147 int Util::CountSubstring (const std::string &str,
148 const std::string &subStr)
150 int count = 0; // counts how many times it appears
151 std::string::size_type x = 0; // The index position in the string
155 x = str.find(subStr,x); // Find the substring
156 if (x != std::string::npos) // If present
158 count++; // increase the count
159 x += subStr.length(); // Skip this word
162 while (x != std::string::npos); // Carry on until not present
168 * \brief Weed out a string from the non-printable characters (in order
169 * to avoid corrupting the terminal of invocation when printing)
170 * @param s string to remove non printable characters from
172 std::string Util::CreateCleanString(std::string const &s)
176 for(unsigned int i=0; i<str.size(); i++)
178 if(!isprint((unsigned char)str[i]))
186 if(!isprint((unsigned char)s[str.size()-1]))
188 if(s[str.size()-1] == 0)
190 str[str.size()-1] = ' ';
199 * \brief Add a SEPARATOR to the end of the name is necessary
200 * @param pathname file/directory name to normalize
202 std::string Util::NormalizePath(std::string const &pathname)
204 const char SEPARATOR_X = '/';
205 const char SEPARATOR_WIN = '\\';
206 const std::string SEPARATOR = "/";
207 std::string name = pathname;
208 int size = name.size();
210 if( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
218 * \brief Get the (directory) path from a full path file name
219 * @param fullName file/directory name to extract Path from
221 std::string Util::GetPath(std::string const &fullName)
223 std::string res = fullName;
224 int pos1 = res.rfind("/");
225 int pos2 = res.rfind("\\");
239 * \brief Get the (last) name of a full path file name
240 * @param fullName file/directory name to extract end name from
242 std::string Util::GetName(std::string const &fullName)
244 std::string filename = fullName;
246 std::string::size_type slash_pos = filename.rfind("/");
247 std::string::size_type backslash_pos = filename.rfind("\\");
248 slash_pos = slash_pos > backslash_pos ? slash_pos : backslash_pos;
249 if(slash_pos != std::string::npos)
251 return filename.substr(slash_pos + 1);
260 * \brief Get the current date of the system in a dicom string
262 std::string Util::GetCurrentDate()
267 strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
272 * \brief Get the current time of the system in a dicom string
274 std::string Util::GetCurrentTime()
279 strftime(tmp,512,"%H%M%S", localtime(&tloc) );
284 * \brief Get both the date and time at the same time to avoid problem
285 * around midnight where two call could be before and after midnight
287 std::string Util::GetCurrentDateTime()
293 // We need implementation specific functions to obtain millisecond precision
294 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
298 milliseconds = tb.millitm;
301 gettimeofday (&tv, NULL);
303 // Compute milliseconds from microseconds.
304 milliseconds = tv.tv_usec / 1000;
306 // Obtain the time of day, and convert it to a tm struct.
307 struct tm *ptm = localtime (&timep);
308 // Format the date and time, down to a single second.
309 strftime (tmp, sizeof (tmp), "%Y%m%d%H%M%S", ptm);
313 r += Format("%03ld", milliseconds);
319 * \brief Create a /DICOM/ string:
320 * It should a of even length (no odd length ever)
321 * It can contain as many (if you are reading this from your
322 * editor the following character is is backslash followed by zero
323 * that needed to be escaped with an extra backslash for doxygen) \\0
326 std::string Util::DicomString(const char *s, size_t l)
328 std::string r(s, s+l);
329 gdcmAssertMacro( !(r.size() % 2) ); // == basically 'l' is even
334 * \brief Create a /DICOM/ string:
335 * It should a of even length (no odd length ever)
336 * It can contain as many (if you are reading this from your
337 * editor the following character is is backslash followed by zero
338 * that needed to be escaped with an extra backslash for doxygen) \\0
340 * This function is similar to DicomString(const char*),
341 * except it doesn't take a length.
342 * It only pad with a null character if length is odd
344 std::string Util::DicomString(const char *s)
346 size_t l = strlen(s);
351 std::string r(s, s+l);
352 gdcmAssertMacro( !(r.size() % 2) );
357 * \brief Safely compare two Dicom String:
358 * - Both string should be of even length
359 * - We allow padding of even length string by either a null
360 * character of a space
362 bool Util::DicomStringEqual(const std::string &s1, const char *s2)
364 // s2 is the string from the DICOM reference: 'MONOCHROME1'
365 std::string s1_even = s1; //Never change input parameter
366 std::string s2_even = DicomString( s2 );
367 if( s1_even[s1_even.size()-1] == ' ')
369 s1_even[s1_even.size()-1] = '\0'; //replace space character by null
371 return s1_even == s2_even;
375 * \brief tells us if the processor we are working with is BigEndian or not
377 bool Util::IsCurrentProcessorBigEndian()
379 #ifdef GDCM_WORDS_BIGENDIAN
387 typedef BOOL(WINAPI * pSnmpExtensionInit) (
388 IN DWORD dwTimeZeroReference,
389 OUT HANDLE * hPollForTrapEvent,
390 OUT AsnObjectIdentifier * supportedView);
392 typedef BOOL(WINAPI * pSnmpExtensionTrap) (
393 OUT AsnObjectIdentifier * enterprise,
394 OUT AsnInteger * genericTrap,
395 OUT AsnInteger * specificTrap,
396 OUT AsnTimeticks * timeStamp,
397 OUT RFC1157VarBindList * variableBindings);
399 typedef BOOL(WINAPI * pSnmpExtensionQuery) (
401 IN OUT RFC1157VarBindList * variableBindings,
402 OUT AsnInteger * errorStatus,
403 OUT AsnInteger * errorIndex);
405 typedef BOOL(WINAPI * pSnmpExtensionInitEx) (
406 OUT AsnObjectIdentifier * supportedView);
410 int GetMacAddrSys ( unsigned char *addr )
414 if (WSAStartup(MAKEWORD(2, 0), &WinsockData) != 0)
416 std::cerr << "This program requires Winsock 2.x!" << std::endl;
420 HANDLE PollForTrapEvent;
421 AsnObjectIdentifier SupportedView;
422 UINT OID_ifEntryType[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 3 };
423 UINT OID_ifEntryNum[] = { 1, 3, 6, 1, 2, 1, 2, 1 };
424 UINT OID_ipMACEntAddr[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 6 };
425 AsnObjectIdentifier MIB_ifMACEntAddr = {
426 sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr };
427 AsnObjectIdentifier MIB_ifEntryType = {
428 sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType };
429 AsnObjectIdentifier MIB_ifEntryNum = {
430 sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum };
431 RFC1157VarBindList varBindList;
432 RFC1157VarBind varBind[2];
433 AsnInteger errorStatus;
434 AsnInteger errorIndex;
435 AsnObjectIdentifier MIB_NULL = { 0, 0 };
440 // Load the SNMP dll and get the addresses of the functions necessary
441 HINSTANCE m_hInst = LoadLibrary("inetmib1.dll");
442 if (m_hInst < (HINSTANCE) HINSTANCE_ERROR)
446 pSnmpExtensionInit m_Init =
447 (pSnmpExtensionInit) GetProcAddress(m_hInst, "SnmpExtensionInit");
448 pSnmpExtensionQuery m_Query =
449 (pSnmpExtensionQuery) GetProcAddress(m_hInst, "SnmpExtensionQuery");
450 m_Init(GetTickCount(), &PollForTrapEvent, &SupportedView);
452 /* Initialize the variable list to be retrieved by m_Query */
453 varBindList.list = varBind;
454 varBind[0].name = MIB_NULL;
455 varBind[1].name = MIB_NULL;
457 // Copy in the OID to find the number of entries in the
459 varBindList.len = 1; // Only retrieving one item
460 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryNum);
461 m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
463 // printf("# of adapters in this system : %i\n",
464 // varBind[0].value.asnValue.number);
467 // Copy in the OID of ifType, the type of interface
468 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryType);
470 // Copy in the OID of ifPhysAddress, the address
471 SNMP_oidcpy(&varBind[1].name, &MIB_ifMACEntAddr);
475 // Submit the query. Responses will be loaded into varBindList.
476 // We can expect this call to succeed a # of times corresponding
477 // to the # of adapters reported to be in the system
478 ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
486 // Confirm that the proper type has been returned
487 ret = SNMP_oidncmp(&varBind[0].name, &MIB_ifEntryType,
488 MIB_ifEntryType.idLength);
493 dtmp = varBind[0].value.asnValue.number;
495 // Type 6 describes ethernet interfaces
498 // Confirm that we have an address here
499 ret = SNMP_oidncmp(&varBind[1].name, &MIB_ifMACEntAddr,
500 MIB_ifMACEntAddr.idLength);
501 if ( !ret && varBind[1].value.asnValue.address.stream != NULL )
503 if ( (varBind[1].value.asnValue.address.stream[0] == 0x44)
504 && (varBind[1].value.asnValue.address.stream[1] == 0x45)
505 && (varBind[1].value.asnValue.address.stream[2] == 0x53)
506 && (varBind[1].value.asnValue.address.stream[3] == 0x54)
507 && (varBind[1].value.asnValue.address.stream[4] == 0x00) )
509 // Ignore all dial-up networking adapters
510 std::cerr << "Interface #" << j << " is a DUN adapter\n";
513 if ( (varBind[1].value.asnValue.address.stream[0] == 0x00)
514 && (varBind[1].value.asnValue.address.stream[1] == 0x00)
515 && (varBind[1].value.asnValue.address.stream[2] == 0x00)
516 && (varBind[1].value.asnValue.address.stream[3] == 0x00)
517 && (varBind[1].value.asnValue.address.stream[4] == 0x00)
518 && (varBind[1].value.asnValue.address.stream[5] == 0x00) )
520 // Ignore NULL addresses returned by other network
522 std::cerr << "Interface #" << j << " is a NULL address\n";
525 memcpy( addr, varBind[1].value.asnValue.address.stream, 6);
532 SNMP_FreeVarBind(&varBind[0]);
533 SNMP_FreeVarBind(&varBind[1]);
535 #endif //Win32 version
538 // implementation for POSIX system
540 //The POSIX version is broken anyway on Solaris, plus would require full
542 struct arpreq parpreq;
543 struct sockaddr_in *psa;
544 struct hostent *phost;
545 char hostname[MAXHOSTNAMELEN];
549 if(gethostname(hostname, MAXHOSTNAMELEN) != 0)
551 perror("gethostname");
554 phost = gethostbyname(hostname);
555 paddrs = phost->h_addr_list;
557 sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
563 memset(&parpreq, 0, sizeof(struct arpreq));
564 psa = (struct sockaddr_in *) &parpreq.arp_pa;
566 memset(psa, 0, sizeof(struct sockaddr_in));
567 psa->sin_family = AF_INET;
568 memcpy(&psa->sin_addr, *paddrs, sizeof(struct in_addr));
570 status = ioctl(sock, SIOCGARP, &parpreq);
576 memcpy(addr, parpreq.arp_ha.sa_data, 6);
580 #ifdef CMAKE_HAVE_NET_IF_H
582 struct ifreq ifr, *ifrp;
587 #if defined(AF_LINK) && (!defined(SIOCGIFHWADDR) && !defined(SIOCGENADDR))
588 struct sockaddr_dl *sdlp;
592 // BSD 4.4 defines the size of an ifreq to be
593 // max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len
594 // However, under earlier systems, sa_len isn't present, so the size is
595 // just sizeof(struct ifreq)
596 // We should investiage the use of SIZEOF_ADDR_IFREQ
600 #define max(a,b) ((a) > (b) ? (a) : (b))
602 #define ifreq_size(i) max(sizeof(struct ifreq),\
603 sizeof((i).ifr_name)+(i).ifr_addr.sa_len)
605 #define ifreq_size(i) sizeof(struct ifreq)
606 #endif // HAVE_SA_LEN
608 if( (sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0 )
612 memset(buf, 0, sizeof(buf));
613 ifc.ifc_len = sizeof(buf);
615 if (ioctl (sd, SIOCGIFCONF, (char *)&ifc) < 0)
621 for (i = 0; i < n; i+= ifreq_size(*ifrp) )
623 ifrp = (struct ifreq *)((char *) ifc.ifc_buf+i);
624 strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ);
626 if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0)
628 a = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
631 // In theory this call should also work on Sun Solaris, but apparently
632 // SIOCGENADDR is not implemented properly thus the call
633 // ioctl(sd, SIOCGENADDR, &ifr) always returns errno=2
634 // (No such file or directory)
635 // Furthermore the DLAPI seems to require full root access
636 if (ioctl(sd, SIOCGENADDR, &ifr) < 0)
638 a = (unsigned char *) ifr.ifr_enaddr;
641 sdlp = (struct sockaddr_dl *) &ifrp->ifr_addr;
642 if ((sdlp->sdl_family != AF_LINK) || (sdlp->sdl_alen != 6))
644 a = (unsigned char *) &sdlp->sdl_data[sdlp->sdl_nlen];
646 perror("No way to access hardware");
650 #endif // SIOCGENADDR
651 #endif // SIOCGIFHWADDR
652 if (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5]) continue;
663 // Not implemented platforms
664 perror("There was a configuration problem on your plateform");
671 * Mini function to return the last digit from a number express in base 256
672 * pre condition data contain an array of 6 unsigned char
673 * post condition carry contain the last digit
675 inline int getlastdigit(unsigned char *data)
677 int extended, carry = 0;
680 extended = (carry << 8) + data[i];
681 data[i] = extended / 10;
682 carry = extended % 10;
688 * \brief Encode the mac address on a fixed lenght string of 15 characters.
689 * we save space this way.
691 std::string Util::GetMACAddress()
693 // This code is the result of a long internet search to find something
694 // as compact as possible (not OS independant). We only have to separate
695 // 3 OS: Win32, SunOS and 'real' POSIX
696 // http://groups-beta.google.com/group/comp.unix.solaris/msg/ad36929d783d63be
697 // http://bdn.borland.com/article/0,1410,26040,00.html
698 unsigned char addr[6];
700 int stat = GetMacAddrSys(addr);
703 // We need to convert a 6 digit number from base 256 to base 10, using integer
704 // would requires a 48bits one. To avoid this we have to reimplement the div + modulo
711 res = getlastdigit(addr);
712 sres.insert(sres.begin(), '0' + res);
713 zero = (addr[0] == 0) && (addr[1] == 0) && (addr[2] == 0) && (addr[3] == 0) && (addr[4] == 0) && (addr[5] == 0);
720 gdcmVerboseMacro("Problem in finding the MAC Address");
726 * \brief Return the IP adress of the machine writting the DICOM image
728 std::string Util::GetIPAddress()
730 // This is a rip from
731 // http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
732 #ifndef HOST_NAME_MAX
733 // SUSv2 guarantees that `Host names are limited to 255 bytes'.
734 // POSIX 1003.1-2001 guarantees that `Host names (not including the
735 // terminating NUL) are limited to HOST_NAME_MAX bytes'.
736 #define HOST_NAME_MAX 255
737 // In this case we should maybe check the string was not truncated.
738 // But I don't known how to check that...
739 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
740 // with WinSock DLL we need to initialize the WinSock before using gethostname
741 WORD wVersionRequested = MAKEWORD(1,0);
743 int err = WSAStartup(wVersionRequested,&WSAData);
746 // Tell the user that we could not find a usable
753 #endif //HOST_NAME_MAX
756 char szHostName[HOST_NAME_MAX+1];
757 int r = gethostname(szHostName, HOST_NAME_MAX);
762 struct hostent *pHost = gethostbyname(szHostName);
764 for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
766 for( int j = 0; j<pHost->h_length; j++ )
768 if( j > 0 ) str += ".";
770 str += Util::Format("%u",
771 (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
773 // str now contains one local IP address
775 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
781 // If an error occur r == -1
782 // Most of the time it will return 127.0.0.1...
786 unsigned int Util::GetCurrentThreadID()
788 // FIXME the implementation is far from complete
789 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
790 return (unsigned int)GetCurrentThreadId();
794 // Doesn't work on fedora, but is in the man page...
795 //return (unsigned int)gettid();
798 return (unsigned int)thr_self();
800 //default implementation
805 unsigned int Util::GetCurrentProcessID()
807 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
808 // NOTE: There is also a _getpid()...
809 return (unsigned int)GetCurrentProcessId();
811 // get process identification, POSIX
812 return (unsigned int)getpid();
817 * \brief Creates a new UID. As stipulate in the DICOM ref
818 * each time a DICOM image is create it should have
819 * a unique identifier (URI)
820 * @param root is the DICOM prefix assigned by IOS group
822 std::string Util::CreateUniqueUID(const std::string &root)
828 // gdcm UID prefix, as supplied by http://www.medicalconnections.co.uk
836 // A root was specified use it to forge our new UID:
838 append += Util::GetMACAddress();
840 append += Util::GetCurrentDateTime();
842 //Also add a mini random number just in case:
843 int r = (int) (100.0*rand()/RAND_MAX);
844 append += Format("%02d", r);
846 // If append is too long we need to rehash it
847 if( (prefix + append).size() > 64 )
849 gdcmErrorMacro( "Size of UID is too long." );
850 // we need a hash function to truncate this number
851 // if only md5 was cross plateform
855 return prefix + append;
858 void Util::SetRootUID(const std::string &root)
866 const std::string &Util::GetRootUID()
871 //-------------------------------------------------------------------------
874 * @param os ostream to write to
878 std::ostream &binary_write(std::ostream &os, const T &val)
880 return os.write(reinterpret_cast<const char*>(&val), sizeof val);
884 * \brief binary_write binary_write
885 * @param os ostream to write to
888 std::ostream &binary_write(std::ostream &os, const uint16_t &val)
890 #ifdef GDCM_WORDS_BIGENDIAN
892 swap = ((( val << 8 ) & 0x0ff00 ) | (( val >> 8 ) & 0x00ff ) );
893 return os.write(reinterpret_cast<const char*>(&swap), 2);
895 return os.write(reinterpret_cast<const char*>(&val), 2);
896 #endif //GDCM_WORDS_BIGENDIAN
900 * \brief binary_write binary_write
901 * @param os ostream to write to
904 std::ostream &binary_write(std::ostream &os, const uint32_t &val)
906 #ifdef GDCM_WORDS_BIGENDIAN
908 swap = ( ((val<<24) & 0xff000000) | ((val<<8) & 0x00ff0000) |
909 ((val>>8) & 0x0000ff00) | ((val>>24) & 0x000000ff) );
910 return os.write(reinterpret_cast<const char*>(&swap), 4);
912 return os.write(reinterpret_cast<const char*>(&val), 4);
913 #endif //GDCM_WORDS_BIGENDIAN
917 * \brief binary_write binary_write
918 * @param os ostream to write to
921 std::ostream &binary_write(std::ostream &os, const char *val)
923 return os.write(val, strlen(val));
928 * @param os ostream to write to
931 std::ostream &binary_write(std::ostream &os, std::string const &val)
933 return os.write(val.c_str(), val.size());
936 //-------------------------------------------------------------------------
937 } // end namespace gdcm