]> git.draconx.ca Git - upkg.git/blob - libupkg.c
Reorganise the upkg structures a bit.
[upkg.git] / libupkg.c
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 #include "upkg.h"
5 #include "pack.h"
6
7
8 struct upkg_private {
9         FILE *f;
10
11
12         unsigned long name_offset, export_offset, import_offset;
13         unsigned char guid[16];
14 };
15
16 static struct upkg *init_upkg(unsigned char hdr[static UPKG_HDR_SIZE])
17 {
18         struct upkg *pkg;
19
20         pkg = malloc(sizeof *pkg);
21         if (!pkg) {
22                 return NULL;
23         }
24
25         pkg->priv = malloc(sizeof *pkg->priv);
26         if (!pkg->priv) {
27                 free(pkg);
28                 return NULL;
29         }
30
31         pkg->version      = unpack_16_le(hdr+4);
32         pkg->license      = unpack_16_le(hdr+6);
33         pkg->flags        = unpack_32_le(hdr+8);
34         pkg->name_count   = unpack_32_le(hdr+12);
35         pkg->export_count = unpack_32_le(hdr+20);
36         pkg->import_count = unpack_32_le(hdr+28);
37
38         pkg->priv->name_offset   = unpack_32_le(hdr+16);
39         pkg->priv->export_offset = unpack_32_le(hdr+24);
40         pkg->priv->import_offset = unpack_32_le(hdr+32);
41
42         return pkg;
43 }
44
45 struct upkg *upkg_fopen(const char *path)
46 {
47         unsigned char hdr_buf[UPKG_HDR_SIZE];
48         struct upkg *pkg;
49         FILE *f;
50         
51         if (!(f = fopen(path, "rb"))) {
52                 return NULL;
53         }
54         if (fread(hdr_buf, sizeof hdr_buf, 1, f) != 1) {
55                 goto err;
56         }
57         if (unpack_32_le(hdr_buf) != UPKG_HDR_MAGIC) {
58                 goto err;
59         }
60
61         /* Initialize package structure. */
62         pkg = init_upkg(hdr_buf);
63         if (!pkg) {
64                 goto err;
65         }
66         pkg->priv->f = f;
67
68         return pkg;
69 err:
70         fclose(f);
71         return NULL;
72 }
73
74 int upkg_close(struct upkg *pkg)
75 {
76         if (pkg->priv->f)
77                 return fclose(pkg->priv->f);
78         return 0;
79 }