1 /*=========================================================================
4 Module: $RCSfile: gdcmUtil.cxx,v $
6 Date: $Date: 2005/01/21 11:40:56 $
7 Version: $Revision: 1.113 $
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
31 #if defined(_MSC_VER) || defined(__MINGW32__)
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 #ifdef CMAKE_HAVE_SYS_IOCTL_H
53 #include <sys/ioctl.h> // For SIOCGIFCONF on Linux
55 #ifdef CMAKE_HAVE_SYS_SOCKET_H
56 #include <sys/socket.h>
58 #ifdef CMAKE_HAVE_SYS_SOCKIO_H
59 #include <sys/sockio.h> // For SIOCGIFCONF on SunOS
61 #ifdef CMAKE_HAVE_NET_IF_H
64 #ifdef CMAKE_HAVE_NETINET_IN_H
65 #include <netinet/in.h> //For IPPROTO_IP
67 #ifdef CMAKE_HAVE_NET_IF_DL_H
68 #include <net/if_dl.h>
70 #if defined(CMAKE_HAVE_NET_IF_ARP_H) && defined(__sun)
71 // This is absolutely necesseray on SunOS
72 #include <net/if_arp.h>
78 * \brief Provide a better 'c++' approach for sprintf
79 * For example c code is:
80 * sprintf(trash, "%04x|%04x", group , elem);
83 * std::ostringstream buf;
84 * buf << std::right << std::setw(4) << std::setfill('0') << std::hex
85 * << group << "|" << std::right << std::setw(4) << std::setfill('0')
86 * << std::hex << elem;
90 * Format("%04x|%04x", group , elem);
93 std::string Util::Format(const char *format, ...)
97 va_start(args, format);
98 vsprintf(buffer, format, args); //might be a security flaw
99 va_end(args); // Each invocation of va_start should be matched
100 // by a corresponding invocation of va_end
101 // args is then 'undefined'
107 * \brief Because not available in C++ (?)
109 void Util::Tokenize (const std::string &str,
110 std::vector<std::string> &tokens,
111 const std::string& delimiters)
113 std::string::size_type lastPos = str.find_first_not_of(delimiters,0);
114 std::string::size_type pos = str.find_first_of (delimiters,lastPos);
115 while (std::string::npos != pos || std::string::npos != lastPos)
117 tokens.push_back(str.substr(lastPos, pos - lastPos));
118 lastPos = str.find_first_not_of(delimiters, pos);
119 pos = str.find_first_of (delimiters, lastPos);
124 * \brief Because not available in C++ (?)
125 * Counts the number of occurences of a substring within a string
128 int Util::CountSubstring (const std::string &str,
129 const std::string &subStr)
131 int count = 0; // counts how many times it appears
132 std::string::size_type x = 0; // The index position in the string
136 x = str.find(subStr,x); // Find the substring
137 if (x != std::string::npos) // If present
139 count++; // increase the count
140 x += subStr.length(); // Skip this word
143 while (x != std::string::npos); // Carry on until not present
149 * \brief Weed out a string from the non-printable characters (in order
150 * to avoid corrupting the terminal of invocation when printing)
151 * @param s string to remove non printable characters from
153 std::string Util::CreateCleanString(std::string const &s)
157 for(unsigned int i=0; i<str.size(); i++)
159 if(!isprint((unsigned char)str[i]))
167 if(!isprint((unsigned char)s[str.size()-1]))
169 if(s[str.size()-1] == 0)
171 str[str.size()-1] = ' ';
180 * \brief Add a SEPARATOR to the end of the name is necessary
181 * @param pathname file/directory name to normalize
183 std::string Util::NormalizePath(std::string const &pathname)
185 const char SEPARATOR_X = '/';
186 const char SEPARATOR_WIN = '\\';
187 const std::string SEPARATOR = "/";
188 std::string name = pathname;
189 int size = name.size();
191 if( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
199 * \brief Get the (directory) path from a full path file name
200 * @param fullName file/directory name to extract Path from
202 std::string Util::GetPath(std::string const &fullName)
204 std::string res = fullName;
205 int pos1 = res.rfind("/");
206 int pos2 = res.rfind("\\");
220 * \brief Get the (last) name of a full path file name
221 * @param fullName file/directory name to extract end name from
223 std::string Util::GetName(std::string const &fullName)
225 std::string filename = fullName;
227 std::string::size_type slash_pos = filename.rfind("/");
228 std::string::size_type backslash_pos = filename.rfind("\\");
229 slash_pos = slash_pos > backslash_pos ? slash_pos : backslash_pos;
230 if(slash_pos != std::string::npos)
232 return filename.substr(slash_pos + 1);
241 * \brief Get the current date of the system in a dicom string
243 std::string Util::GetCurrentDate()
248 strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
253 * \brief Get the current time of the system in a dicom string
255 std::string Util::GetCurrentTime()
260 strftime(tmp,512,"%H%M%S", localtime(&tloc) );
265 * \brief Create a /DICOM/ string:
266 * It should a of even length (no odd length ever)
267 * It can contain as many (if you are reading this from your
268 * editor the following character is is backslash followed by zero
269 * that needed to be escaped with an extra backslash for doxygen) \\0
272 std::string Util::DicomString(const char *s, size_t l)
274 std::string r(s, s+l);
275 gdcmAssertMacro( !(r.size() % 2) ); // == basically 'l' is even
280 * \brief Create a /DICOM/ string:
281 * It should a of even lenght (no odd length ever)
282 * It can contain as many (if you are reading this from your
283 * editor the following character is is backslash followed by zero
284 * that needed to be escaped with an extra backslash for doxygen) \\0
286 * This function is similar to DicomString(const char*),
287 * except it doesn't take a lenght.
288 * It only pad with a null character if length is odd
290 std::string Util::DicomString(const char *s)
292 size_t l = strlen(s);
297 std::string r(s, s+l);
298 gdcmAssertMacro( !(r.size() % 2) );
303 * \brief Safely compare two Dicom String:
304 * - Both string should be of even lenght
305 * - We allow padding of even lenght string by either a null
306 * character of a space
308 bool Util::DicomStringEqual(const std::string &s1, const char *s2)
310 // s2 is the string from the DICOM reference: 'MONOCHROME1'
311 std::string s1_even = s1; //Never change input parameter
312 std::string s2_even = DicomString( s2 );
313 if( s1_even[s1_even.size()-1] == ' ')
315 s1_even[s1_even.size()-1] = '\0'; //replace space character by null
317 return s1_even == s2_even;
323 * \brief tells us if the processor we are working with is BigEndian or not
325 bool Util::IsCurrentProcessorBigEndian()
327 #ifdef GDCM_WORDS_BIGENDIAN
337 typedef BOOL(WINAPI * pSnmpExtensionInit) (
338 IN DWORD dwTimeZeroReference,
339 OUT HANDLE * hPollForTrapEvent,
340 OUT AsnObjectIdentifier * supportedView);
342 typedef BOOL(WINAPI * pSnmpExtensionTrap) (
343 OUT AsnObjectIdentifier * enterprise,
344 OUT AsnInteger * genericTrap,
345 OUT AsnInteger * specificTrap,
346 OUT AsnTimeticks * timeStamp,
347 OUT RFC1157VarBindList * variableBindings);
349 typedef BOOL(WINAPI * pSnmpExtensionQuery) (
351 IN OUT RFC1157VarBindList * variableBindings,
352 OUT AsnInteger * errorStatus,
353 OUT AsnInteger * errorIndex);
355 typedef BOOL(WINAPI * pSnmpExtensionInitEx) (
356 OUT AsnObjectIdentifier * supportedView);
360 int GetMacAddrSys ( unsigned char *addr )
364 if (WSAStartup(MAKEWORD(2, 0), &WinsockData) != 0)
366 std::cerr << "This program requires Winsock 2.x!" << std::endl;
370 HANDLE PollForTrapEvent;
371 AsnObjectIdentifier SupportedView;
372 UINT OID_ifEntryType[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 3 };
373 UINT OID_ifEntryNum[] = { 1, 3, 6, 1, 2, 1, 2, 1 };
374 UINT OID_ipMACEntAddr[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 6 };
375 AsnObjectIdentifier MIB_ifMACEntAddr = {
376 sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr };
377 AsnObjectIdentifier MIB_ifEntryType = {
378 sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType };
379 AsnObjectIdentifier MIB_ifEntryNum = {
380 sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum };
381 RFC1157VarBindList varBindList;
382 RFC1157VarBind varBind[2];
383 AsnInteger errorStatus;
384 AsnInteger errorIndex;
385 AsnObjectIdentifier MIB_NULL = { 0, 0 };
391 // Load the SNMP dll and get the addresses of the functions necessary
392 HINSTANCE m_hInst = LoadLibrary("inetmib1.dll");
393 if (m_hInst < (HINSTANCE) HINSTANCE_ERROR)
398 pSnmpExtensionInit m_Init =
399 (pSnmpExtensionInit) GetProcAddress(m_hInst, "SnmpExtensionInit");
400 pSnmpExtensionInitEx m_InitEx =
401 (pSnmpExtensionInitEx) GetProcAddress(m_hInst, "SnmpExtensionInitEx");
402 pSnmpExtensionQuery m_Query =
403 (pSnmpExtensionQuery) GetProcAddress(m_hInst, "SnmpExtensionQuery");
404 pSnmpExtensionTrap m_Trap =
405 (pSnmpExtensionTrap) GetProcAddress(m_hInst, "SnmpExtensionTrap");
406 m_Init(GetTickCount(), &PollForTrapEvent, &SupportedView);
408 /* Initialize the variable list to be retrieved by m_Query */
409 varBindList.list = varBind;
410 varBind[0].name = MIB_NULL;
411 varBind[1].name = MIB_NULL;
413 // Copy in the OID to find the number of entries in the
415 varBindList.len = 1; // Only retrieving one item
416 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryNum);
417 ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
419 // printf("# of adapters in this system : %i\n",
420 // varBind[0].value.asnValue.number);
423 // Copy in the OID of ifType, the type of interface
424 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryType);
426 // Copy in the OID of ifPhysAddress, the address
427 SNMP_oidcpy(&varBind[1].name, &MIB_ifMACEntAddr);
431 // Submit the query. Responses will be loaded into varBindList.
432 // We can expect this call to succeed a # of times corresponding
433 // to the # of adapters reported to be in the system
434 ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
442 // Confirm that the proper type has been returned
443 ret = SNMP_oidncmp(&varBind[0].name, &MIB_ifEntryType,
444 MIB_ifEntryType.idLength);
449 dtmp = varBind[0].value.asnValue.number;
450 std::cerr << "Interface #" << j << " type : " << dtmp << std::endl;
452 // Type 6 describes ethernet interfaces
455 // Confirm that we have an address here
456 ret = SNMP_oidncmp(&varBind[1].name, &MIB_ifMACEntAddr,
457 MIB_ifMACEntAddr.idLength);
458 if ( !ret && varBind[1].value.asnValue.address.stream != NULL )
460 if ( (varBind[1].value.asnValue.address.stream[0] == 0x44)
461 && (varBind[1].value.asnValue.address.stream[1] == 0x45)
462 && (varBind[1].value.asnValue.address.stream[2] == 0x53)
463 && (varBind[1].value.asnValue.address.stream[3] == 0x54)
464 && (varBind[1].value.asnValue.address.stream[4] == 0x00) )
466 // Ignore all dial-up networking adapters
467 std::cerr << "Interface #" << j << " is a DUN adapter\n";
470 if ( (varBind[1].value.asnValue.address.stream[0] == 0x00)
471 && (varBind[1].value.asnValue.address.stream[1] == 0x00)
472 && (varBind[1].value.asnValue.address.stream[2] == 0x00)
473 && (varBind[1].value.asnValue.address.stream[3] == 0x00)
474 && (varBind[1].value.asnValue.address.stream[4] == 0x00)
475 && (varBind[1].value.asnValue.address.stream[5] == 0x00) )
477 // Ignore NULL addresses returned by other network
479 std::cerr << "Interface #" << j << " is a NULL address\n";
482 memcpy( addr, varBind[1].value.asnValue.address.stream, 6);
489 SNMP_FreeVarBind(&varBind[0]);
490 SNMP_FreeVarBind(&varBind[1]);
492 #endif //Win32 version
495 // implementation for POSIX system
497 //The POSIX version is broken anyway on Solaris, plus would require full
499 struct arpreq parpreq;
500 struct sockaddr_in *psa;
501 struct hostent *phost;
502 char hostname[MAXHOSTNAMELEN];
506 if(gethostname(hostname, MAXHOSTNAMELEN) != 0)
508 perror("gethostname");
511 phost = gethostbyname(hostname);
512 paddrs = phost->h_addr_list;
514 sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
520 memset(&parpreq, 0, sizeof(struct arpreq));
521 psa = (struct sockaddr_in *) &parpreq.arp_pa;
523 memset(psa, 0, sizeof(struct sockaddr_in));
524 psa->sin_family = AF_INET;
525 memcpy(&psa->sin_addr, *paddrs, sizeof(struct in_addr));
527 status = ioctl(sock, SIOCGARP, &parpreq);
533 memcpy(addr, parpreq.arp_ha.sa_data, 6);
537 #ifdef CMAKE_HAVE_NET_IF_H
539 struct ifreq ifr, *ifrp;
544 #if defined(AF_LINK) && (!defined(SIOCGIFHWADDR) && !defined(SIOCGENADDR))
545 struct sockaddr_dl *sdlp;
549 // BSD 4.4 defines the size of an ifreq to be
550 // max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len
551 // However, under earlier systems, sa_len isn't present, so the size is
552 // just sizeof(struct ifreq)
553 // We should investiage the use of SIZEOF_ADDR_IFREQ
557 #define max(a,b) ((a) > (b) ? (a) : (b))
559 #define ifreq_size(i) max(sizeof(struct ifreq),\
560 sizeof((i).ifr_name)+(i).ifr_addr.sa_len)
562 #define ifreq_size(i) sizeof(struct ifreq)
563 #endif // HAVE_SA_LEN
565 if( (sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0 )
569 memset(buf, 0, sizeof(buf));
570 ifc.ifc_len = sizeof(buf);
572 if (ioctl (sd, SIOCGIFCONF, (char *)&ifc) < 0)
578 for (i = 0; i < n; i+= ifreq_size(*ifrp) )
580 ifrp = (struct ifreq *)((char *) ifc.ifc_buf+i);
581 strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ);
583 if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0)
585 a = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
588 // In theory this call should also work on Sun Solaris, but apparently
589 // SIOCGENADDR is not implemented properly thus the call
590 // ioctl(sd, SIOCGENADDR, &ifr) always returns errno=2
591 // (No such file or directory)
592 // Furthermore the DLAPI seems to require full root access
593 if (ioctl(sd, SIOCGENADDR, &ifr) < 0)
595 a = (unsigned char *) ifr.ifr_enaddr;
598 sdlp = (struct sockaddr_dl *) &ifrp->ifr_addr;
599 if ((sdlp->sdl_family != AF_LINK) || (sdlp->sdl_alen != 6))
601 a = (unsigned char *) &sdlp->sdl_data[sdlp->sdl_nlen];
603 perror("No way to access hardware");
607 #endif // SIOCGENADDR
608 #endif // SIOCGIFHWADDR
609 if (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5]) continue;
620 /* Not implemented platforms */
621 perror("There was a configuration problem on your plateform");
628 * \brief Gets the M.A.C. adress of the machine writting the DICOM image
630 std::string Util::GetMACAddress()
632 // This code is the result of a long internet search to find something
633 // as compact as possible (not OS independant). We only have to separate
634 // 3 OS: Win32, SunOS and 'real' POSIX
635 // http://groups-beta.google.com/group/comp.unix.solaris/msg/ad36929d783d63be
636 // http://bdn.borland.com/article/0,1410,26040,00.html
637 unsigned char addr[6];
640 int stat = GetMacAddrSys(addr);
643 for (int i=0; i<6; ++i)
645 macaddr += Format("%2.2x", addr[i]);
646 //if(i) macaddr += ".";
647 //macaddr += Format("%i", (int)addr[i]);
653 gdcmVerboseMacro("Problem in finding the MAC Address");
659 * \brief Return the IP adress of the machine writting the DICOM image
661 std::string Util::GetIPAddress()
663 // This is a rip from
664 // http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
665 #ifndef HOST_NAME_MAX
666 // SUSv2 guarantees that `Host names are limited to 255 bytes'.
667 // POSIX 1003.1-2001 guarantees that `Host names (not including the
668 // terminating NUL) are limited to HOST_NAME_MAX bytes'.
669 # define HOST_NAME_MAX 255
670 // In this case we should maybe check the string was not truncated.
671 // But I don't known how to check that...
672 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
673 // with WinSock DLL we need to initialize the WinSock before using gethostname
674 WORD wVersionRequested = MAKEWORD(1,0);
676 int err = WSAStartup(wVersionRequested,&WSAData);
679 // Tell the user that we could not find a usable
686 #endif //HOST_NAME_MAX
689 char szHostName[HOST_NAME_MAX+1];
690 int r = gethostname(szHostName, HOST_NAME_MAX);
695 struct hostent *pHost = gethostbyname(szHostName);
697 for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
699 for( int j = 0; j<pHost->h_length; j++ )
701 if( j > 0 ) str += ".";
703 str += Util::Format("%u",
704 (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
706 // str now contains one local IP address
708 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
714 // If an error occur r == -1
715 // Most of the time it will return 127.0.0.1...
720 * \brief Creates a new UID. As stipulate in the DICOM ref
721 * each time a DICOM image is create it should have
722 * a unique identifier (URI)
724 std::string Util::CreateUniqueUID(const std::string &root)
726 std::string radical = root;
729 // No root was specified use "GDCM" then
730 // echo "gdcm" | od -b
731 // 0000000 147 144 143 155 012
732 radical = "147.144.143.155"; // special easter egg
735 // A root was specified use it to forge our new UID:
736 radical += Util::GetMACAddress();
738 radical += Util::GetCurrentDate();
740 radical += Util::GetCurrentTime();
747 * @param os ostream to write to
751 std::ostream &binary_write(std::ostream &os, const T &val)
753 return os.write(reinterpret_cast<const char*>(&val), sizeof val);
757 * \brief binary_write binary_write
758 * @param os ostream to write to
761 std::ostream &binary_write(std::ostream &os, const uint16_t &val)
763 #ifdef GDCM_WORDS_BIGENDIAN
765 swap = ((( val << 8 ) & 0x0ff00 ) | (( val >> 8 ) & 0x00ff ) );
766 return os.write(reinterpret_cast<const char*>(&swap), 2);
768 return os.write(reinterpret_cast<const char*>(&val), 2);
769 #endif //GDCM_WORDS_BIGENDIAN
773 * \brief binary_write binary_write
774 * @param os ostream to write to
777 std::ostream &binary_write(std::ostream &os, const uint32_t &val)
779 #ifdef GDCM_WORDS_BIGENDIAN
781 swap = ( ((val<<24) & 0xff000000) | ((val<<8) & 0x00ff0000) |
782 ((val>>8) & 0x0000ff00) | ((val>>24) & 0x000000ff) );
783 return os.write(reinterpret_cast<const char*>(&swap), 4);
785 return os.write(reinterpret_cast<const char*>(&val), 4);
786 #endif //GDCM_WORDS_BIGENDIAN
790 * \brief binary_write binary_write
791 * @param os ostream to write to
794 std::ostream &binary_write(std::ostream &os, const char *val)
796 return os.write(val, strlen(val));
801 * @param os ostream to write to
804 std::ostream &binary_write(std::ostream &os, std::string const &val)
806 return os.write(val.c_str(), val.size());
809 } // end namespace gdcm