ucmd_curl.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. /* curl: ring-3 command. Fetch one http:// or https:// URL with the shared
  2. * uhttp client and dump the status line, headers and body to the terminal.
  3. *
  4. * The TLS and HTTP code lives in uhttp.c (shared with the browser); this file
  5. * only keeps the CLI and the verbose output hooks. */
  6. #include "ucmd_lib.h"
  7. #include "uhttp.h"
  8. #define LINE_MAX_C 320
  9. static void on_connected(void *ctx, int secure)
  10. {
  11. (void)ctx;
  12. if (secure) {
  13. u_puts("curl: connected, TLS handshake\n");
  14. } else {
  15. u_puts("curl: connected, sending request\n");
  16. }
  17. }
  18. static void on_status(void *ctx, int code, const char *line)
  19. {
  20. (void)ctx;
  21. (void)code;
  22. u_puts("curl: ");
  23. u_puts(line);
  24. u_putc('\n');
  25. }
  26. static void on_header(void *ctx, const char *line)
  27. {
  28. (void)ctx;
  29. u_puts(line);
  30. u_putc('\n');
  31. }
  32. static void on_redirect(void *ctx, const char *location)
  33. {
  34. (void)ctx;
  35. u_puts("curl: redirect -> ");
  36. u_puts(location);
  37. u_putc('\n');
  38. }
  39. static const struct uhttp_hooks hooks = {
  40. .connected = on_connected,
  41. .status = on_status,
  42. .header = on_header,
  43. .redirect = on_redirect,
  44. };
  45. void _start(const char *arg)
  46. {
  47. static struct uhttp h;
  48. unsigned char buf[512];
  49. unsigned int total = 0;
  50. int rv;
  51. if (!arg || !arg[0]) {
  52. u_puts("curl: usage curl <http|https://host[:port]/[path]>\n");
  53. u_exit(1);
  54. }
  55. uhttp_init(&h);
  56. h.user_agent = "nebos-curl/0.1";
  57. u_puts("curl: GET ");
  58. u_puts(arg);
  59. u_putc('\n');
  60. rv = uhttp_open(&h, arg, 0, &hooks);
  61. if (rv != 0) {
  62. u_puts("curl: ");
  63. u_puts(uhttp_error_string(rv));
  64. u_putc('\n');
  65. uhttp_close(&h);
  66. u_exit(1);
  67. }
  68. if (h.url.secure)
  69. u_puts("curl: WARNING: certificate NOT verified "
  70. "(trust-all mode)\n");
  71. u_putc('\n');
  72. for (;;) {
  73. rv = uhttp_read(&h, buf, sizeof(buf), UHTTP_IDLE_TIMEOUT_MS);
  74. if (rv > 0) {
  75. int i;
  76. for (i = 0; i < rv; i++)
  77. u_putc((char)buf[i]);
  78. total += (unsigned int)rv;
  79. continue;
  80. }
  81. if (rv < 0) {
  82. u_puts("\ncurl: ");
  83. u_puts(uhttp_error_string(rv));
  84. u_puts(" while reading body\n");
  85. }
  86. break;
  87. }
  88. u_putc('\n');
  89. u_puts("curl: ");
  90. u_putdec(total);
  91. u_puts(" bytes received, status ");
  92. u_putdec((unsigned int)h.resp.status);
  93. u_putc('\n');
  94. uhttp_close(&h);
  95. u_exit(0);
  96. }