File:  [ELWIX - Embedded LightWeight unIX -] / mqtt / src / daemon.c
Revision 1.6: download - view: text, annotated - select for diffs - revision graph
Sun Oct 8 22:49:24 2017 UTC (6 years, 8 months ago) by misho
Branches: MAIN
CVS tags: mqtt2_1, MQTT2_0, HEAD
version 2.0

    1: /*************************************************************************
    2: * (C) 2011 AITNET ltd - Sofia/Bulgaria - <misho@aitbg.com>
    3: *  by Michael Pounov <misho@openbsd-bg.org>
    4: *
    5: * $Author: misho $
    6: * $Id: daemon.c,v 1.6 2017/10/08 22:49:24 misho Exp $
    7: *
    8: **************************************************************************
    9: The ELWIX and AITNET software is distributed under the following
   10: terms:
   11: 
   12: All of the documentation and software included in the ELWIX and AITNET
   13: Releases is copyrighted by ELWIX - Sofia/Bulgaria <info@elwix.org>
   14: 
   15: Copyright 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013
   16: 	by Michael Pounov <misho@elwix.org>.  All rights reserved.
   17: 
   18: Redistribution and use in source and binary forms, with or without
   19: modification, are permitted provided that the following conditions
   20: are met:
   21: 1. Redistributions of source code must retain the above copyright
   22:    notice, this list of conditions and the following disclaimer.
   23: 2. Redistributions in binary form must reproduce the above copyright
   24:    notice, this list of conditions and the following disclaimer in the
   25:    documentation and/or other materials provided with the distribution.
   26: 3. All advertising materials mentioning features or use of this software
   27:    must display the following acknowledgement:
   28: This product includes software developed by Michael Pounov <misho@elwix.org>
   29: ELWIX - Embedded LightWeight unIX and its contributors.
   30: 4. Neither the name of AITNET nor the names of its contributors
   31:    may be used to endorse or promote products derived from this software
   32:    without specific prior written permission.
   33: 
   34: THIS SOFTWARE IS PROVIDED BY AITNET AND CONTRIBUTORS ``AS IS'' AND
   35: ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   36: IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   37: ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   38: FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   39: DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   40: OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   41: HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   42: LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   43: OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   44: SUCH DAMAGE.
   45: */
   46: #include "global.h"
   47: #include "rtlm.h"
   48: #include "mqttd.h"
   49: #include "mqttd_calls.h"
   50: #include "utils.h"
   51: 
   52: 
   53: static inline struct tagSession *
   54: initSession(int sock, ait_val_t * __restrict v)
   55: {
   56: 	struct tagSession *sess = NULL;
   57: 	const char *str;
   58: 
   59: 	ETRACE();
   60: 
   61: 	if (!v)
   62: 		return NULL;
   63: 
   64: 	sess = e_malloc(sizeof(struct tagSession));
   65: 	if (!sess) {
   66: 		ELIBERR(elwix);
   67: 		return NULL;
   68: 	} else
   69: 		memset(sess, 0, sizeof(struct tagSession));
   70: 
   71: 	SLIST_INIT(&sess->sess_subscr);
   72: 
   73: 	str = cfg_getAttribute(&cfg, "mqttd", "retry");
   74: 	if (!str)
   75: 		sess->sess_retry = DEFAULT_RETRY;
   76: 	else
   77: 		sess->sess_retry = strtol(str, NULL, 0);
   78: 
   79: 	sess->sess_buf = mqtt_msgAlloc(USHRT_MAX);
   80: 	if (!sess->sess_buf) {
   81: 		ELIBERR(mqtt);
   82: 		e_free(sess);
   83: 		return NULL;
   84: 	}
   85: 
   86: 	/* init server actor */
   87: 	sess->sess_srv = mqtt_srv_cliInit(sock, sess->sess_buf, sess->sess_ka, 1);
   88: 	if (!sess->sess_srv) {
   89: 		EVERBOSE(3, "Error:: in srv_Init #%d - %s", mqtt_GetErrno(), mqtt_GetError());
   90: 		mqtt_msgFree(&sess->sess_buf, 42);
   91: 		e_free(sess);
   92: 		return NULL;
   93: 	} else {
   94: 		mqtt_srv_setCmd(sess->sess_srv, MQTT_TYPE_CONNECT, cmdCONNECT);
   95: 		mqtt_srv_setCmd(sess->sess_srv, MQTT_TYPE_PUBLISH, cmdPUBLISH);
   96: 		mqtt_srv_setCmd(sess->sess_srv, MQTT_TYPE_PUBREL, cmdPUBREL);
   97: 		mqtt_srv_setCmd(sess->sess_srv, MQTT_TYPE_SUBSCRIBE, cmdSUBSCRIBE);
   98: 		mqtt_srv_setCmd(sess->sess_srv, MQTT_TYPE_UNSUBSCRIBE, cmdUNSUBSCRIBE);
   99: 		mqtt_srv_setCmd(sess->sess_srv, MQTT_TYPE_PINGREQ, cmdPINGREQ);
  100: 		mqtt_srv_setCmd(sess->sess_srv, MQTT_TYPE_DISCONNECT, cmdDISCONNECT);
  101: 	}
  102: 
  103: 	sess->sess_sock = sock;
  104: 	strlcpy(sess->sess_addr, (char*) AIT_GET_STR(v), sizeof sess->sess_addr);
  105: 	return sess;
  106: }
  107: 
  108: static void
  109: finiSession(struct tagSession *sess)
  110: {
  111: 	struct tagStore *store;
  112: 
  113: 	ETRACE();
  114: 
  115: 	if (!sess)
  116: 		return;
  117: 
  118: 	schedCancelby(root, taskTIMER, CRITERIA_CALL, sendRetain, NULL);
  119: 
  120: 	if (sess->sess_clean) {
  121: 		if (call.FiniSessPUB)
  122: 			call.FiniSessPUB(&cfg, pub, sess->sess_cid, sess->sess_user, "%");
  123: 		if (call.DeletePUB_subscribe)
  124: 			call.DeletePUB_subscribe(&cfg, pub, sess->sess_cid, "%", sess->sess_user, "%");
  125: 		if (call.WipePUB_topic)	/* only dynamic messages */
  126: 			call.WipePUB_topic(&cfg, pub, sess->sess_cid, sess->sess_user, 0);
  127: 	}
  128: 
  129: 	while ((store = SLIST_FIRST(&sess->sess_subscr))) {
  130: 		SLIST_REMOVE_HEAD(&sess->sess_subscr, st_node);
  131: 
  132: 		if (store->st_subscr.sub_topic.msg_base)
  133: 			free(store->st_subscr.sub_topic.msg_base);
  134: 		if (store->st_subscr.sub_value.msg_base)
  135: 			free(store->st_subscr.sub_value.msg_base);
  136: 
  137: 		e_free(store);
  138: 	}
  139: 
  140: 	if (sess->sess_will.flag)
  141: 		pubWill(sess);
  142: 
  143: 	if (sess->sess_will.topic)
  144: 		free(sess->sess_will.topic);
  145: 	if (sess->sess_will.msg)
  146: 		free(sess->sess_will.msg);
  147: 
  148: 	if (sess->sess_sock > STDERR_FILENO)
  149: 		srv_Close(sess->sess_sock);
  150: 
  151: 	mqtt_srv_cliFini(&sess->sess_srv);
  152: 	mqtt_msgFree(&sess->sess_buf, 42);
  153: 
  154: 	e_free(sess);
  155: }
  156: 
  157: static void *
  158: leaveClient(sched_task_t *task)
  159: {
  160: 	struct tagSession *sess;
  161: 	int ret;
  162: 
  163: 	ETRACE();
  164: 
  165: 	assert(task);
  166: 
  167: 	sess = TASK_ARG(task);
  168: 	assert(sess);
  169: 
  170: 	TAILQ_REMOVE(&Sessions, sess, sess_node);
  171: 
  172: 	ret = mqtt_msgDISCONNECT(sess->sess_buf);
  173: 	send(TASK_FD(task), sess->sess_buf->msg_base, ret, MSG_NOSIGNAL);
  174: 
  175: 	EVERBOSE(1, "Close socket=%ld", (long) TASK_FD(task));
  176: 	call.LOG(logg, "Session %s stopped from %s for user %s.\n", sess->sess_cid, 
  177: 			sess->sess_addr, sess->sess_user);
  178: 
  179: 	finiSession(sess);
  180: 	return NULL;
  181: }
  182: 
  183: static void *
  184: dispatchSession(sched_task_t *task)
  185: {
  186: 	int ret, len = 0;
  187: 	struct tagSession *sess;
  188: 
  189: 	ETRACE();
  190: 
  191: 	assert(task);
  192: 
  193: 	sess = TASK_ARG(task);
  194: 	assert(sess);
  195: 
  196: 	/* receive & decode packet */
  197: 	if ((ret = recv(TASK_FD(task), sess->sess_buf->msg_base, sess->sess_buf->msg_len, 0)) == -1) {
  198: 		EVERBOSE(3, "Error:: recv(%d) #%d - %s", sess->sess_sock, errno, strerror(errno));
  199: 		TAILQ_REMOVE(&Sessions, sess, sess_node);
  200: 		finiSession(sess);
  201: 		return NULL;
  202: 	} else if (!ret) {
  203: 		EVERBOSE(4, "Session %s EOF received.", sess->sess_cid);
  204: 		TAILQ_REMOVE(&Sessions, sess, sess_node);
  205: 		finiSession(sess);
  206: 		return NULL;
  207: 	}
  208: 
  209: 	do {
  210: 		/* dispatch message type */
  211: 		if ((len = mqtt_srv_cliDispatch(sess->sess_srv, ret, sess)) < 0) {
  212: 			if (len == -1) {
  213: 				ELIBERR(mqtt);
  214: 				finiSession(sess);
  215: 			} else if (len == -2) {
  216: 				TAILQ_REMOVE(&Sessions, sess, sess_node);
  217: 				finiSession(sess);
  218: 			} else if (len == -3)
  219: 				schedEvent(root, startSession, NULL, (u_long) TASK_FD(task), sess, ret);
  220: 		} else
  221: 			ret -= len;
  222: 	} while (len > 0 && ret > 0);
  223: 
  224: 	if (len >= 0 && !schedRead(root, dispatchSession, TASK_ARG(task), TASK_FD(task), NULL, 0)) {
  225: 		ELIBERR(sched);
  226: 		TAILQ_REMOVE(&Sessions, sess, sess_node);
  227: 		finiSession(sess);
  228: 	}
  229: 	return NULL;
  230: }
  231: 
  232: static int
  233: loadSubscribes(struct tagSession * __restrict sess, mqtt_subscr_t * __restrict subs)
  234: {
  235: 	register int i;
  236: 	struct tagStore *store;
  237: 
  238: 	if (!subs)
  239: 		return -1;
  240: 
  241: 	for (i = 0; subs[i].sub_topic.msg_base; i++) {
  242: 		store = e_malloc(sizeof(struct tagStore));
  243: 		if (!store) {
  244: 			ELIBERR(elwix);
  245: 			continue;
  246: 		} else {
  247: 			store->st_msgid = 0;
  248: 			mqtt_subCopy(&store->st_subscr, &subs[i]);
  249: 		}
  250: 
  251: 		/* add to cache */
  252: 		SLIST_INSERT_HEAD(&sess->sess_subscr, store, st_node);
  253: 	}
  254: 
  255: 	return 0;
  256: }
  257: 
  258: void *
  259: startSession(sched_task_t *task)
  260: {
  261: 	u_char basebuf[USHRT_MAX];
  262: 	mqtt_msg_t buf = { basebuf, sizeof basebuf };
  263: 	mqtthdr_connflgs_t flg;
  264: 	mqtthdr_connack_t cack;
  265: 	ait_val_t *v;
  266: 	struct tagSession *s, *sess = NULL;
  267: 	int ret, wlen;
  268: 	mqtt_subscr_t *subs;
  269: 	struct timespec ts = { RETAIN_TIMEOUT, 0 };
  270: 	intptr_t sock;
  271: 
  272: 	ETRACE();
  273: 
  274: 	assert(task);
  275: 
  276: 	if (!TASK_DATA(task)) {
  277: 		v = TASK_ARG(task);
  278: 		/* flow from accept new clients */
  279: 		sess = initSession(TASK_FD(task), v);
  280: 		ait_freeVar(&v);
  281: 		if (!sess) {
  282: 			close(TASK_FD(task));
  283: 			return NULL;
  284: 		}
  285: 
  286: 		/* receive & decode packet */
  287: 		if (recv(sess->sess_sock, buf.msg_base, buf.msg_len, 0) == -1) {
  288: 			EVERBOSE(3, "Error:: recv(%d) #%d - %s", sess->sess_sock, errno, strerror(errno));
  289: 			finiSession(sess);
  290: 			return NULL;
  291: 		}
  292: 	} else {
  293: 		sess = TASK_DATA(task);
  294: 		assert(sess);
  295: 
  296: 		buf.msg_len = TASK_DATLEN(task) > sizeof basebuf ? sizeof basebuf : TASK_DATLEN(task);
  297: 		memcpy(buf.msg_base, sess->sess_buf->msg_base, buf.msg_len);
  298: 	}
  299: 
  300: 	cack = mqtt_readCONNECT(&buf, &sess->sess_ka, sess->sess_cid, sizeof sess->sess_cid, 
  301: 			sess->sess_user, sizeof sess->sess_user, sess->sess_pass, sizeof sess->sess_pass, 
  302: 			&sess->sess_will.topic, &sess->sess_will.msg);
  303: 	ret = cack.retcode;
  304: 	flg.flags = cack.reserved;
  305: 	if (flg.reserved) {
  306: 		EVERBOSE(3, "Error:: in MQTT protocol #%d - %s", mqtt_GetErrno(), mqtt_GetError());
  307: 		goto end;
  308: 	} else {
  309: 		sess->sess_clean = flg.clean_sess;
  310: 		sess->sess_will.qos = flg.will_qos;
  311: 		sess->sess_will.retain = flg.will_retain;
  312: 		sess->sess_will.flag = flg.will_flg;
  313: 
  314: 		sess->sess_srv->timeout = sess->sess_ka;
  315: 	}
  316: 
  317: 	/* check online table for user */
  318: 	if (call.LoginACC(&cfg, acc, sess->sess_user, sess->sess_pass) < 1) {
  319: 		EVERBOSE(0, "Login:: DENIED for username %s and password %s", 
  320: 				sess->sess_user, sess->sess_pass);
  321: 		ret = MQTT_RETCODE_DENIED;
  322: 		goto end;
  323: 	} else {
  324: 		EVERBOSE(1, "Login:: ALLOWED for username %s ...", sess->sess_user);
  325: 		ret = MQTT_RETCODE_ACCEPTED;
  326: 	}
  327: 
  328: 	/* db management */
  329: 	if (call.FiniSessPUB(&cfg, pub, sess->sess_cid, sess->sess_user, "%") > 0) {
  330: 		EVERBOSE(2, "Old session %s should be disconnect!", sess->sess_cid);
  331: 		TAILQ_FOREACH(s, &Sessions, sess_node)
  332: 			if (!strcmp(s->sess_cid, sess->sess_cid)) {
  333: 				/* found stale session & disconnect it! */
  334: 				sock = s->sess_sock;
  335: 				schedCancelby(root, taskMAX, CRITERIA_FD, (void*) sock, NULL);
  336: 				schedWrite(root, leaveClient, s, s->sess_sock, NULL, 0);
  337: 				break;
  338: 			}
  339: 	}
  340: 	if (call.InitSessPUB(&cfg, pub, sess->sess_cid, sess->sess_user, sess->sess_addr, 
  341: 				sess->sess_will.flag, sess->sess_will.topic, sess->sess_will.msg, 
  342: 				sess->sess_will.qos, sess->sess_will.retain) == -1) {
  343: 		EVERBOSE(0, "Session %s DENIED for username %s", sess->sess_cid, sess->sess_user);
  344: 		ret = MQTT_RETCODE_DENIED;
  345: 		goto end;
  346: 	} else {
  347: 		EVERBOSE(0, "Session %s from %s and username %s is started", 
  348: 				sess->sess_cid, sess->sess_addr, sess->sess_user);
  349: 		ret = MQTT_RETCODE_ACCEPTED;
  350: 	}
  351: 	/* clean/load session if requested */
  352: 	if (sess->sess_clean) {
  353: 		if (call.DeletePUB_subscribe)
  354: 			call.DeletePUB_subscribe(&cfg, pub, sess->sess_cid, "%", sess->sess_user, "%");
  355: 		if (call.WipePUB_topic)	/* delete ALL messages */
  356: 			call.WipePUB_topic(&cfg, pub, sess->sess_cid, sess->sess_user, -1);
  357: 	} else if (call.ReadPUB_subscribe) {
  358: 		/* load subscribes */
  359: 		subs = call.ReadPUB_subscribe(&cfg, pub, sess->sess_cid, "%");
  360: 		loadSubscribes(sess, subs);
  361: 		mqtt_subFree(&subs);
  362: 	}
  363: 
  364: 	/* timer event for retain messages */
  365: 	if (call.ReadPUB_topic)
  366: 		schedTimer(root, sendRetain, sess, ts, NULL, 0);
  367: 
  368: 	/* Start session task OK ... */
  369: 	if (!schedRead(root, dispatchSession, sess, TASK_FD(task), NULL, 0)) {
  370: 		ELIBERR(sched);
  371: 		ret = MQTT_RETCODE_DENIED;
  372: 	} else
  373: 		TAILQ_INSERT_TAIL(&Sessions, sess, sess_node);
  374: 
  375: 	call.LOG(logg, "Session %s started from %s for user %s (timeout=%d) OK!\n", sess->sess_cid, 
  376: 			sess->sess_addr, sess->sess_user, sess->sess_ka);
  377: end:	/* close client connection */
  378: 	wlen = mqtt_msgCONNACK(sess->sess_buf, ret);
  379: 	if ((wlen = send(TASK_FD(task), sess->sess_buf->msg_base, wlen, 0)) == -1) {
  380: 		EVERBOSE(3, "Error:: send(%ld) #%d - %s", (long) TASK_FD(task), errno, strerror(errno));
  381: 	} else
  382: 		EVERBOSE(5, "Sended %d bytes", wlen);
  383: 
  384: 	if (ret != MQTT_RETCODE_ACCEPTED) {
  385: 		EVERBOSE(1, "Close client %s with socket=%ld", sess->sess_addr, (long) TASK_FD(task));
  386: 		finiSession(sess);
  387: 	}
  388: 	return NULL;
  389: }
  390: 
  391: static void *
  392: acceptClient(sched_task_t *task)
  393: {
  394: 	int cli;
  395: 	sockaddr_t sa;
  396: 	socklen_t sslen = sizeof sa.ss;
  397: 	ait_val_t *v;
  398: 	char str[STRSIZ];
  399: 
  400: 	ETRACE();
  401: 
  402: 	assert(task);
  403: 
  404: 	if ((cli = accept(TASK_FD(task), &sa.sa, &sslen)) == -1)
  405: 		goto end;
  406: 	else
  407: 		fcntl(cli, F_SETFL, fcntl(cli, F_GETFL) | O_NONBLOCK);
  408: 
  409: 	v = ait_allocVar();
  410: 	if (!v) {
  411: 		ELIBERR(elwix);
  412: 		close(cli);
  413: 		goto end;
  414: 	} else {
  415: 		memset(str, 0, sizeof str);
  416: 		snprintf(str, sizeof str, "%s:%hu", e_n2addr(&sa, v), e_n2port(&sa));
  417: 		AIT_FREE_VAL(v);
  418: 		AIT_SET_STR(v, str);
  419: 	}
  420: 	EVERBOSE(1, "Connected client with socket=%d from %s", cli, AIT_GET_STR(v));
  421: 
  422: 	if (!schedRead(root, startSession, v, cli, NULL, 0)) {
  423: 		ait_freeVar(&v);
  424: 		close(cli);
  425: 		EVERBOSE(1, "Terminated client with socket=%d", cli);
  426: 	}
  427: end:
  428: 	if (!schedRead(root, acceptClient, NULL, TASK_FD(task), NULL, 0))
  429: 		ELIBERR(sched);
  430: 	return NULL;
  431: }
  432: 
  433: /* ----------------------------------------------------------------------- */
  434: 
  435: int
  436: Run(int sock)
  437: {
  438: 	struct tagSession *sess;
  439: 	struct timespec pl = { 0, 100000000 };
  440: 
  441: 	ETRACE();
  442: 
  443: 	if (mqtt_srv_Listen(sock, 0, 1) == -1) {
  444: 		ELIBERR(mqtt);
  445: 		return -1;
  446: 	}
  447: 
  448: 	/* state machine - accept new connections */
  449: 	if (!schedRead(root, acceptClient, NULL, sock, NULL, 0)) {
  450: 		ELIBERR(sched);
  451: 		return -1;
  452: 	}
  453: 
  454: 	schedPolling(root, &pl, NULL);
  455: 	schedRun(root, &Kill);
  456: 
  457: 	schedCancelby(root, taskTIMER, CRITERIA_CALL, sendRetain, NULL);
  458: 
  459: 	/* free all undeleted elements into lists */
  460: 	TAILQ_FOREACH(sess, &Sessions, sess_node) {
  461: 		TAILQ_REMOVE(&Sessions, sess, sess_node);
  462: 
  463: 		finiSession(sess);
  464: 	}
  465: 	return 0;
  466: }

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>