/
main.go
218 lines (195 loc) · 6.38 KB
/
main.go
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
// Copyright © 2022 Marcus Franke <marcus.franke@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package main
import (
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"github.com/julienschmidt/httprouter"
"github.com/russross/blackfriday/v2"
"github.com/spf13/viper"
)
var (
cmdOut []byte
mutex sync.Mutex
)
type yummyConfiguration struct {
port string
repoPath string
createrepoBinary string
rpmBinary string
helpFile string
}
// Main function for the repository webserver
func main() {
// parse config file
config := initConfig()
validateConfig(config)
repoPath := viper.GetString("yum.repoPath")
router := httprouter.New()
router.NotFound = http.FileServer(http.Dir(repoPath))
router.GET("/help", helpHandler)
router.POST("/api/upload", apiPostUploadHandler)
router.DELETE("/api/delete/:filename", apiDeleteHandler)
log.Fatal(http.ListenAndServe(":"+config.port, router))
}
func updateRepo() bool {
mutex.Lock()
workers := viper.GetString("yum.workers")
repoPath := viper.GetString("yum.repoPath")
createrepoBinary := viper.GetString("yum.createrepoBinary")
cmdOut, err := exec.Command(createrepoBinary, "--update", "--workers", workers, repoPath).CombinedOutput()
if err != nil {
log.Println(err, string(cmdOut))
mutex.Unlock()
return false
}
log.Println(string(cmdOut))
mutex.Unlock()
return true
}
func helpHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
// get helpFile path from configuration
helpFile := viper.GetString("yum.helpFile")
// ingest the configured helpFile
help, err := ioutil.ReadFile(helpFile)
if err != nil {
log.Println("Help file could not be read!")
http.Error(w, "Could not load the help file", http.StatusInternalServerError)
return
}
// render the Markdown file to HTML using the
// blackfriday library
output := blackfriday.Run(help)
log.Println("/help requested!")
fmt.Fprintf(w, string(output))
}
func checkAuthentication(r *http.Request) bool {
// check if authentication is enabled
if !viper.GetBool("yum.auth.enabled") {
return true
}
// check if header is set
authString := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
if len(authString) != 2 {
return false
}
// decode auth data
authBytes, err := base64.StdEncoding.DecodeString(authString[1])
if err != nil {
return false
}
// check user and password
if string(authBytes) == viper.GetString("yum.auth.user")+":"+viper.GetString("yum.auth.password") {
return true
} else {
return false
}
}
func apiDeleteHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fileName := ps.ByName("filename")
repoPath := viper.GetString("yum.repoPath")
if !checkAuthentication(r) {
http.Error(w, "not authorized", http.StatusUnauthorized)
return
}
if _, err := os.Stat(repoPath + "/" + fileName); err == nil {
// requested file exists
if err := os.Remove(repoPath + "/" + fileName); err != nil {
errText := fmt.Sprintf("%s - Could not delete file!\n", r.URL)
log.Printf(errText)
http.Error(w, errText, http.StatusInternalServerError)
return
} else {
// file deleted
logText := fmt.Sprintf("%s - File deleted!\n", r.URL.Path)
log.Printf(logText)
// update repository
if !updateRepo() {
http.Error(w, "Could not update repository", http.StatusInternalServerError)
}
}
} else {
// file does not exists
errText := fmt.Sprintf("%s - File not found!\n", r.URL.Path)
log.Println(errText)
http.Error(w, errText, http.StatusNotFound)
}
}
func apiPostUploadHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
errText := ""
repoPath := viper.GetString("yum.repoPath")
file, handler, err := r.FormFile("fileupload")
if err != nil {
errText = fmt.Sprintf("%s - incorrect FormFile used, must be fileupload!\n", r.URL)
log.Println(errText)
http.Error(w, errText, http.StatusBadRequest)
return
}
defer file.Close()
if filepath.Ext(handler.Filename) != ".rpm" {
errText = fmt.Sprintf("%s - %s uploaded, not an rpm package!\n", r.URL, handler.Filename)
log.Printf(errText)
http.Error(w, errText, http.StatusUnsupportedMediaType)
return
}
// check if the uploaded file already exists
// if the repository is configured in protected mode
// the request will return status 403 (forbidden)
if viper.GetBool("yum.protected") {
if _, err := os.Stat(repoPath + "/" + handler.Filename); err == nil {
errText = fmt.Sprintf("%s - File already exists, forbidden to overwrite!", r.URL)
log.Println(errText)
http.Error(w, errText, http.StatusForbidden)
return
}
}
// create file handler to write uploaded file to
f, err := os.OpenFile(repoPath+"/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
errText = fmt.Sprintf("%s - %s/%s could not be created!\n", r.URL, repoPath, handler.Filename)
log.Println(errText)
http.Error(w, errText, http.StatusInternalServerError)
log.Fatal(err)
}
defer f.Close()
// copy the file buffer into the file handle
_, err = io.Copy(f, file)
if err != nil {
errText = fmt.Sprintf("%s - an error occured copying the uploaded file to servers filesystem!\n",
r.URL)
log.Println(errText)
log.Println(err)
http.Error(w, errText, http.StatusInternalServerError)
return
}
// update repository
if !updateRepo() {
http.Error(w, "Could not update repository", http.StatusInternalServerError)
}
}