summaryrefslogtreecommitdiff
path: root/smtp.c
blob: 14f1df6c5d8ddcded5dbe99c340e7f4d8f0f6ac3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
/**
 * \file smtp.c
 * Send a message via libESMTP.
 *
 * \author Adapted from the libESMTP's mail-file example by José Fonseca.
 */


#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <signal.h>
#include <errno.h>

#include <auth-client.h>
#include <libesmtp.h>

#include "smtp.h"
#include "main.h"
#include "xmalloc.h"


/**
 * \name Identity management
 */
/*@{*/

identity_t *default_identity = NULL;

static LIST_HEAD(identities);

identity_t *identity_new(void)
{
	identity_t *identity;

	identity = (identity_t *)xmalloc(sizeof(identity_t));

	memset(identity, 0, sizeof(identity_t));

	identity->starttls = Starttls_DISABLED;
		
	return identity;
}

void identity_free(identity_t *identity)
{
	if(identity->address)
		free(identity->address);

	if(identity->host)
		free(identity->host);

	if(identity->user)
		free(identity->user);

	if(identity->pass)
		free(identity->pass);

	if(identity->certificate_passphrase)
		free(identity->certificate_passphrase);

	free(identity);
}

void identity_add(identity_t *identity)
{
	list_add(&identity->list, &identities);
}

identity_t *identity_lookup(const char *address)
{
	if(address)
	{
		struct list_head *ptr;

		list_for_each(ptr, &identities)
		{
			identity_t *identity;
			
			identity = list_entry(ptr, identity_t, list);
			if(identity->address && !strcmp(identity->address, address))
				return identity;
		}
	}

	return default_identity;
}
	
void identities_init(void)
{
}

void identities_cleanup(void)
{
	default_identity = NULL;

	if(!list_empty(&identities))
	{
		struct list_head *ptr, *tmp;
	
		list_for_each_safe(ptr, tmp, &identities)
		{
			identity_t *identity;
			
			identity = list_entry(ptr, identity_t, list);
			list_del(ptr);
			
			identity_free(identity);
		}

	}
}
	
/*@}*/


/**
 * \name libESMTP interface
 */
/*@{*/

/**
 * Callback function to read the message from a file.  
 *
 * Since libESMTP does not provide callbacks which translate line endings, one
 * must be provided by the application.
 */
static const char * message_cb (void **buf, int *len, void *arg)
{
	message_t *message = (message_t *)arg;
	int octets;

	if (len == NULL)
	{
		/* only allow rewinding in the beginning of a message otherwise
		 * it will break the pipes */
		assert(*buf == NULL);
		return;
	}

	if (*buf == NULL)
		*buf = malloc (BUFSIZ);

	*len = message_read(message, *buf, BUFSIZ);
	
	return *buf;
}

#define SIZETICKER 1024		/**< print 1 dot per this many bytes */

static void event_cb (smtp_session_t session, int event_no, void *arg, ...)
{
	va_list ap;
	const char *mailbox;
	smtp_message_t message;
	smtp_recipient_t recipient;
	const smtp_status_t *status;

	va_start (ap, arg);
		
	switch (event_no) {
		case SMTP_EV_EXTNA_DSN:
			fprintf(stderr, "Delivery Status Notification extension not supported by MTA\n");
			break;
		case SMTP_EV_EXTNA_8BITMIME:
			fprintf(stderr, "8bit-MIME extension not supported by MTA\n");
			break;
		case SMTP_EV_EXTNA_STARTTLS:
			fprintf(stderr, "StartTLS extension not supported by MTA\n");
			break;
	}
	
	if (verbose)
	{
		static int sizeticking = 0, sizeticker;

		if (event_no != SMTP_EV_MESSAGEDATA && sizeticking)
		{
			fputs("\n", stdout);
			sizeticking = 0;
		}

		switch (event_no) {
			case SMTP_EV_CONNECT:
				fputs("Connected to MTA\n", stdout);
				break;
				
			case SMTP_EV_MAILSTATUS:
				mailbox = va_arg (ap, const char *);
				message = va_arg (ap, smtp_message_t);
				status = smtp_reverse_path_status (message);
				fprintf (stdout, "From %s: %d %s", mailbox, status->code, status->text);
				break;

			case SMTP_EV_RCPTSTATUS:
				mailbox = va_arg (ap, const char *);
				recipient = va_arg (ap, smtp_recipient_t);
				status = smtp_recipient_status (recipient);
				fprintf (stdout, "To %s: %d %s", mailbox, status->code, status->text);
				break;
				
			case SMTP_EV_MESSAGEDATA:
				message = va_arg (ap, smtp_message_t);
				if (!sizeticking)
				{
					fputs("Message data: ", stdout);
					sizeticking = 1;
					sizeticker = SIZETICKER - 1;
				}
				sizeticker += va_arg (ap, int);
				while (sizeticker >= SIZETICKER)
				{
					fputc('.', stdout);
					sizeticker -= SIZETICKER;
				}
				break;

			case SMTP_EV_MESSAGESENT:
				message = va_arg (ap, smtp_message_t);
				status = smtp_message_transfer_status (message);
				fprintf (stdout, "Message sent: %d %s", status->code, status->text);
				break;
				
			case SMTP_EV_DISCONNECT:
				fputs("Disconnected to MTA\n", stdout);
				break;
		}
	}
		
	va_end (ap);
}

static void monitor_cb (const char *buf, int buflen, int writing, void *arg)
{
	assert(log_fp);

	if (writing == SMTP_CB_HEADERS)
	{
		fputs ("H: ", log_fp);
		fwrite (buf, 1, buflen, log_fp);
		return;
	}
	
	fputs (writing ? "C: " : "S: ", log_fp);
	fwrite (buf, 1, buflen, log_fp);
	if (buf[buflen - 1] != '\n')
		putc ('\n', log_fp);
}

/**
 * Callback to request user/password info.  
 *
 * Not thread safe. 
 */
static int authinteract (auth_client_request_t request, char **result, int fields,
				  void *arg)
{
	identity_t *identity = (identity_t *)arg;
	int i;

	if(!identity)
		return 0;
	
	for (i = 0; i < fields; i++)
	{
		if (request[i].flags & AUTH_USER && identity->user)
			result[i] = identity->user;
		else if (request[i].flags & AUTH_PASS && identity->pass)
			result[i] = identity->pass;
		else
			return 0;
	}
	return 1;
}

static int tlsinteract (char *buf, int buflen, int rwflag, void *arg)
{
	identity_t *identity = (identity_t *)arg;
	char *pw;
	int len;

	if(!identity)
		return 0;
	
	if (identity->certificate_passphrase)
	{
		pw = identity->certificate_passphrase;
		len = strlen (pw);
		if (len + 1 > buflen)
			return 0;
		strcpy (buf, pw);
		return len;
	}
	else
		return 0;
}

/**
 * Callback to print the recipient status.
 */
void print_recipient_status (smtp_recipient_t recipient, const char *mailbox, 
							 void *arg)
{
	const smtp_status_t *status;

	status = smtp_recipient_status (recipient);
	fprintf (stderr, "%s: %d %s\n", mailbox, status->code, status->text);
}

void smtp_send(message_t *msg)
{
	smtp_session_t session;
	smtp_message_t message;
	smtp_recipient_t recipient;
	auth_context_t authctx;
	const smtp_status_t *status;
	struct sigaction sa;
	identity_t *identity;
	struct list_head *ptr;
	
	/* This program sends only one message at a time.  Create an SMTP
	 * session.
	 */
	auth_client_init ();
	if(!(session = smtp_create_session ()))
		goto failure;

	/* Add a protocol monitor. */
	if(log_fp)
		if(!smtp_set_monitorcb (session, monitor_cb, NULL, 1))
			goto failure;

	/* Lookup the identity */
	identity = identity_lookup(msg->reverse_path); 
	assert(identity);

	/* Set the event callback. */
	if(!smtp_set_eventcb (session, event_cb, NULL))
		goto failure;

	/* NB.  libESMTP sets timeouts as it progresses through the protocol.  In
	 * addition the remote server might close its socket on a timeout.
	 * Consequently libESMTP may sometimes try to write to a socket with no
	 * reader.  Ignore SIGPIPE, then the program doesn't get killed if/when
	 * this happens.
	 */
	sa.sa_handler = SIG_IGN; sigemptyset (&sa.sa_mask); sa.sa_flags = 0;
	sigaction (SIGPIPE, &sa, NULL);

	/* Set the host running the SMTP server.  LibESMTP has a default port
	 * number of 587, however this is not widely deployed so the port is
	 * specified as 25 along with the default MTA host.
	 */
	if(!smtp_set_server (session, identity->host ? identity->host : "localhost:25"))
		goto failure;

	/* Set the SMTP Starttls extension. */
	if(identity->starttls && !smtp_starttls_enable (session, identity->starttls))
		goto failure;

	/* Do what's needed at application level to use authentication. */
	authctx = auth_create_context ();
	auth_set_mechanism_flags (authctx, AUTH_PLUGIN_PLAIN, 0);
	auth_set_interact_cb (authctx, authinteract, identity);

	/* Use our callback for X.509 certificate passwords.  If STARTTLS is not in
	 * use or disabled in configure, the following is harmless.
	 */
	if(!smtp_starttls_set_password_cb (tlsinteract, identity))
		goto failure;

	/* Now tell libESMTP it can use the SMTP AUTH extension. */
	if(!smtp_auth_set_context (session, authctx))
		goto failure;

	/* At present it can't handle one recipient only out of many failing.  Make
	 * libESMTP require all specified recipients to succeed before transferring
	 * a message.
	 */
	if(!smtp_option_require_all_recipients (session, 1))
		goto failure;

	/* Add a message to the SMTP session. */
	if(!(message = smtp_add_message (session)))
		goto failure;

	/* Set the reverse path for the mail envelope.  (NULL is ok) */
	if(msg->reverse_path)
	{
		if(!smtp_set_reverse_path (message, msg->reverse_path))
			goto failure;
	}
	else
	{
		if(!smtp_set_reverse_path (message, identity->address))
			goto failure;
	}

	/* Open the message file and set the callback to read it. */
	if(!smtp_set_messagecb (message, message_cb, msg))
		goto failure;

	/* DSN options */
	if(!smtp_dsn_set_ret(message, msg->ret))
		goto failure;
	if(msg->envid)
		if(!smtp_dsn_set_envid(message, msg->envid))
			goto failure;
	
	/* 8bit-MIME */
	if(!smtp_8bitmime_set_body(message, msg->body))
		goto failure;

	/* Add remaining program arguments as message recipients. */
	list_for_each(ptr, &msg->remote_recipients)
	{
		recipient_t *entry = list_entry(ptr, recipient_t, list);
		
		assert(entry->address);

		if(!(recipient = smtp_add_recipient (message, entry->address)))
			goto failure;
		
		/* Recipient options set here */
		if (msg->notify != Notify_NOTSET)
			if(!smtp_dsn_set_notify (recipient, msg->notify))
				goto failure;
	}

	/* Initiate a connection to the SMTP server and transfer the message. */
	if (!smtp_start_session (session))
	{
		char buf[128];

		fprintf (stderr, "SMTP server problem %s\n",
				 smtp_strerror (smtp_errno (), buf, sizeof(buf)));

		exit(EX_UNAVAILABLE);
	}


	/* Report on the success or otherwise of the mail transfer. */
	if(!(status = smtp_message_transfer_status (message)))
		goto failure;
	if (status->code / 100 != 2)
	{
		/* Report on the failure of the mail transfer. */
		status = smtp_message_transfer_status (message);
		fprintf (stderr, "%d %s\n", status->code, status->text);
		smtp_enumerate_recipients (message, print_recipient_status, NULL);

		exit(EX_SOFTWARE);
	}

	if (log_fp)
		fputc('\n', log_fp);

	smtp_destroy_session (session);
	auth_destroy_context (authctx);
	auth_client_exit ();

	return;

failure:
	{
		char buf[128];

		fprintf (stderr, "%s\n",
				 smtp_strerror (smtp_errno (), buf, sizeof(buf)));

		exit(EX_SOFTWARE);
	}
}

/*@}*/