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