]> Creatis software - gdcm.git/blob - src/gdcmUtil.cxx
Minor Typo
[gdcm.git] / src / gdcmUtil.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmUtil.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/12/22 14:46:36 $
7   Version:   $Revision: 1.181 $
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 if necessary
282  * \todo ask the writer of this method *why* he always add a /
283  * @param   pathname file/directory name to normalize 
284  */
285 std::string Util::NormalizePath(std::string const &pathname)
286 {
287    const char SEPARATOR_X      = '/';
288    const char SEPARATOR_WIN    = '\\';
289    const std::string SEPARATOR = "/";
290    std::string name = pathname;
291    int size = name.size();
292
293    if ( name[size-1] != SEPARATOR_X && name[size-1] != SEPARATOR_WIN )
294    {
295       name += SEPARATOR;
296    }
297    return name;
298 }
299
300 /**
301  * \brief   Get the (directory) path from a full path file name
302  * @param   fullName file/directory name to extract Path from
303  */
304 std::string Util::GetPath(std::string const &fullName)
305 {
306    std::string res = fullName;
307    int pos1 = res.rfind("/");
308    int pos2 = res.rfind("\\");
309    if ( pos1 > pos2 )
310    {
311       res.resize(pos1);
312    }
313    else
314    {
315       res.resize(pos2);
316    }
317
318    return res;
319 }
320
321 /**
322  * \brief   Get the (last) name of a full path file name
323  * @param   fullName file/directory name to extract end name from
324  */
325 std::string Util::GetName(std::string const &fullName)
326 {   
327   std::string filename = fullName;
328
329   std::string::size_type slash_pos = filename.rfind("/");
330   std::string::size_type backslash_pos = filename.rfind("\\");
331   // At least with my gcc4.0.1, unfound char results in pos =4294967295 ...
332   //slash_pos = slash_pos > backslash_pos ? slash_pos : backslash_pos;
333   slash_pos = slash_pos < backslash_pos ? slash_pos : backslash_pos;
334   if (slash_pos != std::string::npos )
335     {
336     return filename.substr(slash_pos + 1);
337     }
338   else
339     {
340     return filename;
341     }
342
343
344 /**
345  * \brief   Get the current date of the system in a dicom string
346  */
347 std::string Util::GetCurrentDate()
348 {
349     char tmp[512];
350     time_t tloc;
351     time (&tloc);    
352     strftime(tmp,512,"%Y%m%d", localtime(&tloc) );
353     return tmp;
354 }
355
356 /**
357  * \brief   Get the current time of the system in a dicom string
358  */
359 std::string Util::GetCurrentTime()
360 {
361     char tmp[512];
362     time_t tloc;
363     time (&tloc);
364     strftime(tmp,512,"%H%M%S", localtime(&tloc) );
365     return tmp;  
366 }
367
368 /**
369  * \brief  Get both the date and time at the same time to avoid problem 
370  * around midnight where the two calls could be before and after midnight
371  */
372 std::string Util::GetCurrentDateTime()
373 {
374    char tmp[40];
375    long milliseconds;
376    time_t timep;
377   
378    // We need implementation specific functions to obtain millisecond precision
379 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
380    struct timeb tb;
381    ::ftime(&tb);
382    timep = tb.time;
383    milliseconds = tb.millitm;
384 #else
385    struct timeval tv;
386    gettimeofday (&tv, NULL);
387    timep = tv.tv_sec;
388    // Compute milliseconds from microseconds.
389    milliseconds = tv.tv_usec / 1000;
390 #endif
391    // Obtain the time of day, and convert it to a tm struct.
392    struct tm *ptm = localtime (&timep);
393    // Format the date and time, down to a single second.
394    strftime (tmp, sizeof (tmp), "%Y%m%d%H%M%S", ptm);
395
396    // Add milliseconds
397    // Don't use Util::Format to accelerate execution of code
398    char tmpAll[80];
399    sprintf(tmpAll,"%s%03ld",tmp,milliseconds);
400
401    return tmpAll;
402 }
403
404 unsigned int Util::GetCurrentThreadID()
405 {
406 // FIXME the implementation is far from complete
407 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
408   return (unsigned int)GetCurrentThreadId();
409 #else
410 #ifdef __linux__
411    return 0;
412    // Doesn't work on fedora, but is in the man page...
413    //return (unsigned int)gettid();
414 #else
415 #ifdef __sun
416    return (unsigned int)thr_self();
417 #else
418    //default implementation
419    return 0;
420 #endif // __sun
421 #endif // __linux__
422 #endif // Win32
423 }
424
425 unsigned int Util::GetCurrentProcessID()
426 {
427 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
428   // NOTE: There is also a _getpid()...
429   return (unsigned int)GetCurrentProcessId();
430 #else
431   // get process identification, POSIX
432   return (unsigned int)getpid();
433 #endif
434 }
435
436 /**
437  * \brief   tells us whether the processor we are working with is BigEndian or not
438  */
439 bool Util::IsCurrentProcessorBigEndian()
440 {
441 #if defined(GDCM_WORDS_BIGENDIAN)
442    return true;
443 #else
444    return false;
445 #endif
446 }
447
448 /**
449  * \brief Create a /DICOM/ string:
450  * It should a of even length (no odd length ever)
451  * It can contain as many (if you are reading this from your
452  * editor the following character is backslash followed by zero
453  * that needed to be escaped with an extra backslash for doxygen) \\0
454  * as you want.
455  */
456 std::string Util::DicomString(const char *s, size_t l)
457 {
458    std::string r(s, s+l);
459    gdcmAssertMacro( !(r.size() % 2) ); // == basically 'l' is even
460    return r;
461 }
462
463 /**
464  * \brief Create a /DICOM/ string:
465  * It should a of even length (no odd length ever)
466  * It can contain as many (if you are reading this from your
467  * editor the following character is backslash followed by zero
468  * that needed to be escaped with an extra backslash for doxygen) \\0
469  * as you want.
470  * This function is similar to DicomString(const char*), 
471  * except it doesn't take a length. 
472  * It only pad with a null character if length is odd
473  */
474 std::string Util::DicomString(const char *s)
475 {
476    size_t l = strlen(s);
477    if ( l%2 )
478    {
479       l++;
480    }
481    std::string r(s, s+l);
482    gdcmAssertMacro( !(r.size() % 2) );
483    return r;
484 }
485
486 /**
487  * \brief Safely check the equality of two Dicom String:
488  *        - Both strings should be of even length
489  *        - We allow padding of even length string by either 
490  *           a null character of a space
491  */
492 bool Util::DicomStringEqual(const std::string &s1, const char *s2)
493 {
494   // s2 is the string from the DICOM reference e.g. : 'MONOCHROME1'
495   std::string s1_even = s1; //Never change input parameter
496   std::string s2_even = DicomString( s2 );
497   if ( s1_even[s1_even.size()-1] == ' ' )
498   {
499     s1_even[s1_even.size()-1] = '\0'; //replace space character by null
500   }
501   return s1_even == s2_even;
502 }
503
504 /**
505  * \brief Safely compare two Dicom String:
506  *        - Both strings should be of even length
507  *        - We allow padding of even length string by either  
508  *          a null character of a space
509  */
510 bool Util::CompareDicomString(const std::string &s1, const char *s2, int op)
511 {
512   // s2 is the string from the DICOM reference e.g. : 'MONOCHROME1'
513   std::string s1_even = s1; //Never change input parameter
514   std::string s2_even = DicomString( s2 );
515   if ( s1_even[s1_even.size()-1] == ' ' )
516   {
517     s1_even[s1_even.size()-1] = '\0'; //replace space character by null
518   }
519   switch (op)
520   {
521      case GDCM_EQUAL :
522         return s1_even == s2_even;
523      case GDCM_DIFFERENT :  
524         return s1_even != s2_even;
525      case GDCM_GREATER :  
526         return s1_even >  s2_even;  
527      case GDCM_GREATEROREQUAL :  
528         return s1_even >= s2_even;
529      case GDCM_LESS :
530         return s1_even <  s2_even;
531      case GDCM_LESSOREQUAL :
532         return s1_even <= s2_even;
533      default :
534         gdcmDebugMacro(" Wrong operator : " << op);
535         return false;
536   }
537 }
538
539 #ifdef _WIN32
540    typedef BOOL(WINAPI * pSnmpExtensionInit) (
541            IN DWORD dwTimeZeroReference,
542            OUT HANDLE * hPollForTrapEvent,
543            OUT AsnObjectIdentifier * supportedView);
544
545    typedef BOOL(WINAPI * pSnmpExtensionTrap) (
546            OUT AsnObjectIdentifier * enterprise,
547            OUT AsnInteger * genericTrap,
548            OUT AsnInteger * specificTrap,
549            OUT AsnTimeticks * timeStamp,
550            OUT RFC1157VarBindList * variableBindings);
551
552    typedef BOOL(WINAPI * pSnmpExtensionQuery) (
553            IN BYTE requestType,
554            IN OUT RFC1157VarBindList * variableBindings,
555            OUT AsnInteger * errorStatus,
556            OUT AsnInteger * errorIndex);
557
558    typedef BOOL(WINAPI * pSnmpExtensionInitEx) (
559            OUT AsnObjectIdentifier * supportedView);
560 #endif //_WIN32
561
562 /// \brief gets current M.A.C adress (for internal use only)
563 int GetMacAddrSys ( unsigned char *addr );
564 int GetMacAddrSys ( unsigned char *addr )
565 {
566 #ifdef _WIN32
567    WSADATA WinsockData;
568    if ( (WSAStartup(MAKEWORD(2, 0), &WinsockData)) != 0 ) 
569    {
570       std::cerr << "in Get MAC Adress (internal) : This program requires Winsock 2.x!" 
571              << std::endl;
572       return -1;
573    }
574
575    HANDLE PollForTrapEvent;
576    AsnObjectIdentifier SupportedView;
577    UINT OID_ifEntryType[]  = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 3 };
578    UINT OID_ifEntryNum[]   = { 1, 3, 6, 1, 2, 1, 2, 1 };
579    UINT OID_ipMACEntAddr[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 6 };
580    AsnObjectIdentifier MIB_ifMACEntAddr = {
581        sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr };
582    AsnObjectIdentifier MIB_ifEntryType = {
583        sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType };
584    AsnObjectIdentifier MIB_ifEntryNum = {
585        sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum };
586    RFC1157VarBindList varBindList;
587    RFC1157VarBind varBind[2];
588    AsnInteger errorStatus;
589    AsnInteger errorIndex;
590    AsnObjectIdentifier MIB_NULL = { 0, 0 };
591    int ret;
592    int dtmp;
593    int j = 0;
594
595    // Load the SNMP dll and get the addresses of the functions necessary
596    HINSTANCE m_hInst = LoadLibrary("inetmib1.dll");
597    if (m_hInst < (HINSTANCE) HINSTANCE_ERROR)
598    {
599       return -1;
600    }
601    pSnmpExtensionInit m_Init =
602        (pSnmpExtensionInit) GetProcAddress(m_hInst, "SnmpExtensionInit");
603    pSnmpExtensionQuery m_Query =
604        (pSnmpExtensionQuery) GetProcAddress(m_hInst, "SnmpExtensionQuery");
605    m_Init(GetTickCount(), &PollForTrapEvent, &SupportedView);
606
607    /* Initialize the variable list to be retrieved by m_Query */
608    varBindList.list = varBind;
609    varBind[0].name = MIB_NULL;
610    varBind[1].name = MIB_NULL;
611
612    // Copy in the OID to find the number of entries in the
613    // Inteface table
614    varBindList.len = 1;        // Only retrieving one item
615    SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryNum);
616    m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
617                  &errorIndex);
618 //   printf("# of adapters in this system : %i\n",
619 //          varBind[0].value.asnValue.number);
620    varBindList.len = 2;
621
622    // Copy in the OID of ifType, the type of interface
623    SNMP_oidcpy(&varBind[0].name, &MIB_ifEntryType);
624
625    // Copy in the OID of ifPhysAddress, the address
626    SNMP_oidcpy(&varBind[1].name, &MIB_ifMACEntAddr);
627
628    do
629    {
630       // Submit the query.  Responses will be loaded into varBindList.
631       // We can expect this call to succeed a # of times corresponding
632       // to the # of adapters reported to be in the system
633       ret = m_Query(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus,
634                     &errorIndex); 
635       if (!ret)
636       {
637          ret = 1;
638       }
639       else
640       {
641          // Confirm that the proper type has been returned
642          ret = SNMP_oidncmp(&varBind[0].name, &MIB_ifEntryType,
643                             MIB_ifEntryType.idLength);
644       }
645       if (!ret)
646       {
647          j++;
648          dtmp = varBind[0].value.asnValue.number;
649
650          // Type 6 describes ethernet interfaces
651          if (dtmp == 6)
652          {
653             // Confirm that we have an address here
654             ret = SNMP_oidncmp(&varBind[1].name, &MIB_ifMACEntAddr,
655                                MIB_ifMACEntAddr.idLength);
656             if ( !ret && varBind[1].value.asnValue.address.stream != NULL )
657             {
658                if ( (varBind[1].value.asnValue.address.stream[0] == 0x44)
659                  && (varBind[1].value.asnValue.address.stream[1] == 0x45)
660                  && (varBind[1].value.asnValue.address.stream[2] == 0x53)
661                  && (varBind[1].value.asnValue.address.stream[3] == 0x54)
662                  && (varBind[1].value.asnValue.address.stream[4] == 0x00) )
663                {
664                    // Ignore all dial-up networking adapters
665                    std::cerr << "in Get MAC Adress (internal) : Interface #" 
666                              << j << " is a DUN adapter\n";
667                    continue;
668                }
669                if ( (varBind[1].value.asnValue.address.stream[0] == 0x00)
670                  && (varBind[1].value.asnValue.address.stream[1] == 0x00)
671                  && (varBind[1].value.asnValue.address.stream[2] == 0x00)
672                  && (varBind[1].value.asnValue.address.stream[3] == 0x00)
673                  && (varBind[1].value.asnValue.address.stream[4] == 0x00)
674                  && (varBind[1].value.asnValue.address.stream[5] == 0x00) )
675                {
676                   // Ignore NULL addresses returned by other network
677                   // interfaces
678                   std::cerr << "in Get MAC Adress (internal) :  Interface #" 
679                             << j << " is a NULL address\n";
680                   continue;
681                }
682                memcpy( addr, varBind[1].value.asnValue.address.stream, 6);
683             }
684          }
685       }
686    } while (!ret);
687
688    // Free the bindings
689    SNMP_FreeVarBind(&varBind[0]);
690    SNMP_FreeVarBind(&varBind[1]);
691    return 0;
692 #endif //Win32 version
693
694
695 // implementation for POSIX system
696 #if defined(CMAKE_HAVE_NET_IF_ARP_H) && defined(__sun)
697    //The POSIX version is broken anyway on Solaris, plus would require full
698    //root power
699    struct  arpreq          parpreq;
700    struct  sockaddr_in     *psa;
701    struct  hostent         *phost;
702    char                    hostname[MAXHOSTNAMELEN];
703    char                    **paddrs;
704    int                     sock, status=0;
705
706    if (gethostname(hostname,  MAXHOSTNAMELEN) != 0 )
707    {
708       perror("in Get MAC Adress (internal) : gethostname");
709       return -1;
710    }
711    phost = gethostbyname(hostname);
712    paddrs = phost->h_addr_list;
713
714    sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
715    if (sock == -1 )
716    {
717       perror("in Get MAC Adress (internal) : sock");
718       return -1;
719    }
720    memset(&parpreq, 0, sizeof(struct arpreq));
721    psa = (struct sockaddr_in *) &parpreq.arp_pa;
722
723    memset(psa, 0, sizeof(struct sockaddr_in));
724    psa->sin_family = AF_INET;
725    memcpy(&psa->sin_addr, *paddrs, sizeof(struct in_addr));
726
727    status = ioctl(sock, SIOCGARP, &parpreq);
728    if (status == -1 )
729    {
730       perror("in Get MAC Adress (internal) : SIOCGARP");
731       return -1;
732    }
733    memcpy(addr, parpreq.arp_ha.sa_data, 6);
734
735    return 0;
736 #else
737 #ifdef CMAKE_HAVE_NET_IF_H
738    int       sd;
739    struct ifreq    ifr, *ifrp;
740    struct ifconf    ifc;
741    char buf[1024];
742    int      n, i;
743    unsigned char    *a;
744 #if defined(AF_LINK) && (!defined(SIOCGIFHWADDR) && !defined(SIOCGENADDR))
745    struct sockaddr_dl *sdlp;
746 #endif
747
748 //
749 // BSD 4.4 defines the size of an ifreq to be
750 // max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len
751 // However, under earlier systems, sa_len isn't present, so the size is 
752 // just sizeof(struct ifreq)
753 // We should investigate the use of SIZEOF_ADDR_IFREQ
754 //
755 #ifdef HAVE_SA_LEN
756    #ifndef max
757       #define max(a,b) ((a) > (b) ? (a) : (b))
758    #endif
759    #define ifreq_size(i) max(sizeof(struct ifreq),\
760         sizeof((i).ifr_name)+(i).ifr_addr.sa_len)
761 #else
762    #define ifreq_size(i) sizeof(struct ifreq)
763 #endif // HAVE_SA_LEN
764
765    if ( (sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0 )
766    {
767       return -1;
768    }
769    memset(buf, 0, sizeof(buf));
770    ifc.ifc_len = sizeof(buf);
771    ifc.ifc_buf = buf;
772    if (ioctl (sd, SIOCGIFCONF, (char *)&ifc) < 0)
773    {
774       close(sd);
775       return -1;
776    }
777    n = ifc.ifc_len;
778    for (i = 0; i < n; i+= ifreq_size(*ifrp) )
779    {
780       ifrp = (struct ifreq *)((char *) ifc.ifc_buf+i);
781       strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ);
782 #ifdef SIOCGIFHWADDR
783       if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0)
784          continue;
785       a = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
786 #else
787 #ifdef SIOCGENADDR
788       // In theory this call should also work on Sun Solaris, but apparently
789       // SIOCGENADDR is not implemented properly thus the call 
790       // ioctl(sd, SIOCGENADDR, &ifr) always returns errno=2 
791       // (No such file or directory)
792       // Furthermore the DLAPI seems to require full root access
793       if (ioctl(sd, SIOCGENADDR, &ifr) < 0)
794          continue;
795       a = (unsigned char *) ifr.ifr_enaddr;
796 #else
797 #ifdef AF_LINK
798       sdlp = (struct sockaddr_dl *) &ifrp->ifr_addr;
799       if ((sdlp->sdl_family != AF_LINK) || (sdlp->sdl_alen != 6))
800          continue;
801       a = (unsigned char *) &sdlp->sdl_data[sdlp->sdl_nlen];
802 #else
803       perror("in Get MAC Adress (internal) : No way to access hardware");
804       close(sd);
805       return -1;
806 #endif // AF_LINK
807 #endif // SIOCGENADDR
808 #endif // SIOCGIFHWADDR
809       if (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5]) continue;
810
811       if (addr) 
812       {
813          memcpy(addr, a, 6);
814          close(sd);
815          return 0;
816       }
817    }
818    close(sd);
819 #endif
820    // Not implemented platforms (or no cable !)
821    perror("in Get MAC Adress (internal) : There was a configuration problem (or no cable !) on your plateform");
822    memset(addr,0,6);
823    return -1;
824 #endif //__sun
825 }
826
827 /**
828  * \brief Mini function to return the last digit from a number express in base 256
829  *        pre condition data contain an array of 6 unsigned char
830  *        post condition carry contain the last digit
831  */
832 inline int getlastdigit(unsigned char *data)
833 {
834   int extended, carry = 0;
835   for(int i=0;i<6;i++)
836     {
837     extended = (carry << 8) + data[i];
838     data[i] = extended / 10;
839     carry = extended % 10;
840     }
841   return carry;
842 }
843
844 /**
845  * \brief Encode the mac address on a fixed length string of 15 characters.
846  * we save space this way.
847  */
848 std::string Util::GetMACAddress()
849 {
850    // This code is the result of a long internet search to find something
851    // as compact as possible (not OS independant). We only have to separate
852    // 3 OS: Win32, SunOS and 'real' POSIX
853    // http://groups-beta.google.com/group/comp.unix.solaris/msg/ad36929d783d63be
854    // http://bdn.borland.com/article/0,1410,26040,00.html
855    unsigned char addr[6];
856
857    int stat = GetMacAddrSys(addr);
858    if (stat == 0)
859    {
860       // We need to convert a 6 digit number from base 256 to base 10, using integer
861       // would requires a 48bits one. To avoid this we have to reimplement the div + modulo 
862       // with string only
863       bool zero = false;
864       int res;
865       std::string sres;
866       while(!zero)
867       {
868          res = getlastdigit(addr);
869          sres.insert(sres.begin(), '0' + res);
870          zero = (addr[0] == 0) && (addr[1] == 0) && (addr[2] == 0) 
871              && (addr[3] == 0) && (addr[4] == 0) && (addr[5] == 0);
872       }
873
874       return sres;
875    }
876    else
877    {
878       gdcmStaticWarningMacro("Problem in finding the MAC Address");
879       return "";
880    }
881 }
882
883 /**
884  * \brief Creates a new UID. As stipulated in the DICOM ref
885  *        each time a DICOM image is created it should have 
886  *        a unique identifier (URI)
887  * @param root is the DICOM prefix assigned by IOS group
888  */
889 std::string Util::CreateUniqueUID(const std::string &root)
890 {
891    std::string prefix;
892    std::string append;
893    if ( root.empty() )
894    {
895       // gdcm UID prefix, as supplied by http://www.medicalconnections.co.uk
896       prefix = RootUID; 
897    }
898    else
899    {
900       prefix = root;
901    }
902
903    // A root was specified use it to forge our new UID:
904    append += ".";
905    //append += Util::GetMACAddress(); // to save CPU time
906    append += Util::GDCM_MAC_ADRESS;
907    append += ".";
908    append += Util::GetCurrentDateTime();
909    append += ".";
910    //Also add a mini random number just in case:
911    char tmp[10];
912    int r = (int) (100.0*rand()/RAND_MAX);
913    // Don't use Util::Format to accelerate the execution
914    sprintf(tmp,"%02d", r);
915    append += tmp;
916
917    // If append is too long we need to rehash it
918    if ( (prefix + append).size() > 64 )
919    {
920       gdcmStaticErrorMacro( "Size of UID is too long." );
921       // we need a hash function to truncate this number
922       // if only md5 was cross plateform
923       // MD5(append);
924    }
925
926    return prefix + append;
927 }
928
929 void Util::SetRootUID(const std::string &root)
930 {
931    if ( root.empty() )
932       RootUID = GDCM_UID;
933    else
934       RootUID = root;
935 }
936
937 const std::string &Util::GetRootUID()
938 {
939    return RootUID;
940 }
941
942 //-------------------------------------------------------------------------
943 /**
944  * \brief binary_write binary_write
945  * @param os ostream to write to 
946  * @param val 16 bits value to write
947  */ 
948 std::ostream &binary_write(std::ostream &os, const uint16_t &val)
949 {
950 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
951    uint16_t swap;
952    swap = ( val << 8 | val >> 8 );
953
954    return os.write(reinterpret_cast<const char*>(&swap), 2);
955 #else
956    return os.write(reinterpret_cast<const char*>(&val), 2);
957 #endif //GDCM_WORDS_BIGENDIAN
958 }
959
960 /**
961  * \brief binary_write binary_write
962  * @param os ostream to write to
963  * @param val 32 bits value to write
964  */ 
965 std::ostream &binary_write(std::ostream &os, const uint32_t &val)
966 {
967 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
968    uint32_t swap;
969    swap = (  (val<<24)               | ((val<<8)  & 0x00ff0000) | 
970             ((val>>8)  & 0x0000ff00) |  (val>>24)               );
971    return os.write(reinterpret_cast<const char*>(&swap), 4);
972 #else
973    return os.write(reinterpret_cast<const char*>(&val), 4);
974 #endif //GDCM_WORDS_BIGENDIAN
975 }
976
977
978 /**
979  * \brief binary_write binary_write
980  * @param os ostream to write to
981  * @param val double (64 bits) value to write
982  */ 
983 std::ostream &binary_write(std::ostream &os, const double &val)
984 {
985 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)    
986    double swap = val;
987    
988    char *beg = (char *)&swap;
989    char *end = beg + 7;
990    char t;
991    for (unsigned int i = 0; i<7; i++)
992    {
993       t    = *beg;
994       *beg = *end;
995       *end = t;
996       beg++,
997       end--;  
998    }  
999    return os.write(reinterpret_cast<const char*>(&swap), 8);
1000 #else
1001    return os.write(reinterpret_cast<const char*>(&val), 8);
1002 #endif //GDCM_WORDS_BIGENDIAN
1003 }
1004
1005
1006 /**
1007  * \brief  binary_write binary_write
1008  * @param os ostream to write to
1009  * @param val 8 bits characters aray to write
1010  */ 
1011 std::ostream &binary_write(std::ostream &os, const char *val)
1012 {
1013    return os.write(val, strlen(val));
1014 }
1015
1016 /**
1017  * \brief  binary_write binary_write
1018  * @param os ostream to write to
1019  * @param val std::string value to write
1020  */ 
1021 std::ostream &binary_write(std::ostream &os, std::string const &val)
1022 {
1023    return os.write(val.c_str(), val.size());
1024 }
1025
1026 /**
1027  * \brief  binary_write binary_write
1028  * @param os ostream to write to
1029  * @param val 8 bits 'characters' aray to write
1030  * @param len length of the 'value' to be written
1031  */ 
1032 std::ostream &binary_write(std::ostream &os, const uint8_t *val, size_t len)
1033 {
1034    // We are writting sizeof(char) thus no need to swap bytes
1035    return os.write(reinterpret_cast<const char*>(val), len);
1036 }
1037
1038 /**
1039  * \brief  binary_write binary_write
1040  * @param os ostream to write to
1041  * @param val 16 bits words aray to write
1042  * @param len length (in bytes) of the 'value' to be written 
1043  */ 
1044 std::ostream &binary_write(std::ostream &os, const uint16_t *val, size_t len)
1045 {
1046 // This is tricky since we are writting two bytes buffer. 
1047 // Be carefull with little endian vs big endian. 
1048 // Also this other trick is to allocate a small (efficient) buffer that store
1049 // intermediate result before writting it.
1050 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
1051    const int BUFFER_SIZE = 4096;
1052    static char buffer[BUFFER_SIZE];
1053    uint16_t *binArea16 = (uint16_t*)val; //for the const
1054  
1055    // how many BUFFER_SIZE long pieces in binArea ?
1056    int nbPieces = len/BUFFER_SIZE; //(16 bits = 2 Bytes)
1057    int remainingSize = len%BUFFER_SIZE;
1058
1059    for (int j=0;j<nbPieces;j++)
1060    {
1061       uint16_t *pbuffer  = (uint16_t*)buffer; //reinitialize pbuffer
1062       for (int i = 0; i < BUFFER_SIZE/2; i++)
1063       {
1064          *pbuffer = *binArea16 >> 8 | *binArea16 << 8;
1065          pbuffer++;
1066          binArea16++;
1067       }
1068       os.write ( buffer, BUFFER_SIZE );
1069    }
1070    if ( remainingSize > 0)
1071    {
1072       uint16_t *pbuffer  = (uint16_t*)buffer; //reinitialize pbuffer
1073       for (int i = 0; i < remainingSize/2; i++)
1074       {
1075          *pbuffer = *binArea16 >> 8 | *binArea16 << 8;
1076          pbuffer++;
1077          binArea16++;
1078       }
1079       os.write ( buffer, remainingSize );
1080    }
1081    return os;
1082 #else
1083    return os.write(reinterpret_cast<const char*>(val), len);
1084 #endif
1085 }
1086
1087 //-------------------------------------------------------------------------
1088 // Protected
1089
1090 //-------------------------------------------------------------------------
1091 // Private
1092 /**
1093  * \brief   Return the IP adress of the machine writting the DICOM image
1094  */
1095 std::string Util::GetIPAddress()
1096 {
1097    // This is a rip from 
1098    // http://www.codeguru.com/Cpp/I-N/internet/network/article.php/c3445/
1099 #ifndef HOST_NAME_MAX
1100    // SUSv2 guarantees that `Host names are limited to 255 bytes'.
1101    // POSIX 1003.1-2001 guarantees that `Host names (not including the
1102    // terminating NUL) are limited to HOST_NAME_MAX bytes'.
1103 #define HOST_NAME_MAX 255
1104    // In this case we should maybe check the string was not truncated.
1105    // But I don't known how to check that...
1106 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
1107    // with WinSock DLL we need to initialize the WinSock before using gethostname
1108    WORD wVersionRequested = MAKEWORD(1,0);
1109    WSADATA WSAData;
1110    int err = WSAStartup(wVersionRequested,&WSAData);
1111    if (err != 0)
1112    {
1113       // Tell the user that we could not find a usable
1114       // WinSock DLL.
1115       WSACleanup();
1116       return "127.0.0.1";
1117    }
1118 #endif
1119   
1120 #endif //HOST_NAME_MAX
1121
1122    std::string str;
1123    char szHostName[HOST_NAME_MAX+1];
1124    int r = gethostname(szHostName, HOST_NAME_MAX);
1125  
1126    if ( r == 0 )
1127    {
1128       // Get host adresses
1129       struct hostent *pHost = gethostbyname(szHostName);
1130  
1131       for( int i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
1132       {
1133          for( int j = 0; j<pHost->h_length; j++ )
1134          {
1135             if ( j > 0 ) str += ".";
1136  
1137             str += Util::Format("%u", 
1138                 (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
1139          }
1140          // str now contains one local IP address 
1141  
1142 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__)
1143    WSACleanup();
1144 #endif
1145
1146       }
1147    }
1148    // If an error occur r == -1
1149    // Most of the time it will return 127.0.0.1...
1150    return str;
1151 }
1152
1153 void Util::hfpswap(double *a, double *b)
1154 {
1155    double tmp;
1156    tmp=*a;
1157    *a=*b;
1158    *b=tmp;
1159 }
1160
1161 //-------------------------------------------------------------------------
1162 } // end namespace gdcm
1163