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