1 /*=========================================================================
4 Module: $RCSfile: gdcmUtil.cxx,v $
6 Date: $Date: 2005/01/17 23:11:25 $
7 Version: $Revision: 1.109 $
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 #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>
79 * \brief Provide a better 'c++' approach for sprintf
80 * For example c code is:
81 * sprintf(trash, "%04x|%04x", group , elem);
84 * std::ostringstream buf;
85 * buf << std::right << std::setw(4) << std::setfill('0') << std::hex
86 * << group << "|" << std::right << std::setw(4) << std::setfill('0')
87 * << std::hex << elem;
91 * Format("%04x|%04x", group , elem);
94 std::string Util::Format(const char *format, ...)
98 va_start(args, format);
99 vsprintf(buffer, format, args); //might be a security flaw
100 va_end(args); // Each invocation of va_start should be matched
101 // by a corresponding invocation of va_end
102 // args is then 'undefined'
109 * \brief Because not available in C++ (?)
111 void Util::Tokenize (const std::string &str,
112 std::vector<std::string> &tokens,
113 const std::string& delimiters)
115 std::string::size_type lastPos = str.find_first_not_of(delimiters,0);
116 std::string::size_type pos = str.find_first_of (delimiters,lastPos);
117 while (std::string::npos != pos || std::string::npos != lastPos)
119 tokens.push_back(str.substr(lastPos, pos - lastPos));
120 lastPos = str.find_first_not_of(delimiters, pos);
121 pos = str.find_first_of (delimiters, lastPos);
127 * \brief Because not available in C++ (?)
128 * Counts the number of occurences of a substring within a string
131 int Util::CountSubstring (const std::string &str,
132 const std::string &subStr)
134 int count = 0; // counts how many times it appears
135 std::string::size_type x = 0; // The index position in the string
139 x = str.find(subStr,x); // Find the substring
140 if (x != std::string::npos) // If present
142 count++; // increase the count
143 x += subStr.length(); // Skip this word
146 while (x != std::string::npos); // Carry on until not present
153 * \brief Weed out a string from the non-printable characters (in order
154 * to avoid corrupting the terminal of invocation when printing)
155 * @param s string to remove non printable characters from
157 std::string Util::CreateCleanString(std::string const &s)
161 for(unsigned int i=0; i<str.size(); i++)
163 if(!isprint((unsigned char)str[i]))
171 if(!isprint((unsigned char)s[str.size()-1]))
173 if(s[str.size()-1] == 0)
175 str[str.size()-1] = ' ';
185 * \brief Add a SEPARATOR to the end of the name is necessary
186 * @param pathname file/directory name to normalize
188 std::string Util::NormalizePath(std::string const &pathname)
190 const char SEPARATOR_X = '/';
191 const char SEPARATOR_WIN = '\\';
192 const std::string SEPARATOR = "/";
193 std::string name = pathname;
194 int size = name.size();
196 if( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
205 * \brief Get the (directory) path from a full path file name
206 * @param fullName file/directory name to extract Path from
208 std::string Util::GetPath(std::string const &fullName)
210 std::string res = fullName;
211 int pos1 = res.rfind("/");
212 int pos2 = res.rfind("\\");
227 * \brief Get the (last) name of a full path file name
228 * @param fullName file/directory name to extract end name from
230 std::string Util::GetName(std::string const &fullName)
232 std::string filename = fullName;
234 std::string::size_type slash_pos = filename.rfind("/");
235 std::string::size_type backslash_pos = filename.rfind("\\");
236 slash_pos = slash_pos > backslash_pos ? slash_pos : backslash_pos;
237 if(slash_pos != std::string::npos)
239 return filename.substr(slash_pos + 1);
249 * \brief Get the current date of the system in a dicom string
251 std::string Util::GetCurrentDate()
256 strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
262 * \brief Get the current time of the system in a dicom string
264 std::string Util::GetCurrentTime()
269 strftime(tmp,512,"%H%M%S", localtime(&tloc) );
274 * \brief Create a /DICOM/ string:
275 * It should a of even length (no odd length ever)
276 * It can contain as many (if you are reading this from your
277 * editor the following character is is backslash followed by zero
278 * that needed to be escaped with an extra backslash for doxygen) \\0
281 std::string Util::DicomString(const char *s, size_t l)
283 std::string r(s, s+l);
284 gdcmAssertMacro( !(r.size() % 2) ); // == basically 'l' is even
290 * \brief Create a /DICOM/ string:
291 * It should a of even lenght (no odd length ever)
292 * It can contain as many (if you are reading this from your
293 * editor the following character is is backslash followed by zero
294 * that needed to be escaped with an extra backslash for doxygen) \\0
296 * This function is similar to DicomString(const char*),
297 * except it doesn't take a lenght.
298 * It only pad with a null character if length is odd
300 std::string Util::DicomString(const char *s)
302 size_t l = strlen(s);
307 std::string r(s, s+l);
308 gdcmAssertMacro( !(r.size() % 2) );
314 * \brief Safely compare two Dicom String:
315 * - Both string should be of even lenght
316 * - We allow padding of even lenght string by either a null
317 * character of a space
319 bool Util::DicomStringEqual(const std::string &s1, const char *s2)
321 // s2 is the string from the DICOM reference: 'MONOCHROME1'
322 std::string s1_even = s1; //Never change input parameter
323 std::string s2_even = DicomString( s2 );
324 if( s1_even[s1_even.size()-1] == ' ')
326 s1_even[s1_even.size()-1] = '\0'; //replace space character by null
328 return s1_even == s2_even;
335 * \brief tells us if the processor we are working with is BigEndian or not
337 bool Util::IsCurrentProcessorBigEndian()
339 #ifdef GDCM_WORDS_BIGENDIAN
349 typedef BOOL(WINAPI * pSnmpExtensionInit) (
350 IN DWORD dwTimeZeroReference,
351 OUT HANDLE * hPollForTrapEvent,
352 OUT AsnObjectIdentifier * supportedView);
354 typedef BOOL(WINAPI * pSnmpExtensionTrap) (
355 OUT AsnObjectIdentifier * enterprise,
356 OUT AsnInteger * genericTrap,
357 OUT AsnInteger * specificTrap,
358 OUT AsnTimeticks * timeStamp,
359 OUT RFC1157VarBindList * variableBindings);
361 typedef BOOL(WINAPI * pSnmpExtensionQuery) (
363 IN OUT RFC1157VarBindList * variableBindings,
364 OUT AsnInteger * errorStatus,
365 OUT AsnInteger * errorIndex);
367 typedef BOOL(WINAPI * pSnmpExtensionInitEx) (
368 OUT AsnObjectIdentifier * supportedView);
372 int GetMacAddrSys ( unsigned char *addr )
376 if (WSAStartup(MAKEWORD(2, 0), &WinsockData) != 0)
378 std::cerr << "This program requires Winsock 2.x!" << std::endl;
382 HANDLE PollForTrapEvent;
383 AsnObjectIdentifier SupportedView;
384 UINT OID_ifEntryType[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 3 };
385 UINT OID_ifEntryNum[] = { 1, 3, 6, 1, 2, 1, 2, 1 };
386 UINT OID_ipMACEntAddr[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 6 };
387 AsnObjectIdentifier MIB_ifMACEntAddr = {
388 sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr };
389 AsnObjectIdentifier MIB_ifEntryType = {
390 sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType };
391 AsnObjectIdentifier MIB_ifEntryNum = {
392 sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum };
393 RFC1157VarBindList varBindList;
394 RFC1157VarBind varBind[2];
395 AsnInteger errorStatus;
396 AsnInteger errorIndex;
397 AsnObjectIdentifier MIB_NULL = { 0, 0 };
403 // Load the SNMP dll and get the addresses of the functions necessary
404 HINSTANCE m_hInst = LoadLibrary("inetmib1.dll");
405 if (m_hInst < (HINSTANCE) HINSTANCE_ERROR)
410 pSnmpExtensionInit m_Init =
411 (pSnmpExtensionInit) GetProcAddress(m_hInst, "SnmpExtensionInit");
412 pSnmpExtensionInitEx m_InitEx =
413 (pSnmpExtensionInitEx) GetProcAddress(m_hInst, "SnmpExtensionInitEx");
414 pSnmpExtensionQuery m_Query =
415 (pSnmpExtensionQuery) GetProcAddress(m_hInst, "SnmpExtensionQuery");
416 pSnmpExtensionTrap m_Trap =
417 (pSnmpExtensionTrap) GetProcAddress(m_hInst, "SnmpExtensionTrap");
418 m_Init(GetTickCount(), &PollForTrapEvent, &SupportedView);
420 /* Initialize the variable list to be retrieved by m_Query */
421 varBindList.list = varBind;
422 varBind[0].name = MIB_NULL;
423 varBind[1].name = MIB_NULL;
425 // Copy in the OID to find the number of entries in the
427 varBindList.len = 1; // Only retrieving one item
428 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryNum);
429 ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
431 // printf("# of adapters in this system : %i\n",
432 // varBind[0].value.asnValue.number);
435 // Copy in the OID of ifType, the type of interface
436 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryType);
438 // Copy in the OID of ifPhysAddress, the address
439 SNMP_oidcpy(&varBind[1].name, &MIB_ifMACEntAddr);
443 // Submit the query. Responses will be loaded into varBindList.
444 // We can expect this call to succeed a # of times corresponding
445 // to the # of adapters reported to be in the system
446 ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
454 // Confirm that the proper type has been returned
455 ret = SNMP_oidncmp(&varBind[0].name, &MIB_ifEntryType,
456 MIB_ifEntryType.idLength);
461 dtmp = varBind[0].value.asnValue.number;
462 std::cerr << "Interface #" << j << " type : " << dtmp << std::endl;
464 // Type 6 describes ethernet interfaces
467 // Confirm that we have an address here
468 ret = SNMP_oidncmp(&varBind[1].name, &MIB_ifMACEntAddr,
469 MIB_ifMACEntAddr.idLength);
470 if ( !ret && varBind[1].value.asnValue.address.stream != NULL )
472 if ( (varBind[1].value.asnValue.address.stream[0] == 0x44)
473 && (varBind[1].value.asnValue.address.stream[1] == 0x45)
474 && (varBind[1].value.asnValue.address.stream[2] == 0x53)
475 && (varBind[1].value.asnValue.address.stream[3] == 0x54)
476 && (varBind[1].value.asnValue.address.stream[4] == 0x00) )
478 // Ignore all dial-up networking adapters
479 std::cerr << "Interface #" << j << " is a DUN adapter\n";
482 if ( (varBind[1].value.asnValue.address.stream[0] == 0x00)
483 && (varBind[1].value.asnValue.address.stream[1] == 0x00)
484 && (varBind[1].value.asnValue.address.stream[2] == 0x00)
485 && (varBind[1].value.asnValue.address.stream[3] == 0x00)
486 && (varBind[1].value.asnValue.address.stream[4] == 0x00)
487 && (varBind[1].value.asnValue.address.stream[5] == 0x00) )
489 // Ignore NULL addresses returned by other network
491 std::cerr << "Interface #" << j << " is a NULL address\n";
494 memcpy( addr, varBind[1].value.asnValue.address.stream, 6);
501 SNMP_FreeVarBind(&varBind[0]);
502 SNMP_FreeVarBind(&varBind[1]);
504 #endif //Win32 version
507 // implementation for POSIX system
509 //The POSIX version is broken anyway on Solaris, plus would require full
512 struct arpreq parpreq;
513 struct sockaddr_in sa, *psa;
514 struct in_addr inaddr;
515 struct hostent *phost;
516 char hostname[MAXHOSTNAMELEN];
521 if(gethostname(hostname, MAXHOSTNAMELEN) != 0)
523 perror("gethostname");
526 phost = gethostbyname(hostname);
527 paddrs = phost->h_addr_list;
529 sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
535 memset(&parpreq, 0, sizeof(struct arpreq));
536 psa = (struct sockaddr_in *) &parpreq.arp_pa;
538 memset(psa, 0, sizeof(struct sockaddr_in));
539 psa->sin_family = AF_INET;
540 memcpy(&psa->sin_addr, *paddrs, sizeof(struct in_addr));
542 status = ioctl(sock, SIOCGARP, &parpreq);
548 memcpy(addr, parpreq.arp_ha.sa_data, 6);
552 #ifdef CMAKE_HAVE_NET_IF_H
554 struct ifreq ifr, *ifrp;
559 #if defined(AF_LINK) && (!defined(SIOCGIFHWADDR) && !defined(SIOCGENADDR))
560 struct sockaddr_dl *sdlp;
564 // BSD 4.4 defines the size of an ifreq to be
565 // max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len
566 // However, under earlier systems, sa_len isn't present, so the size is
567 // just sizeof(struct ifreq)
568 // We should investiage the use of SIZEOF_ADDR_IFREQ
572 #define max(a,b) ((a) > (b) ? (a) : (b))
574 #define ifreq_size(i) max(sizeof(struct ifreq),\
575 sizeof((i).ifr_name)+(i).ifr_addr.sa_len)
577 #define ifreq_size(i) sizeof(struct ifreq)
578 #endif // HAVE_SA_LEN
580 if( (sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0 )
584 memset(buf, 0, sizeof(buf));
585 ifc.ifc_len = sizeof(buf);
587 if (ioctl (sd, SIOCGIFCONF, (char *)&ifc) < 0)
593 for (i = 0; i < n; i+= ifreq_size(*ifrp) )
595 ifrp = (struct ifreq *)((char *) ifc.ifc_buf+i);
596 strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ);
598 if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0)
600 a = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
603 // In theory this call should also work on Sun Solaris, but apparently
604 // SIOCGENADDR is not implemented properly thus the call
605 // ioctl(sd, SIOCGENADDR, &ifr) always returns errno=2
606 // (No such file or directory)
607 // Furthermore the DLAPI seems to require full root access
608 if (ioctl(sd, SIOCGENADDR, &ifr) < 0)
610 a = (unsigned char *) ifr.ifr_enaddr;
613 sdlp = (struct sockaddr_dl *) &ifrp->ifr_addr;
614 if ((sdlp->sdl_family != AF_LINK) || (sdlp->sdl_alen != 6))
616 a = (unsigned char *) &sdlp->sdl_data[sdlp->sdl_nlen];
618 perror("No way to access hardware");
622 #endif // SIOCGENADDR
623 #endif // SIOCGIFHWADDR
624 if (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5]) continue;
635 /* Not implemented platforms */
636 perror("There was a configuration problem on your plateform");
642 std::string Util::GetMACAddress()
644 // This code is the result of a long internet search to find something
645 // as compact as possible (not OS independant). We only have to separate
646 // 3 OS: Win32, SunOS and 'real' POSIX
647 // http://groups-beta.google.com/group/comp.unix.solaris/msg/ad36929d783d63be
648 // http://bdn.borland.com/article/0,1410,26040,00.html
649 unsigned char addr[6];
652 int stat = GetMacAddrSys(addr);
655 for (int i=0; i<6; ++i)
657 macaddr += Format("%2.2x", addr[i]);
658 //if(i) macaddr += ".";
659 //macaddr += Format("%i", (int)addr[i]);
665 gdcmVerboseMacro("Problem in finding the MAC Address");
672 * \brief Return the IP adress of the machine writting the DICOM image
674 std::string Util::GetIPAddress()
676 // This is a rip from
677 // http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
678 #ifndef HOST_NAME_MAX
679 // SUSv2 guarantees that `Host names are limited to 255 bytes'.
680 // POSIX 1003.1-2001 guarantees that `Host names (not including the
681 // terminating NUL) are limited to HOST_NAME_MAX bytes'.
682 # define HOST_NAME_MAX 255
683 // In this case we should maybe check the string was not truncated.
684 // But I don't known how to check that...
685 #if defined(_MSC_VER) || defined(__BORLANDC__)
686 // with WinSock DLL we need to initialise the WinSock before using gethostname
687 WORD wVersionRequested = MAKEWORD(1,0);
689 int err = WSAStartup(wVersionRequested,&WSAData);
692 // Tell the user that we could not find a usable
699 #endif //HOST_NAME_MAX
702 char szHostName[HOST_NAME_MAX+1];
703 int r = gethostname(szHostName, HOST_NAME_MAX);
708 struct hostent *pHost = gethostbyname(szHostName);
710 for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
712 for( int j = 0; j<pHost->h_length; j++ )
714 if( j > 0 ) str += ".";
716 str += Util::Format("%u",
717 (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
719 // str now contains one local IP address
721 #if defined(_MSC_VER) || defined(__BORLANDC__)
727 // If an error occur r == -1
728 // Most of the time it will return 127.0.0.1...
734 * \brief Creates a new UID. As stipulate in the DICOM ref
735 * each time a DICOM image is create it should have
736 * a unique identifier (URI)
738 std::string Util::CreateUniqueUID(const std::string &root)
740 std::string radical = root;
743 // No root was specified use "GDCM" then
744 // echo "gdcm" | od -b
745 // 0000000 147 144 143 155 012
746 radical = "147.144.143.155"; // special easter egg
749 // A root was specified use it to forge our new UID:
750 radical += Util::GetMACAddress();
752 radical += Util::GetCurrentDate();
754 radical += Util::GetCurrentTime();
760 std::ostream &binary_write(std::ostream &os, const T &val)
762 return os.write(reinterpret_cast<const char*>(&val), sizeof val);
765 std::ostream &binary_write(std::ostream &os, const uint16_t &val)
767 #ifdef GDCM_WORDS_BIGENDIAN
769 swap = ((( val << 8 ) & 0x0ff00 ) | (( val >> 8 ) & 0x00ff ) );
770 return os.write(reinterpret_cast<const char*>(&swap), 2);
772 return os.write(reinterpret_cast<const char*>(&val), 2);
773 #endif //GDCM_WORDS_BIGENDIAN
776 std::ostream &binary_write(std::ostream &os, const uint32_t &val)
778 #ifdef GDCM_WORDS_BIGENDIAN
780 swap = ( ((val<<24) & 0xff000000) | ((val<<8) & 0x00ff0000) |
781 ((val>>8) & 0x0000ff00) | ((val>>24) & 0x000000ff) );
782 return os.write(reinterpret_cast<const char*>(&swap), 4);
784 return os.write(reinterpret_cast<const char*>(&val), 4);
785 #endif //GDCM_WORDS_BIGENDIAN
788 std::ostream &binary_write(std::ostream &os, const char *val)
790 return os.write(val, strlen(val));
793 std::ostream &binary_write(std::ostream &os, std::string const &val)
795 return os.write(val.c_str(), val.size());
798 } // end namespace gdcm