|
| 1 | +package corehttp |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "fmt" |
| 7 | + "html" |
| 8 | + "io" |
| 9 | + "net/http" |
| 10 | + "strings" |
| 11 | + "time" |
| 12 | + |
| 13 | + cid "github.com/ipfs/go-cid" |
| 14 | + ipldlegacy "github.com/ipfs/go-ipld-legacy" |
| 15 | + ipath "github.com/ipfs/interface-go-ipfs-core/path" |
| 16 | + "github.com/ipfs/kubo/assets" |
| 17 | + dih "github.com/ipfs/kubo/assets/dag-index-html" |
| 18 | + "github.com/ipfs/kubo/tracing" |
| 19 | + "github.com/ipld/go-ipld-prime" |
| 20 | + "github.com/ipld/go-ipld-prime/multicodec" |
| 21 | + mc "github.com/multiformats/go-multicodec" |
| 22 | + "go.opentelemetry.io/otel/attribute" |
| 23 | + "go.opentelemetry.io/otel/trace" |
| 24 | +) |
| 25 | + |
| 26 | +// codecToContentType maps the supported IPLD codecs to the HTTP Content |
| 27 | +// Type they should have. |
| 28 | +var codecToContentType = map[uint64]string{ |
| 29 | + uint64(mc.Json): "application/json", |
| 30 | + uint64(mc.Cbor): "application/cbor", |
| 31 | + uint64(mc.DagJson): "application/vnd.ipld.dag-json", |
| 32 | + uint64(mc.DagCbor): "application/vnd.ipld.dag-cbor", |
| 33 | +} |
| 34 | + |
| 35 | +// contentTypeToCodecs maps the HTTP Content Type to the respective |
| 36 | +// possible codecs. If the original data is in one of those codecs, |
| 37 | +// we stream the raw bytes. Otherwise, we encode in the last codec |
| 38 | +// of the list. |
| 39 | +var contentTypeToCodecs = map[string][]uint64{ |
| 40 | + "application/json": {uint64(mc.Json), uint64(mc.DagJson)}, |
| 41 | + "application/vnd.ipld.dag-json": {uint64(mc.DagJson)}, |
| 42 | + "application/cbor": {uint64(mc.Cbor), uint64(mc.DagCbor)}, |
| 43 | + "application/vnd.ipld.dag-cbor": {uint64(mc.DagCbor)}, |
| 44 | +} |
| 45 | + |
| 46 | +// contentTypeToExtension maps the HTTP Content Type to the respective file |
| 47 | +// extension, used in Content-Disposition header when downloading the file. |
| 48 | +var contentTypeToExtension = map[string]string{ |
| 49 | + "application/json": ".json", |
| 50 | + "application/vnd.ipld.dag-json": ".json", |
| 51 | + "application/cbor": ".cbor", |
| 52 | + "application/vnd.ipld.dag-cbor": ".cbor", |
| 53 | +} |
| 54 | + |
| 55 | +func (i *gatewayHandler) serveCodec(ctx context.Context, w http.ResponseWriter, r *http.Request, resolvedPath ipath.Resolved, contentPath ipath.Path, begin time.Time, requestedContentType string) { |
| 56 | + ctx, span := tracing.Span(ctx, "Gateway", "ServeCodec", trace.WithAttributes(attribute.String("path", resolvedPath.String()), attribute.String("requestedContentType", requestedContentType))) |
| 57 | + defer span.End() |
| 58 | + |
| 59 | + cidCodec := resolvedPath.Cid().Prefix().Codec |
| 60 | + responseContentType := requestedContentType |
| 61 | + |
| 62 | + // If the resolved path still has some remainder, return error for now. |
| 63 | + // TODO: handle this when we have IPLD Patch (https://ipld.io/specs/patch/) via HTTP PUT |
| 64 | + // TODO: (depends on https://github.com/ipfs/kubo/issues/4801 and https://github.com/ipfs/kubo/issues/4782) |
| 65 | + if resolvedPath.Remainder() != "" { |
| 66 | + path := strings.TrimSuffix(resolvedPath.String(), resolvedPath.Remainder()) |
| 67 | + err := fmt.Errorf("%q of %q could not be returned: reading IPLD Kinds other than Links (CBOR Tag 42) is not implemented: try reading %q instead", resolvedPath.Remainder(), resolvedPath.String(), path) |
| 68 | + webError(w, "unsupported pathing", err, http.StatusNotImplemented) |
| 69 | + return |
| 70 | + } |
| 71 | + |
| 72 | + // If no explicit content type was requested, the response will have one based on the codec from the CID |
| 73 | + if requestedContentType == "" { |
| 74 | + cidContentType, ok := codecToContentType[cidCodec] |
| 75 | + if !ok { |
| 76 | + // Should not happen unless function is called with wrong parameters. |
| 77 | + err := fmt.Errorf("content type not found for codec: %v", cidCodec) |
| 78 | + webError(w, "internal error", err, http.StatusInternalServerError) |
| 79 | + return |
| 80 | + } |
| 81 | + responseContentType = cidContentType |
| 82 | + } |
| 83 | + |
| 84 | + // Set HTTP headers (for caching etc) |
| 85 | + modtime := addCacheControlHeaders(w, r, contentPath, resolvedPath.Cid()) |
| 86 | + name := setCodecContentDisposition(w, r, resolvedPath, responseContentType) |
| 87 | + w.Header().Set("Content-Type", responseContentType) |
| 88 | + w.Header().Set("X-Content-Type-Options", "nosniff") |
| 89 | + |
| 90 | + // No content type is specified by the user (via Accept, or format=). However, |
| 91 | + // we support this format. Let's handle it. |
| 92 | + if requestedContentType == "" { |
| 93 | + isDAG := cidCodec == uint64(mc.DagJson) || cidCodec == uint64(mc.DagCbor) |
| 94 | + acceptsHTML := strings.Contains(r.Header.Get("Accept"), "text/html") |
| 95 | + download := r.URL.Query().Get("download") == "true" |
| 96 | + |
| 97 | + if isDAG && acceptsHTML && !download { |
| 98 | + i.serveCodecHTML(ctx, w, r, resolvedPath, contentPath) |
| 99 | + } else { |
| 100 | + i.serveCodecRaw(ctx, w, r, resolvedPath, contentPath, name, modtime) |
| 101 | + } |
| 102 | + |
| 103 | + return |
| 104 | + } |
| 105 | + |
| 106 | + // Otherwise, the user has requested a specific content type. Let's first get |
| 107 | + // the codecs that can be used with this content type. |
| 108 | + codecs, ok := contentTypeToCodecs[requestedContentType] |
| 109 | + if !ok { |
| 110 | + // This is never supposed to happen unless function is called with wrong parameters. |
| 111 | + err := fmt.Errorf("unsupported content type: %s", requestedContentType) |
| 112 | + webError(w, err.Error(), err, http.StatusInternalServerError) |
| 113 | + return |
| 114 | + } |
| 115 | + |
| 116 | + // If we need to convert, use the last codec (strict dag- variant) |
| 117 | + toCodec := codecs[len(codecs)-1] |
| 118 | + |
| 119 | + // If the requested content type has "dag-", ALWAYS go through the encoding |
| 120 | + // process in order to validate the content. |
| 121 | + if strings.Contains(requestedContentType, "dag-") { |
| 122 | + i.serveCodecConverted(ctx, w, r, resolvedPath, contentPath, toCodec, modtime) |
| 123 | + return |
| 124 | + } |
| 125 | + |
| 126 | + // Otherwise, check if the data is encoded with the requested content type. |
| 127 | + // If so, we can directly stream the raw data. serveRawBlock cannot be directly |
| 128 | + // used here as it sets different headers. |
| 129 | + for _, codec := range codecs { |
| 130 | + if resolvedPath.Cid().Prefix().Codec == codec { |
| 131 | + i.serveCodecRaw(ctx, w, r, resolvedPath, contentPath, name, modtime) |
| 132 | + return |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + // Finally, if nothing of the above is true, we have to actually convert the codec. |
| 137 | + i.serveCodecConverted(ctx, w, r, resolvedPath, contentPath, toCodec, modtime) |
| 138 | +} |
| 139 | + |
| 140 | +func (i *gatewayHandler) serveCodecHTML(ctx context.Context, w http.ResponseWriter, r *http.Request, resolvedPath ipath.Resolved, contentPath ipath.Path) { |
| 141 | + // A HTML directory index will be presented, be sure to set the correct |
| 142 | + // type instead of relying on autodetection (which may fail). |
| 143 | + w.Header().Set("Content-Type", "text/html") |
| 144 | + |
| 145 | + // Clear Content-Disposition -- we want HTML to be rendered inline |
| 146 | + w.Header().Del("Content-Disposition") |
| 147 | + |
| 148 | + // Generated index requires custom Etag (output may change between Kubo versions) |
| 149 | + dagEtag := getDagIndexEtag(resolvedPath.Cid()) |
| 150 | + w.Header().Set("Etag", dagEtag) |
| 151 | + |
| 152 | + // Remove Cache-Control for now to match UnixFS dir-index-html responses |
| 153 | + // (we don't want browser to cache HTML forever) |
| 154 | + // TODO: if we ever change behavior for UnixFS dir listings, same changes should be applied here |
| 155 | + w.Header().Del("Cache-Control") |
| 156 | + |
| 157 | + cidCodec := mc.Code(resolvedPath.Cid().Prefix().Codec) |
| 158 | + if err := dih.DagIndexTemplate.Execute(w, dih.DagIndexTemplateData{ |
| 159 | + Path: contentPath.String(), |
| 160 | + CID: resolvedPath.Cid().String(), |
| 161 | + CodecName: cidCodec.String(), |
| 162 | + CodecHex: fmt.Sprintf("0x%x", uint64(cidCodec)), |
| 163 | + }); err != nil { |
| 164 | + webError(w, "failed to generate HTML listing for this DAG: try fetching raw block with ?format=raw", err, http.StatusInternalServerError) |
| 165 | + } |
| 166 | +} |
| 167 | + |
| 168 | +func (i *gatewayHandler) serveCodecRaw(ctx context.Context, w http.ResponseWriter, r *http.Request, resolvedPath ipath.Resolved, contentPath ipath.Path, name string, modtime time.Time) { |
| 169 | + blockCid := resolvedPath.Cid() |
| 170 | + blockReader, err := i.api.Block().Get(ctx, resolvedPath) |
| 171 | + if err != nil { |
| 172 | + webError(w, "ipfs block get "+blockCid.String(), err, http.StatusInternalServerError) |
| 173 | + return |
| 174 | + } |
| 175 | + block, err := io.ReadAll(blockReader) |
| 176 | + if err != nil { |
| 177 | + webError(w, "ipfs block get "+blockCid.String(), err, http.StatusInternalServerError) |
| 178 | + return |
| 179 | + } |
| 180 | + content := bytes.NewReader(block) |
| 181 | + |
| 182 | + // ServeContent will take care of |
| 183 | + // If-None-Match+Etag, Content-Length and range requests |
| 184 | + _, _, _ = ServeContent(w, r, name, modtime, content) |
| 185 | +} |
| 186 | + |
| 187 | +func (i *gatewayHandler) serveCodecConverted(ctx context.Context, w http.ResponseWriter, r *http.Request, resolvedPath ipath.Resolved, contentPath ipath.Path, toCodec uint64, modtime time.Time) { |
| 188 | + obj, err := i.api.Dag().Get(ctx, resolvedPath.Cid()) |
| 189 | + if err != nil { |
| 190 | + webError(w, "ipfs dag get "+html.EscapeString(resolvedPath.String()), err, http.StatusInternalServerError) |
| 191 | + return |
| 192 | + } |
| 193 | + |
| 194 | + universal, ok := obj.(ipldlegacy.UniversalNode) |
| 195 | + if !ok { |
| 196 | + err = fmt.Errorf("%T is not a valid IPLD node", obj) |
| 197 | + webError(w, err.Error(), err, http.StatusInternalServerError) |
| 198 | + return |
| 199 | + } |
| 200 | + finalNode := universal.(ipld.Node) |
| 201 | + |
| 202 | + encoder, err := multicodec.LookupEncoder(toCodec) |
| 203 | + if err != nil { |
| 204 | + webError(w, err.Error(), err, http.StatusInternalServerError) |
| 205 | + return |
| 206 | + } |
| 207 | + |
| 208 | + // Ensure IPLD node conforms to the codec specification. |
| 209 | + var buf bytes.Buffer |
| 210 | + err = encoder(finalNode, &buf) |
| 211 | + if err != nil { |
| 212 | + webError(w, err.Error(), err, http.StatusInternalServerError) |
| 213 | + return |
| 214 | + } |
| 215 | + |
| 216 | + // Sets correct Last-Modified header. This code is borrowed from the standard |
| 217 | + // library (net/http/server.go) as we cannot use serveFile. |
| 218 | + if !(modtime.IsZero() || modtime.Equal(unixEpochTime)) { |
| 219 | + w.Header().Set("Last-Modified", modtime.UTC().Format(http.TimeFormat)) |
| 220 | + } |
| 221 | + |
| 222 | + _, _ = w.Write(buf.Bytes()) |
| 223 | +} |
| 224 | + |
| 225 | +func setCodecContentDisposition(w http.ResponseWriter, r *http.Request, resolvedPath ipath.Resolved, contentType string) string { |
| 226 | + var dispType, name string |
| 227 | + |
| 228 | + ext, ok := contentTypeToExtension[contentType] |
| 229 | + if !ok { |
| 230 | + // Should never happen. |
| 231 | + ext = ".bin" |
| 232 | + } |
| 233 | + |
| 234 | + if urlFilename := r.URL.Query().Get("filename"); urlFilename != "" { |
| 235 | + name = urlFilename |
| 236 | + } else { |
| 237 | + name = resolvedPath.Cid().String() + ext |
| 238 | + } |
| 239 | + |
| 240 | + // JSON should be inlined, but ?download=true should still override |
| 241 | + if r.URL.Query().Get("download") == "true" { |
| 242 | + dispType = "attachment" |
| 243 | + } else { |
| 244 | + switch ext { |
| 245 | + case ".json": // codecs that serialize to JSON can be rendered by browsers |
| 246 | + dispType = "inline" |
| 247 | + default: // everything else is assumed binary / opaque bytes |
| 248 | + dispType = "attachment" |
| 249 | + } |
| 250 | + } |
| 251 | + |
| 252 | + setContentDispositionHeader(w, name, dispType) |
| 253 | + return name |
| 254 | +} |
| 255 | + |
| 256 | +func getDagIndexEtag(dagCid cid.Cid) string { |
| 257 | + return `"DagIndex-` + assets.AssetHash + `_CID-` + dagCid.String() + `"` |
| 258 | +} |
0 commit comments