ftp.c (2122B)
1 /*
2 * Copyright (c) 2019 Joris Vink <joris@coders.se>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
16
17 /*
18 * This example is the same as the HTTP one (see src/http.c) except
19 * we fetch an FTP URL.
20 */
21
22 #include <kore/kore.h>
23 #include <kore/http.h>
24 #include <kore/curl.h>
25
26 int ftp(struct http_request *);
27
28 static int state_setup(struct http_request *);
29 static int state_result(struct http_request *);
30
31 static struct http_state states[] = {
32 KORE_HTTP_STATE(state_setup),
33 KORE_HTTP_STATE(state_result)
34 };
35
36 int
37 ftp(struct http_request *req)
38 {
39 return (http_state_run(states, 2, req));
40 }
41
42 static int
43 state_setup(struct http_request *req)
44 {
45 struct kore_curl *client;
46
47 client = http_state_create(req, sizeof(*client));
48
49 if (!kore_curl_init(client,
50 "http://ftp.eu.openbsd.org/pub/OpenBSD/README", KORE_CURL_ASYNC)) {
51 http_response(req, 500, NULL, 0);
52 return (HTTP_STATE_COMPLETE);
53 }
54
55 kore_curl_bind_request(client, req);
56 kore_curl_run(client);
57
58 req->fsm_state = 1;
59 return (HTTP_STATE_RETRY);
60 }
61
62 static int
63 state_result(struct http_request *req)
64 {
65 size_t len;
66 const u_int8_t *body;
67 struct kore_curl *client;
68
69 client = http_state_get(req);
70
71 if (!kore_curl_success(client)) {
72 kore_curl_logerror(client);
73 http_response(req, 500, NULL, 0);
74 } else {
75 kore_curl_response_as_bytes(client, &body, &len);
76 http_response(req, HTTP_STATUS_OK, body, len);
77 }
78
79 kore_curl_cleanup(client);
80
81 return (HTTP_STATE_COMPLETE);
82 }