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