]> Creatis software - gdcm.git/blob - src/gdcmUtil.cxx
* Remove all gdcmStaticXxxMacro with Xxx : Debug, Warning, Error or Assert when...
[gdcm.git] / src / gdcmUtil.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmUtil.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/11/28 16:50:33 $
7   Version:   $Revision: 1.178 $
8                                                                                 
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.
12                                                                                 
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.
16                                                                                 
17 =========================================================================*/
18
19 #include "gdcmUtil.h"
20 #include "gdcmDebug.h"
21
22 #include <iostream>
23 #include <stdarg.h> // for va_list
24
25 // For GetCurrentDate, GetCurrentTime
26 #include <time.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29
30 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
31 #include <sys/timeb.h>
32 #else
33 #include <sys/time.h>
34 #endif
35
36 #include <stdarg.h>  //only included in implementation file
37 #include <stdio.h>   //only included in implementation file
38
39 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
40    #include <winsock.h>  // for gethostname and gethostbyname and GetTickCount...
41 // I haven't find a way to determine wether we need to under GetCurrentTime or not...
42 // I think the best solution would simply to get rid of this problematic function
43 // and use a 'less' common name...
44 #if !defined(__BORLANDC__) || (__BORLANDC__ >= 0x0560)
45    #undef GetCurrentTime
46 #endif
47 #else
48    #include <unistd.h>  // for gethostname
49    #include <netdb.h>   // for gethostbyname
50 #endif
51
52 // For GetMACAddress
53 #ifdef _WIN32
54    #include <snmp.h>
55    #include <conio.h>
56 #else
57    #include <unistd.h>
58    #include <stdlib.h>
59    #include <string.h>
60    #include <sys/types.h>
61 #endif
62
63 #ifdef CMAKE_HAVE_SYS_IOCTL_H
64    #include <sys/ioctl.h>  // For SIOCGIFCONF on Linux
65 #endif
66 #ifdef CMAKE_HAVE_SYS_SOCKET_H
67    #include <sys/socket.h>
68 #endif
69 #ifdef CMAKE_HAVE_SYS_SOCKIO_H
70    #include <sys/sockio.h>  // For SIOCGIFCONF on SunOS
71 #endif
72 #ifdef CMAKE_HAVE_NET_IF_H
73    #include <net/if.h>
74 #endif
75 #ifdef CMAKE_HAVE_NETINET_IN_H
76    #include <netinet/in.h>   //For IPPROTO_IP
77 #endif
78 #ifdef CMAKE_HAVE_NET_IF_DL_H
79    #include <net/if_dl.h>
80 #endif
81 #if defined(CMAKE_HAVE_NET_IF_ARP_H) && defined(__sun)
82    // This is absolutely necessary on SunOS
83    #include <net/if_arp.h>
84 #endif
85
86 // For GetCurrentThreadID()
87 #ifdef __linux__
88    #include <sys/types.h>
89    #include <linux/unistd.h>
90 #endif
91 #ifdef __sun
92    #include <thread.h>
93 #endif
94
95 namespace gdcm 
96 {
97 //-------------------------------------------------------------------------
98 const std::string Util::GDCM_UID = "1.2.826.0.1.3680043.2.1143";
99 std::string Util::RootUID        = GDCM_UID;
100 /*
101  * File Meta Information Version (0002,0001) shall contain a two byte OB 
102  * value consisting of a 0x00 byte, followed by 0x01 byte, and not the 
103  * value 0x0001 encoded as a little endian 16 bit short value, 
104  * which would be the other way around...
105  */
106 const uint16_t Util::FMIV = 0x0100;
107 uint8_t *Util::FileMetaInformationVersion = (uint8_t *)&FMIV;
108 std::string Util::GDCM_MAC_ADRESS = GetMACAddress();
109
110 //-------------------------------------------------------------------------
111 // Public
112 /**
113  * \brief Provide a better 'c++' approach for sprintf
114  * For example c code is:
115  * char result[2048]; // hope 2048 is enough
116  * sprintf(result, "%04x|%04x", group , elem);
117  *
118  * c++ code is 
119  * std::ostringstream buf;
120  * buf << std::right << std::setw(4) << std::setfill('0') << std::hex
121  *     << group << "|" << std::right << std::setw(4) << std::setfill('0') 
122  *     << std::hex <<  elem;
123  * buf.str();
124  *
125  * gdcm style code is
126  * string result;
127  * result = gdcm::Util::Format("%04x|%04x", group , elem);
128  */
129 std::string Util::Format(const char *format, ...)
130 {
131    char buffer[2048]; // hope 2048 is enough
132    va_list args;
133    va_start(args, format);
134    vsprintf(buffer, format, args);  //might be a security flaw
135    va_end(args); // Each invocation of va_start should be matched 
136                  // by a corresponding invocation of va_end
137                  // args is then 'undefined'
138    return buffer;
139 }
140
141
142 /**
143  * \brief Because not available in C++ (?)
144  * @param str string to check
145  * @param tokens std::vector to receive the tokenized substrings
146  * @param delimiters string containing the character delimitors
147  
148  */
149 void Util::Tokenize (const std::string &str,
150                      std::vector<std::string> &tokens,
151                      const std::string &delimiters)
152 {
153    std::string::size_type lastPos = str.find_first_not_of(delimiters,0);
154    std::string::size_type pos     = str.find_first_of    (delimiters,lastPos);
155    while (std::string::npos != pos || std::string::npos != lastPos)
156    {
157       tokens.push_back(str.substr(lastPos, pos - lastPos));
158       lastPos = str.find_first_not_of(delimiters, pos);
159       pos     = str.find_first_of    (delimiters, lastPos);
160    }
161 }
162
163 /**
164  * \brief Because not available in C++ (?)
165  *        Counts the number of occurences of a substring within a string
166  * @param str string to check
167  * @param subStr substring to count
168  */
169  
170 int Util::CountSubstring (const std::string &str,
171                           const std::string &subStr)
172 {
173    int count = 0;                 // counts how many times it appears
174    std::string::size_type x = 0;  // The index position in the string
175
176    do
177    {
178       x = str.find(subStr,x);     // Find the substring
179       if (x != std::string::npos) // If present
180       {
181          count++;                 // increase the count
182          x += subStr.length();    // Skip this word
183       }
184    }
185    while (x != std::string::npos);// Carry on until not present
186
187    return count;
188 }
189
190 /**
191  * \brief  Checks whether a 'string' is printable or not (in order
192  *         to avoid corrupting the terminal of invocation when printing)
193  * @param s string to check
194  */
195 bool Util::IsCleanString(std::string const &s)
196 {
197    //std::cout<< std::endl << s << std::endl;
198    for(unsigned int i=0; i<s.size(); i++)
199    {
200       if (!isprint((unsigned char)s[i]) )
201       {
202          return false;
203       }
204    }
205    return true;   
206 }
207
208 /**
209  * \brief  Checks whether an 'area' is printable or not (in order
210  *         to avoid corrupting the terminal of invocation when printing)
211  * @param s area to check (uint8_t is just for prototyping. feel free to cast)
212  * @param l area length to check
213  */
214 bool Util::IsCleanArea(uint8_t *s, int l)
215 {
216    for( int i=0; i<l; i++)
217    {
218       if (!isprint((unsigned char)s[i]) )
219       {
220          return false;
221       }
222    }
223    return true;   
224 }
225 /**
226  * \brief  Weed out a string from the non-printable characters (in order
227  *         to avoid corrupting the terminal of invocation when printing)
228  * @param s string to check (uint8_t is just for prototyping. feel free to cast)
229  */
230 std::string Util::CreateCleanString(std::string const &s)
231 {
232    std::string str = s;
233
234    for(unsigned int i=0; i<str.size(); i++)
235    {
236       if (!isprint((unsigned char)str[i]) )
237       {
238          str[i] = '.';
239       }
240    }
241
242    if (str.size() > 0 )
243    {
244       if (!isprint((unsigned char)s[str.size()-1]) )
245       {
246          if (s[str.size()-1] == 0 )
247          {
248             str[str.size()-1] = ' ';
249          }
250       }
251    }
252
253    return str;
254 }
255
256 /**
257  * \brief  Weed out a string from the non-printable characters (in order
258  *         to avoid corrupting the terminal of invocation when printing)
259  * @param s area to process (uint8_t is just for prototyping. feel free to cast)
260  * @param l area length to check
261  */
262 std::string Util::CreateCleanString(uint8_t *s, int l)
263 {
264    std::string str;
265
266    for( int i=0; i<l; i++)
267    {
268       if (!isprint((unsigned char)s[i]) )
269       {
270          str = str + '.';
271       }
272    else
273       {
274          str = str + (char )s[i];
275       }
276    }
277
278    return str;
279 }
280 /**
281  * \brief   Add a SEPARATOR to the end of the name is necessary
282  * @param   pathname file/directory name to normalize 
283  */
284 std::string Util::NormalizePath(std::string const &pathname)
285 {
286    const char SEPARATOR_X      = '/';
287    const char SEPARATOR_WIN    = '\\';
288    const std::string SEPARATOR = "/";
289    std::string name = pathname;
290    int size = name.size();
291
292    if ( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
293    {
294       name += SEPARATOR;
295    }
296    return name;
297 }
298
299 /**
300  * \brief   Get the (directory) path from a full path file name
301  * @param   fullName file/directory name to extract Path from
302  */
303 std::string Util::GetPath(std::string const &fullName)
304 {
305    std::string res = fullName;
306    int pos1 = res.rfind("/");
307    int pos2 = res.rfind("\\");
308    if ( pos1 > pos2 )
309    {
310       res.resize(pos1);
311    }
312    else
313    {
314       res.resize(pos2);
315    }
316
317    return res;
318 }
319
320 /**
321  * \brief   Get the (last) name of a full path file name
322  * @param   fullName file/directory name to extract end name from
323  */
324 std::string Util::GetName(std::string const &fullName)
325 {   
326   std::string filename = fullName;
327
328   std::string::size_type slash_pos = filename.rfind("/");
329   std::string::size_type backslash_pos = filename.rfind("\\");
330   slash_pos = slash_pos > backslash_pos ? slash_pos : backslash_pos;
331   if (slash_pos != std::string::npos )
332     {
333     return filename.substr(slash_pos + 1);
334     }
335   else
336     {
337     return filename;
338     }
339
340
341 /**
342  * \brief   Get the current date of the system in a dicom string
343  */
344 std::string Util::GetCurrentDate()
345 {
346     char tmp[512];
347     time_t tloc;
348     time (&tloc);    
349     strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
350     return tmp;
351 }
352
353 /**
354  * \brief   Get the current time of the system in a dicom string
355  */
356 std::string Util::GetCurrentTime()
357 {
358     char tmp[512];
359     time_t tloc;
360     time (&tloc);
361     strftime(tmp,512,"%H%M%S", localtime(&tloc) );
362     return tmp;  
363 }
364
365 /**
366  * \brief  Get both the date and time at the same time to avoid problem 
367  * around midnight where the two calls could be before and after midnight
368  */
369 std::string Util::GetCurrentDateTime()
370 {
371    char tmp[40];
372    long milliseconds;
373    time_t timep;
374   
375    // We need implementation specific functions to obtain millisecond precision
376 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
377    struct timeb tb;
378    ::ftime(&tb);
379    timep = tb.time;
380    milliseconds = tb.millitm;
381 #else
382    struct timeval tv;
383    gettimeofday (&tv, NULL);
384    timep = tv.tv_sec;
385    // Compute milliseconds from microseconds.
386    milliseconds = tv.tv_usec / 1000;
387 #endif
388    // Obtain the time of day, and convert it to a tm struct.
389    struct tm *ptm = localtime (&timep);
390    // Format the date and time, down to a single second.
391    strftime (tmp, sizeof (tmp), "%Y%m%d%H%M%S", ptm);
392
393    // Add milliseconds
394    // Don't use Util::Format to accelerate execution of code
395    char tmpAll[80];
396    sprintf(tmpAll,"%s%03ld",tmp,milliseconds);
397
398    return tmpAll;
399 }
400
401 unsigned int Util::GetCurrentThreadID()
402 {
403 // FIXME the implementation is far from complete
404 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
405   return (unsigned int)GetCurrentThreadId();
406 #else
407 #ifdef __linux__
408    return 0;
409    // Doesn't work on fedora, but is in the man page...
410    //return (unsigned int)gettid();
411 #else
412 #ifdef __sun
413    return (unsigned int)thr_self();
414 #else
415    //default implementation
416    return 0;
417 #endif // __sun
418 #endif // __linux__
419 #endif // Win32
420 }
421
422 unsigned int Util::GetCurrentProcessID()
423 {
424 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
425   // NOTE: There is also a _getpid()...
426   return (unsigned int)GetCurrentProcessId();
427 #else
428   // get process identification, POSIX
429   return (unsigned int)getpid();
430 #endif
431 }
432
433 /**
434  * \brief   tells us whether the processor we are working with is BigEndian or not
435  */
436 bool Util::IsCurrentProcessorBigEndian()
437 {
438 #if defined(GDCM_WORDS_BIGENDIAN)
439    return true;
440 #else
441    return false;
442 #endif
443 }
444
445 /**
446  * \brief Create a /DICOM/ string:
447  * It should a of even length (no odd length ever)
448  * It can contain as many (if you are reading this from your
449  * editor the following character is backslash followed by zero
450  * that needed to be escaped with an extra backslash for doxygen) \\0
451  * as you want.
452  */
453 std::string Util::DicomString(const char *s, size_t l)
454 {
455    std::string r(s, s+l);
456    gdcmAssertMacro( !(r.size() % 2) ); // == basically 'l' is even
457    return r;
458 }
459
460 /**
461  * \brief Create a /DICOM/ string:
462  * It should a of even length (no odd length ever)
463  * It can contain as many (if you are reading this from your
464  * editor the following character is backslash followed by zero
465  * that needed to be escaped with an extra backslash for doxygen) \\0
466  * as you want.
467  * This function is similar to DicomString(const char*), 
468  * except it doesn't take a length. 
469  * It only pad with a null character if length is odd
470  */
471 std::string Util::DicomString(const char *s)
472 {
473    size_t l = strlen(s);
474    if ( l%2 )
475    {
476       l++;
477    }
478    std::string r(s, s+l);
479    gdcmAssertMacro( !(r.size() % 2) );
480    return r;
481 }
482
483 /**
484  * \brief Safely check the equality of two Dicom String:
485  *        - Both strings should be of even length
486  *        - We allow padding of even length string by either a null 
487  *          character of a space
488  */
489 bool Util::DicomStringEqual(const std::string &s1, const char *s2)
490 {
491   // s2 is the string from the DICOM reference e.g. : 'MONOCHROME1'
492   std::string s1_even = s1; //Never change input parameter
493   std::string s2_even = DicomString( s2 );
494   if ( s1_even[s1_even.size()-1] == ' ' )
495   {
496     s1_even[s1_even.size()-1] = '\0'; //replace space character by null
497   }
498   return s1_even == s2_even;
499 }
500
501 /**
502  * \brief Safely compare two Dicom String:
503  *        - Both strings should be of even length
504  *        - We allow padding of even length string by either a null 
505  *          character of a space
506  */
507 bool Util::CompareDicomString(const std::string &s1, const char *s2, int op)
508 {
509   // s2 is the string from the DICOM reference e.g. : 'MONOCHROME1'
510   std::string s1_even = s1; //Never change input parameter
511   std::string s2_even = DicomString( s2 );
512   if ( s1_even[s1_even.size()-1] == ' ' )
513   {
514     s1_even[s1_even.size()-1] = '\0'; //replace space character by null
515   }
516   switch (op)
517   {
518      case GDCM_EQUAL :
519         return s1_even == s2_even;
520      case GDCM_DIFFERENT :  
521         return s1_even != s2_even;
522      case GDCM_GREATER :  
523         return s1_even >  s2_even;  
524      case GDCM_GREATEROREQUAL :  
525         return s1_even >= s2_even;
526      case GDCM_LESS :
527         return s1_even <  s2_even;
528      case GDCM_LESSOREQUAL :
529         return s1_even <= s2_even;
530      default :
531         gdcmDebugMacro(" Wrong operator : " << op);
532         return false;
533   }
534 }
535
536 #ifdef _WIN32
537    typedef BOOL(WINAPI * pSnmpExtensionInit) (
538            IN DWORD dwTimeZeroReference,
539            OUT HANDLE * hPollForTrapEvent,
540            OUT AsnObjectIdentifier * supportedView);
541
542    typedef BOOL(WINAPI * pSnmpExtensionTrap) (
543            OUT AsnObjectIdentifier * enterprise,
544            OUT AsnInteger * genericTrap,
545            OUT AsnInteger * specificTrap,
546            OUT AsnTimeticks * timeStamp,
547            OUT RFC1157VarBindList * variableBindings);
548
549    typedef BOOL(WINAPI * pSnmpExtensionQuery) (
550            IN BYTE requestType,
551            IN OUT RFC1157VarBindList * variableBindings,
552            OUT AsnInteger * errorStatus,
553            OUT AsnInteger * errorIndex);
554
555    typedef BOOL(WINAPI * pSnmpExtensionInitEx) (
556            OUT AsnObjectIdentifier * supportedView);
557 #endif //_WIN32
558
559 /// \brief gets current M.A.C adress (for internal use only)
560 int GetMacAddrSys ( unsigned char *addr );
561 int GetMacAddrSys ( unsigned char *addr )
562 {
563 #ifdef _WIN32
564    WSADATA WinsockData;
565    if ( (WSAStartup(MAKEWORD(2, 0), &WinsockData)) != 0 ) 
566    {
567       std::cerr << "in Get MAC Adress (internal) : This program requires Winsock 2.x!" 
568              << std::endl;
569       return -1;
570    }
571
572    HANDLE PollForTrapEvent;
573    AsnObjectIdentifier SupportedView;
574    UINT OID_ifEntryType[]  = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 3 };
575    UINT OID_ifEntryNum[]   = { 1, 3, 6, 1, 2, 1, 2, 1 };
576    UINT OID_ipMACEntAddr[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 6 };
577    AsnObjectIdentifier MIB_ifMACEntAddr = {
578        sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr };
579    AsnObjectIdentifier MIB_ifEntryType = {
580        sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType };
581    AsnObjectIdentifier MIB_ifEntryNum = {
582        sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum };
583    RFC1157VarBindList varBindList;
584    RFC1157VarBind varBind[2];
585    AsnInteger errorStatus;
586    AsnInteger errorIndex;
587    AsnObjectIdentifier MIB_NULL = { 0, 0 };
588    int ret;
589    int dtmp;
590    int j = 0;
591
592    // Load the SNMP dll and get the addresses of the functions necessary
593    HINSTANCE m_hInst = LoadLibrary("inetmib1.dll");
594    if (m_hInst < (HINSTANCE) HINSTANCE_ERROR)
595    {
596       return -1;
597    }
598    pSnmpExtensionInit m_Init =
599        (pSnmpExtensionInit) GetProcAddress(m_hInst, "SnmpExtensionInit");
600    pSnmpExtensionQuery m_Query =
601        (pSnmpExtensionQuery) GetProcAddress(m_hInst, "SnmpExtensionQuery");
602    m_Init(GetTickCount(), &PollForTrapEvent, &SupportedView);
603
604    /* Initialize the variable list to be retrieved by m_Query */
605    varBindList.list = varBind;
606    varBind[0].name = MIB_NULL;
607    varBind[1].name = MIB_NULL;
608
609    // Copy in the OID to find the number of entries in the
610    // Inteface table
611    varBindList.len = 1;        // Only retrieving one item
612    SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryNum);
613    m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
614                  &errorIndex);
615 //   printf("# of adapters in this system : %i\n",
616 //          varBind[0].value.asnValue.number);
617    varBindList.len = 2;
618
619    // Copy in the OID of ifType, the type of interface
620    SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryType);
621
622    // Copy in the OID of ifPhysAddress, the address
623    SNMP_oidcpy(&varBind[1].name, &MIB_ifMACEntAddr);
624
625    do
626    {
627       // Submit the query.  Responses will be loaded into varBindList.
628       // We can expect this call to succeed a # of times corresponding
629       // to the # of adapters reported to be in the system
630       ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
631                     &errorIndex); 
632       if (!ret)
633       {
634          ret = 1;
635       }
636       else
637       {
638          // Confirm that the proper type has been returned
639          ret = SNMP_oidncmp(&varBind[0].name, &MIB_ifEntryType,
640                             MIB_ifEntryType.idLength);
641       }
642       if (!ret)
643       {
644          j++;
645          dtmp = varBind[0].value.asnValue.number;
646
647          // Type 6 describes ethernet interfaces
648          if (dtmp == 6)
649          {
650             // Confirm that we have an address here
651             ret = SNMP_oidncmp(&varBind[1].name, &MIB_ifMACEntAddr,
652                                MIB_ifMACEntAddr.idLength);
653             if ( !ret && varBind[1].value.asnValue.address.stream != NULL )
654             {
655                if ( (varBind[1].value.asnValue.address.stream[0] == 0x44)
656                  && (varBind[1].value.asnValue.address.stream[1] == 0x45)
657                  && (varBind[1].value.asnValue.address.stream[2] == 0x53)
658                  && (varBind[1].value.asnValue.address.stream[3] == 0x54)
659                  && (varBind[1].value.asnValue.address.stream[4] == 0x00) )
660                {
661                    // Ignore all dial-up networking adapters
662                    std::cerr << "in Get MAC Adress (internal) : Interface #" 
663                              << j << " is a DUN adapter\n";
664                    continue;
665                }
666                if ( (varBind[1].value.asnValue.address.stream[0] == 0x00)
667                  && (varBind[1].value.asnValue.address.stream[1] == 0x00)
668                  && (varBind[1].value.asnValue.address.stream[2] == 0x00)
669                  && (varBind[1].value.asnValue.address.stream[3] == 0x00)
670                  && (varBind[1].value.asnValue.address.stream[4] == 0x00)
671                  && (varBind[1].value.asnValue.address.stream[5] == 0x00) )
672                {
673                   // Ignore NULL addresses returned by other network
674                   // interfaces
675                   std::cerr << "in Get MAC Adress (internal) :  Interface #" 
676                             << j << " is a NULL address\n";
677                   continue;
678                }
679                memcpy( addr, varBind[1].value.asnValue.address.stream, 6);
680             }
681          }
682       }
683    } while (!ret);
684
685    // Free the bindings
686    SNMP_FreeVarBind(&varBind[0]);
687    SNMP_FreeVarBind(&varBind[1]);
688    return 0;
689 #endif //Win32 version
690
691
692 // implementation for POSIX system
693 #if defined(CMAKE_HAVE_NET_IF_ARP_H) && defined(__sun)
694    //The POSIX version is broken anyway on Solaris, plus would require full
695    //root power
696    struct  arpreq          parpreq;
697    struct  sockaddr_in     *psa;
698    struct  hostent         *phost;
699    char                    hostname[MAXHOSTNAMELEN];
700    char                    **paddrs;
701    int                     sock, status=0;
702
703    if (gethostname(hostname,  MAXHOSTNAMELEN) != 0 )
704    {
705       perror("in Get MAC Adress (internal) : gethostname");
706       return -1;
707    }
708    phost = gethostbyname(hostname);
709    paddrs = phost->h_addr_list;
710
711    sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
712    if (sock == -1 )
713    {
714       perror("in Get MAC Adress (internal) : sock");
715       return -1;
716    }
717    memset(&parpreq, 0, sizeof(struct arpreq));
718    psa = (struct sockaddr_in *) &parpreq.arp_pa;
719
720    memset(psa, 0, sizeof(struct sockaddr_in));
721    psa->sin_family = AF_INET;
722    memcpy(&psa->sin_addr, *paddrs, sizeof(struct in_addr));
723
724    status = ioctl(sock, SIOCGARP, &parpreq);
725    if (status == -1 )
726    {
727       perror("in Get MAC Adress (internal) : SIOCGARP");
728       return -1;
729    }
730    memcpy(addr, parpreq.arp_ha.sa_data, 6);
731
732    return 0;
733 #else
734 #ifdef CMAKE_HAVE_NET_IF_H
735    int       sd;
736    struct ifreq    ifr, *ifrp;
737    struct ifconf    ifc;
738    char buf[1024];
739    int      n, i;
740    unsigned char    *a;
741 #if defined(AF_LINK) && (!defined(SIOCGIFHWADDR) && !defined(SIOCGENADDR))
742    struct sockaddr_dl *sdlp;
743 #endif
744
745 //
746 // BSD 4.4 defines the size of an ifreq to be
747 // max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len
748 // However, under earlier systems, sa_len isn't present, so the size is 
749 // just sizeof(struct ifreq)
750 // We should investigate the use of SIZEOF_ADDR_IFREQ
751 //
752 #ifdef HAVE_SA_LEN
753    #ifndef max
754       #define max(a,b) ((a) > (b) ? (a) : (b))
755    #endif
756    #define ifreq_size(i) max(sizeof(struct ifreq),\
757         sizeof((i).ifr_name)+(i).ifr_addr.sa_len)
758 #else
759    #define ifreq_size(i) sizeof(struct ifreq)
760 #endif // HAVE_SA_LEN
761
762    if ( (sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0 )
763    {
764       return -1;
765    }
766    memset(buf, 0, sizeof(buf));
767    ifc.ifc_len = sizeof(buf);
768    ifc.ifc_buf = buf;
769    if (ioctl (sd, SIOCGIFCONF, (char *)&ifc) < 0)
770    {
771       close(sd);
772       return -1;
773    }
774    n = ifc.ifc_len;
775    for (i = 0; i < n; i+= ifreq_size(*ifrp) )
776    {
777       ifrp = (struct ifreq *)((char *) ifc.ifc_buf+i);
778       strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ);
779 #ifdef SIOCGIFHWADDR
780       if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0)
781          continue;
782       a = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
783 #else
784 #ifdef SIOCGENADDR
785       // In theory this call should also work on Sun Solaris, but apparently
786       // SIOCGENADDR is not implemented properly thus the call 
787       // ioctl(sd, SIOCGENADDR, &ifr) always returns errno=2 
788       // (No such file or directory)
789       // Furthermore the DLAPI seems to require full root access
790       if (ioctl(sd, SIOCGENADDR, &ifr) < 0)
791          continue;
792       a = (unsigned char *) ifr.ifr_enaddr;
793 #else
794 #ifdef AF_LINK
795       sdlp = (struct sockaddr_dl *) &ifrp->ifr_addr;
796       if ((sdlp->sdl_family != AF_LINK) || (sdlp->sdl_alen != 6))
797          continue;
798       a = (unsigned char *) &sdlp->sdl_data[sdlp->sdl_nlen];
799 #else
800       perror("in Get MAC Adress (internal) : No way to access hardware");
801       close(sd);
802       return -1;
803 #endif // AF_LINK
804 #endif // SIOCGENADDR
805 #endif // SIOCGIFHWADDR
806       if (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5]) continue;
807
808       if (addr) 
809       {
810          memcpy(addr, a, 6);
811          close(sd);
812          return 0;
813       }
814    }
815    close(sd);
816 #endif
817    // Not implemented platforms (or no cable !)
818    perror("in Get MAC Adress (internal) : There was a configuration problem (or no cable !) on your plateform");
819    memset(addr,0,6);
820    return -1;
821 #endif //__sun
822 }
823
824 /**
825  * \brief Mini function to return the last digit from a number express in base 256
826  *        pre condition data contain an array of 6 unsigned char
827  *        post condition carry contain the last digit
828  */
829 inline int getlastdigit(unsigned char *data)
830 {
831   int extended, carry = 0;
832   for(int i=0;i<6;i++)
833     {
834     extended = (carry << 8) + data[i];
835     data[i] = extended / 10;
836     carry = extended % 10;
837     }
838   return carry;
839 }
840
841 /**
842  * \brief Encode the mac address on a fixed length string of 15 characters.
843  * we save space this way.
844  */
845 std::string Util::GetMACAddress()
846 {
847    // This code is the result of a long internet search to find something
848    // as compact as possible (not OS independant). We only have to separate
849    // 3 OS: Win32, SunOS and 'real' POSIX
850    // http://groups-beta.google.com/group/comp.unix.solaris/msg/ad36929d783d63be
851    // http://bdn.borland.com/article/0,1410,26040,00.html
852    unsigned char addr[6];
853
854    int stat = GetMacAddrSys(addr);
855    if (stat == 0)
856    {
857       // We need to convert a 6 digit number from base 256 to base 10, using integer
858       // would requires a 48bits one. To avoid this we have to reimplement the div + modulo 
859       // with string only
860       bool zero = false;
861       int res;
862       std::string sres;
863       while(!zero)
864       {
865          res = getlastdigit(addr);
866          sres.insert(sres.begin(), '0' + res);
867          zero = (addr[0] == 0) && (addr[1] == 0) && (addr[2] == 0) 
868              && (addr[3] == 0) && (addr[4] == 0) && (addr[5] == 0);
869       }
870
871       return sres;
872    }
873    else
874    {
875       gdcmStaticWarningMacro("Problem in finding the MAC Address");
876       return "";
877    }
878 }
879
880 /**
881  * \brief Creates a new UID. As stipulated in the DICOM ref
882  *        each time a DICOM image is created it should have 
883  *        a unique identifier (URI)
884  * @param root is the DICOM prefix assigned by IOS group
885  */
886 std::string Util::CreateUniqueUID(const std::string &root)
887 {
888    std::string prefix;
889    std::string append;
890    if ( root.empty() )
891    {
892       // gdcm UID prefix, as supplied by http://www.medicalconnections.co.uk
893       prefix = RootUID; 
894    }
895    else
896    {
897       prefix = root;
898    }
899
900    // A root was specified use it to forge our new UID:
901    append += ".";
902    //append += Util::GetMACAddress(); // to save CPU time
903    append += Util::GDCM_MAC_ADRESS;
904    append += ".";
905    append += Util::GetCurrentDateTime();
906    append += ".";
907    //Also add a mini random number just in case:
908    char tmp[10];
909    int r = (int) (100.0*rand()/RAND_MAX);
910    // Don't use Util::Format to accelerate the execution
911    sprintf(tmp,"%02d", r);
912    append += tmp;
913
914    // If append is too long we need to rehash it
915    if ( (prefix + append).size() > 64 )
916    {
917       gdcmStaticErrorMacro( "Size of UID is too long." );
918       // we need a hash function to truncate this number
919       // if only md5 was cross plateform
920       // MD5(append);
921    }
922
923    return prefix + append;
924 }
925
926 void Util::SetRootUID(const std::string &root)
927 {
928    if ( root.empty() )
929       RootUID = GDCM_UID;
930    else
931       RootUID = root;
932 }
933
934 const std::string &Util::GetRootUID()
935 {
936    return RootUID;
937 }
938
939 //-------------------------------------------------------------------------
940 /**
941  * \brief binary_write binary_write
942  * @param os ostream to write to 
943  * @param val 16 bits value to write
944  */ 
945 std::ostream &binary_write(std::ostream &os, const uint16_t &val)
946 {
947 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
948    uint16_t swap;
949    swap = ( val << 8 | val >> 8 );
950
951    return os.write(reinterpret_cast<const char*>(&swap), 2);
952 #else
953    return os.write(reinterpret_cast<const char*>(&val), 2);
954 #endif //GDCM_WORDS_BIGENDIAN
955 }
956
957 /**
958  * \brief binary_write binary_write
959  * @param os ostream to write to
960  * @param val 32 bits value to write
961  */ 
962 std::ostream &binary_write(std::ostream &os, const uint32_t &val)
963 {
964 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
965    uint32_t swap;
966    swap = (  (val<<24)               | ((val<<8)  & 0x00ff0000) | 
967             ((val>>8)  & 0x0000ff00) |  (val>>24)               );
968    return os.write(reinterpret_cast<const char*>(&swap), 4);
969 #else
970    return os.write(reinterpret_cast<const char*>(&val), 4);
971 #endif //GDCM_WORDS_BIGENDIAN
972 }
973
974
975 /**
976  * \brief binary_write binary_write
977  * @param os ostream to write to
978  * @param val double (64 bits) value to write
979  */ 
980 std::ostream &binary_write(std::ostream &os, const double &val)
981 {
982 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)    
983    double swap = val;
984    
985    char *beg = (char *)&swap;
986    char *end = beg + 7;
987    char t;
988    for (unsigned int i = 0; i<7; i++)
989    {
990       t    = *beg;
991       *beg = *end;
992       *end = t;
993       beg++,
994       end--;  
995    }  
996    return os.write(reinterpret_cast<const char*>(&swap), 8);
997 #else
998    return os.write(reinterpret_cast<const char*>(&val), 8);
999 #endif //GDCM_WORDS_BIGENDIAN
1000 }
1001
1002
1003 /**
1004  * \brief  binary_write binary_write
1005  * @param os ostream to write to
1006  * @param val 8 bits characters aray to write
1007  */ 
1008 std::ostream &binary_write(std::ostream &os, const char *val)
1009 {
1010    return os.write(val, strlen(val));
1011 }
1012
1013 /**
1014  * \brief  binary_write binary_write
1015  * @param os ostream to write to
1016  * @param val std::string value to write
1017  */ 
1018 std::ostream &binary_write(std::ostream &os, std::string const &val)
1019 {
1020    return os.write(val.c_str(), val.size());
1021 }
1022
1023 /**
1024  * \brief  binary_write binary_write
1025  * @param os ostream to write to
1026  * @param val 8 bits 'characters' aray to write
1027  * @param len length of the 'value' to be written
1028  */ 
1029 std::ostream &binary_write(std::ostream &os, const uint8_t *val, size_t len)
1030 {
1031    // We are writting sizeof(char) thus no need to swap bytes
1032    return os.write(reinterpret_cast<const char*>(val), len);
1033 }
1034
1035 /**
1036  * \brief  binary_write binary_write
1037  * @param os ostream to write to
1038  * @param val 16 bits words aray to write
1039  * @param len length (in bytes) of the 'value' to be written 
1040  */ 
1041 std::ostream &binary_write(std::ostream &os, const uint16_t *val, size_t len)
1042 {
1043 // This is tricky since we are writting two bytes buffer. 
1044 // Be carefull with little endian vs big endian. 
1045 // Also this other trick is to allocate a small (efficient) buffer that store
1046 // intermediate result before writting it.
1047 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
1048    const int BUFFER_SIZE = 4096;
1049    static char buffer[BUFFER_SIZE];
1050    uint16_t *binArea16 = (uint16_t*)val; //for the const
1051  
1052    // how many BUFFER_SIZE long pieces in binArea ?
1053    int nbPieces = len/BUFFER_SIZE; //(16 bits = 2 Bytes)
1054    int remainingSize = len%BUFFER_SIZE;
1055
1056    for (int j=0;j<nbPieces;j++)
1057    {
1058       uint16_t *pbuffer  = (uint16_t*)buffer; //reinitialize pbuffer
1059       for (int i = 0; i < BUFFER_SIZE/2; i++)
1060       {
1061          *pbuffer = *binArea16 >> 8 | *binArea16 << 8;
1062          pbuffer++;
1063          binArea16++;
1064       }
1065       os.write ( buffer, BUFFER_SIZE );
1066    }
1067    if ( remainingSize > 0)
1068    {
1069       uint16_t *pbuffer  = (uint16_t*)buffer; //reinitialize pbuffer
1070       for (int i = 0; i < remainingSize/2; i++)
1071       {
1072          *pbuffer = *binArea16 >> 8 | *binArea16 << 8;
1073          pbuffer++;
1074          binArea16++;
1075       }
1076       os.write ( buffer, remainingSize );
1077    }
1078    return os;
1079 #else
1080    return os.write(reinterpret_cast<const char*>(val), len);
1081 #endif
1082 }
1083
1084 //-------------------------------------------------------------------------
1085 // Protected
1086
1087 //-------------------------------------------------------------------------
1088 // Private
1089 /**
1090  * \brief   Return the IP adress of the machine writting the DICOM image
1091  */
1092 std::string Util::GetIPAddress()
1093 {
1094    // This is a rip from 
1095    // http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
1096 #ifndef HOST_NAME_MAX
1097    // SUSv2 guarantees that `Host names are limited to 255 bytes'.
1098    // POSIX 1003.1-2001 guarantees that `Host names (not including the
1099    // terminating NUL) are limited to HOST_NAME_MAX bytes'.
1100 #define HOST_NAME_MAX 255
1101    // In this case we should maybe check the string was not truncated.
1102    // But I don't known how to check that...
1103 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
1104    // with WinSock DLL we need to initialize the WinSock before using gethostname
1105    WORD wVersionRequested = MAKEWORD(1,0);
1106    WSADATA WSAData;
1107    int err = WSAStartup(wVersionRequested,&WSAData);
1108    if (err != 0)
1109    {
1110       // Tell the user that we could not find a usable
1111       // WinSock DLL.
1112       WSACleanup();
1113       return "127.0.0.1";
1114    }
1115 #endif
1116   
1117 #endif //HOST_NAME_MAX
1118
1119    std::string str;
1120    char szHostName[HOST_NAME_MAX+1];
1121    int r = gethostname(szHostName, HOST_NAME_MAX);
1122  
1123    if ( r == 0 )
1124    {
1125       // Get host adresses
1126       struct hostent *pHost = gethostbyname(szHostName);
1127  
1128       for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
1129       {
1130          for( int j = 0; j<pHost->h_length; j++ )
1131          {
1132             if ( j > 0 ) str += ".";
1133  
1134             str += Util::Format("%u", 
1135                 (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
1136          }
1137          // str now contains one local IP address 
1138  
1139 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
1140    WSACleanup();
1141 #endif
1142
1143       }
1144    }
1145    // If an error occur r == -1
1146    // Most of the time it will return 127.0.0.1...
1147    return str;
1148 }
1149
1150 //-------------------------------------------------------------------------
1151 } // end namespace gdcm
1152