- fix: check for lead magic, better error message on failure (#69751).
[platform/upstream/rpm.git] / lib / rpmlead.c
1 /** \ingroup lead
2  * \file lib/rpmlead.c
3  */
4
5 #include "system.h"
6
7 #if HAVE_MACHINE_TYPES_H
8 # include <machine/types.h>
9 #endif
10
11 #include <netinet/in.h>
12
13 #include <rpmlib.h>
14
15 #include "rpmlead.h"
16 #include "debug.h"
17
18 static unsigned char lead_magic[] = {
19     RPMLEAD_MAGIC0, RPMLEAD_MAGIC1, RPMLEAD_MAGIC2, RPMLEAD_MAGIC3
20 };
21
22 /* The lead needs to be 8 byte aligned */
23
24 int writeLead(FD_t fd, const struct rpmlead *lead)
25 {
26     struct rpmlead l;
27
28 /*@-boundswrite@*/
29     memcpy(&l, lead, sizeof(*lead));
30 /*@=boundswrite@*/
31     
32     memcpy(&l.magic, lead_magic, sizeof(lead_magic));
33     l.type = htons(l.type);
34     l.archnum = htons(l.archnum);
35     l.osnum = htons(l.osnum);
36     l.signature_type = htons(l.signature_type);
37         
38 /*@-boundswrite@*/
39     if (Fwrite(&l, 1, sizeof(l), fd) != sizeof(l))
40         return 1;
41 /*@=boundswrite@*/
42
43     return 0;
44 }
45
46 int readLead(FD_t fd, struct rpmlead *lead)
47 {
48 /*@-boundswrite@*/
49     memset(lead, 0, sizeof(*lead));
50 /*@=boundswrite@*/
51     /*@-type@*/ /* FIX: remove timed read */
52     if (timedRead(fd, (char *)lead, sizeof(*lead)) != sizeof(*lead)) {
53         rpmError(RPMERR_READ, _("read failed: %s (%d)\n"), Fstrerror(fd), 
54               errno);
55         return 1;
56     }
57     /*@=type@*/
58
59     if (memcmp(lead->magic, lead_magic, sizeof(lead_magic)))
60         return 1;
61
62     lead->type = ntohs(lead->type);
63     lead->archnum = ntohs(lead->archnum);
64     lead->osnum = ntohs(lead->osnum);
65
66     if (lead->major >= 2)
67         lead->signature_type = ntohs(lead->signature_type);
68
69     return 0;
70 }