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