1 /*=========================================================================
4 Module: $RCSfile: gdcmUtil.cxx,v $
6 Date: $Date: 2005/01/17 13:55:26 $
7 Version: $Revision: 1.100 $
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 #include <stdarg.h> //only included in implementation file
29 #include <stdio.h> //only included in implementation file
32 #include <winsock.h> // for gethostname & gethostbyname
36 #include <unistd.h> // for gethostname
37 #include <netdb.h> // for gethostbyname
49 #include <sys/types.h>
52 // How do I do that in CMake ?
55 #define CMAKE_HAVE_NET_IF_DL_H
56 #define CMAKE_HAVE_NETINET_IN_H
57 #define CMAKE_HAVE_NET_IF_H
60 #ifdef CMAKE_HAVE_SYS_IOCTL_H
61 #include <sys/ioctl.h> // For SIOCGIFCONF on Linux
63 #ifdef CMAKE_HAVE_SYS_SOCKET_H
64 #include <sys/socket.h>
66 #ifdef CMAKE_HAVE_SYS_SOCKIO_H
67 #include <sys/sockio.h> // For SIOCGIFCONF on SunOS
69 #ifdef CMAKE_HAVE_NET_IF_H
72 #ifdef CMAKE_HAVE_NETINET_IN_H
73 #include <netinet/in.h> //For IPPROTO_IP
75 #ifdef CMAKE_HAVE_NET_IF_DL_H
76 #include <net/if_dl.h>
79 //#if defined(CMAKE_HAVE_NET_IF_ARP_H) && defined(__sun)
80 // This is absolutely necesseray on SunOS
81 #include <net/if_arp.h>
88 * \brief Provide a better 'c++' approach for sprintf
89 * For example c code is:
90 * sprintf(trash, "%04x|%04x", group , elem);
93 * std::ostringstream buf;
94 * buf << std::right << std::setw(4) << std::setfill('0') << std::hex
95 * << group << "|" << std::right << std::setw(4) << std::setfill('0')
96 * << std::hex << elem;
100 * Format("%04x|%04x", group , elem);
103 std::string Util::Format(const char *format, ...)
107 va_start(args, format);
108 vsprintf(buffer, format, args); //might be a security flaw
109 va_end(args); // Each invocation of va_start should be matched
110 // by a corresponding invocation of va_end
111 // args is then 'undefined'
118 * \brief Because not available in C++ (?)
120 void Util::Tokenize (const std::string &str,
121 std::vector<std::string> &tokens,
122 const std::string& delimiters)
124 std::string::size_type lastPos = str.find_first_not_of(delimiters,0);
125 std::string::size_type pos = str.find_first_of (delimiters,lastPos);
126 while (std::string::npos != pos || std::string::npos != lastPos)
128 tokens.push_back(str.substr(lastPos, pos - lastPos));
129 lastPos = str.find_first_not_of(delimiters, pos);
130 pos = str.find_first_of (delimiters, lastPos);
136 * \brief Because not available in C++ (?)
137 * Counts the number of occurences of a substring within a string
140 int Util::CountSubstring (const std::string &str,
141 const std::string &subStr)
143 int count = 0; // counts how many times it appears
144 std::string::size_type x = 0; // The index position in the string
148 x = str.find(subStr,x); // Find the substring
149 if (x != std::string::npos) // If present
151 count++; // increase the count
152 x += subStr.length(); // Skip this word
155 while (x != std::string::npos); // Carry on until not present
162 * \brief Weed out a string from the non-printable characters (in order
163 * to avoid corrupting the terminal of invocation when printing)
164 * @param s string to remove non printable characters from
166 std::string Util::CreateCleanString(std::string const &s)
170 for(unsigned int i=0; i<str.size(); i++)
172 if(!isprint((unsigned char)str[i]))
180 if(!isprint((unsigned char)s[str.size()-1]))
182 if(s[str.size()-1] == 0)
184 str[str.size()-1] = ' ';
194 * \brief Add a SEPARATOR to the end of the name is necessary
195 * @param pathname file/directory name to normalize
197 std::string Util::NormalizePath(std::string const &pathname)
199 const char SEPARATOR_X = '/';
200 const char SEPARATOR_WIN = '\\';
201 const std::string SEPARATOR = "/";
202 std::string name = pathname;
203 int size = name.size();
205 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("\\");
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);
258 * \brief Get the current date of the system in a dicom string
260 std::string Util::GetCurrentDate()
265 strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
271 * \brief Get the current time of the system in a dicom string
273 std::string Util::GetCurrentTime()
278 strftime(tmp,512,"%H%M%S", localtime(&tloc) );
283 * \brief Create a /DICOM/ string:
284 * It should a of even length (no odd length ever)
285 * It can contain as many (if you are reading this from your
286 * editor the following character is is backslash followed by zero
287 * that needed to be escaped with an extra backslash for doxygen) \\0
290 std::string Util::DicomString(const char *s, size_t l)
292 std::string r(s, s+l);
293 gdcmAssertMacro( !(r.size() % 2) ); // == basically 'l' is even
299 * \brief Create a /DICOM/ string:
300 * It should a of even lenght (no odd length ever)
301 * It can contain as many (if you are reading this from your
302 * editor the following character is is backslash followed by zero
303 * that needed to be escaped with an extra backslash for doxygen) \\0
305 * This function is similar to DicomString(const char*),
306 * except it doesn't take a lenght.
307 * It only pad with a null character if length is odd
309 std::string Util::DicomString(const char *s)
311 size_t l = strlen(s);
316 std::string r(s, s+l);
317 gdcmAssertMacro( !(r.size() % 2) );
323 * \brief Safely compare two Dicom String:
324 * - Both string should be of even lenght
325 * - We allow padding of even lenght string by either a null
326 * character of a space
328 bool Util::DicomStringEqual(const std::string &s1, const char *s2)
330 // s2 is the string from the DICOM reference: 'MONOCHROME1'
331 std::string s1_even = s1; //Never change input parameter
332 std::string s2_even = DicomString( s2 );
333 if( s1_even[s1_even.size()-1] == ' ')
335 s1_even[s1_even.size()-1] = '\0'; //replace space character by null
337 return s1_even == s2_even;
344 * \brief tells us if the processor we are working with is BigEndian or not
346 bool Util::IsCurrentProcessorBigEndian()
348 #ifdef GDCM_WORDS_BIGENDIAN
358 typedef BOOL(WINAPI * pSnmpExtensionInit) (
359 IN DWORD dwTimeZeroReference,
360 OUT HANDLE * hPollForTrapEvent,
361 OUT AsnObjectIdentifier * supportedView);
363 typedef BOOL(WINAPI * pSnmpExtensionTrap) (
364 OUT AsnObjectIdentifier * enterprise,
365 OUT AsnInteger * genericTrap,
366 OUT AsnInteger * specificTrap,
367 OUT AsnTimeticks * timeStamp,
368 OUT RFC1157VarBindList * variableBindings);
370 typedef BOOL(WINAPI * pSnmpExtensionQuery) (
372 IN OUT RFC1157VarBindList * variableBindings,
373 OUT AsnInteger * errorStatus,
374 OUT AsnInteger * errorIndex);
376 typedef BOOL(WINAPI * pSnmpExtensionInitEx) (
377 OUT AsnObjectIdentifier * supportedView);
381 int GetMacAddrSys ( unsigned char *addr )
385 if (WSAStartup(MAKEWORD(2, 0), &WinsockData) != 0)
387 std::cerr << "This program requires Winsock 2.x!" << std::endl;
391 HANDLE PollForTrapEvent;
392 AsnObjectIdentifier SupportedView;
393 UINT OID_ifEntryType[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 3 };
394 UINT OID_ifEntryNum[] = { 1, 3, 6, 1, 2, 1, 2, 1 };
395 UINT OID_ipMACEntAddr[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 6 };
396 AsnObjectIdentifier MIB_ifMACEntAddr = {
397 sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr };
398 AsnObjectIdentifier MIB_ifEntryType = {
399 sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType };
400 AsnObjectIdentifier MIB_ifEntryNum = {
401 sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum };
402 RFC1157VarBindList varBindList;
403 RFC1157VarBind varBind[2];
404 AsnInteger errorStatus;
405 AsnInteger errorIndex;
406 AsnObjectIdentifier MIB_NULL = { 0, 0 };
412 // Load the SNMP dll and get the addresses of the functions necessary
413 HINSTANCE m_hInst = LoadLibrary("inetmib1.dll");
414 if (m_hInst < (HINSTANCE) HINSTANCE_ERROR)
419 pSnmpExtensionInit m_Init =
420 (pSnmpExtensionInit) GetProcAddress(m_hInst, "SnmpExtensionInit");
421 pSnmpExtensionInitEx m_InitEx =
422 (pSnmpExtensionInitEx) GetProcAddress(m_hInst, "SnmpExtensionInitEx");
423 pSnmpExtensionQuery m_Query =
424 (pSnmpExtensionQuery) GetProcAddress(m_hInst, "SnmpExtensionQuery");
425 pSnmpExtensionTrap m_Trap =
426 (pSnmpExtensionTrap) GetProcAddress(m_hInst, "SnmpExtensionTrap");
427 m_Init(GetTickCount(), &PollForTrapEvent, &SupportedView);
429 /* Initialize the variable list to be retrieved by m_Query */
430 varBindList.list = varBind;
431 varBind[0].name = MIB_NULL;
432 varBind[1].name = MIB_NULL;
434 // Copy in the OID to find the number of entries in the
436 varBindList.len = 1; // Only retrieving one item
437 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryNum);
438 ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
440 // printf("# of adapters in this system : %i\n",
441 // varBind[0].value.asnValue.number); varBindList.len = 2;
443 // Copy in the OID of ifType, the type of interface
444 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryType);
446 // Copy in the OID of ifPhysAddress, the address
447 SNMP_oidcpy(&varBind[1].name, &MIB_ifMACEntAddr);
451 // Submit the query. Responses will be loaded into varBindList.
452 // We can expect this call to succeed a # of times corresponding
453 // to the # of adapters reported to be in the system
454 ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
462 // Confirm that the proper type has been returned
463 ret = SNMP_oidncmp(&varBind[0].name, &MIB_ifEntryType,
464 MIB_ifEntryType.idLength);
469 dtmp = varBind[0].value.asnValue.number;
470 std::cerr << "Interface #" << j << " type : " << dtmp << std::endl;
472 // Type 6 describes ethernet interfaces
475 // Confirm that we have an address here
476 ret = SNMP_oidncmp(&varBind[1].name, &MIB_ifMACEntAddr,
477 MIB_ifMACEntAddr.idLength);
478 if ( !ret && varBind[1].value.asnValue.address.stream != NULL )
480 if ( varBind[1].value.asnType != ASN_RFC1155_IPADDRESS )
482 // Ignore all dial-up networking adapters
483 std::cerr << "Interface #" << j << " is not an IP adress\n";
487 if ( (varBind[1].value.asnValue.address.stream[0] == 0x44)
488 && (varBind[1].value.asnValue.address.stream[1] == 0x45)
489 && (varBind[1].value.asnValue.address.stream[2] == 0x53)
490 && (varBind[1].value.asnValue.address.stream[3] == 0x54)
491 && (varBind[1].value.asnValue.address.stream[4] == 0x00) )
493 // Ignore all dial-up networking adapters
494 std::cerr << "Interface #" << j << " is a DUN adapter\n";
497 if ( (varBind[1].value.asnValue.address.stream[0] == 0x00)
498 && (varBind[1].value.asnValue.address.stream[1] == 0x00)
499 && (varBind[1].value.asnValue.address.stream[2] == 0x00)
500 && (varBind[1].value.asnValue.address.stream[3] == 0x00)
501 && (varBind[1].value.asnValue.address.stream[4] == 0x00)
502 && (varBind[1].value.asnValue.address.stream[5] == 0x00) )
504 // Ignore NULL addresses returned by other network
506 std::cerr << "Interface #" << j << " is a NULL address\n";
510 memcpy( addr, varBind[1].value.asnValue.address.stream, 6);
517 SNMP_FreeVarBind(&varBind[0]);
518 SNMP_FreeVarBind(&varBind[1]);
520 #endif //Win32 version
523 // implementation for POSIX system
525 //The POSIX version is broken anyway on Solaris, plus would require full
528 struct arpreq parpreq;
529 struct sockaddr_in sa, *psa;
530 struct in_addr inaddr;
531 struct hostent *phost;
532 char hostname[MAXHOSTNAMELEN];
537 if(gethostname(hostname, MAXHOSTNAMELEN) != 0)
539 perror("gethostname");
542 phost = gethostbyname(hostname);
543 paddrs = phost->h_addr_list;
545 sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
551 memset(&parpreq, 0, sizeof(struct arpreq));
552 psa = (struct sockaddr_in *) &parpreq.arp_pa;
554 memset(psa, 0, sizeof(struct sockaddr_in));
555 psa->sin_family = AF_INET;
556 memcpy(&psa->sin_addr, *paddrs, sizeof(struct in_addr));
558 status = ioctl(sock, SIOCGARP, &parpreq);
564 memcpy(addr, parpreq.arp_ha.sa_data, 6);
568 #ifdef CMAKE_HAVE_NET_IF_H
570 struct ifreq ifr, *ifrp;
576 struct sockaddr_dl *sdlp;
580 // BSD 4.4 defines the size of an ifreq to be
581 // max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len
582 // However, under earlier systems, sa_len isn't present, so the size is
583 // just sizeof(struct ifreq)
584 // We should investiage the use of SIZEOF_ADDR_IFREQ
588 #define max(a,b) ((a) > (b) ? (a) : (b))
590 #define ifreq_size(i) max(sizeof(struct ifreq),\
591 sizeof((i).ifr_name)+(i).ifr_addr.sa_len)
593 #define ifreq_size(i) sizeof(struct ifreq)
594 #endif // HAVE_SA_LEN
596 if( (sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0 )
600 memset(buf, 0, sizeof(buf));
601 ifc.ifc_len = sizeof(buf);
603 if (ioctl (sd, SIOCGIFCONF, (char *)&ifc) < 0)
609 for (i = 0; i < n; i+= ifreq_size(*ifrp) )
611 ifrp = (struct ifreq *)((char *) ifc.ifc_buf+i);
612 strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ);
614 if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0)
616 a = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
619 // In theory this call should also work on Sun Solaris, but apparently
620 // SIOCGENADDR is not implemented properly thus the call
621 // ioctl(sd, SIOCGENADDR, &ifr) always returns errno=2
622 // (No such file or directory)
623 // Furthermore the DLAPI seems to require full root access
624 if (ioctl(sd, SIOCGENADDR, &ifr) < 0)
626 a = (unsigned char *) ifr.ifr_enaddr;
629 sdlp = (struct sockaddr_dl *) &ifrp->ifr_addr;
630 if ((sdlp->sdl_family != AF_LINK) || (sdlp->sdl_alen != 6))
632 a = (unsigned char *) &sdlp->sdl_data[sdlp->sdl_nlen];
634 perror("No way to access hardware");
638 #endif // SIOCGENADDR
639 #endif // SIOCGIFHWADDR
640 if (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5]) continue;
655 std::string Util::GetMACAddress()
657 // This code is the result of a long internet search to find something
658 // as compact as possible (not OS independant). We only have to separate
659 // 3 OS: Win32, SunOS and 'real' POSIX
660 // http://groups-beta.google.com/group/comp.unix.solaris/msg/ad36929d783d63be
661 // http://bdn.borland.com/article/0,1410,26040,00.html
662 unsigned char addr[6];
663 int stat = GetMacAddrSys(addr);
667 std::string macaddr = "";
668 for (int i=0; i<6; ++i)
670 //macaddr += Format("%2.2x", addr[i]);
673 macaddr += Format("%i", (int)addr[i]);
679 gdcmVerboseMacro("Problem in finding the MAC Address");
686 * \brief Return the IP adress of the machine writting the DICOM image
688 std::string Util::GetIPAddress()
690 // This is a rip from
691 // http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
692 #ifndef HOST_NAME_MAX
693 // SUSv2 guarantees that `Host names are limited to 255 bytes'.
694 // POSIX 1003.1-2001 guarantees that `Host names (not including the
695 // terminating NUL) are limited to HOST_NAME_MAX bytes'.
696 # define HOST_NAME_MAX 255
697 // In this case we should maybe check the string was not truncated.
698 // But I don't known how to check that...
699 #if defined(_MSC_VER) || defined(__BORLANDC__)
700 // with WinSock DLL we need to initialise the WinSock before using gethostname
701 WORD wVersionRequested = MAKEWORD(1,0);
703 int err = WSAStartup(wVersionRequested,&WSAData);
706 // Tell the user that we could not find a usable
713 #endif //HOST_NAME_MAX
716 char szHostName[HOST_NAME_MAX+1];
717 int r = gethostname(szHostName, HOST_NAME_MAX);
722 struct hostent *pHost = gethostbyname(szHostName);
724 for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
726 for( int j = 0; j<pHost->h_length; j++ )
728 if( j > 0 ) str += ".";
730 str += Util::Format("%u",
731 (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
733 // str now contains one local IP address
735 #if defined(_MSC_VER) || defined(__BORLANDC__)
741 // If an error occur r == -1
742 // Most of the time it will return 127.0.0.1...
748 * \brief Creates a new UID. As stipulate in the DICOM ref
749 * each time a DICOM image is create it should have
750 * a unique identifier (URI)
752 std::string Util::CreateUniqueUID(const std::string &root)
754 std::string radical = root;
757 // No root was specified use "GDCM" then
758 // echo "gdcm" | od -b
759 // 0000000 147 144 143 155 012
760 radical = "147.144.143.155"; // special easter egg
763 // A root was specified use it to forge our new UID:
764 radical += Util::GetMACAddress();
766 radical += Util::GetCurrentDate();
768 radical += Util::GetCurrentTime();
774 std::ostream &binary_write(std::ostream &os, const T &val)
776 return os.write(reinterpret_cast<const char*>(&val), sizeof val);
779 std::ostream &binary_write(std::ostream &os, const uint16_t &val)
781 #ifdef GDCM_WORDS_BIGENDIAN
783 swap = ((( val << 8 ) & 0x0ff00 ) | (( val >> 8 ) & 0x00ff ) );
784 return os.write(reinterpret_cast<const char*>(&swap), 2);
786 return os.write(reinterpret_cast<const char*>(&val), 2);
787 #endif //GDCM_WORDS_BIGENDIAN
790 std::ostream &binary_write(std::ostream &os, const uint32_t &val)
792 #ifdef GDCM_WORDS_BIGENDIAN
794 swap = ( ((val<<24) & 0xff000000) | ((val<<8) & 0x00ff0000) |
795 ((val>>8) & 0x0000ff00) | ((val>>24) & 0x000000ff) );
796 return os.write(reinterpret_cast<const char*>(&swap), 4);
798 return os.write(reinterpret_cast<const char*>(&val), 4);
799 #endif //GDCM_WORDS_BIGENDIAN
802 std::ostream &binary_write(std::ostream &os, const char *val)
804 return os.write(val, strlen(val));
807 std::ostream &binary_write(std::ostream &os, std::string const &val)
809 return os.write(val.c_str(), val.size());
812 } // end namespace gdcm