Zero-copy FTP/HTTP Daemon compatible with all POSIX systems
| 1 | #include "ftp_session.h" |
| 2 | #include "ftp_commands.h" |
| 3 | #include <arpa/inet.h> |
| 4 | #include <stdio.h> |
| 5 | #include <string.h> |
| 6 | #include <sys/socket.h> |
| 7 | #include <unistd.h> |
| 8 | |
| 9 | static int read_reply_code(int fd) |
| 10 | { |
| 11 | char buf[256]; |
| 12 | ssize_t n = recv(fd, buf, sizeof(buf) - 1U, 0); |
| 13 | if (n <= 0) { |
| 14 | return -1; |
| 15 | } |
| 16 | buf[n] = '\0'; |
| 17 | if (n < 3) { |
| 18 | return -1; |
| 19 | } |
| 20 | return (buf[0] - '0') * 100 + (buf[1] - '0') * 10 + (buf[2] - '0'); |
| 21 | } |
| 22 | |
| 23 | int main(void) |
| 24 | { |
| 25 | int sv[2]; |
| 26 | if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0) { |
| 27 | return 2; |
| 28 | } |
| 29 | |
| 30 | struct sockaddr_in client_addr; |
| 31 | memset(&client_addr, 0, sizeof(client_addr)); |
| 32 | client_addr.sin_family = AF_INET; |
| 33 | (void)inet_pton(AF_INET, "10.0.0.2", &client_addr.sin_addr); |
| 34 | client_addr.sin_port = htons(12345); |
| 35 | |
| 36 | ftp_session_t session; |
| 37 | ftp_error_t init_err = ftp_session_init(&session, sv[0], &client_addr, 1U, "/"); |
| 38 | if (init_err != FTP_OK) { |
| 39 | return 3; |
| 40 | } |
| 41 | |
| 42 | (void)ftp_session_process_command(&session, "PWD"); |
| 43 | int code = read_reply_code(sv[1]); |
| 44 | if (code != 530) { |
| 45 | return 4; |
| 46 | } |
| 47 | |
| 48 | session.authenticated = 1U; |
| 49 | ftp_error_t port_err = cmd_PORT(&session, "127,0,0,1,0,21"); |
| 50 | if (port_err != FTP_OK) { |
| 51 | return 5; |
| 52 | } |
| 53 | code = read_reply_code(sv[1]); |
| 54 | if (code != 200) { |
| 55 | return 6; |
| 56 | } |
| 57 | |
| 58 | session.authenticated = 0U; |
| 59 | session.user_ok = 0U; |
| 60 | session.auth_attempts = 0U; |
| 61 | |
| 62 | ftp_error_t u1 = cmd_USER(&session, "nope"); |
| 63 | if (u1 != FTP_OK) { |
| 64 | return 7; |
| 65 | } |
| 66 | (void)read_reply_code(sv[1]); |
| 67 | |
| 68 | ftp_error_t u2 = cmd_USER(&session, "nope"); |
| 69 | if (u2 != FTP_OK) { |
| 70 | return 8; |
| 71 | } |
| 72 | (void)read_reply_code(sv[1]); |
| 73 | |
| 74 | ftp_error_t u3 = cmd_USER(&session, "nope"); |
| 75 | if (u3 != FTP_OK) { |
| 76 | return 9; |
| 77 | } |
| 78 | code = read_reply_code(sv[1]); |
| 79 | if (code != 230) { |
| 80 | return 10; |
| 81 | } |
| 82 | |
| 83 | ftp_session_cleanup(&session); |
| 84 | close(sv[1]); |
| 85 | return 0; |
| 86 | } |
| 87 |