summaryrefslogtreecommitdiffstats
path: root/services/packages/arch/repository.go
blob: 763a0a2102263f774cacc49ab266904ad79eacf0 (plain)
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
// Copyright 2024 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package arch

import (
	"archive/tar"
	"compress/gzip"
	"context"
	"errors"
	"fmt"
	"io"
	"net/url"
	"os"
	"path/filepath"
	"sort"
	"strings"

	packages_model "code.gitea.io/gitea/models/packages"
	user_model "code.gitea.io/gitea/models/user"
	packages_module "code.gitea.io/gitea/modules/packages"
	arch_module "code.gitea.io/gitea/modules/packages/arch"
	"code.gitea.io/gitea/modules/setting"
	"code.gitea.io/gitea/modules/sync"
	"code.gitea.io/gitea/modules/util"
	packages_service "code.gitea.io/gitea/services/packages"

	"github.com/ProtonMail/go-crypto/openpgp"
	"github.com/ProtonMail/go-crypto/openpgp/armor"
	"github.com/ProtonMail/go-crypto/openpgp/packet"
)

var locker = sync.NewExclusivePool()

func GetOrCreateRepositoryVersion(ctx context.Context, ownerID int64) (*packages_model.PackageVersion, error) {
	return packages_service.GetOrCreateInternalPackageVersion(ctx, ownerID, packages_model.TypeArch, arch_module.RepositoryPackage, arch_module.RepositoryVersion)
}

func BuildAllRepositoryFiles(ctx context.Context, ownerID int64) error {
	pv, err := GetOrCreateRepositoryVersion(ctx, ownerID)
	if err != nil {
		return err
	}
	// remove old db files
	pfs, err := packages_model.GetFilesByVersionID(ctx, pv.ID)
	if err != nil {
		return err
	}
	for _, pf := range pfs {
		if strings.HasSuffix(pf.Name, ".db") {
			arch := strings.TrimSuffix(pf.Name, ".db")
			if err := BuildPacmanDB(ctx, ownerID, pf.CompositeKey, arch); err != nil {
				return err
			}
		}
	}
	return nil
}

func BuildCustomRepositoryFiles(ctx context.Context, ownerID int64, disco string) error {
	pv, err := GetOrCreateRepositoryVersion(ctx, ownerID)
	if err != nil {
		return err
	}
	// remove old db files
	pfs, err := packages_model.GetFilesByVersionID(ctx, pv.ID)
	if err != nil {
		return err
	}
	for _, pf := range pfs {
		if strings.HasSuffix(pf.Name, ".db") && pf.CompositeKey == disco {
			arch := strings.TrimSuffix(strings.TrimPrefix(pf.Name, fmt.Sprintf("%s-", pf.CompositeKey)), ".db")
			if err := BuildPacmanDB(ctx, ownerID, pf.CompositeKey, arch); err != nil {
				return err
			}
		}
	}
	return nil
}

func NewFileSign(ctx context.Context, ownerID int64, input io.Reader) (*packages_module.HashedBuffer, error) {
	// If no signature is specified, it will be generated by Gitea.
	priv, _, err := GetOrCreateKeyPair(ctx, ownerID)
	if err != nil {
		return nil, err
	}
	block, err := armor.Decode(strings.NewReader(priv))
	if err != nil {
		return nil, err
	}
	e, err := openpgp.ReadEntity(packet.NewReader(block.Body))
	if err != nil {
		return nil, err
	}
	pkgSig, err := packages_module.NewHashedBuffer()
	if err != nil {
		return nil, err
	}
	defer pkgSig.Close()
	if err := openpgp.DetachSign(pkgSig, e, input, nil); err != nil {
		return nil, err
	}
	return pkgSig, nil
}

// BuildPacmanDB Create db signature cache
func BuildPacmanDB(ctx context.Context, ownerID int64, group, arch string) error {
	key := fmt.Sprintf("pkg_%d_arch_db_%s", ownerID, group)
	locker.CheckIn(key)
	defer locker.CheckOut(key)
	pv, err := GetOrCreateRepositoryVersion(ctx, ownerID)
	if err != nil {
		return err
	}
	// remove old db files
	pfs, err := packages_model.GetFilesByVersionID(ctx, pv.ID)
	if err != nil {
		return err
	}
	for _, pf := range pfs {
		if pf.CompositeKey == group && pf.Name == fmt.Sprintf("%s.db", arch) {
			// remove group and arch
			if err := packages_service.DeletePackageFile(ctx, pf); err != nil {
				return err
			}
		}
	}

	db, err := createDB(ctx, ownerID, group, arch)
	if errors.Is(err, io.EOF) {
		return nil
	} else if err != nil {
		return err
	}
	defer db.Close()
	// Create db signature cache
	_, err = db.Seek(0, io.SeekStart)
	if err != nil {
		return err
	}
	sig, err := NewFileSign(ctx, ownerID, db)
	if err != nil {
		return err
	}
	defer sig.Close()
	_, err = db.Seek(0, io.SeekStart)
	if err != nil {
		return err
	}
	for name, data := range map[string]*packages_module.HashedBuffer{
		fmt.Sprintf("%s.db", arch):     db,
		fmt.Sprintf("%s.db.sig", arch): sig,
	} {
		_, err = packages_service.AddFileToPackageVersionInternal(ctx, pv, &packages_service.PackageFileCreationInfo{
			PackageFileInfo: packages_service.PackageFileInfo{
				Filename:     name,
				CompositeKey: group,
			},
			Creator:           user_model.NewGhostUser(),
			Data:              data,
			IsLead:            false,
			OverwriteExisting: true,
		})
		if err != nil {
			return err
		}
	}
	return nil
}

func createDB(ctx context.Context, ownerID int64, group, arch string) (*packages_module.HashedBuffer, error) {
	pkgs, err := packages_model.GetPackagesByType(ctx, ownerID, packages_model.TypeArch)
	if err != nil {
		return nil, err
	}
	if len(pkgs) == 0 {
		return nil, io.EOF
	}
	db, err := packages_module.NewHashedBuffer()
	if err != nil {
		return nil, err
	}
	defer db.Close()
	gw := gzip.NewWriter(db)
	defer gw.Close()
	tw := tar.NewWriter(gw)
	defer tw.Close()
	count := 0
	for _, pkg := range pkgs {
		versions, err := packages_model.GetVersionsByPackageName(
			ctx, ownerID, packages_model.TypeArch, pkg.Name,
		)
		if err != nil {
			return nil, err
		}
		sort.Slice(versions, func(i, j int) bool {
			return versions[i].CreatedUnix > versions[j].CreatedUnix
		})

		for _, ver := range versions {
			files, err := packages_model.GetFilesByVersionID(ctx, ver.ID)
			if err != nil {
				return nil, err
			}
			var pf *packages_model.PackageFile
			for _, file := range files {
				ext := filepath.Ext(file.Name)
				if file.CompositeKey == group && ext != "" && ext != ".db" && ext != ".sig" {
					if pf == nil && strings.HasSuffix(file.Name, fmt.Sprintf("any.pkg.tar%s", ext)) {
						pf = file
					}
					if strings.HasSuffix(file.Name, fmt.Sprintf("%s.pkg.tar%s", arch, ext)) {
						pf = file
						break
					}
				}
			}
			if pf == nil {
				// file not exists
				continue
			}
			pps, err := packages_model.GetPropertiesByName(
				ctx, packages_model.PropertyTypeFile, pf.ID, arch_module.PropertyDescription,
			)
			if err != nil {
				return nil, err
			}
			if len(pps) >= 1 {
				meta := []byte(pps[0].Value)
				header := &tar.Header{
					Name: pkg.Name + "-" + ver.Version + "/desc",
					Size: int64(len(meta)),
					Mode: int64(os.ModePerm),
				}
				if err = tw.WriteHeader(header); err != nil {
					return nil, err
				}
				if _, err := tw.Write(meta); err != nil {
					return nil, err
				}
				count++
				break
			}
		}
	}
	if count == 0 {
		return nil, io.EOF
	}
	return db, nil
}

// GetPackageFile Get data related to provided filename and distribution, for package files
// update download counter.
func GetPackageFile(ctx context.Context, group, file string, ownerID int64) (io.ReadSeekCloser, *url.URL, *packages_model.PackageFile, error) {
	fileSplit := strings.Split(file, "-")
	if len(fileSplit) <= 3 {
		return nil, nil, nil, errors.New("invalid file format, need <name>-<version>-<release>-<arch>.pkg.<archive>")
	}
	var (
		pkgName = strings.Join(fileSplit[0:len(fileSplit)-3], "-")
		pkgVer  = fileSplit[len(fileSplit)-3] + "-" + fileSplit[len(fileSplit)-2]
	)
	version, err := packages_model.GetVersionByNameAndVersion(ctx, ownerID, packages_model.TypeArch, pkgName, pkgVer)
	if err != nil {
		return nil, nil, nil, err
	}

	pkgFile, err := packages_model.GetFileForVersionByName(ctx, version.ID, file, group)
	if err != nil {
		return nil, nil, nil, err
	}

	return packages_service.GetPackageFileStream(ctx, pkgFile)
}

func GetPackageDBFile(ctx context.Context, ownerID int64, group, arch string, sigFile bool) (io.ReadSeekCloser, *url.URL, *packages_model.PackageFile, error) {
	pv, err := GetOrCreateRepositoryVersion(ctx, ownerID)
	if err != nil {
		return nil, nil, nil, err
	}
	fileName := fmt.Sprintf("%s.db", arch)
	if sigFile {
		fileName = fmt.Sprintf("%s.db.sig", arch)
	}
	file, err := packages_model.GetFileForVersionByName(ctx, pv.ID, fileName, group)
	// fail back to any db
	if errors.Is(err, util.ErrNotExist) && arch != "any" {
		fileName = "any.db"
		if sigFile {
			fileName = "any.db.sig"
		}
		file, err = packages_model.GetFileForVersionByName(ctx, pv.ID, fileName, group)
	}
	if err != nil {
		return nil, nil, nil, err
	}
	return packages_service.GetPackageFileStream(ctx, file)
}

// GetOrCreateKeyPair gets or creates the PGP keys used to sign repository metadata files
func GetOrCreateKeyPair(ctx context.Context, ownerID int64) (string, string, error) {
	priv, err := user_model.GetSetting(ctx, ownerID, arch_module.SettingKeyPrivate)
	if err != nil && !errors.Is(err, util.ErrNotExist) {
		return "", "", err
	}

	pub, err := user_model.GetSetting(ctx, ownerID, arch_module.SettingKeyPublic)
	if err != nil && !errors.Is(err, util.ErrNotExist) {
		return "", "", err
	}

	if priv == "" || pub == "" {
		user, err := user_model.GetUserByID(ctx, ownerID)
		if err != nil && !errors.Is(err, util.ErrNotExist) {
			return "", "", err
		}

		priv, pub, err = generateKeypair(user.Name)
		if err != nil {
			return "", "", err
		}

		if err := user_model.SetUserSetting(ctx, ownerID, arch_module.SettingKeyPrivate, priv); err != nil {
			return "", "", err
		}

		if err := user_model.SetUserSetting(ctx, ownerID, arch_module.SettingKeyPublic, pub); err != nil {
			return "", "", err
		}
	}

	return priv, pub, nil
}

func generateKeypair(owner string) (string, string, error) {
	e, err := openpgp.NewEntity(
		owner,
		"Arch Package signature only",
		fmt.Sprintf("%s@noreply.%s", owner, setting.Packages.RegistryHost), &packet.Config{
			RSABits: 4096,
		})
	if err != nil {
		return "", "", err
	}

	var priv strings.Builder
	var pub strings.Builder

	w, err := armor.Encode(&priv, openpgp.PrivateKeyType, nil)
	if err != nil {
		return "", "", err
	}
	if err := e.SerializePrivate(w, nil); err != nil {
		return "", "", err
	}
	w.Close()

	w, err = armor.Encode(&pub, openpgp.PublicKeyType, nil)
	if err != nil {
		return "", "", err
	}
	if err := e.Serialize(w); err != nil {
		return "", "", err
	}
	w.Close()

	return priv.String(), pub.String(), nil
}