File: gdcmFileAnonymizer.cxx

package info (click to toggle)
gdcm 3.0.21-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 26,880 kB
  • sloc: cpp: 203,477; ansic: 78,582; xml: 48,129; python: 3,459; cs: 2,308; java: 1,629; lex: 1,290; sh: 334; php: 128; makefile: 117
file content (585 lines) | stat: -rw-r--r-- 16,310 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
/*=========================================================================

  Program: GDCM (Grassroots DICOM). A DICOM library

  Copyright (c) 2006-2011 Mathieu Malaterre
  All rights reserved.
  See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "gdcmFileAnonymizer.h"

#include "gdcmReader.h"

#include <fstream>
#include <set>
#include <vector>
#include <map>
#include <algorithm> // sort

#ifdef _MSC_VER
#pragma warning (disable : 4068 ) /* disable unknown pragma warnings */
#endif
// See : POD value-init, see GCC #36750
/* Test for GCC < 5.1.1 */
/* GCC 4.2 reports: error: #pragma GCC diagnostic not allowed inside functions */
#if GCC_VERSION < 50101
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#endif

namespace gdcm
{

enum Action
{
  EMPTY,
  REMOVE,
  REPLACE
};

struct PositionEmpty
{
  std::streampos BeginPos;
  std::streampos EndPos;
  Action action;
  bool IsTagFound; // Required for EMPTY
  DataElement DE;
  bool operator() (const PositionEmpty & i, const PositionEmpty & j)
    {
    if( i.BeginPos == j.BeginPos )
      {
      return i.DE.GetTag() < j.DE.GetTag();
      }
    // else
    return (int)i.BeginPos < (int)j.BeginPos;
    }
};

class FileAnonymizerInternals
{
public:
  std::string InputFilename;
  std::string OutputFilename;
  std::set<Tag> EmptyTags;
  std::set<Tag> RemoveTags;
  std::map<Tag, std::string> ReplaceTags;
  TransferSyntax TS;
  std::vector<PositionEmpty> PositionEmptyArray;
};

FileAnonymizer::FileAnonymizer()
{
  Internals = new FileAnonymizerInternals;
}

FileAnonymizer::~FileAnonymizer()
{
  delete Internals;
}

void FileAnonymizer::Empty( Tag const &t )
{
  if( t.GetGroup() >= 0x0008 )
    {
    Internals->EmptyTags.insert( t );
    }
}

void FileAnonymizer::Remove( Tag const &t )
{
  if( t.GetGroup() >= 0x0008 )
    {
    Internals->RemoveTags.insert( t );
    }
}

void FileAnonymizer::Replace( Tag const &t, const char *value )
{
  if( value && t.GetGroup() >= 0x0008 )
    {
    Internals->ReplaceTags.insert(
      std::make_pair( t, value) );
    }
}

void FileAnonymizer::Replace( Tag const &t, const char *value, VL const & vl )
{
  if( value && t.GetGroup() >= 0x0008 )
    {
    Internals->ReplaceTags.insert(
      std::make_pair( t, std::string(value, vl) ) );
    }
}

void FileAnonymizer::SetInputFileName(const char *filename_native)
{
  if( filename_native )
    Internals->InputFilename = filename_native;
}

void FileAnonymizer::SetOutputFileName(const char *filename_native)
{
  if( filename_native )
    Internals->OutputFilename = filename_native;
}

// portable way to check for existence (actually: accessibility):
static inline bool file_exist(const char *filename)
{
  std::ifstream infile(filename, std::ios::binary);
  return infile.good();
}


bool FileAnonymizer::ComputeReplaceTagPosition()
{
/*
 Implementation details:
 We should make sure that the user know what she is doing in case of SQ.
 Let's assume a User call Replace( Tag(0x0008,0x2112), "FOOBAR" )
 For quite a lot of DICOM implementation this Tag is required to be a SQ.
 Therefore even if the Attribute is declared with VR:UN, some implementation
 will try very hard to decode it as SQ...which obviously will fail
 Instead do not support SQ at all here and document it should not be used for SQ
 */
  assert( !Internals->InputFilename.empty() );
  const char *filename = Internals->InputFilename.c_str();
  assert( filename );
  const bool inplace = file_exist(Internals->OutputFilename.c_str());

  std::map<Tag, std::string>::reverse_iterator rit = Internals->ReplaceTags.rbegin();
  for ( ; rit != Internals->ReplaceTags.rend(); rit++ )
    {
    PositionEmpty pe;

    std::set<Tag> removeme;
    const Tag & t = rit->first;
    const std::string & valuereplace = rit->second;
    removeme.insert( t );

    std::ifstream is( filename, std::ios::binary );
    Reader reader;
    reader.SetStream( is );
    if( !reader.ReadSelectedTags( removeme ) )
      {
      return false;
      }

    pe.EndPos = pe.BeginPos = is.tellg();
    pe.action = REPLACE;
    pe.IsTagFound = false;
    const File & f = reader.GetFile();
    const DataSet &ds = f.GetDataSet();
    const TransferSyntax &ts = f.GetHeader().GetDataSetTransferSyntax();
    Internals->TS = ts;

    pe.DE.SetTag( t );
    if( ds.FindDataElement( t ) )
      {
      const DataElement &de = ds.GetDataElement( t );
      pe.IsTagFound = true;
      pe.DE.SetVL( de.GetVL() ); // Length is not used, unless to check undefined flag
      pe.DE.SetVR( de.GetVR() );
      assert( pe.DE.GetVL().IsUndefined() == de.GetVL().IsUndefined() );
      assert( pe.DE.GetVR() == de.GetVR() );
      assert( pe.DE.GetTag() == de.GetTag() );
      if( de.GetVL().IsUndefined() )
        {
        // This is a SQ
        gdcmErrorMacro( "Replacing a SQ is not supported. Use Remove() or Empty()" );
        return false;
        }
      else
        {
        if( inplace && valuereplace.size() != de.GetVL() )
          {
          gdcmErrorMacro( "inplace mode requires same length attribute" ); // TODO we could allow smaller size (and pad with space...)
          return false;
          }
        assert( !de.GetVL().IsUndefined() );
        pe.BeginPos -= de.GetVL();
        pe.BeginPos -= 2 * de.GetVR().GetLength(); // (VR+) VL
        pe.BeginPos -= 4; // Tag
        assert( (int)pe.EndPos ==
          (int)pe.BeginPos + (int)de.GetVL() + 2 * de.GetVR().GetLength() + 4 );
        }
      pe.DE.SetByteValue( valuereplace.c_str(), (uint32_t)valuereplace.size() );
      assert( pe.DE.GetVL() == valuereplace.size() );
      }
    else
      {
      if( inplace )
        {
        gdcmErrorMacro( "inplace mode requires existing tag (cannot insert). Tag: " << t );
        return false;
        }
      // We need to insert an Empty Data Element !
      //FIXME, for some public element we could do something nicer than VR:UN
      pe.DE.SetVR( VR::UN );
      pe.DE.SetByteValue( valuereplace.c_str(), (uint32_t)valuereplace.size() );
      assert( pe.DE.GetVL() == valuereplace.size() );
      }

    // We need to push_back outside of if() since Action:Replace
    // on a missing tag, means insert it !
    Internals->PositionEmptyArray.push_back( pe );

    is.close();
    }
  return true;
}

bool FileAnonymizer::ComputeRemoveTagPosition()
{
  assert( !Internals->InputFilename.empty() );
  const char *filename = Internals->InputFilename.c_str();
  assert( filename );
  const bool inplace = file_exist(Internals->OutputFilename.c_str());
  if( inplace && !Internals->RemoveTags.empty())
    {
    gdcmErrorMacro( "inplace mode requires existing tag (cannot remove)" );
    return false;
    }

  std::set<Tag>::reverse_iterator rit = Internals->RemoveTags.rbegin();
  for ( ; rit != Internals->RemoveTags.rend(); rit++ )
    {
    PositionEmpty pe;

    std::set<Tag> removeme;
    const Tag & t = *rit;
    removeme.insert( t );

    std::ifstream is( filename, std::ios::binary );
    Reader reader;
    reader.SetStream( is );
    if( !reader.ReadSelectedTags( removeme ) )
      {
      return false;
      }

    pe.EndPos = pe.BeginPos = is.tellg();
    pe.action = REMOVE;
    pe.IsTagFound = false;
    const File & f = reader.GetFile();
    const DataSet &ds = f.GetDataSet();
    const TransferSyntax &ts = f.GetHeader().GetDataSetTransferSyntax();
    Internals->TS = ts;

    pe.DE.SetTag( t );
    if( ds.FindDataElement( t ) )
      {
      const DataElement &de = ds.GetDataElement( t );
      pe.IsTagFound = true;
      pe.DE.SetVL( de.GetVL() ); // Length is not used, unless to check undefined flag
      pe.DE.SetVR( de.GetVR() );
      assert( pe.DE.GetVL().IsUndefined() == de.GetVL().IsUndefined() );
      assert( pe.DE.GetVR() == de.GetVR() );
      assert( pe.DE.GetTag() == de.GetTag() );
      if( de.GetVL().IsUndefined() )
        {
        // This is a SQ
        VL vl;
        if( ts.GetNegociatedType() == TransferSyntax::Implicit )
          {
          vl = de.GetLength<ImplicitDataElement>();
          }
        else
          {
          vl = de.GetLength<ExplicitDataElement>();
          }
        assert( pe.BeginPos > vl );
        pe.BeginPos -= vl;
        }
      else
        {
        assert( !de.GetVL().IsUndefined() );
        pe.BeginPos -= de.GetVL();
        pe.BeginPos -= 2 * de.GetVR().GetLength(); // (VR+) VL
        pe.BeginPos -= 4; // Tag
        assert( (int)pe.EndPos ==
          (int)pe.BeginPos + (int)de.GetVL() + 2 * de.GetVR().GetLength() + 4 );
        }
      Internals->PositionEmptyArray.push_back( pe );
      }
    else
      {
      // Yay no need to do anything !
      }

    is.close();
    }

  return true;
}

bool FileAnonymizer::ComputeEmptyTagPosition()
{
  // FIXME we sometime empty, attributes that are already empty...
  assert( !Internals->InputFilename.empty() );
  const char *filename = Internals->InputFilename.c_str();
  assert( filename );
  const bool inplace = file_exist(Internals->OutputFilename.c_str());
  if( inplace && !Internals->EmptyTags.empty())
    {
    gdcmErrorMacro( "inplace mode requires existing tag (cannot empty)" );
    return false;
    }

  std::set<Tag>::reverse_iterator rit = Internals->EmptyTags.rbegin();
  for ( ; rit != Internals->EmptyTags.rend(); rit++ )
    {
    PositionEmpty pe;

    std::set<Tag> removeme;
    const Tag & t = *rit;
    removeme.insert( t );

    std::ifstream is( filename, std::ios::binary );
    Reader reader;
    reader.SetStream( is );
    if( !reader.ReadSelectedTags( removeme ) )
      {
      return false;
      }

    pe.EndPos = pe.BeginPos = is.tellg();
    pe.action = EMPTY;
    pe.IsTagFound = false;
    const File & f = reader.GetFile();
    const DataSet &ds = f.GetDataSet();
    const TransferSyntax &ts = f.GetHeader().GetDataSetTransferSyntax();
    Internals->TS = ts;

    pe.DE.SetTag( t );
    if( ds.FindDataElement( t ) )
      {
      const DataElement &de = ds.GetDataElement( t );
      pe.IsTagFound = true;
      pe.DE.SetVL( de.GetVL() ); // Length is not used, unless to check undefined flag
      pe.DE.SetVR( de.GetVR() );
      assert( pe.DE.GetVL().IsUndefined() == de.GetVL().IsUndefined() );
      assert( pe.DE.GetVR() == de.GetVR() );
      assert( pe.DE.GetTag() == de.GetTag() );
      if( de.GetVL().IsUndefined() )
        {
        // This is a SQ
        VL vl;
        if( ts.GetNegociatedType() == TransferSyntax::Implicit )
          {
          vl = de.GetLength<ImplicitDataElement>();
          }
        else
          {
          vl = de.GetLength<ExplicitDataElement>();
          }
        assert( pe.BeginPos > vl );
        pe.BeginPos -= vl;
        pe.BeginPos += 4; // Tag
        if( ts.GetNegociatedType() == TransferSyntax::Implicit )
          {
          pe.BeginPos += 0;
          }
        else
          {
          pe.BeginPos += de.GetVR().GetLength();
          }
        }
      else
        {
        assert( !de.GetVL().IsUndefined() );
        pe.BeginPos -= de.GetVL();
        if( ts.GetNegociatedType() == TransferSyntax::Implicit )
          {
          pe.BeginPos -= 4;
          }
        else
          {
          pe.BeginPos -= de.GetVR().GetLength();
          assert( (int)pe.EndPos ==
            (int)pe.BeginPos + (int)de.GetVL() + de.GetVR().GetLength() );
          }
        }
      }
    else
      {
      // We need to insert an Empty Data Element !
      //FIXME, for some public element we could do something nicer than VR:UN
      pe.DE.SetVR( VR::UN );
      pe.DE.SetVL( 0 );
      }

    // We need to push_back outside of if() since Action:Empty
    // on a missing tag, means insert it !
    Internals->PositionEmptyArray.push_back( pe );

    is.close();
    }

  return true;
}
bool FileAnonymizer::Write()
{
  if( Internals->OutputFilename.empty() ) return false;
  const char *outfilename = Internals->OutputFilename.c_str();
  if( Internals->InputFilename.empty() ) return false;
  const char *filename = Internals->InputFilename.c_str();

  Internals->PositionEmptyArray.clear();

  // Compute offsets
  if( !ComputeRemoveTagPosition()
    || !ComputeEmptyTagPosition()
    || !ComputeReplaceTagPosition() )
    {
    return false;
    }

  // Make sure we will copy from lower offset to highest:
  // need to loop from the end. Sometimes a replace operation will have *exact*
  // same file offset for multiple attributes. In which case we need to insert
  // first the last attribute, and at the end the first attribute
  PositionEmpty pe_sort = {};
  std::sort (Internals->PositionEmptyArray.begin(),
    Internals->PositionEmptyArray.end(), pe_sort);

  // Step 2. Copy & skip proper portion
  std::ios::openmode om;
  const bool inplace = file_exist(outfilename);
  if( inplace )
    {
    // overwrite:
    om = std::ofstream::in | std::ofstream::out | std::ios::binary;
    }
  else
    {
    // create
    om = std::ofstream::out | std::ios::binary;
    }
  std::fstream of( outfilename, om );
  std::ifstream is( filename, std::ios::binary );
  std::streampos prev = 0;
  const TransferSyntax &ts = Internals->TS;
  std::vector<PositionEmpty>::const_iterator it =
    Internals->PositionEmptyArray.begin();
  for( ; it != Internals->PositionEmptyArray.end(); ++it )
    {
    const PositionEmpty & pe = *it;
    Action action = pe.action;

    if( pe.IsTagFound )
      {
      const DataElement & de = pe.DE;
      int vrlen = de.GetVR().GetLength();
      if( ts.GetNegociatedType() == TransferSyntax::Implicit )
        {
        vrlen = 4;
        }

      std::streampos end = pe.BeginPos;

      // FIXME: most efficient way to copy chunk of file in c++ ?
      for( int i = (int)prev; i < end; ++i)
        {
        of.put( (char)is.get() );
        }
      if( action == EMPTY )
        {
        assert( !inplace );
        // Create a 0 Value Length (VR+Tag was copied in previous loop)
        for( int i = 0; i < vrlen; ++i)
          {
          of.put( 0 );
          }
        }
      else if( action == REPLACE )
        {
        if( ts.GetSwapCode() == SwapCode::BigEndian )
          {
          if( ts.GetNegociatedType() == TransferSyntax::Implicit )
            {
            gdcmErrorMacro( "Cannot write Virtual Big Endian" );
            return true;
            }
          else
            {
            pe.DE.Write<ExplicitDataElement,SwapperDoOp>( of );
            }
          }
        else
          {
          if( ts.GetNegociatedType() == TransferSyntax::Implicit )
            {
            pe.DE.Write<ImplicitDataElement,SwapperNoOp>( of );
            }
          else
            {
            pe.DE.Write<ExplicitDataElement,SwapperNoOp>( of );
            }
          }
        }
      // Skip the Value
      assert( is.good() );
      is.seekg( pe.EndPos );
      assert( is.good() );
      prev = is.tellg();
      assert( prev == pe.EndPos );
      }
    else
      {
      std::streampos end = pe.BeginPos;

      // FIXME: most efficient way to copy chunk of file in c++ ?
      for( int i = (int)prev; i < end; ++i)
        {
        of.put( (char)is.get() );
        }
      if( ts.GetSwapCode() == SwapCode::BigEndian )
        {
        if( ts.GetNegociatedType() == TransferSyntax::Implicit )
          {
          gdcmErrorMacro( "Cannot write Virtual Big Endian" );
          return true;
          }
        else
          {
          pe.DE.Write<ExplicitDataElement,SwapperDoOp>( of );
          }
        }
      else
        {
        if( ts.GetNegociatedType() == TransferSyntax::Implicit )
          {
          pe.DE.Write<ImplicitDataElement,SwapperNoOp>( of );
          }
        else
          {
          pe.DE.Write<ExplicitDataElement,SwapperNoOp>( of );
          }
        }
      prev = is.tellg();
      }
    }

  of << is.rdbuf();
  of.close();
  is.close();

#if 0
  Reader r;
  r.SetFileName( outfilename );
  if( !r.Read() )
    {
    gdcmErrorMacro( "Output file got corrupted, please report" );
    return false;
    }
#endif

  return true;
}

} // end namespace gdcm