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 |
|
29 |
if (sock < 0) { |
30 |
error("imapfilter: create socket; %s\n", strerror(errno)); |
31 |
return ERROR_NETWORK; |
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 |
sa.sin_family = AF_INET; |
39 |
sa.sin_port = htons(port); |
40 |
sa.sin_addr = *(struct in_addr *) he->h_addr; |
41 |
|
42 |
if (connect(sock, (struct sockaddr *) & sa, sizeof(struct sockaddr))) { |
43 |
error("imapfilter: initiating connection; %s\n", strerror(errno)); |
44 |
close_connection(); |
45 |
return ERROR_NETWORK; |
46 |
} |
47 |
strncpy(serv, he->h_name, SERVER_LEN - 1); |
48 |
|
49 |
info("Connected to %s.\n", serv); |
50 |
log_info(LOG_SERVER, serv); |
51 |
|
52 |
return 0; |
53 |
} |
54 |
|
55 |
|
56 |
/* |
57 |
* Disconnect from mail server. |
58 |
*/ |
59 |
int close_connection(void) |
60 |
{ |
61 |
if (close(sock)) { |
62 |
error("imapfilter: closing socket; %s\n", strerror(errno)); |
63 |
return ERROR_NETWORK; |
64 |
} else |
65 |
return 0; |
66 |
} |