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