1 |
#include <string.h> |
2 |
#include <errno.h> |
3 |
#include <unistd.h> |
4 |
#include <sys/types.h> |
5 |
#include <sys/socket.h> |
6 |
#include <netinet/in.h> |
7 |
#include <netdb.h> |
8 |
|
9 |
|
10 |
#include "config.h" |
11 |
#include "imapfilter.h" |
12 |
|
13 |
|
14 |
int sock; |
15 |
|
16 |
|
17 |
/* |
18 |
* Connect to mail server. |
19 |
*/ |
20 |
int init_connection(char *serv, unsigned int port) |
21 |
{ |
22 |
struct sockaddr_in sa; |
23 |
struct hostent *he; |
24 |
|
25 |
memset((char *) &sa, 0, sizeof(struct sockaddr_in)); |
26 |
|
27 |
sock = socket(PF_INET, SOCK_STREAM, 0); |
28 |
if (sock < 0) { |
29 |
error("imapfilter: create socket; %s\n", strerror(errno)); |
30 |
return ERROR_NETWORK; |
31 |
} |
32 |
|
33 |
if (!(he = gethostbyname(serv))) { |
34 |
error("imapfilter: get network host entry; %s\n", strerror(errno)); |
35 |
close_connection(); |
36 |
return ERROR_NETWORK; |
37 |
} |
38 |
|
39 |
sa.sin_family = AF_INET; |
40 |
sa.sin_port = htons(port); |
41 |
sa.sin_addr = *(struct in_addr *) he->h_addr; |
42 |
|
43 |
if (connect(sock, (struct sockaddr *) &sa, sizeof(struct sockaddr))) { |
44 |
error("imapfilter: initiating connection; %s\n", strerror(errno)); |
45 |
close_connection(); |
46 |
return ERROR_NETWORK; |
47 |
} |
48 |
|
49 |
strncpy(serv, he->h_name, SERVER_LEN - 1); |
50 |
|
51 |
info("Connected to %s.\n", serv); |
52 |
log_info(1, serv); |
53 |
|
54 |
return 0; |
55 |
} |
56 |
|
57 |
|
58 |
/* |
59 |
* Disconnect from mail server. |
60 |
*/ |
61 |
int close_connection(void) |
62 |
{ |
63 |
if (close(sock)) { |
64 |
error("imapfilter: closing socket; %s\n", strerror(errno)); |
65 |
return ERROR_NETWORK; |
66 |
} else |
67 |
return 0; |
68 |
} |