1 /*=========================================================================
4 Module: $RCSfile: gdcmUtil.cxx,v $
6 Date: $Date: 2005/01/06 20:03:28 $
7 Version: $Revision: 1.77 $
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"
22 // For GetCurrentDate, GetCurrentTime
24 #include <sys/types.h>
27 #include <stdarg.h> //only included in implementation file
28 #include <stdio.h> //only included in implementation file
31 #include <winsock.h> // for gethostname & gethostbyname
35 #include <unistd.h> // for gethostname
36 #include <netdb.h> // for gethostbyname
44 * \brief Provide a better 'c++' approach for sprintf
45 * For example c code is:
46 * sprintf(trash, "%04x|%04x", group , element);
49 * std::ostringstream buf;
50 * buf << std::right << std::setw(4) << std::setfill('0') << std::hex
51 * << group << "|" << std::right << std::setw(4) << std::setfill('0')
52 * << std::hex << element;
56 std::string Util::Format(const char *format, ...)
60 va_start(args, format);
61 vsprintf(buffer, format, args); //might be a security flaw
62 va_end(args); // Each invocation of va_start should be matched
63 // by a corresponding invocation of va_end
64 // args is then 'undefined'
71 * \brief Because not available in C++ (?)
73 void Util::Tokenize (const std::string &str,
74 std::vector<std::string> &tokens,
75 const std::string& delimiters)
77 std::string::size_type lastPos = str.find_first_not_of(delimiters,0);
78 std::string::size_type pos = str.find_first_of (delimiters,lastPos);
79 while (std::string::npos != pos || std::string::npos != lastPos)
81 tokens.push_back(str.substr(lastPos, pos - lastPos));
82 lastPos = str.find_first_not_of(delimiters, pos);
83 pos = str.find_first_of (delimiters, lastPos);
89 * \brief Because not available in C++ (?)
90 * Counts the number of occurences of a substring within a string
93 int Util::CountSubstring (const std::string &str,
94 const std::string &subStr)
96 int count = 0; // counts how many times it appears
97 std::string::size_type x = 0; // The index position in the string
101 x = str.find(subStr,x); // Find the substring
102 if (x != std::string::npos) // If present
104 count++; // increase the count
105 x += subStr.length(); // Skip this word
108 while (x != std::string::npos); // Carry on until not present
115 * \brief Weed out a string from the non-printable characters (in order
116 * to avoid corrupting the terminal of invocation when printing)
117 * @param s string to remove non printable characters from
119 std::string Util::CreateCleanString(std::string const &s)
123 for(unsigned int i=0; i<str.size(); i++)
125 if(!isprint((unsigned char)str[i]))
133 if(!isprint((unsigned char)s[str.size()-1]))
135 if(s[str.size()-1] == 0)
137 str[str.size()-1] = ' ';
147 * \brief Add a SEPARATOR to the end of the name is necessary
148 * @param pathname file/directory name to normalize
150 std::string Util::NormalizePath(std::string const &pathname)
152 const char SEPARATOR_X = '/';
153 const char SEPARATOR_WIN = '\\';
154 const std::string SEPARATOR = "/";
155 std::string name = pathname;
156 int size = name.size();
158 if( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
167 * \brief Get the (directory) path from a full path file name
168 * @param fullName file/directory name to extract Path from
170 std::string Util::GetPath(std::string const &fullName)
172 std::string res = fullName;
173 int pos1 = res.rfind("/");
174 int pos2 = res.rfind("\\");
189 * \brief Get the (last) name of a full path file name
190 * @param fullName file/directory name to extract end name from
192 std::string Util::GetName(std::string const &fullName)
194 std::string filename = fullName;
196 std::string::size_type slash_pos = filename.rfind("/");
197 std::string::size_type backslash_pos = filename.rfind("\\");
198 slash_pos = slash_pos > backslash_pos ? slash_pos : backslash_pos;
199 if(slash_pos != std::string::npos)
201 return filename.substr(slash_pos + 1);
211 * \brief Get the current date of the system in a dicom string
213 std::string Util::GetCurrentDate()
218 strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
224 * \brief Get the current time of the system in a dicom string
226 std::string Util::GetCurrentTime()
231 strftime(tmp,512,"%H%M%S", localtime(&tloc) );
236 * \brief Create a /DICOM/ string:
237 * It should a of even length (no odd length ever)
238 * It can contain as many (if you are reading this from your
239 * editor the following character is is backslash followed by zero
240 * that needed to be escaped with an extra backslash for doxygen) \\0
243 std::string Util::DicomString(const char *s, size_t l)
245 std::string r(s, s+l);
246 assert( !(r.size() % 2) ); // == basically 'l' is even
252 * \brief Create a /DICOM/ string:
253 * It should a of even lenght (no odd length ever)
254 * It can contain as many (if you are reading this from your
255 * editor the following character is is backslash followed by zero
256 * that needed to be escaped with an extra backslash for doxygen) \\0
258 * This function is similar to DicomString(const char*),
259 * except it doesn't take a lenght.
260 * It only pad with a null character if length is odd
262 std::string Util::DicomString(const char *s)
264 size_t l = strlen(s);
269 std::string r(s, s+l);
270 assert( !(r.size() % 2) );
276 * \brief Safely compare two Dicom String:
277 * - Both string should be of even lenght
278 * - We allow padding of even lenght string by either a null
279 * character of a space
281 bool Util::DicomStringEqual(const std::string &s1, const char *s2)
283 // s2 is the string from the DICOM reference: 'MONOCHROME1'
284 std::string s1_even = s1; //Never change input parameter
285 std::string s2_even = DicomString( s2 );
286 if( s1_even[s1_even.size()-1] == ' ')
288 s1_even[s1_even.size()-1] = '\0'; //replace space character by null
290 return s1_even == s2_even;
297 * \brief tells us if the processor we are working with is BigEndian or not
299 bool Util::IsCurrentProcessorBigEndian()
302 uint8_t bigEndianRepr[4] = { 0x00, 0x00, 0x00, 0x01 };
303 int res = memcmp(reinterpret_cast<const void*>(&intVal),
304 reinterpret_cast<const void*>(bigEndianRepr), 4);
320 typedef BOOL(WINAPI * pSnmpExtensionInit) (
321 IN DWORD dwTimeZeroReference,
322 OUT HANDLE * hPollForTrapEvent,
323 OUT AsnObjectIdentifier * supportedView);
325 typedef BOOL(WINAPI * pSnmpExtensionTrap) (
326 OUT AsnObjectIdentifier * enterprise,
327 OUT AsnInteger * genericTrap,
328 OUT AsnInteger * specificTrap,
329 OUT AsnTimeticks * timeStamp,
330 OUT RFC1157VarBindList * variableBindings);
332 typedef BOOL(WINAPI * pSnmpExtensionQuery) (
334 IN OUT RFC1157VarBindList * variableBindings,
335 OUT AsnInteger * errorStatus,
336 OUT AsnInteger * errorIndex);
338 typedef BOOL(WINAPI * pSnmpExtensionInitEx) (
339 OUT AsnObjectIdentifier * supportedView);
341 #include <strings.h> //for bzero on unix
345 #include <sys/ioctl.h>
346 #include <sys/types.h>
347 #include <sys/socket.h>
348 #include <netinet/in.h>
349 #include <linux/if.h>
357 #include <sys/ndd_var.h>
358 #include <sys/kinfo.h>
361 long GetMacAddrSys ( u_char *addr)
365 if (WSAStartup(MAKEWORD(2, 0), &WinsockData) != 0) {
366 fprintf(stderr, "This program requires Winsock 2.x!\n");
371 pSnmpExtensionInit m_Init;
372 pSnmpExtensionInitEx m_InitEx;
373 pSnmpExtensionQuery m_Query;
374 pSnmpExtensionTrap m_Trap;
375 HANDLE PollForTrapEvent;
376 AsnObjectIdentifier SupportedView;
377 UINT OID_ifEntryType[] = {
378 1, 3, 6, 1, 2, 1, 2, 2, 1, 3
380 UINT OID_ifEntryNum[] = {
381 1, 3, 6, 1, 2, 1, 2, 1
383 UINT OID_ipMACEntAddr[] = {
384 1, 3, 6, 1, 2, 1, 2, 2, 1, 6
386 AsnObjectIdentifier MIB_ifMACEntAddr =
387 { sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr };
388 AsnObjectIdentifier MIB_ifEntryType = {
389 sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType
391 AsnObjectIdentifier MIB_ifEntryNum = {
392 sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum
394 RFC1157VarBindList varBindList;
395 RFC1157VarBind varBind[2];
396 AsnInteger errorStatus;
397 AsnInteger errorIndex;
398 AsnObjectIdentifier MIB_NULL = {
405 char TempEthernet[13];
411 /* Load the SNMP dll and get the addresses of the functions
413 m_hInst = LoadLibrary("inetmib1.dll");
414 if (m_hInst < (HINSTANCE) HINSTANCE_ERROR) {
419 (pSnmpExtensionInit) GetProcAddress(m_hInst, "SnmpExtensionInit");
421 (pSnmpExtensionInitEx) GetProcAddress(m_hInst,
422 "SnmpExtensionInitEx");
424 (pSnmpExtensionQuery) GetProcAddress(m_hInst,
425 "SnmpExtensionQuery");
427 (pSnmpExtensionTrap) GetProcAddress(m_hInst, "SnmpExtensionTrap");
428 m_Init(GetTickCount(), &PollForTrapEvent, &SupportedView);
430 /* Initialize the variable list to be retrieved by m_Query */
431 varBindList.list = varBind;
432 varBind[0].name = MIB_NULL;
433 varBind[1].name = MIB_NULL;
435 /* Copy in the OID to find the number of entries in the
437 varBindList.len = 1; /* Only retrieving one item */
438 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryNum);
440 m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
442 printf("# of adapters in this system : %i\n",
443 varBind[0].value.asnValue.number); varBindList.len = 2;
445 /* Copy in the OID of ifType, the type of interface */
446 SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryType);
448 /* Copy in the OID of ifPhysAddress, the address */
449 SNMP_oidcpy(&varBind[1].name, &MIB_ifMACEntAddr);
453 /* Submit the query. Responses will be loaded into varBindList.
454 We can expect this call to succeed a # of times corresponding
455 to the # of adapters reported to be in the system */
457 m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
458 &errorIndex); if (!ret) ret = 1;
461 /* Confirm that the proper type has been returned */
463 SNMP_oidncmp(&varBind[0].name, &MIB_ifEntryType,
464 MIB_ifEntryType.idLength); if (!ret) {
466 dtmp = varBind[0].value.asnValue.number;
467 printf("Interface #%i type : %i\n", j, dtmp);
469 /* Type 6 describes ethernet interfaces */
472 /* Confirm that we have an address here */
474 SNMP_oidncmp(&varBind[1].name, &MIB_ifMACEntAddr,
475 MIB_ifMACEntAddr.idLength);
477 && (varBind[1].value.asnValue.address.stream != NULL)) {
479 (varBind[1].value.asnValue.address.stream[0] ==
481 && (varBind[1].value.asnValue.address.stream[1] ==
483 && (varBind[1].value.asnValue.address.stream[2] ==
485 && (varBind[1].value.asnValue.address.stream[3] ==
487 && (varBind[1].value.asnValue.address.stream[4] ==
490 /* Ignore all dial-up networking adapters */
491 printf("Interface #%i is a DUN adapter\n", j);
495 (varBind[1].value.asnValue.address.stream[0] ==
497 && (varBind[1].value.asnValue.address.stream[1] ==
499 && (varBind[1].value.asnValue.address.stream[2] ==
501 && (varBind[1].value.asnValue.address.stream[3] ==
503 && (varBind[1].value.asnValue.address.stream[4] ==
505 && (varBind[1].value.asnValue.address.stream[5] ==
508 /* Ignore NULL addresses returned by other network
510 printf("Interface #%i is a NULL address\n", j);
513 sprintf((char*)addr, "%02x%02x%02x%02x%02x%02x",
514 varBind[1].value.asnValue.address.stream[0],
515 varBind[1].value.asnValue.address.stream[1],
516 varBind[1].value.asnValue.address.stream[2],
517 varBind[1].value.asnValue.address.stream[3],
518 varBind[1].value.asnValue.address.stream[4],
519 varBind[1].value.asnValue.address.stream[5]);
520 printf("MAC Address of interface #%i: %s\n", j, TempEthernet);
524 } while (!ret); /* Stop only on an error. An error will occur
525 when we go exhaust the list of interfaces to
529 /* Free the bindings */
530 SNMP_FreeVarBind(&varBind[0]);
531 SNMP_FreeVarBind(&varBind[1]);
535 /* implementation for Linux */
544 s = socket(AF_INET, SOCK_DGRAM, 0);
549 ifc.ifc_len = sizeof(buf);
551 ioctl(s, SIOCGIFCONF, &ifc);
554 for (i = ifc.ifc_len / sizeof(struct ifreq); --i >= 0; IFR++) {
556 strcpy(ifr.ifr_name, IFR->ifr_name);
557 if (ioctl(s, SIOCGIFFLAGS, &ifr) == 0) {
558 if (! (ifr.ifr_flags & IFF_LOOPBACK)) {
559 if (ioctl(s, SIOCGIFHWADDR, &ifr) == 0) {
569 bcopy( ifr.ifr_hwaddr.sa_data, addr, 6);
577 /* implementation for HP-UX */
580 #define LAN_DEV0 "/dev/lan0"
583 struct fis iocnt_block;
585 char net_buf[sizeof(LAN_DEV0)+1];
588 (void)sprintf(net_buf, "%s", LAN_DEV0);
589 p = net_buf + strlen(net_buf) - 1;
592 * Get 802.3 address from card by opening the driver and interrogating it.
594 for (i = 0; i < 10; i++, (*p)++) {
595 if ((fd = open (net_buf, O_RDONLY)) != -1) {
596 iocnt_block.reqtype = LOCAL_ADDRESS;
597 ioctl (fd, NETSTAT, &iocnt_block);
600 if (iocnt_block.vtype == 6)
605 if (fd == -1 || iocnt_block.vtype != 6) {
609 bcopy( &iocnt_block.value.s[0], addr, 6);
614 /* implementation for AIX */
618 struct kinfo_ndd *nddp;
620 size = getkerninfo(KINFO_NDD, 0, 0, 0);
624 nddp = (struct kinfo_ndd *)malloc(size);
629 if (getkerninfo(KINFO_NDD, nddp, &size, 0) < 0) {
633 bcopy(nddp->ndd_addr, addr, 6);
638 /* Not implemented platforms */
642 std::string Util::GetMACAddress()
644 // This is a rip from: http://cplus.kompf.de/macaddr.html for Linux, HPUX and AIX
645 // and http://tangentsoft.net/wskfaq/examples/src/snmpmac.cpp for windows version
650 stat = GetMacAddrSys( addr);
653 //printf( "MAC address = ");
654 for (int i=0; i<6; ++i)
656 //printf("%2.2x", addr[i]);
657 macaddr += Format("%2.2x", addr[i]);
664 //printf( "No MAC address !\n" );
671 * \brief Return the IP adress of the machine writting the DICOM image
673 std::string Util::GetIPAddress()
675 // This is a rip from http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
676 #ifndef HOST_NAME_MAX
677 // SUSv2 guarantees that `Host names are limited to 255 bytes'.
678 // POSIX 1003.1-2001 guarantees that `Host names (not including the
679 // terminating NUL) are limited to HOST_NAME_MAX bytes'.
680 # define HOST_NAME_MAX 255
681 // In this case we should maybe check the string was not truncated.
682 // But I don't known how to check that...
683 #if defined(_MSC_VER) || defined(__BORLANDC__)
684 // with WinSock DLL we need to initialise the WinSock before using gethostname
685 WORD wVersionRequested = MAKEWORD(1,0);
687 int err = WSAStartup(wVersionRequested,&WSAData);
689 /* Tell the user that we could not find a usable */
696 #endif //HOST_NAME_MAX
699 char szHostName[HOST_NAME_MAX+1];
700 int r = gethostname(szHostName, HOST_NAME_MAX);
705 struct hostent *pHost = gethostbyname(szHostName);
707 for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
709 for( int j = 0; j<pHost->h_length; j++ )
711 if( j > 0 ) str += ".";
713 str += Util::Format("%u",
714 (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
716 // str now contains one local IP address
718 #if defined(_MSC_VER) || defined(__BORLANDC__)
724 // If an error occur r == -1
725 // Most of the time it will return 127.0.0.1...
731 * \brief Creates a new UID. As stipulate in the DICOM ref
732 * each time a DICOM image is create it should have
733 * a unique identifier (URI)
735 std::string Util::CreateUniqueUID(const std::string &root)
737 // The code works as follow:
738 // echo "gdcm" | od -b
739 // 0000000 147 144 143 155 012
740 // Therefore we return
741 // radical + 147.144.143.155 + IP + time()
742 std::string radical = root;
743 if( !root.size() ) //anything better ?
745 radical = "0.0."; // Is this really usefull ?
748 // A root was specified use it to forge our new UID:
749 radical += "147.144.143.155"; // gdcm
751 radical += Util::GetIPAddress();
753 radical += Util::GetCurrentDate();
755 radical += Util::GetCurrentTime();
761 std::ostream &binary_write(std::ostream &os, const T &val)
763 return os.write(reinterpret_cast<const char*>(&val), sizeof val);
766 std::ostream &binary_write(std::ostream &os, const uint16_t &val)
768 #ifdef GDCM_WORDS_BIGENDIAN
770 swap = ((( val << 8 ) & 0x0ff00 ) | (( val >> 8 ) & 0x00ff ) );
771 return os.write(reinterpret_cast<const char*>(&swap), 2);
773 return os.write(reinterpret_cast<const char*>(&val), 2);
774 #endif //GDCM_WORDS_BIGENDIAN
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
789 std::ostream &binary_write(std::ostream &os, const char *val)
791 return os.write(val, strlen(val));
794 std::ostream &binary_write(std::ostream &os, std::string const &val)
796 return os.write(val.c_str(), val.size());
799 } // end namespace gdcm