ipfsgateway.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. /*
  2. * IPFS and IPNS protocol support through IPFS Gateway.
  3. * Copyright (c) 2022 Mark Gaiser
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "libavutil/avstring.h"
  22. #include "libavutil/file_open.h"
  23. #include "libavutil/getenv_utf8.h"
  24. #include "libavutil/opt.h"
  25. #include <sys/stat.h>
  26. #include "os_support.h"
  27. #include "url.h"
  28. // Define the posix PATH_MAX if not there already.
  29. // This fixes a compile issue for MSVC.
  30. #ifndef PATH_MAX
  31. #define PATH_MAX 4096
  32. #endif
  33. typedef struct IPFSGatewayContext {
  34. AVClass *class;
  35. URLContext *inner;
  36. // Is filled by the -gateway argument and not changed after.
  37. char *gateway;
  38. // If the above gateway is non null, it will be copied into this buffer.
  39. // Else this buffer will contain the auto detected gateway.
  40. // In either case, the gateway to use will be in this buffer.
  41. char gateway_buffer[PATH_MAX];
  42. } IPFSGatewayContext;
  43. // A best-effort way to find the IPFS gateway.
  44. // Only the most appropiate gateway is set. It's not actually requested
  45. // (http call) to prevent a potential slowdown in startup. A potential timeout
  46. // is handled by the HTTP protocol.
  47. static int populate_ipfs_gateway(URLContext *h)
  48. {
  49. IPFSGatewayContext *c = h->priv_data;
  50. char ipfs_full_data_folder[PATH_MAX];
  51. char ipfs_gateway_file[PATH_MAX];
  52. struct stat st;
  53. int stat_ret = 0;
  54. int ret = AVERROR(EINVAL);
  55. FILE *gateway_file = NULL;
  56. char *env_ipfs_gateway, *env_ipfs_path;
  57. // Test $IPFS_GATEWAY.
  58. env_ipfs_gateway = getenv_utf8("IPFS_GATEWAY");
  59. if (env_ipfs_gateway != NULL) {
  60. int printed = snprintf(c->gateway_buffer, sizeof(c->gateway_buffer),
  61. "%s", env_ipfs_gateway);
  62. freeenv_utf8(env_ipfs_gateway);
  63. if (printed >= sizeof(c->gateway_buffer)) {
  64. av_log(h, AV_LOG_WARNING,
  65. "The IPFS_GATEWAY environment variable "
  66. "exceeds the maximum length. "
  67. "We allow a max of %zu characters\n",
  68. sizeof(c->gateway_buffer));
  69. ret = AVERROR(EINVAL);
  70. goto err;
  71. }
  72. ret = 1;
  73. goto err;
  74. } else
  75. av_log(h, AV_LOG_DEBUG, "$IPFS_GATEWAY is empty.\n");
  76. // We need to know the IPFS folder to - eventually - read the contents of
  77. // the "gateway" file which would tell us the gateway to use.
  78. env_ipfs_path = getenv_utf8("IPFS_PATH");
  79. if (env_ipfs_path == NULL) {
  80. int printed;
  81. char *env_home = getenv_utf8("HOME");
  82. av_log(h, AV_LOG_DEBUG, "$IPFS_PATH is empty.\n");
  83. // Try via the home folder.
  84. if (env_home == NULL) {
  85. av_log(h, AV_LOG_WARNING, "$HOME appears to be empty.\n");
  86. ret = AVERROR(EINVAL);
  87. goto err;
  88. }
  89. // Verify the composed path fits.
  90. printed = snprintf(
  91. ipfs_full_data_folder, sizeof(ipfs_full_data_folder),
  92. "%s/.ipfs/", env_home);
  93. freeenv_utf8(env_home);
  94. if (printed >= sizeof(ipfs_full_data_folder)) {
  95. av_log(h, AV_LOG_WARNING,
  96. "The IPFS data path exceeds the "
  97. "max path length (%zu)\n",
  98. sizeof(ipfs_full_data_folder));
  99. ret = AVERROR(EINVAL);
  100. goto err;
  101. }
  102. // Stat the folder.
  103. // It should exist in a default IPFS setup when run as local user.
  104. stat_ret = stat(ipfs_full_data_folder, &st);
  105. if (stat_ret < 0) {
  106. av_log(h, AV_LOG_INFO,
  107. "Unable to find IPFS folder. We tried:\n"
  108. "- $IPFS_PATH, which was empty.\n"
  109. "- $HOME/.ipfs (full uri: %s) which doesn't exist.\n",
  110. ipfs_full_data_folder);
  111. ret = AVERROR(ENOENT);
  112. goto err;
  113. }
  114. } else {
  115. int printed = snprintf(
  116. ipfs_full_data_folder, sizeof(ipfs_full_data_folder),
  117. "%s", env_ipfs_path);
  118. freeenv_utf8(env_ipfs_path);
  119. if (printed >= sizeof(ipfs_full_data_folder)) {
  120. av_log(h, AV_LOG_WARNING,
  121. "The IPFS_PATH environment variable "
  122. "exceeds the maximum length. "
  123. "We allow a max of %zu characters\n",
  124. sizeof(c->gateway_buffer));
  125. ret = AVERROR(EINVAL);
  126. goto err;
  127. }
  128. }
  129. // Copy the fully composed gateway path into ipfs_gateway_file.
  130. if (snprintf(ipfs_gateway_file, sizeof(ipfs_gateway_file), "%sgateway",
  131. ipfs_full_data_folder)
  132. >= sizeof(ipfs_gateway_file)) {
  133. av_log(h, AV_LOG_WARNING,
  134. "The IPFS gateway file path exceeds "
  135. "the max path length (%zu)\n",
  136. sizeof(ipfs_gateway_file));
  137. ret = AVERROR(ENOENT);
  138. goto err;
  139. }
  140. // Get the contents of the gateway file.
  141. gateway_file = avpriv_fopen_utf8(ipfs_gateway_file, "r");
  142. if (!gateway_file) {
  143. av_log(h, AV_LOG_WARNING,
  144. "The IPFS gateway file (full uri: %s) doesn't exist. "
  145. "Is the gateway enabled?\n",
  146. ipfs_gateway_file);
  147. ret = AVERROR(ENOENT);
  148. goto err;
  149. }
  150. // Read a single line (fgets stops at new line mark).
  151. if (!fgets(c->gateway_buffer, sizeof(c->gateway_buffer) - 1, gateway_file)) {
  152. av_log(h, AV_LOG_WARNING, "Unable to read from file (full uri: %s).\n",
  153. ipfs_gateway_file);
  154. ret = AVERROR(ENOENT);
  155. goto err;
  156. }
  157. // Replace first occurence of end of line with \0
  158. c->gateway_buffer[strcspn(c->gateway_buffer, "\r\n")] = 0;
  159. // If strlen finds anything longer then 0 characters then we have a
  160. // potential gateway url.
  161. if (*c->gateway_buffer == '\0') {
  162. av_log(h, AV_LOG_WARNING,
  163. "The IPFS gateway file (full uri: %s) appears to be empty. "
  164. "Is the gateway started?\n",
  165. ipfs_gateway_file);
  166. ret = AVERROR(EILSEQ);
  167. goto err;
  168. } else {
  169. // We're done, the c->gateway_buffer has something that looks valid.
  170. ret = 1;
  171. goto err;
  172. }
  173. err:
  174. if (gateway_file)
  175. fclose(gateway_file);
  176. return ret;
  177. }
  178. static int translate_ipfs_to_http(URLContext *h, const char *uri, int flags, AVDictionary **options)
  179. {
  180. const char *ipfs_cid;
  181. char *fulluri = NULL;
  182. int ret;
  183. IPFSGatewayContext *c = h->priv_data;
  184. // Test for ipfs://, ipfs:, ipns:// and ipns:. This prefix is stripped from
  185. // the string leaving just the CID in ipfs_cid.
  186. int is_ipfs = av_stristart(uri, "ipfs://", &ipfs_cid);
  187. int is_ipns = av_stristart(uri, "ipns://", &ipfs_cid);
  188. // We must have either ipns or ipfs.
  189. if (!is_ipfs && !is_ipns) {
  190. ret = AVERROR(EINVAL);
  191. av_log(h, AV_LOG_WARNING, "Unsupported url %s\n", uri);
  192. goto err;
  193. }
  194. // If the CID has a length greater then 0 then we assume we have a proper working one.
  195. // It could still be wrong but in that case the gateway should save us and
  196. // ruturn a 403 error. The http protocol handles this.
  197. if (strlen(ipfs_cid) < 1) {
  198. av_log(h, AV_LOG_WARNING, "A CID must be provided.\n");
  199. ret = AVERROR(EILSEQ);
  200. goto err;
  201. }
  202. // Populate c->gateway_buffer with whatever is in c->gateway
  203. if (c->gateway != NULL) {
  204. if (snprintf(c->gateway_buffer, sizeof(c->gateway_buffer), "%s",
  205. c->gateway)
  206. >= sizeof(c->gateway_buffer)) {
  207. av_log(h, AV_LOG_WARNING,
  208. "The -gateway parameter is too long. "
  209. "We allow a max of %zu characters\n",
  210. sizeof(c->gateway_buffer));
  211. ret = AVERROR(EINVAL);
  212. goto err;
  213. }
  214. } else {
  215. // Populate the IPFS gateway if we have any.
  216. // If not, inform the user how to properly set one.
  217. ret = populate_ipfs_gateway(h);
  218. if (ret < 1) {
  219. av_log(h, AV_LOG_ERROR,
  220. "IPFS does not appear to be running.\n\n"
  221. "Installing IPFS locally is recommended to "
  222. "improve performance and reliability, "
  223. "and not share all your activity with a single IPFS gateway.\n"
  224. "There are multiple options to define this gateway.\n"
  225. "1. Call ffmpeg with a gateway param, "
  226. "without a trailing slash: -gateway <url>.\n"
  227. "2. Define an $IPFS_GATEWAY environment variable with the "
  228. "full HTTP URL to the gateway "
  229. "without trailing forward slash.\n"
  230. "3. Define an $IPFS_PATH environment variable "
  231. "and point it to the IPFS data path "
  232. "- this is typically ~/.ipfs\n");
  233. ret = AVERROR(EINVAL);
  234. goto err;
  235. }
  236. }
  237. // Test if the gateway starts with either http:// or https://
  238. if (av_stristart(c->gateway_buffer, "http://", NULL) == 0
  239. && av_stristart(c->gateway_buffer, "https://", NULL) == 0) {
  240. av_log(h, AV_LOG_WARNING,
  241. "The gateway URL didn't start with http:// or "
  242. "https:// and is therefore invalid.\n");
  243. ret = AVERROR(EILSEQ);
  244. goto err;
  245. }
  246. // Concatenate the url.
  247. // This ends up with something like: http://localhost:8080/ipfs/Qm.....
  248. // The format of "%s%s%s%s" is the following:
  249. // 1st %s = The gateway.
  250. // 2nd %s = If the gateway didn't end in a slash, add a "/". Otherwise it's an empty string
  251. // 3rd %s = Either ipns/ or ipfs/.
  252. // 4th %s = The IPFS CID (Qm..., bafy..., ...).
  253. fulluri = av_asprintf("%s%s%s%s",
  254. c->gateway_buffer,
  255. (c->gateway_buffer[strlen(c->gateway_buffer) - 1] == '/') ? "" : "/",
  256. (is_ipns) ? "ipns/" : "ipfs/",
  257. ipfs_cid);
  258. if (!fulluri) {
  259. av_log(h, AV_LOG_ERROR, "Failed to compose the URL\n");
  260. ret = AVERROR(ENOMEM);
  261. goto err;
  262. }
  263. // Pass the URL back to FFMpeg's protocol handler.
  264. ret = ffurl_open_whitelist(&c->inner, fulluri, flags,
  265. &h->interrupt_callback, options,
  266. h->protocol_whitelist,
  267. h->protocol_blacklist, h);
  268. if (ret < 0) {
  269. av_log(h, AV_LOG_WARNING, "Unable to open resource: %s\n", fulluri);
  270. goto err;
  271. }
  272. err:
  273. av_free(fulluri);
  274. return ret;
  275. }
  276. static int ipfs_read(URLContext *h, unsigned char *buf, int size)
  277. {
  278. IPFSGatewayContext *c = h->priv_data;
  279. return ffurl_read(c->inner, buf, size);
  280. }
  281. static int64_t ipfs_seek(URLContext *h, int64_t pos, int whence)
  282. {
  283. IPFSGatewayContext *c = h->priv_data;
  284. return ffurl_seek(c->inner, pos, whence);
  285. }
  286. static int ipfs_close(URLContext *h)
  287. {
  288. IPFSGatewayContext *c = h->priv_data;
  289. return ffurl_closep(&c->inner);
  290. }
  291. #define OFFSET(x) offsetof(IPFSGatewayContext, x)
  292. static const AVOption options[] = {
  293. {"gateway", "The gateway to ask for IPFS data.", OFFSET(gateway), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, AV_OPT_FLAG_DECODING_PARAM},
  294. {NULL},
  295. };
  296. static const AVClass ipfs_gateway_context_class = {
  297. .class_name = "IPFS Gateway",
  298. .item_name = av_default_item_name,
  299. .option = options,
  300. .version = LIBAVUTIL_VERSION_INT,
  301. };
  302. const URLProtocol ff_ipfs_gateway_protocol = {
  303. .name = "ipfs",
  304. .url_open2 = translate_ipfs_to_http,
  305. .url_read = ipfs_read,
  306. .url_seek = ipfs_seek,
  307. .url_close = ipfs_close,
  308. .priv_data_size = sizeof(IPFSGatewayContext),
  309. .priv_data_class = &ipfs_gateway_context_class,
  310. };
  311. const URLProtocol ff_ipns_gateway_protocol = {
  312. .name = "ipns",
  313. .url_open2 = translate_ipfs_to_http,
  314. .url_read = ipfs_read,
  315. .url_seek = ipfs_seek,
  316. .url_close = ipfs_close,
  317. .priv_data_size = sizeof(IPFSGatewayContext),
  318. .priv_data_class = &ipfs_gateway_context_class,
  319. };