1 /*=========================================================================
4 Module: $RCSfile: gdcmUtil.cxx,v $
6 Date: $Date: 2005/01/28 00:02:15 $
7 Version: $Revision: 1.125 $
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"
24 // For GetCurrentDate, GetCurrentTime
26 #include <sys/types.h>
29 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
30 #include <sys/timeb.h>
35 #include <stdarg.h> //only included in implementation file
36 #include <stdio.h> //only included in implementation file
38 #if defined(_MSC_VER) || defined(__MINGW32__)
39 #include <winsock.h> // for gethostname & gethostbyname
43 #include <unistd.h> // for gethostname
44 #include <netdb.h> // for gethostbyname
56 #include <sys/types.h>
59 #ifdef CMAKE_HAVE_SYS_IOCTL_H
60 #include <sys/ioctl.h> // For SIOCGIFCONF on Linux
62 #ifdef CMAKE_HAVE_SYS_SOCKET_H
63 #include <sys/socket.h>
65 #ifdef CMAKE_HAVE_SYS_SOCKIO_H
66 #include <sys/sockio.h> // For SIOCGIFCONF on SunOS
68 #ifdef CMAKE_HAVE_NET_IF_H
71 #ifdef CMAKE_HAVE_NETINET_IN_H
72 #include <netinet/in.h> //For IPPROTO_IP
74 #ifdef CMAKE_HAVE_NET_IF_DL_H
75 #include <net/if_dl.h>
77 #if defined(CMAKE_HAVE_NET_IF_ARP_H) && defined(__sun)
78 // This is absolutely necessary on SunOS
79 #include <net/if_arp.h>
82 // For GetCurrentThreadID()
84 #include <sys/types.h>
85 #include <linux/unistd.h>
94 * \brief Provide a better 'c++' approach for sprintf
95 * For example c code is:
96 * sprintf(trash, "%04x|%04x", group , elem);
99 * std::ostringstream buf;
100 * buf << std::right << std::setw(4) << std::setfill('0') << std::hex
101 * << group << "|" << std::right << std::setw(4) << std::setfill('0')
102 * << std::hex << elem;
106 * Format("%04x|%04x", group , elem);
109 std::string Util::Format(const char *format, ...)
113 va_start(args, format);
114 vsprintf(buffer, format, args); //might be a security flaw
115 va_end(args); // Each invocation of va_start should be matched
116 // by a corresponding invocation of va_end
117 // args is then 'undefined'
123 * \brief Because not available in C++ (?)
125 void Util::Tokenize (const std::string &str,
126 std::vector<std::string> &tokens,
127 const std::string& delimiters)
129 std::string::size_type lastPos = str.find_first_not_of(delimiters,0);
130 std::string::size_type pos = str.find_first_of (delimiters,lastPos);
131 while (std::string::npos != pos || std::string::npos != lastPos)
133 tokens.push_back(str.substr(lastPos, pos - lastPos));
134 lastPos = str.find_first_not_of(delimiters, pos);
135 pos = str.find_first_of (delimiters, lastPos);
140 * \brief Because not available in C++ (?)
141 * Counts the number of occurences of a substring within a string
144 int Util::CountSubstring (const std::string &str,
145 const std::string &subStr)
147 int count = 0; // counts how many times it appears
148 std::string::size_type x = 0; // The index position in the string
152 x = str.find(subStr,x); // Find the substring
153 if (x != std::string::npos) // If present
155 count++; // increase the count
156 x += subStr.length(); // Skip this word
159 while (x != std::string::npos); // Carry on until not present
165 * \brief Weed out a string from the non-printable characters (in order
166 * to avoid corrupting the terminal of invocation when printing)
167 * @param s string to remove non printable characters from
169 std::string Util::CreateCleanString(std::string const &s)
173 for(unsigned int i=0; i<str.size(); i++)
175 if(!isprint((unsigned char)str[i]))
183 if(!isprint((unsigned char)s[str.size()-1]))
185 if(s[str.size()-1] == 0)
187 str[str.size()-1] = ' ';
196 * \brief Add a SEPARATOR to the end of the name is necessary
197 * @param pathname file/directory name to normalize
199 std::string Util::NormalizePath(std::string const &pathname)
201 const char SEPARATOR_X = '/';
202 const char SEPARATOR_WIN = '\\';
203 const std::string SEPARATOR = "/";
204 std::string name = pathname;
205 int size = name.size();
207 if( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
215 * \brief Get the (directory) path from a full path file name
216 * @param fullName file/directory name to extract Path from
218 std::string Util::GetPath(std::string const &fullName)
220 std::string res = fullName;
221 int pos1 = res.rfind("/");
222 int pos2 = res.rfind("\\");
236 * \brief Get the (last) name of a full path file name
237 * @param fullName file/directory name to extract end name from
239 std::string Util::GetName(std::string const &fullName)
241 std::string filename = fullName;
243 std::string::size_type slash_pos = filename.rfind("/");
244 std::string::size_type backslash_pos = filename.rfind("\\");
245 slash_pos = slash_pos > backslash_pos ? slash_pos : backslash_pos;
246 if(slash_pos != std::string::npos)
248 return filename.substr(slash_pos + 1);
257 * \brief Get the current date of the system in a dicom string
259 std::string Util::GetCurrentDate()
264 strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
269 * \brief Get the current time of the system in a dicom string
271 std::string Util::GetCurrentTime()
276 strftime(tmp,512,"%H%M%S", localtime(&tloc) );
281 * \brief Get both the date and time at the same time to avoid problem
282 * around midnight where two call could be before and after midnight
284 std::string Util::GetCurrentDateTime()
290 // We need implementation specific functions to obtain millisecond precision
291 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
295 milliseconds = tb.millitm;
298 gettimeofday (&tv, NULL);
300 // Compute milliseconds from microseconds.
301 milliseconds = tv.tv_usec / 1000;
303 // Obtain the time of day, and convert it to a tm struct.
304 struct tm *ptm = localtime (&timep);
305 // Format the date and time, down to a single second.
306 strftime (tmp, sizeof (tmp), "%Y%m%d%H%M%S", ptm);
310 r += Format("%03ld", milliseconds);
316 * \brief Create a /DICOM/ string:
317 * It should a of even length (no odd length ever)
318 * It can contain as many (if you are reading this from your
319 * editor the following character is is backslash followed by zero
320 * that needed to be escaped with an extra backslash for doxygen) \\0
323 std::string Util::DicomString(const char *s, size_t l)
325 std::string r(s, s+l);
326 gdcmAssertMacro( !(r.size() % 2) ); // == basically 'l' is even
331 * \brief Create a /DICOM/ string:
332 * It should a of even length (no odd length ever)
333 * It can contain as many (if you are reading this from your
334 * editor the following character is is backslash followed by zero
335 * that needed to be escaped with an extra backslash for doxygen) \\0
337 * This function is similar to DicomString(const char*),
338 * except it doesn't take a length.
339 * It only pad with a null character if length is odd
341 std::string Util::DicomString(const char *s)
343 size_t l = strlen(s);
348 std::string r(s, s+l);
349 gdcmAssertMacro( !(r.size() % 2) );
354 * \brief Safely compare two Dicom String:
355 * - Both string should be of even length
356 * - We allow padding of even length string by either a null
357 * character of a space
359 bool Util::DicomStringEqual(const std::string &s1, const char *s2)
361 // s2 is the string from the DICOM reference: 'MONOCHROME1'
362 std::string s1_even = s1; //Never change input parameter
363 std::string s2_even = DicomString( s2 );
364 if( s1_even[s1_even.size()-1] == ' ')
366 s1_even[s1_even.size()-1] = '\0'; //replace space character by null
368 return s1_even == s2_even;
372 * \brief tells us if the processor we are working with is BigEndian or not
374 bool Util::IsCurrentProcessorBigEndian()
376 #ifdef GDCM_WORDS_BIGENDIAN
386 typedef BOOL(WINAPI * pSnmpExtensionInit) (
387 IN DWORD dwTimeZeroReference,
388 OUT HANDLE * hPollForTrapEvent,
389 OUT AsnObjectIdentifier * supportedView);
391 typedef BOOL(WINAPI * pSnmpExtensionTrap) (
392 OUT AsnObjectIdentifier * enterprise,
393 OUT AsnInteger * genericTrap,
394 OUT AsnInteger * specificTrap,
395 OUT AsnTimeticks * timeStamp,
396 OUT RFC1157VarBindList * variableBindings);
398 typedef BOOL(WINAPI * pSnmpExtensionQuery) (
400 IN OUT RFC1157VarBindList * variableBindings,
401 OUT AsnInteger * errorStatus,
402 OUT AsnInteger * errorIndex);
404 typedef BOOL(WINAPI * pSnmpExtensionInitEx) (
405 OUT AsnObjectIdentifier * supportedView);
409 int GetMacAddrSys ( unsigned char *addr )
413 if (WSAStartup(MAKEWORD(2, 0), &WinsockData) != 0)
415 std::cerr << "This program requires Winsock 2.x!" << std::endl;
419 HANDLE PollForTrapEvent;
420 AsnObjectIdentifier SupportedView;
421 UINT OID_ifEntryType[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 3 };
422 UINT OID_ifEntryNum[] = { 1, 3, 6, 1, 2, 1, 2, 1 };
423 UINT OID_ipMACEntAddr[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 6 };
424 AsnObjectIdentifier MIB_ifMACEntAddr = {
425 sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr };
426 AsnObjectIdentifier MIB_ifEntryType = {
427 sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType };
428 AsnObjectIdentifier MIB_ifEntryNum = {
429 sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum };
430 RFC1157VarBindList varBindList;
431 RFC1157VarBind varBind[2];
432 AsnInteger errorStatus;
433 AsnInteger errorIndex;
434 AsnObjectIdentifier MIB_NULL = { 0, 0 };
439 // Load the SNMP dll and get the addresses of the functions necessary
440 HINSTANCE m_hInst = LoadLibrary("inetmib1.dll");
441 if (m_hInst < (HINSTANCE) HINSTANCE_ERROR)
445 pSnmpExtensionInit m_Init =
446 (pSnmpExtensionInit) GetProcAddress(m_hInst, "SnmpExtensionInit");
447 pSnmpExtensionQuery m_Query =
448 (pSnmpExtensionQuery) GetProcAddress(m_hInst, "SnmpExtensionQuery");
449 m_Init(GetTickCount(), &PollForTrapEvent, &SupportedView);
451 /* Initialize the variable list to be retrieved by m_Query */
452 varBindList.list = varBind;
453 varBind[0].name = MIB_NULL;
454 varBind[1].name = MIB_NULL;
456 // Copy in the OID to find the number of entries in the
458 varBindList.len = 1; // Only retrieving one item
459 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryNum);
460 m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
462 // printf("# of adapters in this system : %i\n",
463 // varBind[0].value.asnValue.number);
466 // Copy in the OID of ifType, the type of interface
467 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryType);
469 // Copy in the OID of ifPhysAddress, the address
470 SNMP_oidcpy(&varBind[1].name, &MIB_ifMACEntAddr);
474 // Submit the query. Responses will be loaded into varBindList.
475 // We can expect this call to succeed a # of times corresponding
476 // to the # of adapters reported to be in the system
477 ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
485 // Confirm that the proper type has been returned
486 ret = SNMP_oidncmp(&varBind[0].name, &MIB_ifEntryType,
487 MIB_ifEntryType.idLength);
492 dtmp = varBind[0].value.asnValue.number;
494 // Type 6 describes ethernet interfaces
497 // Confirm that we have an address here
498 ret = SNMP_oidncmp(&varBind[1].name, &MIB_ifMACEntAddr,
499 MIB_ifMACEntAddr.idLength);
500 if ( !ret && varBind[1].value.asnValue.address.stream != NULL )
502 if ( (varBind[1].value.asnValue.address.stream[0] == 0x44)
503 && (varBind[1].value.asnValue.address.stream[1] == 0x45)
504 && (varBind[1].value.asnValue.address.stream[2] == 0x53)
505 && (varBind[1].value.asnValue.address.stream[3] == 0x54)
506 && (varBind[1].value.asnValue.address.stream[4] == 0x00) )
508 // Ignore all dial-up networking adapters
509 std::cerr << "Interface #" << j << " is a DUN adapter\n";
512 if ( (varBind[1].value.asnValue.address.stream[0] == 0x00)
513 && (varBind[1].value.asnValue.address.stream[1] == 0x00)
514 && (varBind[1].value.asnValue.address.stream[2] == 0x00)
515 && (varBind[1].value.asnValue.address.stream[3] == 0x00)
516 && (varBind[1].value.asnValue.address.stream[4] == 0x00)
517 && (varBind[1].value.asnValue.address.stream[5] == 0x00) )
519 // Ignore NULL addresses returned by other network
521 std::cerr << "Interface #" << j << " is a NULL address\n";
524 memcpy( addr, varBind[1].value.asnValue.address.stream, 6);
531 SNMP_FreeVarBind(&varBind[0]);
532 SNMP_FreeVarBind(&varBind[1]);
534 #endif //Win32 version
537 // implementation for POSIX system
539 //The POSIX version is broken anyway on Solaris, plus would require full
541 struct arpreq parpreq;
542 struct sockaddr_in *psa;
543 struct hostent *phost;
544 char hostname[MAXHOSTNAMELEN];
548 if(gethostname(hostname, MAXHOSTNAMELEN) != 0)
550 perror("gethostname");
553 phost = gethostbyname(hostname);
554 paddrs = phost->h_addr_list;
556 sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
562 memset(&parpreq, 0, sizeof(struct arpreq));
563 psa = (struct sockaddr_in *) &parpreq.arp_pa;
565 memset(psa, 0, sizeof(struct sockaddr_in));
566 psa->sin_family = AF_INET;
567 memcpy(&psa->sin_addr, *paddrs, sizeof(struct in_addr));
569 status = ioctl(sock, SIOCGARP, &parpreq);
575 memcpy(addr, parpreq.arp_ha.sa_data, 6);
579 #ifdef CMAKE_HAVE_NET_IF_H
581 struct ifreq ifr, *ifrp;
586 #if defined(AF_LINK) && (!defined(SIOCGIFHWADDR) && !defined(SIOCGENADDR))
587 struct sockaddr_dl *sdlp;
591 // BSD 4.4 defines the size of an ifreq to be
592 // max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len
593 // However, under earlier systems, sa_len isn't present, so the size is
594 // just sizeof(struct ifreq)
595 // We should investiage the use of SIZEOF_ADDR_IFREQ
599 #define max(a,b) ((a) > (b) ? (a) : (b))
601 #define ifreq_size(i) max(sizeof(struct ifreq),\
602 sizeof((i).ifr_name)+(i).ifr_addr.sa_len)
604 #define ifreq_size(i) sizeof(struct ifreq)
605 #endif // HAVE_SA_LEN
607 if( (sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0 )
611 memset(buf, 0, sizeof(buf));
612 ifc.ifc_len = sizeof(buf);
614 if (ioctl (sd, SIOCGIFCONF, (char *)&ifc) < 0)
620 for (i = 0; i < n; i+= ifreq_size(*ifrp) )
622 ifrp = (struct ifreq *)((char *) ifc.ifc_buf+i);
623 strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ);
625 if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0)
627 a = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
630 // In theory this call should also work on Sun Solaris, but apparently
631 // SIOCGENADDR is not implemented properly thus the call
632 // ioctl(sd, SIOCGENADDR, &ifr) always returns errno=2
633 // (No such file or directory)
634 // Furthermore the DLAPI seems to require full root access
635 if (ioctl(sd, SIOCGENADDR, &ifr) < 0)
637 a = (unsigned char *) ifr.ifr_enaddr;
640 sdlp = (struct sockaddr_dl *) &ifrp->ifr_addr;
641 if ((sdlp->sdl_family != AF_LINK) || (sdlp->sdl_alen != 6))
643 a = (unsigned char *) &sdlp->sdl_data[sdlp->sdl_nlen];
645 perror("No way to access hardware");
649 #endif // SIOCGENADDR
650 #endif // SIOCGIFHWADDR
651 if (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5]) continue;
662 // Not implemented platforms
663 perror("There was a configuration problem on your plateform");
670 * Mini function to return the last digit from a number express in base 256
671 * pre condition data contain an array of 6 unsigned char
672 * post condition carry contain the last digit
674 inline int getlastdigit(unsigned char *data)
676 int extended, carry = 0;
679 extended = (carry << 8) + data[i];
680 data[i] = extended / 10;
681 carry = extended % 10;
687 * \brief Encode the mac address on a fixed lenght string of 15 characters.
688 * we save space this way.
690 std::string Util::GetMACAddress()
692 // This code is the result of a long internet search to find something
693 // as compact as possible (not OS independant). We only have to separate
694 // 3 OS: Win32, SunOS and 'real' POSIX
695 // http://groups-beta.google.com/group/comp.unix.solaris/msg/ad36929d783d63be
696 // http://bdn.borland.com/article/0,1410,26040,00.html
697 unsigned char addr[6];
699 int stat = GetMacAddrSys(addr);
702 // We need to convert a 6 digit number from base 256 to base 10, using integer
703 // would requires a 48bits one. To avoid this we have to reimplement the div + modulo
710 res = getlastdigit(addr);
711 sres.push_back( '0' + res );
712 zero = (addr[0] == 0) && (addr[1] == 0) && (addr[2] == 0) && (addr[3] == 0) && (addr[4] == 0) && (addr[5] == 0);
714 // Since we push back the proper number is reversed:
715 std::reverse(sres.begin(),sres.end());
721 gdcmVerboseMacro("Problem in finding the MAC Address");
727 * \brief Return the IP adress of the machine writting the DICOM image
729 std::string Util::GetIPAddress()
731 // This is a rip from
732 // http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
733 #ifndef HOST_NAME_MAX
734 // SUSv2 guarantees that `Host names are limited to 255 bytes'.
735 // POSIX 1003.1-2001 guarantees that `Host names (not including the
736 // terminating NUL) are limited to HOST_NAME_MAX bytes'.
737 # define HOST_NAME_MAX 255
738 // In this case we should maybe check the string was not truncated.
739 // But I don't known how to check that...
740 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
741 // with WinSock DLL we need to initialize the WinSock before using gethostname
742 WORD wVersionRequested = MAKEWORD(1,0);
744 int err = WSAStartup(wVersionRequested,&WSAData);
747 // Tell the user that we could not find a usable
754 #endif //HOST_NAME_MAX
757 char szHostName[HOST_NAME_MAX+1];
758 int r = gethostname(szHostName, HOST_NAME_MAX);
763 struct hostent *pHost = gethostbyname(szHostName);
765 for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
767 for( int j = 0; j<pHost->h_length; j++ )
769 if( j > 0 ) str += ".";
771 str += Util::Format("%u",
772 (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
774 // str now contains one local IP address
776 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
782 // If an error occur r == -1
783 // Most of the time it will return 127.0.0.1...
788 * \brief Creates a new UID. As stipulate in the DICOM ref
789 * each time a DICOM image is create it should have
790 * a unique identifier (URI)
791 * @param root is the DICOM prefix assigned by IOS group
793 std::string Util::CreateUniqueUID(const std::string &root)
795 std::string prefix = root;
799 // No root was specified use "GDCM" then
800 // echo "gdcm" | od -b
801 // 0000000 147 144 143 155 012
802 //prefix = "147.144.143.155"; // special easter egg
804 // gdcm UID prefix, as supplied by http://www.medicalconnections.co.uk
805 prefix = "1.2.826.0.1.3680043.2.1143";
808 // A root was specified use it to forge our new UID:
810 append += Util::GetMACAddress();
812 append += Util::GetCurrentDateTime();
814 //Also add a mini random number just in case:
815 int r = (int) (100.0*rand()/RAND_MAX);
816 append += Format("%02d", r);
818 // If append is too long we need to rehash it
819 if( (prefix + append).size() > 64 )
821 gdcmErrorMacro( "Size of UID is too long." );
822 // we need a hash function to truncate this number
823 // if only md5 was cross plateform
827 return prefix + append;
830 unsigned int Util::GetCurrentThreadID()
832 // FIXME the implementation is far from complete
833 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
834 return (unsigned int)GetCurrentThreadId();
838 // Doesn't work on fedora, but is in the man page...
839 //return (unsigned int)gettid();
842 return (unsigned int)thr_self();
844 //default implementation
849 unsigned int Util::GetCurrentProcessID()
851 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
852 // NOTE: There is also a _getpid()...
853 return (unsigned int)GetCurrentProcessId();
855 // get process identification, POSIX
856 return (unsigned int)getpid();
863 * @param os ostream to write to
867 std::ostream &binary_write(std::ostream &os, const T &val)
869 return os.write(reinterpret_cast<const char*>(&val), sizeof val);
873 * \brief binary_write binary_write
874 * @param os ostream to write to
877 std::ostream &binary_write(std::ostream &os, const uint16_t &val)
879 #ifdef GDCM_WORDS_BIGENDIAN
881 swap = ((( val << 8 ) & 0x0ff00 ) | (( val >> 8 ) & 0x00ff ) );
882 return os.write(reinterpret_cast<const char*>(&swap), 2);
884 return os.write(reinterpret_cast<const char*>(&val), 2);
885 #endif //GDCM_WORDS_BIGENDIAN
889 * \brief binary_write binary_write
890 * @param os ostream to write to
893 std::ostream &binary_write(std::ostream &os, const uint32_t &val)
895 #ifdef GDCM_WORDS_BIGENDIAN
897 swap = ( ((val<<24) & 0xff000000) | ((val<<8) & 0x00ff0000) |
898 ((val>>8) & 0x0000ff00) | ((val>>24) & 0x000000ff) );
899 return os.write(reinterpret_cast<const char*>(&swap), 4);
901 return os.write(reinterpret_cast<const char*>(&val), 4);
902 #endif //GDCM_WORDS_BIGENDIAN
906 * \brief binary_write binary_write
907 * @param os ostream to write to
910 std::ostream &binary_write(std::ostream &os, const char *val)
912 return os.write(val, strlen(val));
917 * @param os ostream to write to
920 std::ostream &binary_write(std::ostream &os, std::string const &val)
922 return os.write(val.c_str(), val.size());
925 } // end namespace gdcm