1 /*=========================================================================
4 Module: $RCSfile: gdcmUtil.cxx,v $
6 Date: $Date: 2005/01/25 15:35:15 $
7 Version: $Revision: 1.123 $
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 & 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>
93 * \brief Provide a better 'c++' approach for sprintf
94 * For example c code is:
95 * sprintf(trash, "%04x|%04x", group , elem);
98 * std::ostringstream buf;
99 * buf << std::right << std::setw(4) << std::setfill('0') << std::hex
100 * << group << "|" << std::right << std::setw(4) << std::setfill('0')
101 * << std::hex << elem;
105 * Format("%04x|%04x", group , elem);
108 std::string Util::Format(const char *format, ...)
112 va_start(args, format);
113 vsprintf(buffer, format, args); //might be a security flaw
114 va_end(args); // Each invocation of va_start should be matched
115 // by a corresponding invocation of va_end
116 // args is then 'undefined'
122 * \brief Because not available in C++ (?)
124 void Util::Tokenize (const std::string &str,
125 std::vector<std::string> &tokens,
126 const std::string& delimiters)
128 std::string::size_type lastPos = str.find_first_not_of(delimiters,0);
129 std::string::size_type pos = str.find_first_of (delimiters,lastPos);
130 while (std::string::npos != pos || std::string::npos != lastPos)
132 tokens.push_back(str.substr(lastPos, pos - lastPos));
133 lastPos = str.find_first_not_of(delimiters, pos);
134 pos = str.find_first_of (delimiters, lastPos);
139 * \brief Because not available in C++ (?)
140 * Counts the number of occurences of a substring within a string
143 int Util::CountSubstring (const std::string &str,
144 const std::string &subStr)
146 int count = 0; // counts how many times it appears
147 std::string::size_type x = 0; // The index position in the string
151 x = str.find(subStr,x); // Find the substring
152 if (x != std::string::npos) // If present
154 count++; // increase the count
155 x += subStr.length(); // Skip this word
158 while (x != std::string::npos); // Carry on until not present
164 * \brief Weed out a string from the non-printable characters (in order
165 * to avoid corrupting the terminal of invocation when printing)
166 * @param s string to remove non printable characters from
168 std::string Util::CreateCleanString(std::string const &s)
172 for(unsigned int i=0; i<str.size(); i++)
174 if(!isprint((unsigned char)str[i]))
182 if(!isprint((unsigned char)s[str.size()-1]))
184 if(s[str.size()-1] == 0)
186 str[str.size()-1] = ' ';
195 * \brief Add a SEPARATOR to the end of the name is necessary
196 * @param pathname file/directory name to normalize
198 std::string Util::NormalizePath(std::string const &pathname)
200 const char SEPARATOR_X = '/';
201 const char SEPARATOR_WIN = '\\';
202 const std::string SEPARATOR = "/";
203 std::string name = pathname;
204 int size = name.size();
206 if( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
214 * \brief Get the (directory) path from a full path file name
215 * @param fullName file/directory name to extract Path from
217 std::string Util::GetPath(std::string const &fullName)
219 std::string res = fullName;
220 int pos1 = res.rfind("/");
221 int pos2 = res.rfind("\\");
235 * \brief Get the (last) name of a full path file name
236 * @param fullName file/directory name to extract end name from
238 std::string Util::GetName(std::string const &fullName)
240 std::string filename = fullName;
242 std::string::size_type slash_pos = filename.rfind("/");
243 std::string::size_type backslash_pos = filename.rfind("\\");
244 slash_pos = slash_pos > backslash_pos ? slash_pos : backslash_pos;
245 if(slash_pos != std::string::npos)
247 return filename.substr(slash_pos + 1);
256 * \brief Get the current date of the system in a dicom string
258 std::string Util::GetCurrentDate()
263 strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
268 * \brief Get the current time of the system in a dicom string
270 std::string Util::GetCurrentTime()
275 strftime(tmp,512,"%H%M%S", localtime(&tloc) );
280 * \brief Get both the date and time at the same time to avoid problem
281 * around midnight where two call could be before and after midnight
283 std::string Util::GetCurrentDateTime()
289 // We need implementation specific functions to obtain millisecond precision
290 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
294 milliseconds = tb.millitm;
297 gettimeofday (&tv, NULL);
299 // Compute milliseconds from microseconds.
300 milliseconds = tv.tv_usec / 1000;
302 // Obtain the time of day, and convert it to a tm struct.
303 struct tm *ptm = localtime (&timep);
304 // Format the date and time, down to a single second.
305 strftime (tmp, sizeof (tmp), "%Y%m%d%H%M%S", ptm);
309 r += Format("%03ld", milliseconds);
315 * \brief Create a /DICOM/ string:
316 * It should a of even length (no odd length ever)
317 * It can contain as many (if you are reading this from your
318 * editor the following character is is backslash followed by zero
319 * that needed to be escaped with an extra backslash for doxygen) \\0
322 std::string Util::DicomString(const char *s, size_t l)
324 std::string r(s, s+l);
325 gdcmAssertMacro( !(r.size() % 2) ); // == basically 'l' is even
330 * \brief Create a /DICOM/ string:
331 * It should a of even length (no odd length ever)
332 * It can contain as many (if you are reading this from your
333 * editor the following character is is backslash followed by zero
334 * that needed to be escaped with an extra backslash for doxygen) \\0
336 * This function is similar to DicomString(const char*),
337 * except it doesn't take a length.
338 * It only pad with a null character if length is odd
340 std::string Util::DicomString(const char *s)
342 size_t l = strlen(s);
347 std::string r(s, s+l);
348 gdcmAssertMacro( !(r.size() % 2) );
353 * \brief Safely compare two Dicom String:
354 * - Both string should be of even length
355 * - We allow padding of even length string by either a null
356 * character of a space
358 bool Util::DicomStringEqual(const std::string &s1, const char *s2)
360 // s2 is the string from the DICOM reference: 'MONOCHROME1'
361 std::string s1_even = s1; //Never change input parameter
362 std::string s2_even = DicomString( s2 );
363 if( s1_even[s1_even.size()-1] == ' ')
365 s1_even[s1_even.size()-1] = '\0'; //replace space character by null
367 return s1_even == s2_even;
371 * \brief tells us if the processor we are working with is BigEndian or not
373 bool Util::IsCurrentProcessorBigEndian()
375 #ifdef GDCM_WORDS_BIGENDIAN
385 typedef BOOL(WINAPI * pSnmpExtensionInit) (
386 IN DWORD dwTimeZeroReference,
387 OUT HANDLE * hPollForTrapEvent,
388 OUT AsnObjectIdentifier * supportedView);
390 typedef BOOL(WINAPI * pSnmpExtensionTrap) (
391 OUT AsnObjectIdentifier * enterprise,
392 OUT AsnInteger * genericTrap,
393 OUT AsnInteger * specificTrap,
394 OUT AsnTimeticks * timeStamp,
395 OUT RFC1157VarBindList * variableBindings);
397 typedef BOOL(WINAPI * pSnmpExtensionQuery) (
399 IN OUT RFC1157VarBindList * variableBindings,
400 OUT AsnInteger * errorStatus,
401 OUT AsnInteger * errorIndex);
403 typedef BOOL(WINAPI * pSnmpExtensionInitEx) (
404 OUT AsnObjectIdentifier * supportedView);
408 int GetMacAddrSys ( unsigned char *addr )
412 if (WSAStartup(MAKEWORD(2, 0), &WinsockData) != 0)
414 std::cerr << "This program requires Winsock 2.x!" << std::endl;
418 HANDLE PollForTrapEvent;
419 AsnObjectIdentifier SupportedView;
420 UINT OID_ifEntryType[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 3 };
421 UINT OID_ifEntryNum[] = { 1, 3, 6, 1, 2, 1, 2, 1 };
422 UINT OID_ipMACEntAddr[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 6 };
423 AsnObjectIdentifier MIB_ifMACEntAddr = {
424 sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr };
425 AsnObjectIdentifier MIB_ifEntryType = {
426 sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType };
427 AsnObjectIdentifier MIB_ifEntryNum = {
428 sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum };
429 RFC1157VarBindList varBindList;
430 RFC1157VarBind varBind[2];
431 AsnInteger errorStatus;
432 AsnInteger errorIndex;
433 AsnObjectIdentifier MIB_NULL = { 0, 0 };
438 // Load the SNMP dll and get the addresses of the functions necessary
439 HINSTANCE m_hInst = LoadLibrary("inetmib1.dll");
440 if (m_hInst < (HINSTANCE) HINSTANCE_ERROR)
444 pSnmpExtensionInit m_Init =
445 (pSnmpExtensionInit) GetProcAddress(m_hInst, "SnmpExtensionInit");
446 pSnmpExtensionQuery m_Query =
447 (pSnmpExtensionQuery) GetProcAddress(m_hInst, "SnmpExtensionQuery");
448 m_Init(GetTickCount(), &PollForTrapEvent, &SupportedView);
450 /* Initialize the variable list to be retrieved by m_Query */
451 varBindList.list = varBind;
452 varBind[0].name = MIB_NULL;
453 varBind[1].name = MIB_NULL;
455 // Copy in the OID to find the number of entries in the
457 varBindList.len = 1; // Only retrieving one item
458 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryNum);
459 m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
461 // printf("# of adapters in this system : %i\n",
462 // varBind[0].value.asnValue.number);
465 // Copy in the OID of ifType, the type of interface
466 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryType);
468 // Copy in the OID of ifPhysAddress, the address
469 SNMP_oidcpy(&varBind[1].name, &MIB_ifMACEntAddr);
473 // Submit the query. Responses will be loaded into varBindList.
474 // We can expect this call to succeed a # of times corresponding
475 // to the # of adapters reported to be in the system
476 ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
484 // Confirm that the proper type has been returned
485 ret = SNMP_oidncmp(&varBind[0].name, &MIB_ifEntryType,
486 MIB_ifEntryType.idLength);
491 dtmp = varBind[0].value.asnValue.number;
493 // Type 6 describes ethernet interfaces
496 // Confirm that we have an address here
497 ret = SNMP_oidncmp(&varBind[1].name, &MIB_ifMACEntAddr,
498 MIB_ifMACEntAddr.idLength);
499 if ( !ret && varBind[1].value.asnValue.address.stream != NULL )
501 if ( (varBind[1].value.asnValue.address.stream[0] == 0x44)
502 && (varBind[1].value.asnValue.address.stream[1] == 0x45)
503 && (varBind[1].value.asnValue.address.stream[2] == 0x53)
504 && (varBind[1].value.asnValue.address.stream[3] == 0x54)
505 && (varBind[1].value.asnValue.address.stream[4] == 0x00) )
507 // Ignore all dial-up networking adapters
508 std::cerr << "Interface #" << j << " is a DUN adapter\n";
511 if ( (varBind[1].value.asnValue.address.stream[0] == 0x00)
512 && (varBind[1].value.asnValue.address.stream[1] == 0x00)
513 && (varBind[1].value.asnValue.address.stream[2] == 0x00)
514 && (varBind[1].value.asnValue.address.stream[3] == 0x00)
515 && (varBind[1].value.asnValue.address.stream[4] == 0x00)
516 && (varBind[1].value.asnValue.address.stream[5] == 0x00) )
518 // Ignore NULL addresses returned by other network
520 std::cerr << "Interface #" << j << " is a NULL address\n";
523 memcpy( addr, varBind[1].value.asnValue.address.stream, 6);
530 SNMP_FreeVarBind(&varBind[0]);
531 SNMP_FreeVarBind(&varBind[1]);
533 #endif //Win32 version
536 // implementation for POSIX system
538 //The POSIX version is broken anyway on Solaris, plus would require full
540 struct arpreq parpreq;
541 struct sockaddr_in *psa;
542 struct hostent *phost;
543 char hostname[MAXHOSTNAMELEN];
547 if(gethostname(hostname, MAXHOSTNAMELEN) != 0)
549 perror("gethostname");
552 phost = gethostbyname(hostname);
553 paddrs = phost->h_addr_list;
555 sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
561 memset(&parpreq, 0, sizeof(struct arpreq));
562 psa = (struct sockaddr_in *) &parpreq.arp_pa;
564 memset(psa, 0, sizeof(struct sockaddr_in));
565 psa->sin_family = AF_INET;
566 memcpy(&psa->sin_addr, *paddrs, sizeof(struct in_addr));
568 status = ioctl(sock, SIOCGARP, &parpreq);
574 memcpy(addr, parpreq.arp_ha.sa_data, 6);
578 #ifdef CMAKE_HAVE_NET_IF_H
580 struct ifreq ifr, *ifrp;
585 #if defined(AF_LINK) && (!defined(SIOCGIFHWADDR) && !defined(SIOCGENADDR))
586 struct sockaddr_dl *sdlp;
590 // BSD 4.4 defines the size of an ifreq to be
591 // max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len
592 // However, under earlier systems, sa_len isn't present, so the size is
593 // just sizeof(struct ifreq)
594 // We should investiage the use of SIZEOF_ADDR_IFREQ
598 #define max(a,b) ((a) > (b) ? (a) : (b))
600 #define ifreq_size(i) max(sizeof(struct ifreq),\
601 sizeof((i).ifr_name)+(i).ifr_addr.sa_len)
603 #define ifreq_size(i) sizeof(struct ifreq)
604 #endif // HAVE_SA_LEN
606 if( (sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0 )
610 memset(buf, 0, sizeof(buf));
611 ifc.ifc_len = sizeof(buf);
613 if (ioctl (sd, SIOCGIFCONF, (char *)&ifc) < 0)
619 for (i = 0; i < n; i+= ifreq_size(*ifrp) )
621 ifrp = (struct ifreq *)((char *) ifc.ifc_buf+i);
622 strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ);
624 if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0)
626 a = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
629 // In theory this call should also work on Sun Solaris, but apparently
630 // SIOCGENADDR is not implemented properly thus the call
631 // ioctl(sd, SIOCGENADDR, &ifr) always returns errno=2
632 // (No such file or directory)
633 // Furthermore the DLAPI seems to require full root access
634 if (ioctl(sd, SIOCGENADDR, &ifr) < 0)
636 a = (unsigned char *) ifr.ifr_enaddr;
639 sdlp = (struct sockaddr_dl *) &ifrp->ifr_addr;
640 if ((sdlp->sdl_family != AF_LINK) || (sdlp->sdl_alen != 6))
642 a = (unsigned char *) &sdlp->sdl_data[sdlp->sdl_nlen];
644 perror("No way to access hardware");
648 #endif // SIOCGENADDR
649 #endif // SIOCGIFHWADDR
650 if (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5]) continue;
661 // Not implemented platforms
662 perror("There was a configuration problem on your plateform");
669 * \brief Encode the mac address on a fixed lenght string of 15 characters.
670 * we save space this way.
672 std::string Util::GetMACAddress()
674 // This code is the result of a long internet search to find something
675 // as compact as possible (not OS independant). We only have to separate
676 // 3 OS: Win32, SunOS and 'real' POSIX
677 // http://groups-beta.google.com/group/comp.unix.solaris/msg/ad36929d783d63be
678 // http://bdn.borland.com/article/0,1410,26040,00.html
679 unsigned char addr[6];
682 int stat = GetMacAddrSys(addr);
686 for(int i=0; i<6; i++)
692 // we fit on 15 bytes maximum < 256^6.
693 #if defined(_MSC_VER) || defined(__BORLANDC__)
694 return Format("%I64u", n);
696 return Format("%llu", n);
701 gdcmVerboseMacro("Problem in finding the MAC Address");
707 * \brief Return the IP adress of the machine writting the DICOM image
709 std::string Util::GetIPAddress()
711 // This is a rip from
712 // http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
713 #ifndef HOST_NAME_MAX
714 // SUSv2 guarantees that `Host names are limited to 255 bytes'.
715 // POSIX 1003.1-2001 guarantees that `Host names (not including the
716 // terminating NUL) are limited to HOST_NAME_MAX bytes'.
717 # define HOST_NAME_MAX 255
718 // In this case we should maybe check the string was not truncated.
719 // But I don't known how to check that...
720 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
721 // with WinSock DLL we need to initialize the WinSock before using gethostname
722 WORD wVersionRequested = MAKEWORD(1,0);
724 int err = WSAStartup(wVersionRequested,&WSAData);
727 // Tell the user that we could not find a usable
734 #endif //HOST_NAME_MAX
737 char szHostName[HOST_NAME_MAX+1];
738 int r = gethostname(szHostName, HOST_NAME_MAX);
743 struct hostent *pHost = gethostbyname(szHostName);
745 for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
747 for( int j = 0; j<pHost->h_length; j++ )
749 if( j > 0 ) str += ".";
751 str += Util::Format("%u",
752 (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
754 // str now contains one local IP address
756 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
762 // If an error occur r == -1
763 // Most of the time it will return 127.0.0.1...
768 * \brief Creates a new UID. As stipulate in the DICOM ref
769 * each time a DICOM image is create it should have
770 * a unique identifier (URI)
771 * @param root is the DICOM prefix assigned by IOS group
773 std::string Util::CreateUniqueUID(const std::string &root)
775 std::string prefix = root;
779 // No root was specified use "GDCM" then
780 // echo "gdcm" | od -b
781 // 0000000 147 144 143 155 012
782 prefix = "147.144.143.155"; // special easter egg
785 // A root was specified use it to forge our new UID:
787 append += Util::GetMACAddress();
789 append += Util::GetCurrentDateTime();
791 //Also add a mini random number just in case:
792 int r = (int) (100.0*rand()/RAND_MAX);
793 append += Format("%02d", r);
795 // If append is too long we need to rehash it
796 if( (prefix + append).size() > 64 )
798 gdcmErrorMacro( "Size of UID is too long." );
799 // we need a hash function to truncate this number
800 // if only md5 was cross plateform
804 return prefix + append;
807 unsigned int Util::GetCurrentThreadID()
809 // FIXME the implementation is far from complete
810 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
811 return (unsigned int)GetCurrentThreadId();
815 // Doesn't work on fedora, but is in the man page...
816 //return (unsigned int)gettid();
819 return (unsigned int)thr_self();
821 //default implementation
826 unsigned int Util::GetCurrentProcessID()
828 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
829 // NOTE: There is also a _getpid()...
830 return (unsigned int)GetCurrentProcessId();
832 // get process identification, POSIX
833 return (unsigned int)getpid();
840 * @param os ostream to write to
844 std::ostream &binary_write(std::ostream &os, const T &val)
846 return os.write(reinterpret_cast<const char*>(&val), sizeof val);
850 * \brief binary_write binary_write
851 * @param os ostream to write to
854 std::ostream &binary_write(std::ostream &os, const uint16_t &val)
856 #ifdef GDCM_WORDS_BIGENDIAN
858 swap = ((( val << 8 ) & 0x0ff00 ) | (( val >> 8 ) & 0x00ff ) );
859 return os.write(reinterpret_cast<const char*>(&swap), 2);
861 return os.write(reinterpret_cast<const char*>(&val), 2);
862 #endif //GDCM_WORDS_BIGENDIAN
866 * \brief binary_write binary_write
867 * @param os ostream to write to
870 std::ostream &binary_write(std::ostream &os, const uint32_t &val)
872 #ifdef GDCM_WORDS_BIGENDIAN
874 swap = ( ((val<<24) & 0xff000000) | ((val<<8) & 0x00ff0000) |
875 ((val>>8) & 0x0000ff00) | ((val>>24) & 0x000000ff) );
876 return os.write(reinterpret_cast<const char*>(&swap), 4);
878 return os.write(reinterpret_cast<const char*>(&val), 4);
879 #endif //GDCM_WORDS_BIGENDIAN
883 * \brief binary_write binary_write
884 * @param os ostream to write to
887 std::ostream &binary_write(std::ostream &os, const char *val)
889 return os.write(val, strlen(val));
894 * @param os ostream to write to
897 std::ostream &binary_write(std::ostream &os, std::string const &val)
899 return os.write(val.c_str(), val.size());
902 } // end namespace gdcm