generated from ipfs/ipfs-repository-template
-
Notifications
You must be signed in to change notification settings - Fork 75
/
handler_unixfs_dir.go
226 lines (198 loc) · 7.16 KB
/
handler_unixfs_dir.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
219
220
221
222
223
224
225
226
package gateway
import (
"context"
"fmt"
"io"
"net/http"
"net/url"
gopath "path"
"strings"
"time"
"github.com/dustin/go-humanize"
"github.com/ipfs/boxo/files"
"github.com/ipfs/boxo/gateway/assets"
"github.com/ipfs/boxo/path"
cid "github.com/ipfs/go-cid"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
)
// serveDirectory returns the best representation of UnixFS directory
//
// It will return index.html if present, or generate directory listing otherwise.
func (i *handler) serveDirectory(ctx context.Context, w http.ResponseWriter, r *http.Request, resolvedPath path.ImmutablePath, rq *requestData, isHeadRequest bool, directoryMetadata *directoryMetadata, ranges []ByteRange) bool {
ctx, span := spanTrace(ctx, "Handler.ServeDirectory", trace.WithAttributes(attribute.String("path", resolvedPath.String())))
defer span.End()
// WithHostname might have constructed an IPNS/IPFS path using the Host header.
// In this case, we need the original path for constructing redirects and links
// that match the requested URL.
// For example, http://example.net would become /ipns/example.net, and
// the redirects and links would end up as http://example.net/ipns/example.net
requestURI, err := url.ParseRequestURI(r.RequestURI)
if err != nil {
i.webError(w, r, fmt.Errorf("failed to parse request path: %w", err), http.StatusInternalServerError)
return false
}
originalURLPath := requestURI.Path
// Ensure directory paths end with '/'
if originalURLPath[len(originalURLPath)-1] != '/' {
// don't redirect to trailing slash if it's go get
// https://github.com/ipfs/kubo/pull/3963
goget := r.URL.Query().Get("go-get") == "1"
if !goget {
suffix := "/"
// preserve query parameters
if r.URL.RawQuery != "" {
suffix = suffix + "?" + r.URL.RawQuery
}
// /ipfs/cid/foo?bar must be redirected to /ipfs/cid/foo/?bar
redirectURL := originalURLPath + suffix
rq.logger.Debugw("directory location moved permanently", "status", http.StatusMovedPermanently)
http.Redirect(w, r, redirectURL, http.StatusMovedPermanently)
return true
}
}
// Check if directory has index.html, if so, serveFile
idxPath, err := path.Join(rq.contentPath, "index.html")
if err != nil {
i.webError(w, r, err, http.StatusInternalServerError)
return false
}
indexPath, err := path.Join(resolvedPath, "index.html")
if err != nil {
i.webError(w, r, err, http.StatusInternalServerError)
return false
}
imIndexPath, err := path.NewImmutablePath(indexPath)
if err != nil {
i.webError(w, r, err, http.StatusInternalServerError)
return false
}
// TODO: could/should this all be skipped to have HEAD requests just return html content type and save the complexity? If so can we skip the above code as well?
var idxFileBytes io.ReadCloser
var idxFileSize int64
var returnRangeStartsAtZero bool
if isHeadRequest {
var idxHeadResp *HeadResponse
_, idxHeadResp, err = i.backend.Head(ctx, imIndexPath)
if err == nil {
defer idxHeadResp.Close()
if !idxHeadResp.isFile {
i.webError(w, r, fmt.Errorf("%q could not be read: %w", imIndexPath, files.ErrNotReader), http.StatusUnprocessableEntity)
return false
}
returnRangeStartsAtZero = true
idxFileBytes = idxHeadResp.startingBytes
idxFileSize = idxHeadResp.bytesSize
}
} else {
var idxGetResp *GetResponse
_, idxGetResp, err = i.backend.Get(ctx, imIndexPath, ranges...)
if err == nil {
defer idxGetResp.Close()
if idxGetResp.bytes == nil {
i.webError(w, r, fmt.Errorf("%q could not be read: %w", imIndexPath, files.ErrNotReader), http.StatusUnprocessableEntity)
return false
}
if len(ranges) > 0 {
ra := ranges[0]
returnRangeStartsAtZero = ra.From == 0
}
idxFileBytes = idxGetResp.bytes
idxFileSize = idxGetResp.bytesSize
}
}
if err == nil {
rq.logger.Debugw("serving index.html file", "path", idxPath)
originalContentPath := rq.contentPath
rq.contentPath = idxPath
// write to request
success := i.serveFile(ctx, w, r, resolvedPath, rq, idxFileSize, idxFileBytes, false, returnRangeStartsAtZero, "text/html")
if success {
i.unixfsDirIndexGetMetric.WithLabelValues(originalContentPath.Namespace()).Observe(time.Since(rq.begin).Seconds())
}
return success
}
if isErrNotFound(err) {
rq.logger.Debugw("no index.html; noop", "path", idxPath)
} else if err != nil {
i.webError(w, r, err, http.StatusInternalServerError)
return false
}
// A HTML directory index will be presented, be sure to set the correct
// type instead of relying on autodetection (which may fail).
w.Header().Set("Content-Type", "text/html")
// Generated dir index requires custom Etag (output may change between go-libipfs versions)
dirEtag := getDirListingEtag(resolvedPath.RootCid())
w.Header().Set("Etag", dirEtag)
// Add TTL if known.
if rq.ttl > 0 {
w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%d", int(rq.ttl.Seconds())))
}
if r.Method == http.MethodHead {
rq.logger.Debug("return as request's HTTP method is HEAD")
return true
}
var dirListing []assets.DirectoryItem
for l := range directoryMetadata.entries {
if l.Err != nil {
i.webError(w, r, l.Err, http.StatusInternalServerError)
return false
}
name := l.Link.Name
sz := l.Link.Size
linkCid := l.Link.Cid
hash := linkCid.String()
di := assets.DirectoryItem{
Size: humanize.Bytes(sz),
Name: name,
Path: gopath.Join(originalURLPath, name),
Hash: hash,
ShortHash: assets.ShortHash(hash),
}
dirListing = append(dirListing, di)
}
// construct the correct back link
// https://github.com/ipfs/kubo/issues/1365
backLink := originalURLPath
// don't go further up than /ipfs/$hash/
pathSplit := strings.Split(rq.contentPath.String(), "/")
switch {
// skip backlink when listing a content root
case len(pathSplit) == 3: // url: /ipfs/$hash
backLink = ""
// skip backlink when listing a content root
case len(pathSplit) == 4 && pathSplit[3] == "": // url: /ipfs/$hash/
backLink = ""
// add the correct link depending on whether the path ends with a slash
default:
if strings.HasSuffix(backLink, "/") {
backLink += ".."
} else {
backLink += "/.."
}
}
size := humanize.Bytes(directoryMetadata.dagSize)
hash := resolvedPath.RootCid().String()
globalData := i.getTemplateGlobalData(r, rq.contentPath)
// See comment above where originalUrlPath is declared.
tplData := assets.DirectoryTemplateData{
GlobalData: globalData,
Listing: dirListing,
Size: size,
Path: rq.contentPath.String(),
Breadcrumbs: assets.Breadcrumbs(rq.contentPath.String(), globalData.DNSLink),
BackLink: backLink,
Hash: hash,
}
rq.logger.Debugw("request processed", "tplDataDNSLink", globalData.DNSLink, "tplDataSize", size, "tplDataBackLink", backLink, "tplDataHash", hash)
if err := assets.DirectoryTemplate.Execute(w, tplData); err != nil {
_, _ = w.Write([]byte(fmt.Sprintf("error during body generation: %v", err)))
return false
}
// Update metrics
i.unixfsGenDirListingGetMetric.WithLabelValues(rq.contentPath.Namespace()).Observe(time.Since(rq.begin).Seconds())
return true
}
func getDirListingEtag(dirCid cid.Cid) string {
return `"DirIndex-` + assets.AssetHash + `_CID-` + dirCid.String() + `"`
}