1/*
2 * lws-api-test-smtp_client
3 *
4 * Written in 2010-2019 by Andy Green <andy@warmcat.com>
5 *
6 * This file is made available under the Creative Commons CC0 1.0
7 * Universal Public Domain Dedication.
8 */
9
10#include <libwebsockets.h>
11
12#include <signal.h>
13
14static int interrupted, result = 1;
15static const char *recip;
16
17static void
18sigint_handler(int sig)
19{
20	interrupted = 1;
21}
22
23static int
24done_cb(struct lws_smtp_email *email, void *buf, size_t len)
25{
26	/* you could examine email->data here */
27	if (buf) {
28		char dotstar[96];
29		lws_strnncpy(dotstar, (const char *)buf, len, sizeof(dotstar));
30		lwsl_notice("%s: %s\n", __func__, dotstar);
31	} else
32		lwsl_notice("%s:\n", __func__);
33
34	/* destroy any allocations in email */
35
36	free((char *)email->payload);
37
38	result = 0;
39	interrupted = 1;
40
41	return 0;
42}
43
44int main(int argc, const char **argv)
45{
46	int n = 1, logs = LLL_USER | LLL_ERR | LLL_WARN | LLL_NOTICE;
47	struct lws_context_creation_info info;
48	lws_smtp_sequencer_args_t ss_args;
49	struct lws_context *context;
50	lws_smtp_sequencer_t *sseq;
51	lws_smtp_email_t *email;
52	struct lws_vhost *vh;
53	char payload[2048];
54	const char *p;
55
56	/* the normal lws init */
57
58	signal(SIGINT, sigint_handler);
59
60	if ((p = lws_cmdline_option(argc, argv, "-d")))
61		logs = atoi(p);
62
63	p = lws_cmdline_option(argc, argv, "-r");
64	if (!p) {
65		lwsl_err("-r <recipient email> is required\n");
66		return 1;
67	}
68	recip = p;
69
70	lws_set_log_level(logs, NULL);
71	lwsl_user("LWS API selftest: SMTP client\n");
72
73	memset(&info, 0, sizeof info); /* otherwise uninitialized garbage */
74	info.port = CONTEXT_PORT_NO_LISTEN;
75	info.options = LWS_SERVER_OPTION_EXPLICIT_VHOSTS;
76
77	context = lws_create_context(&info);
78	if (!context) {
79		lwsl_err("lws init failed\n");
80		return 1;
81	}
82
83	vh = lws_create_vhost(context, &info);
84	if (!vh) {
85		lwsl_err("Failed to create first vhost\n");
86		goto bail1;
87	}
88
89	memset(&ss_args, 0, sizeof(ss_args));
90	ss_args.helo = "lws-abs-smtp-test";
91	ss_args.vhost = vh;
92
93	sseq = lws_smtp_sequencer_create(&ss_args);
94	if (!sseq) {
95		lwsl_err("%s: smtp sequencer create failed\n", __func__);
96		goto bail1;
97	}
98
99	/* attach an email to it */
100
101	n = lws_snprintf(payload, sizeof(payload),
102			"From: noreply@example.com\n"
103			"To: %s\n"
104			"Subject: Test email for lws smtp-client\n"
105			"\n"
106			"Hello this was an api test for lws smtp-client\n"
107			"\r\n.\r\n", recip);
108
109	if (lws_smtpc_add_email(sseq, payload, n, "testserver",
110				"andy@warmcat.com", recip, NULL, done_cb)) {
111		lwsl_err("%s: failed to add email\n", __func__);
112		goto bail1;
113	}
114
115	/* the usual lws event loop */
116
117	while (n >= 0 && !interrupted)
118		n = lws_service(context, 0);
119
120bail1:
121	lwsl_user("Completed: %s\n", result ? "FAIL" : "PASS");
122
123	lws_context_destroy(context);
124
125	return result;
126}
127