refactor _InitQuery()
[ntk/apt.git] / ftparchive / cachedb.cc
1 // -*- mode: cpp; mode: fold -*-
2 // Description /*{{{*/
3 // $Id: cachedb.cc,v 1.7 2004/05/08 19:41:01 mdz Exp $
4 /* ######################################################################
5
6 CacheDB
7
8 Simple uniform interface to a cache database.
9
10 ##################################################################### */
11 /*}}}*/
12 // Include Files /*{{{*/
13 #include <config.h>
14
15 #include <apt-pkg/error.h>
16 #include <apt-pkg/md5.h>
17 #include <apt-pkg/sha1.h>
18 #include <apt-pkg/sha2.h>
19 #include <apt-pkg/strutl.h>
20 #include <apt-pkg/configuration.h>
21 #include <apt-pkg/fileutl.h>
22 #include <apt-pkg/debfile.h>
23 #include <apt-pkg/gpgv.h>
24
25 #include <netinet/in.h> // htonl, etc
26 #include <ctype.h>
27 #include <stddef.h>
28 #include <sys/stat.h>
29
30 #include "cachedb.h"
31
32 #include <apti18n.h>
33 /*}}}*/
34
35 // CacheDB::ReadyDB - Ready the DB2 /*{{{*/
36 // ---------------------------------------------------------------------
37 /* This opens the DB2 file for caching package information */
38 bool CacheDB::ReadyDB(std::string const &DB)
39 {
40 int err;
41
42 ReadOnly = _config->FindB("APT::FTPArchive::ReadOnlyDB",false);
43
44 // Close the old DB
45 if (Dbp != 0)
46 Dbp->close(Dbp,0);
47
48 /* Check if the DB was disabled while running and deal with a
49 corrupted DB */
50 if (DBFailed() == true)
51 {
52 _error->Warning(_("DB was corrupted, file renamed to %s.old"),DBFile.c_str());
53 rename(DBFile.c_str(),(DBFile+".old").c_str());
54 }
55
56 DBLoaded = false;
57 Dbp = 0;
58 DBFile = std::string();
59
60 if (DB.empty())
61 return true;
62
63 db_create(&Dbp, NULL, 0);
64 if ((err = Dbp->open(Dbp, NULL, DB.c_str(), NULL, DB_BTREE,
65 (ReadOnly?DB_RDONLY:DB_CREATE),
66 0644)) != 0)
67 {
68 if (err == DB_OLD_VERSION)
69 {
70 _error->Warning(_("DB is old, attempting to upgrade %s"),DBFile.c_str());
71 err = Dbp->upgrade(Dbp, DB.c_str(), 0);
72 if (!err)
73 err = Dbp->open(Dbp, NULL, DB.c_str(), NULL, DB_HASH,
74 (ReadOnly?DB_RDONLY:DB_CREATE), 0644);
75
76 }
77 // the database format has changed from DB_HASH to DB_BTREE in
78 // apt 0.6.44
79 if (err == EINVAL)
80 {
81 _error->Error(_("DB format is invalid. If you upgraded from an older version of apt, please remove and re-create the database."));
82 }
83 if (err)
84 {
85 Dbp = 0;
86 return _error->Error(_("Unable to open DB file %s: %s"),DB.c_str(), db_strerror(err));
87 }
88 }
89
90 DBFile = DB;
91 DBLoaded = true;
92 return true;
93 }
94 /*}}}*/
95 // CacheDB::OpenFile - Open the file /*{{{*/
96 // ---------------------------------------------------------------------
97 /* */
98 bool CacheDB::OpenFile()
99 {
100 // its open already
101 if(Fd && Fd->Name() == this->FileName)
102 return true;
103
104 // a different file is open, close it first
105 if(Fd && Fd->Name() != this->FileName)
106 CloseFile();
107
108 // open a new file
109 Fd = new FileFd(FileName,FileFd::ReadOnly);
110 if (_error->PendingError() == true)
111 {
112 CloseFile();
113 return false;
114 }
115 return true;
116 }
117 /*}}}*/
118 // CacheDB::CloseFile - Close the file /*{{{*/
119 void CacheDB::CloseFile()
120 {
121 if(Fd != NULL)
122 {
123 delete Fd;
124 Fd = NULL;
125 }
126 }
127 /*}}}*/
128 // CacheDB::OpenDebFile - Open a debfile /*{{{*/
129 bool CacheDB::OpenDebFile()
130 {
131 // debfile is already open
132 if(DebFile && &DebFile->GetFile() == Fd)
133 return true;
134
135 // a different debfile is open, close it first
136 if(DebFile && &DebFile->GetFile() != Fd)
137 CloseDebFile();
138
139 // first open the fd, then pass it to the debDebFile
140 if(OpenFile() == false)
141 return false;
142 DebFile = new debDebFile(*Fd);
143 if (_error->PendingError() == true)
144 return false;
145 return true;
146 }
147 /*}}}*/
148 // CacheDB::CloseDebFile - Close a debfile again /*{{{*/
149 void CacheDB::CloseDebFile()
150 {
151 CloseFile();
152
153 if(DebFile != NULL)
154 {
155 delete DebFile;
156 DebFile = NULL;
157 }
158 }
159 /*}}}*/
160 // CacheDB::GetFileStat - Get stats from the file /*{{{*/
161 // ---------------------------------------------------------------------
162 /* This gets the size from the database if it's there. If we need
163 * to look at the file, also get the mtime from the file. */
164 bool CacheDB::GetFileStat(bool const &doStat)
165 {
166 if ((CurStat.Flags & FlSize) == FlSize && doStat == false)
167 return true;
168
169 /* Get it from the file. */
170 if (OpenFile() == false)
171 return false;
172
173 // Stat the file
174 struct stat St;
175 if (fstat(Fd->Fd(),&St) != 0)
176 {
177 CloseFile();
178 return _error->Errno("fstat",
179 _("Failed to stat %s"),FileName.c_str());
180 }
181 CurStat.FileSize = St.st_size;
182 CurStat.mtime = htonl(St.st_mtime);
183 CurStat.Flags |= FlSize;
184
185 return true;
186 }
187 /*}}}*/
188 // CacheDB::GetCurStat - Set the CurStat variable. /*{{{*/
189 // ---------------------------------------------------------------------
190 /* Sets the CurStat variable. Either to 0 if no database is used
191 * or to the value in the database if one is used */
192 bool CacheDB::GetCurStat()
193 {
194 memset(&CurStat,0,sizeof(CurStat));
195
196 if (DBLoaded)
197 {
198 /* First see if there is anything about it
199 in the database */
200
201 /* Get the flags (and mtime) */
202 InitQueryStats();
203 // Ensure alignment of the returned structure
204 Data.data = &CurStat;
205 Data.ulen = sizeof(CurStat);
206 Data.flags = DB_DBT_USERMEM;
207 if (Get() == false)
208 {
209 CurStat.Flags = 0;
210 }
211 CurStat.Flags = ntohl(CurStat.Flags);
212 CurStat.FileSize = ntohl(CurStat.FileSize);
213 }
214 return true;
215 }
216 /*}}}*/
217 // CacheDB::GetFileInfo - Get all the info about the file /*{{{*/
218 // ---------------------------------------------------------------------
219 bool CacheDB::GetFileInfo(std::string const &FileName, bool const &DoControl,
220 bool const &DoContents,
221 bool const &GenContentsOnly,
222 bool const &DoSource,
223 bool const &DoMD5, bool const &DoSHA1,
224 bool const &DoSHA256, bool const &DoSHA512,
225 bool const &checkMtime)
226 {
227 bool result = true;
228 this->FileName = FileName;
229
230 if (GetCurStat() == false)
231 return false;
232 OldStat = CurStat;
233
234 if (GetFileStat(checkMtime) == false)
235 return false;
236
237 /* if mtime changed, update CurStat from disk */
238 if (checkMtime == true && OldStat.mtime != CurStat.mtime)
239 CurStat.Flags = FlSize;
240
241 Stats.Bytes += CurStat.FileSize;
242 Stats.Packages++;
243
244 if ((DoControl && LoadControl() == false)
245 || (DoContents && LoadContents(GenContentsOnly) == false)
246 || (DoSource && LoadSource() == false)
247 || (DoMD5 && GetMD5(false) == false)
248 || (DoSHA1 && GetSHA1(false) == false)
249 || (DoSHA256 && GetSHA256(false) == false)
250 || (DoSHA512 && GetSHA512(false) == false) )
251 {
252 result = false;
253 }
254
255 return result;
256 }
257 /*}}}*/
258
259 bool CacheDB::LoadSource()
260 {
261 // Try to read the control information out of the DB.
262 if ((CurStat.Flags & FlSource) == FlSource)
263 {
264 // Lookup the control information
265 InitQuerySource();
266 if (Get() == true && Dsc.TakeDsc(Data.data, Data.size) == true)
267 {
268 return true;
269 }
270 CurStat.Flags &= ~FlSource;
271 }
272 if (OpenFile() == false)
273 return false;
274
275 Stats.Misses++;
276 if (Dsc.Read(FileName) == false)
277 return false;
278
279 if (Dsc.Data == 0)
280 return _error->Error(_("Failed to read .dsc"));
281
282 // Write back the control information
283 InitQuerySource();
284 if (Put(Dsc.Data, Dsc.Length) == true)
285 CurStat.Flags |= FlSource;
286
287 return true;
288 }
289
290 // CacheDB::LoadControl - Load Control information /*{{{*/
291 // ---------------------------------------------------------------------
292 /* */
293 bool CacheDB::LoadControl()
294 {
295 // Try to read the control information out of the DB.
296 if ((CurStat.Flags & FlControl) == FlControl)
297 {
298 // Lookup the control information
299 InitQueryControl();
300 if (Get() == true && Control.TakeControl(Data.data,Data.size) == true)
301 return true;
302 CurStat.Flags &= ~FlControl;
303 }
304
305 if(OpenDebFile() == false)
306 return false;
307
308 Stats.Misses++;
309 if (Control.Read(*DebFile) == false)
310 return false;
311
312 if (Control.Control == 0)
313 return _error->Error(_("Archive has no control record"));
314
315 // Write back the control information
316 InitQueryControl();
317 if (Put(Control.Control,Control.Length) == true)
318 CurStat.Flags |= FlControl;
319 return true;
320 }
321 /*}}}*/
322 // CacheDB::LoadContents - Load the File Listing /*{{{*/
323 // ---------------------------------------------------------------------
324 /* */
325 bool CacheDB::LoadContents(bool const &GenOnly)
326 {
327 // Try to read the control information out of the DB.
328 if ((CurStat.Flags & FlContents) == FlContents)
329 {
330 if (GenOnly == true)
331 return true;
332
333 // Lookup the contents information
334 InitQueryContent();
335 if (Get() == true)
336 {
337 if (Contents.TakeContents(Data.data,Data.size) == true)
338 return true;
339 }
340
341 CurStat.Flags &= ~FlContents;
342 }
343
344 if(OpenDebFile() == false)
345 return false;
346
347 Stats.Misses++;
348 if (Contents.Read(*DebFile) == false)
349 return false;
350
351 // Write back the control information
352 InitQueryContent();
353 if (Put(Contents.Data,Contents.CurSize) == true)
354 CurStat.Flags |= FlContents;
355 return true;
356 }
357 /*}}}*/
358
359 static std::string bytes2hex(uint8_t *bytes, size_t length) {
360 char buf[3];
361 std::string space;
362
363 space.reserve(length*2 + 1);
364 for (size_t i = 0; i < length; i++) {
365 snprintf(buf, sizeof(buf), "%02x", bytes[i]);
366 space.append(buf);
367 }
368 return space;
369 }
370
371 static inline unsigned char xdig2num(char const &dig) {
372 if (isdigit(dig)) return dig - '0';
373 if ('a' <= dig && dig <= 'f') return dig - 'a' + 10;
374 if ('A' <= dig && dig <= 'F') return dig - 'A' + 10;
375 return 0;
376 }
377
378 static void hex2bytes(uint8_t *bytes, const char *hex, int length) {
379 while (length-- > 0) {
380 *bytes = 0;
381 if (isxdigit(hex[0]) && isxdigit(hex[1])) {
382 *bytes = xdig2num(hex[0]) * 16 + xdig2num(hex[1]);
383 hex += 2;
384 }
385 bytes++;
386 }
387 }
388
389 // CacheDB::GetMD5 - Get the MD5 hash /*{{{*/
390 // ---------------------------------------------------------------------
391 /* */
392 bool CacheDB::GetMD5(bool const &GenOnly)
393 {
394 // Try to read the control information out of the DB.
395 if ((CurStat.Flags & FlMD5) == FlMD5)
396 {
397 if (GenOnly == true)
398 return true;
399
400 MD5Res = bytes2hex(CurStat.MD5, sizeof(CurStat.MD5));
401 return true;
402 }
403
404 Stats.MD5Bytes += CurStat.FileSize;
405
406 if (OpenFile() == false)
407 return false;
408
409 MD5Summation MD5;
410 if (Fd->Seek(0) == false || MD5.AddFD(*Fd, CurStat.FileSize) == false)
411 return false;
412
413 MD5Res = MD5.Result();
414 hex2bytes(CurStat.MD5, MD5Res.data(), sizeof(CurStat.MD5));
415 CurStat.Flags |= FlMD5;
416 return true;
417 }
418 /*}}}*/
419 // CacheDB::GetSHA1 - Get the SHA1 hash /*{{{*/
420 // ---------------------------------------------------------------------
421 /* */
422 bool CacheDB::GetSHA1(bool const &GenOnly)
423 {
424 // Try to read the control information out of the DB.
425 if ((CurStat.Flags & FlSHA1) == FlSHA1)
426 {
427 if (GenOnly == true)
428 return true;
429
430 SHA1Res = bytes2hex(CurStat.SHA1, sizeof(CurStat.SHA1));
431 return true;
432 }
433
434 Stats.SHA1Bytes += CurStat.FileSize;
435
436 if (OpenFile() == false)
437 return false;
438
439 SHA1Summation SHA1;
440 if (Fd->Seek(0) == false || SHA1.AddFD(*Fd, CurStat.FileSize) == false)
441 return false;
442
443 SHA1Res = SHA1.Result();
444 hex2bytes(CurStat.SHA1, SHA1Res.data(), sizeof(CurStat.SHA1));
445 CurStat.Flags |= FlSHA1;
446 return true;
447 }
448 /*}}}*/
449 // CacheDB::GetSHA256 - Get the SHA256 hash /*{{{*/
450 // ---------------------------------------------------------------------
451 /* */
452 bool CacheDB::GetSHA256(bool const &GenOnly)
453 {
454 // Try to read the control information out of the DB.
455 if ((CurStat.Flags & FlSHA256) == FlSHA256)
456 {
457 if (GenOnly == true)
458 return true;
459
460 SHA256Res = bytes2hex(CurStat.SHA256, sizeof(CurStat.SHA256));
461 return true;
462 }
463
464 Stats.SHA256Bytes += CurStat.FileSize;
465
466 if (OpenFile() == false)
467 return false;
468
469 SHA256Summation SHA256;
470 if (Fd->Seek(0) == false || SHA256.AddFD(*Fd, CurStat.FileSize) == false)
471 return false;
472
473 SHA256Res = SHA256.Result();
474 hex2bytes(CurStat.SHA256, SHA256Res.data(), sizeof(CurStat.SHA256));
475 CurStat.Flags |= FlSHA256;
476 return true;
477 }
478 /*}}}*/
479 // CacheDB::GetSHA256 - Get the SHA256 hash /*{{{*/
480 // ---------------------------------------------------------------------
481 /* */
482 bool CacheDB::GetSHA512(bool const &GenOnly)
483 {
484 // Try to read the control information out of the DB.
485 if ((CurStat.Flags & FlSHA512) == FlSHA512)
486 {
487 if (GenOnly == true)
488 return true;
489
490 SHA512Res = bytes2hex(CurStat.SHA512, sizeof(CurStat.SHA512));
491 return true;
492 }
493
494 Stats.SHA512Bytes += CurStat.FileSize;
495
496 if (OpenFile() == false)
497 return false;
498
499 SHA512Summation SHA512;
500 if (Fd->Seek(0) == false || SHA512.AddFD(*Fd, CurStat.FileSize) == false)
501 return false;
502
503 SHA512Res = SHA512.Result();
504 hex2bytes(CurStat.SHA512, SHA512Res.data(), sizeof(CurStat.SHA512));
505 CurStat.Flags |= FlSHA512;
506 return true;
507 }
508 /*}}}*/
509 // CacheDB::Finish - Write back the cache structure /*{{{*/
510 // ---------------------------------------------------------------------
511 /* */
512 bool CacheDB::Finish()
513 {
514 // Optimize away some writes.
515 if (CurStat.Flags == OldStat.Flags &&
516 CurStat.mtime == OldStat.mtime)
517 return true;
518
519 // Write the stat information
520 CurStat.Flags = htonl(CurStat.Flags);
521 CurStat.FileSize = htonl(CurStat.FileSize);
522 InitQueryStats();
523 Put(&CurStat,sizeof(CurStat));
524 CurStat.Flags = ntohl(CurStat.Flags);
525 CurStat.FileSize = ntohl(CurStat.FileSize);
526
527 return true;
528 }
529 /*}}}*/
530 // CacheDB::Clean - Clean the Database /*{{{*/
531 // ---------------------------------------------------------------------
532 /* Tidy the database by removing files that no longer exist at all. */
533 bool CacheDB::Clean()
534 {
535 if (DBLoaded == false)
536 return true;
537
538 /* I'm not sure what VERSION_MINOR should be here.. 2.4.14 certainly
539 needs the lower one and 2.7.7 needs the upper.. */
540 DBC *Cursor;
541 if ((errno = Dbp->cursor(Dbp, NULL, &Cursor, 0)) != 0)
542 return _error->Error(_("Unable to get a cursor"));
543
544 DBT Key;
545 DBT Data;
546 memset(&Key,0,sizeof(Key));
547 memset(&Data,0,sizeof(Data));
548 while ((errno = Cursor->c_get(Cursor,&Key,&Data,DB_NEXT)) == 0)
549 {
550 const char *Colon = (char*)memrchr(Key.data, ':', Key.size);
551 if (Colon)
552 {
553 if (stringcmp(Colon + 1, (char *)Key.data+Key.size,"st") == 0 ||
554 stringcmp(Colon + 1, (char *)Key.data+Key.size,"cl") == 0 ||
555 stringcmp(Colon + 1, (char *)Key.data+Key.size,"cs") == 0 ||
556 stringcmp(Colon + 1, (char *)Key.data+Key.size,"cn") == 0)
557 {
558 std::string FileName = std::string((const char *)Key.data,Colon);
559 if (FileExists(FileName) == true) {
560 continue;
561 }
562 }
563 }
564 Cursor->c_del(Cursor,0);
565 }
566 int res = Dbp->compact(Dbp, NULL, NULL, NULL, NULL, DB_FREE_SPACE, NULL);
567 if (res < 0)
568 _error->Warning("compact failed with result %i", res);
569
570 if(_config->FindB("Debug::APT::FTPArchive::Clean", false) == true)
571 Dbp->stat_print(Dbp, 0);
572
573
574 return true;
575 }
576 /*}}}*/