262140d79b2e3b2432539cb9d7a3dc9cac44f886
[oftp] / src / ftp.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <sys/socket.h>
5 #include <arpa/inet.h>
6 #include <netinet/in.h>
7 #include <netdb.h>
8 #include "darray.h"
9 #include "ftp.h"
10 #include "util.h"
11
12 #ifdef __unix__
13 #include <unistd.h>
14 #define closesocket(s) close(s)
15 #endif
16
17 struct ftp *ftp_alloc(void)
18 {
19         struct ftp *ftp;
20
21         if(!(ftp = malloc(sizeof *ftp))) {
22                 return 0;
23         }
24         ftp->ctl = ftp->data = -1;
25         return ftp;
26 }
27
28 void ftp_free(struct ftp *ftp)
29 {
30         if(!ftp) return;
31         if(ftp->ctl >= 0) {
32                 ftp_close(ftp);
33         }
34 }
35
36 int ftp_connect(struct ftp *ftp, const char *hostname, int port)
37 {
38         struct hostent *host;
39         struct sockaddr_in addr;
40
41         if((ftp->ctl = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
42                 errmsg("failed to create control socket\n");
43                 return -1;
44         }
45
46         if(!(host = gethostbyname(hostname))) {
47                 errmsg("failed to resolve host: %s\n", hostname);
48                 closesocket(ftp->ctl);
49                 ftp->ctl = -1;
50                 return -1;
51         }
52
53         memset(&addr, 0, sizeof addr);
54         addr.sin_family = AF_INET;
55         addr.sin_addr = *((struct in_addr*)host->h_addr);
56         addr.sin_port = htons(port);
57
58         if(connect(ftp->ctl, (struct sockaddr*)&addr, sizeof addr) == -1) {
59                 errmsg("failed to connect to: %s (port: %d)\n", hostname, port);
60                 closesocket(ftp->ctl);
61                 ftp->ctl = -1;
62                 return -1;
63         }
64         return 0;
65 }
66
67 void ftp_close(struct ftp *ftp)
68 {
69         if(ftp->ctl >= 0) {
70                 closesocket(ftp->ctl);
71         }
72         if(ftp->data >= 0) {
73                 closesocket(ftp->data);
74         }
75 }
76
77 int ftp_update(struct ftp *ftp)
78 {
79         return -1;
80 }
81
82 int ftp_chdir(struct ftp *ftp, const char *dirname)
83 {
84         return -1;
85 }