]> git.mxchange.org Git - simgear.git/blob - simgear/io/SVNReportParser.cxx
SVN read-only client code using our HTTP engine.
[simgear.git] / simgear / io / SVNReportParser.cxx
1 // SVNReportParser -- parser for SVN report XML data
2 //
3 // Copyright (C) 2012  James Turner <zakalawe@mac.com>
4 //
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License as
7 // published by the Free Software Foundation; either version 2 of the
8 // License, or (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful, but
11 // WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 // General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18
19 #include "SVNReportParser.hxx"
20
21 #include <iostream>
22 #include <cstring>
23 #include <cassert>
24 #include <algorithm>
25 #include <sstream>
26 #include <fstream>
27
28 #include <boost/foreach.hpp>
29
30 #include "simgear/misc/sg_path.hxx"
31 #include "simgear/misc/sg_dir.hxx"
32 #include "simgear/debug/logstream.hxx"
33 #include "simgear/xml/xmlparse.h"
34 #include "simgear/xml/easyxml.hxx"
35 #include "simgear/misc/strutils.hxx"
36 #include "simgear/package/md5.h"
37
38 #include "SVNDirectory.hxx"
39 #include "SVNRepository.hxx"
40 #include "DAVMultiStatus.hxx"
41
42 using std::cout;
43 using std::cerr;
44 using std::endl;
45 using std::string;
46
47 using namespace simgear;
48
49 #define DAV_NS "DAV::"
50 #define SVN_NS "svn::"
51 #define SUBVERSION_DAV_NS "http://subversion.tigris.org/xmlns/dav/"
52
53 namespace {
54     
55     #define MAX_ENCODED_INT_LEN 10
56     
57     static size_t
58     decode_size(unsigned char* &p,
59                 const unsigned char *end)
60     {
61       if (p + MAX_ENCODED_INT_LEN < end)
62         end = p + MAX_ENCODED_INT_LEN;
63       /* Decode bytes until we're done.  */
64       size_t result = 0;
65       
66       while (p < end) {
67           result = (result << 7) | (*p & 0x7f);
68           if (((*p++ >> 7) & 0x1) == 0) {
69               break;
70           }
71       }
72       
73       return result;
74     }
75     
76     static bool
77     try_decode_size(unsigned char* &p,
78                 const unsigned char *end)
79     {
80       if (p + MAX_ENCODED_INT_LEN < end)
81         end = p + MAX_ENCODED_INT_LEN;
82
83       while (p < end) {
84           if (((*p++ >> 7) & 0x1) == 0) {
85               return true;
86           }
87       }
88       
89       return false;
90     }
91     
92 //  const char* SVN_UPDATE_REPORT_TAG = SVN_NS "update-report";
93  // const char* SVN_TARGET_REVISION_TAG = SVN_NS "target-revision";
94   const char* SVN_OPEN_DIRECTORY_TAG = SVN_NS "open-directory";
95   const char* SVN_OPEN_FILE_TAG = SVN_NS "open-file";
96   const char* SVN_ADD_DIRECTORY_TAG = SVN_NS "add-directory";
97   const char* SVN_ADD_FILE_TAG = SVN_NS "add-file";
98   const char* SVN_TXDELTA_TAG = SVN_NS "txdelta";
99   const char* SVN_SET_PROP_TAG = SVN_NS "set-prop";
100   const char* SVN_DELETE_ENTRY_TAG = SVN_NS "delete-entry";
101   
102   const char* SVN_DAV_MD5_CHECKSUM = SUBVERSION_DAV_NS ":md5-checksum";
103   
104   const char* DAV_HREF_TAG = DAV_NS "href";
105   const char* DAV_CHECKED_IN_TAG = SVN_NS "checked-in";
106   
107
108   const int svn_txdelta_source = 0;
109   const int svn_txdelta_target = 1;
110   const int svn_txdelta_new = 2;
111
112   const size_t DELTA_HEADER_SIZE = 4;
113     
114   /**
115    * helper struct to decode and store the SVN delta header
116    * values
117    */
118   struct SVNDeltaWindow
119   {
120   public:
121
122       static bool isWindowComplete(unsigned char* buffer, size_t bytes)
123       {
124           unsigned char* p = buffer;
125           unsigned char* pEnd = p + bytes;
126           // if we can't decode five sizes, certainly incomplete
127           for (int i=0; i<5; i++) {
128               if (!try_decode_size(p, pEnd)) {
129                   return false;
130               }
131           }
132           
133           p = buffer;
134         // ignore these three
135           decode_size(p, pEnd);
136           decode_size(p, pEnd);
137           decode_size(p, pEnd);
138           size_t instructionLen = decode_size(p, pEnd);
139           size_t newLength = decode_size(p, pEnd);
140           size_t headerLength = p - buffer;
141           
142           return (bytes >= (instructionLen + newLength + headerLength));
143       }
144       
145      SVNDeltaWindow(unsigned char* p) :
146          headerLength(0),
147          _ptr(p)
148      {
149          sourceViewOffset = decode_size(p, p+20);
150          sourceViewLength = decode_size(p, p+20);
151          targetViewLength = decode_size(p, p+20);
152          instructionLength = decode_size(p, p+20);
153          newLength = decode_size(p, p+20);
154          
155          headerLength = p - _ptr;
156          _ptr = p;
157          
158          if (sourceViewOffset != 0) {
159              cout << "sourceViewOffset:" << sourceViewOffset << endl;
160          }
161      }
162   
163     bool apply(std::vector<char>& output, std::istream& source)
164     {
165         unsigned char* pEnd = _ptr + instructionLength;
166         unsigned char* newData = pEnd;
167         
168         while (_ptr < pEnd) {
169           int op = ((*_ptr >> 6) & 0x3);  
170           if (op >= 3) {
171               std::cerr << "weird opcode" << endl;
172               return false;
173           }
174       
175           int length = *_ptr++ & 0x3f;
176           int offset = 0;
177         
178           if (length == 0) {
179             length = decode_size(_ptr, pEnd);
180           }
181         
182           if (length == 0) {
183             std::cerr << "malformed stream, 0 length" << std::endl;
184             return false;
185           }
186       
187           // if op != new, decode another size value
188           if (op != svn_txdelta_new) {
189             offset = decode_size(_ptr, pEnd);
190           }
191
192           if (op == svn_txdelta_target) {
193             while (length > 0) {
194               output.push_back(output[offset++]);
195               --length;
196             }
197           } else if (op == svn_txdelta_new) {
198               output.insert(output.end(), newData, newData + length);
199           } else if (op == svn_txdelta_source) {
200             source.seekg(offset);
201             char* sourceBuf = (char*) malloc(length);
202             assert(sourceBuf);
203             source.read(sourceBuf, length);
204             output.insert(output.end(), sourceBuf, sourceBuf + length);
205             free(sourceBuf);
206           }
207         } // of instruction loop
208         
209         return true;
210     }  
211   
212     size_t size() const
213     {
214         return headerLength + instructionLength + newLength;
215     }
216   
217     unsigned int sourceViewOffset;
218     size_t sourceViewLength,
219       targetViewLength;
220     size_t headerLength,
221         instructionLength,
222         newLength;
223     
224 private:  
225     unsigned char* _ptr;
226   };
227   
228   
229 } // of anonymous namespace
230
231 class SVNReportParser::SVNReportParserPrivate
232 {
233 public:
234   SVNReportParserPrivate(SVNRepository* repo) :
235     tree(repo),
236     status(SVNRepository::NO_ERROR),
237     parserInited(false),
238     currentPath(repo->fsBase())
239   {
240     inFile = false;
241     currentDir = repo->rootDir();
242   }
243
244   ~SVNReportParserPrivate()
245   {
246   }
247   
248   void startElement (const char * name, const char** attributes)
249   {    
250       if (status != SVNRepository::NO_ERROR) {
251           return;
252       }
253       
254     ExpatAtts attrs(attributes);
255     tagStack.push_back(name);
256     if (!strcmp(name, SVN_TXDELTA_TAG)) {
257         txDeltaData.clear();
258     } else if (!strcmp(name, SVN_ADD_FILE_TAG)) {
259       string fileName(attrs.getValue("name"));
260       SGPath filePath(currentDir->fsDir().file(fileName));
261       currentPath = filePath;
262       inFile = true;
263     } else if (!strcmp(name, SVN_OPEN_FILE_TAG)) {
264       string fileName(attrs.getValue("name"));
265       SGPath filePath(Dir(currentPath).file(fileName));
266       currentPath = filePath;
267       
268       DAVResource* res = currentDir->collection()->childWithName(fileName);   
269       if (!res || !filePath.exists()) {
270         // set error condition
271       }
272       
273       inFile = true;
274     } else if (!strcmp(name, SVN_ADD_DIRECTORY_TAG)) {
275       string dirName(attrs.getValue("name"));
276       Dir d(currentDir->fsDir().file(dirName));
277       if (d.exists()) {
278           // policy decision : if we're doing an add, wipe the existing
279           d.remove(true);
280       }
281     
282       currentDir = currentDir->addChildDirectory(dirName);
283       currentPath = currentDir->fsPath();
284       currentDir->beginUpdateReport();
285       //cout << "addDir:" << currentPath << endl;
286     } else if (!strcmp(name, SVN_SET_PROP_TAG)) {
287       setPropName = attrs.getValue("name");
288       setPropValue.clear();
289     } else if (!strcmp(name, SVN_DAV_MD5_CHECKSUM)) {
290       md5Sum.clear();
291     } else if (!strcmp(name, SVN_OPEN_DIRECTORY_TAG)) {
292         string dirName;
293         if (attrs.getValue("name")) {
294             dirName = string(attrs.getValue("name"));
295         }
296         openDirectory(dirName);
297     } else if (!strcmp(name, SVN_DELETE_ENTRY_TAG)) {
298         string entryName(attrs.getValue("name"));
299         deleteEntry(entryName);
300     } else if (!strcmp(name, DAV_CHECKED_IN_TAG) || !strcmp(name, DAV_HREF_TAG)) {
301         // don't warn on these ones
302     } else {
303         //std::cerr << "unhandled element:" << name << std::endl;
304     }
305   } // of startElement
306   
307   void openDirectory(const std::string& dirName)
308   {
309       if (dirName.empty()) {
310           // root directory, we shall assume
311           currentDir = tree->rootDir();
312       } else {
313           assert(currentDir);
314           currentDir = currentDir->child(dirName);
315       }
316       
317       assert(currentDir);
318       currentPath = currentDir->fsPath();
319       currentDir->beginUpdateReport();
320   }
321   
322   void deleteEntry(const std::string& entryName)
323   {
324       currentDir->deleteChildByName(entryName);
325   }
326   
327   bool decodeTextDelta(const SGPath& outputPath)
328   {
329     string decoded = strutils::decodeBase64(txDeltaData);
330     size_t bytesToDecode = decoded.size();
331     std::vector<char> output;      
332     unsigned char* p = (unsigned char*) decoded.data();
333     if (memcmp(decoded.data(), "SVN\0", DELTA_HEADER_SIZE) != 0) {
334         return false; // bad header
335     }
336     
337     bytesToDecode -= DELTA_HEADER_SIZE;
338     p += DELTA_HEADER_SIZE;
339     std::ifstream source;
340     source.open(outputPath.c_str(), std::ios::in | std::ios::binary);
341     
342     while (bytesToDecode > 0) {  
343         SVNDeltaWindow window(p);      
344         assert(bytesToDecode >= window.size());
345         window.apply(output, source);
346         bytesToDecode -= window.size();
347         p += window.size();
348     }
349
350     source.close();
351     std::ofstream f;
352     f.open(outputPath.c_str(), 
353       std::ios::out | std::ios::trunc | std::ios::binary);
354     f.write(output.data(), output.size());
355     
356     // compute MD5 while we have the file in memory
357     MD5_CTX md5;
358     memset(&md5, 0, sizeof(MD5_CTX));
359     MD5Init(&md5);
360     MD5Update(&md5, (unsigned char*) output.data(), output.size());
361     MD5Final(&md5);
362     decodedFileMd5 = strutils::encodeHex(md5.digest, 16);
363     return true;
364   }
365   
366   void endElement (const char * name)
367   {
368       if (status != SVNRepository::NO_ERROR) {
369           return;
370       }
371       
372     assert(tagStack.back() == name);
373     tagStack.pop_back();
374     if (!strcmp(name, SVN_TXDELTA_TAG)) {
375       if (!decodeTextDelta(currentPath)) {
376           fail(SVNRepository::ERROR_TXDELTA);
377       }
378     } else if (!strcmp(name, SVN_ADD_FILE_TAG)) {
379       finishFile(currentDir->addChildFile(currentPath.file()));
380     } else if (!strcmp(name, SVN_OPEN_FILE_TAG)) {
381       DAVResource* res = currentDir->collection()->childWithName(currentPath.file());   
382       assert(res);
383       finishFile(res);
384     } else if (!strcmp(name, SVN_ADD_DIRECTORY_TAG)) {
385       // pop directory
386       currentPath = currentPath.dir();
387       currentDir->updateReportComplete();
388       currentDir = currentDir->parent();
389     } else if (!strcmp(name, SVN_SET_PROP_TAG)) {
390       if (setPropName == "svn:entry:committed-rev") {
391         revision = strutils::to_int(setPropValue);
392         currentVersionName = setPropValue;
393         if (!inFile) {
394           // for directories we have the resource already
395           // for adding files, we might not; we set the version name
396           // above when ending the add/open-file element
397           currentDir->collection()->setVersionName(currentVersionName);
398         } 
399       }
400     } else if (!strcmp(name, SVN_DAV_MD5_CHECKSUM)) {
401       // validate against (presumably) just written file
402       if (decodedFileMd5 != md5Sum) {
403         fail(SVNRepository::ERROR_CHECKSUM);
404       }
405     } else if (!strcmp(name, SVN_OPEN_DIRECTORY_TAG)) {
406         if (currentDir->parent()) {   
407           // pop the collection stack
408           currentDir = currentDir->parent();
409         }
410         
411         currentDir->updateReportComplete();
412         currentPath = currentDir->fsPath();
413     } else {
414     //  std::cout << "element:" << name;
415     }
416   }
417   
418   void finishFile(DAVResource* res)
419   {
420       res->setVersionName(currentVersionName);
421       res->setMD5(md5Sum);
422       currentPath = currentPath.dir();
423       inFile = false;
424   }
425   
426   void data (const char * s, int length)
427   {
428       if (status != SVNRepository::NO_ERROR) {
429           return;
430       }
431       
432     if (tagStack.back() == SVN_SET_PROP_TAG) {
433       setPropValue += string(s, length);
434     } else if (tagStack.back() == SVN_TXDELTA_TAG) {
435       txDeltaData += string(s, length);
436     } else if (tagStack.back() == SVN_DAV_MD5_CHECKSUM) {
437       md5Sum += string(s, length);
438     }
439   }
440   
441   void pi (const char * target, const char * data) {}
442   
443   string tagN(const unsigned int n) const
444   {
445     int sz = tagStack.size();
446     if (n >= sz) {
447       return string();
448     }
449     
450     return tagStack[sz - (1 + n)];
451   }
452   
453   void fail(SVNRepository::ResultCode err)
454   {
455       status = err;
456   }
457   
458   SVNRepository* tree;
459   DAVCollection* rootCollection;
460   SVNDirectory* currentDir;
461   SVNRepository::ResultCode status;
462   
463   bool parserInited;
464   XML_Parser xmlParser;
465   
466 // in-flight data
467   string_list tagStack;
468   string currentVersionName;
469   string txDeltaData;
470   SGPath currentPath;
471   bool inFile;
472     
473   unsigned int revision;
474   string md5Sum, decodedFileMd5;
475   std::string setPropName, setPropValue;
476 };
477
478
479 ////////////////////////////////////////////////////////////////////////
480 // Static callback functions for Expat.
481 ////////////////////////////////////////////////////////////////////////
482
483 #define VISITOR static_cast<SVNReportParser::SVNReportParserPrivate *>(userData)
484
485 static void
486 start_element (void * userData, const char * name, const char ** atts)
487 {
488   VISITOR->startElement(name, atts);
489 }
490
491 static void
492 end_element (void * userData, const char * name)
493 {
494   VISITOR->endElement(name);
495 }
496
497 static void
498 character_data (void * userData, const char * s, int len)
499 {
500   VISITOR->data(s, len);
501 }
502
503 static void
504 processing_instruction (void * userData,
505                         const char * target,
506                         const char * data)
507 {
508   VISITOR->pi(target, data);
509 }
510
511 #undef VISITOR
512
513 ///////////////////////////////////////////////////////////////////////////////
514
515 SVNReportParser::SVNReportParser(SVNRepository* repo) :
516   _d(new SVNReportParserPrivate(repo))
517 {
518   
519 }
520
521 SVNReportParser::~SVNReportParser()
522 {
523 }
524
525 SVNRepository::ResultCode
526 SVNReportParser::innerParseXML(const char* data, int size)
527 {
528     if (_d->status != SVNRepository::NO_ERROR) {
529         return _d->status;
530     }
531     
532     bool isEnd = (data == NULL);
533     if (!XML_Parse(_d->xmlParser, data, size, isEnd)) {
534       SG_LOG(SG_IO, SG_INFO, "SVN parse error:" << XML_ErrorString(XML_GetErrorCode(_d->xmlParser))
535              << " at line:" << XML_GetCurrentLineNumber(_d->xmlParser)
536              << " column " << XML_GetCurrentColumnNumber(_d->xmlParser));
537     
538       XML_ParserFree(_d->xmlParser);
539       _d->parserInited = false;
540       return SVNRepository::ERROR_XML;
541     } else if (isEnd) {
542         XML_ParserFree(_d->xmlParser);
543         _d->parserInited = false;
544     }
545     
546     return _d->status;
547 }
548
549 SVNRepository::ResultCode
550 SVNReportParser::parseXML(const char* data, int size)
551 {
552     if (_d->status != SVNRepository::NO_ERROR) {
553         return _d->status;
554     }
555     
556   if (!_d->parserInited) {
557     _d->xmlParser = XML_ParserCreateNS(0, ':');
558     XML_SetUserData(_d->xmlParser, _d.get());
559     XML_SetElementHandler(_d->xmlParser, start_element, end_element);
560     XML_SetCharacterDataHandler(_d->xmlParser, character_data);
561     XML_SetProcessingInstructionHandler(_d->xmlParser, processing_instruction);
562     _d->parserInited = true;
563   }
564   
565   return innerParseXML(data, size);
566 }
567
568 SVNRepository::ResultCode SVNReportParser::finishParse()
569 {
570     if (_d->status != SVNRepository::NO_ERROR) {
571         return _d->status;
572     }
573     
574     return innerParseXML(NULL, 0);
575 }
576
577 std::string SVNReportParser::etagFromRevision(unsigned int revision)
578 {
579   // etags look like W/"7//", hopefully this is stable
580   // across different servers and similar
581   std::ostringstream os;
582   os << "W/\"" << revision << "//";
583   return os.str();
584 }
585
586