File:  [ELWIX - Embedded LightWeight unIX -] / libaitio / src / aitio.c
Revision 1.10.6.2: download - view: text, annotated - select for diffs - revision graph
Wed May 23 11:59:51 2012 UTC (12 years, 1 month ago) by misho
Branches: io3_1
Diff to: branchpoint 1.10: preferred, unified
add check mpool api and add mpool config

    1: /*************************************************************************
    2: * (C) 2010 AITNET ltd - Sofia/Bulgaria - <misho@aitnet.org>
    3: *  by Michael Pounov <misho@elwix.org>
    4: *
    5: * $Author: misho $
    6: * $Id: aitio.c,v 1.10.6.2 2012/05/23 11:59:51 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
   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: 
   48: 
   49: int io_Debug;
   50: 
   51: 
   52: #pragma GCC visibility push(hidden)
   53: 
   54: int io_mpool;
   55: 
   56: int io_Errno;
   57: char io_Error[STRSIZ];
   58: 
   59: #pragma GCC visibility pop
   60: 
   61: 
   62: // io_GetErrno() Get error code of last operation
   63: inline int
   64: io_GetErrno()
   65: {
   66: 	return io_Errno;
   67: }
   68: 
   69: // io_GetError() Get error text of last operation
   70: inline const char *
   71: io_GetError()
   72: {
   73: 	return io_Error;
   74: }
   75: 
   76: // io_SetErr() Set error to variables for internal use!!!
   77: inline void
   78: io_SetErr(int eno, char *estr, ...)
   79: {
   80: 	va_list lst;
   81: 
   82: 	io_Errno = eno;
   83: 	memset(io_Error, 0, STRSIZ);
   84: 	va_start(lst, estr);
   85: 	vsnprintf(io_Error, STRSIZ, estr, lst);
   86: 	va_end(lst);
   87: }
   88: 
   89: // mpool_inuse() Check for mpool usage
   90: inline int
   91: mpool_inuse()
   92: {
   93: 	return io_mpool;
   94: }
   95: 
   96: 
   97: /*
   98:  * ioPromptRead() - Read data from input h[0] with prompt to output h[1]
   99:  *
  100:  * @h = file handles h[0] = input, h[1] = output, if NULL use stdin, stdout
  101:  * @csPrompt = Prompt before input, may be NULL
  102:  * @psData = Readed data
  103:  * @dataLen = Length of data
  104:  * return: 0 EOF; -1 error:: can`t read; >0 count of readed chars
  105: */
  106: int
  107: ioPromptRead(int *h, const char *csPrompt, char * __restrict psData, int dataLen)
  108: {
  109: 	int ok = 0;
  110: 	FILE *inp, *out;
  111: 	char szLine[BUFSIZ], *pos;
  112: 
  113: 	if (!psData || !dataLen)
  114: 		return -1;
  115: 
  116: 	inp = fdopen(!h ? 0 : h[0], "r");
  117: 	if (!inp) {
  118: 		LOGERR;
  119: 		return -1;
  120: 	}
  121: 	out = fdopen(!h ? 1 : h[1], "w");
  122: 	if (!out) {
  123: 		LOGERR;
  124: 		return -1;
  125: 	}
  126: 
  127: 	while (!ok) {
  128: 		if (csPrompt) {
  129: 			fprintf(out, "%s", csPrompt);
  130: 			fflush(out);
  131: 		}
  132: 
  133: 		memset(szLine, 0, BUFSIZ);
  134: 		if (!fgets(szLine, BUFSIZ, inp)) {
  135: 			clearerr(inp);
  136: 			fpurge(out);
  137: 			fflush(out);
  138: 			return 0;
  139: 		}
  140: 
  141: 		if ((pos = strchr(szLine, '\n')))
  142: 			*pos = 0;
  143: 
  144: 		strlcpy(psData, szLine, dataLen);
  145: 		ok = 1;
  146: 	}
  147: 
  148: 	return pos - szLine;
  149: }
  150: 
  151: /*
  152:  * ioPromptPassword() - Read password from input h[0] with prompt to output h[1]
  153:  *
  154:  * @h = file handles h[0] = input, h[1] = output, if NULL use stdin, stdout
  155:  * @csPrompt = Prompt before input, may be NULL
  156:  * @psPass = Readed password
  157:  * @passLen = Length of password
  158:  * @confirm = Confirm password, 0 - get password, !=0 Ask for confirmation
  159:  * return: 0 EOF; -1 error:: can`t read; >0 count of readed chars
  160: */
  161: int
  162: ioPromptPassword(int *h, const char *csPrompt, char * __restrict psPass, int passLen, int confirm)
  163: {
  164: 	int ret, ok = 0;
  165: 	FILE *inp, *out;
  166: 	char szLine[2][STRSIZ];
  167: 	struct sgttyb tty_state;
  168: 
  169: 	if (!psPass || !passLen)
  170: 		return -1;
  171: 
  172: 	inp = fdopen(!h ? 0 : h[0], "r");
  173: 	if (!inp) {
  174: 		LOGERR;
  175: 		return -1;
  176: 	}
  177: 	out = fdopen(!h ? 1 : h[1], "w");
  178: 	if (!out) {
  179: 		LOGERR;
  180: 		return -1;
  181: 	}
  182: 
  183: 	if (ioctl(fileno(inp), TIOCGETP, &tty_state) == -1) {
  184: 		LOGERR;
  185: 		return -1;
  186: 	} else {
  187: 		tty_state.sg_flags &= ~ECHO;
  188: 		if (ioctl(fileno(inp), TIOCSETP, &tty_state) == -1) {
  189: 			LOGERR;
  190: 			return -1;
  191: 		}
  192: 	}
  193: 
  194: 	while (!ok) {
  195: 		switch ((ret = ioPromptRead(h, (!csPrompt || !*csPrompt) ? "Password:" : csPrompt, 
  196: 						szLine[0], STRSIZ))) {
  197: 			case -1:
  198: 				LOGERR;
  199: 				ok = -1;
  200: 			case 0:
  201: 				goto next;
  202: 		}
  203: 		if (confirm) {
  204: 			fprintf(out, "\n");
  205: 			fflush(out);
  206: 
  207: 			switch (ioPromptRead(h, "Password confirm:", szLine[1], STRSIZ)) {
  208: 				case -1:
  209: 					LOGERR;
  210: 					ok = -1;
  211: 					goto next;
  212: 				case 0:
  213: 				default:
  214: 					if (strcmp(szLine[0], szLine[1])) {
  215: 						fprintf(out, "\n\07\07Mismatch - Try again!\n");
  216: 						fflush(out);
  217: 						continue;
  218: 					}
  219: 			}
  220: 		}
  221: 
  222: 		strlcpy(psPass, szLine[0], passLen);
  223: 		ok = ret;
  224: 		fprintf(out, "\n");
  225: 		fflush(out);
  226: 	}
  227: 
  228: next:
  229: 	tty_state.sg_flags |= ECHO;
  230: 	if (ioctl(fileno(inp), TIOCSETP, &tty_state) == -1) {
  231: 		LOGERR;
  232: 		return -1;
  233: 	}
  234: 
  235: 	return ok;
  236: }
  237: 
  238: /*
  239:  * ioRegexVerify() - Function for verify data match in regex expression
  240:  *
  241:  * @csRegex = Regulare expression pattern
  242:  * @csData = Data for check and verify
  243:  * @startPos = Return start positions
  244:  * @endPos = Return end positions
  245:  * return: NULL not match or error; !=NULL begin of matched data
  246: */
  247: const char *
  248: ioRegexVerify(const char *csRegex, const char *csData, int *startPos, int *endPos)
  249: {
  250: 	regex_t re;
  251: 	regmatch_t match;
  252: 	char szErr[STRSIZ];
  253: 	int ret, flg;
  254: 	const char *pos;
  255: 
  256: 	if (!csRegex || !csData)
  257: 		return NULL;
  258: 
  259: 	if ((ret = regcomp(&re, csRegex, REG_EXTENDED))) {
  260: 		regerror(ret, &re, szErr, STRSIZ);
  261: 		io_SetErr(ret, "%s", szErr);
  262: 		regfree(&re);
  263: 		return NULL;
  264: 	}
  265: 
  266: 	for (ret = flg = 0, pos = csData; !(ret = regexec(&re, pos, 1, &match, flg)); 
  267: 			pos += match.rm_eo, flg = REG_NOTBOL) {
  268: 		if (startPos)
  269: 			*startPos = match.rm_so;
  270: 		if (endPos)
  271: 			*endPos = match.rm_eo;
  272: 
  273: 		pos += match.rm_so;
  274: 		break;
  275: 	}
  276: 
  277: 	if (ret) {
  278: 		regerror(ret, &re, szErr, STRSIZ);
  279: 		io_SetErr(ret, "%s", szErr);
  280: 		pos = NULL;
  281: 	}
  282: 
  283: 	regfree(&re);
  284: 	return pos;
  285: }
  286: 
  287: /*
  288:  * ioRegexGet() - Function for get data match in regex expression
  289:  *
  290:  * @csRegex = Regulare expression pattern
  291:  * @csData = Data from get
  292:  * @psString = Returned string if match
  293:  * @strLen = Length of string
  294:  * return: 0 not match; >0 count of returned chars
  295: */
  296: int
  297: ioRegexGet(const char *csRegex, const char *csData, char * __restrict psString, int strLen)
  298: {
  299: 	int sp, ep, len;
  300: 	const char *str;
  301: 
  302: 	if (!csRegex || !csData)
  303: 		return -1;
  304: 
  305: 	str = ioRegexVerify(csRegex, csData, &sp, &ep);
  306: 	if (!str)
  307: 		return 0;
  308: 
  309: 	len = ep - sp;
  310: 	if (psString && strLen) {
  311: 		memset(psString, 0, strLen);
  312: 		strncpy(psString, str, strLen <= len ? strLen - 1 : len);
  313: 	}
  314: 
  315: 	return len;
  316: }
  317: 
  318: /*
  319:  * ioRegexReplace() - Function for replace data match in regex expression with newdata
  320:  *
  321:  * @csRegex = Regulare expression pattern
  322:  * @csData = Source data
  323:  * @csNew = Data for replace
  324:  * return: NULL not match or error; !=NULL allocated new string, must be xfree after use!
  325: */
  326: char *
  327: ioRegexReplace(const char *csRegex, const char *csData, const char *csNew)
  328: {
  329: 	int sp, ep, len;
  330: 	char *str = NULL;
  331: 
  332: 	if (!csRegex || !csData)
  333: 		return NULL;
  334: 
  335: 	if (!ioRegexVerify(csRegex, csData, &sp, &ep))
  336: 		return NULL;
  337: 
  338: 	// ___ before match
  339: 	len = sp + 1;
  340: 	str = xmalloc(len);
  341: 	if (!str) {
  342: 		LOGERR;
  343: 		return NULL;
  344: 	} else
  345: 		strlcpy(str, csData, len);
  346: 	// * replace match *
  347: 	if (csNew) {
  348: 		len += strlen(csNew);
  349: 		str = xrealloc(str, len);
  350: 		if (!str) {
  351: 			LOGERR;
  352: 			return NULL;
  353: 		} else
  354: 			strlcat(str, csNew, len);
  355: 	}
  356: 	// after match ___
  357: 	len += strlen(csData) - ep;
  358: 	str = xrealloc(str, len);
  359: 	if (!str) {
  360: 		LOGERR;
  361: 		return NULL;
  362: 	} else
  363: 		strlcat(str, csData + ep, len);
  364: 
  365: 	return str;
  366: }
  367: 
  368: /*
  369:  * ioStrAst() - Function for evaluate string like asterisk variable "{text[:[-]#[:#]]}"
  370:  *
  371:  * @csString = Input string
  372:  * return: NULL error, !=NULL Allocated new string evaluated from input string, must be xfree()
  373: */
  374: char *
  375: ioStrAst(const char *csString)
  376: {
  377: 	char *ext, *str, *out = NULL;
  378: 	int e[2] = { 0 };
  379: 
  380: 	if (!csString)
  381: 		return NULL;
  382: 
  383: 	if (!strchr(csString, '{') || !strrchr(csString, '}')) {
  384: 		memset(io_Error, 0, STRSIZ);
  385: 		snprintf(io_Error, STRSIZ, "Invalid input string format ... "
  386: 				"must be like {text[:[-]#[:#]]}");
  387: 		io_Errno = EINVAL;
  388: 		return NULL;
  389: 	} else {
  390: 		str = strdup(strchr(csString, '{') + 1);
  391: 		*strrchr(str, '}') = 0;
  392: 	}
  393: 
  394: 	if ((ext = strchr(str, ':'))) {
  395: 		*ext++ = 0;
  396: 		e[0] = strtol(ext, NULL, 0);
  397: 		if ((ext = strchr(ext, ':')))
  398: 			e[1] = strtol(++ext, NULL, 0);
  399: 
  400: 		/* make cut prefix */
  401: 		if (e[0] >= 0)
  402: 			ext = str + e[0];
  403: 		else
  404: 			ext = str + strlen(str) + e[0];
  405: 		/* make cut suffix */
  406: 		if (e[1] > 0)
  407: 			*(ext + e[1]) = 0;
  408: 	} else
  409: 		/* ok, clear show */
  410: 		ext = str;
  411: 
  412: 	out = strdup(ext);
  413: 	xfree(str);
  414: 
  415: 	return out;
  416: }
  417: 
  418: 
  419: /*
  420:  * ioMkDir() - Function for racursive directory creation and validation
  421:  *
  422:  * @csDir = Full directory path
  423:  * @mode = Mode for directory creation if missing dir
  424:  * return: -1 error, 0 directory path exist, >0 created missing dirs
  425: */
  426: int
  427: ioMkDir(const char *csDir, int mode)
  428: {
  429: 	char *str, *s, *pbrk, szOld[MAXPATHLEN] = { 0 };
  430: 	register int cx = -1;
  431: 
  432: 	if (!csDir)
  433: 		return cx;
  434: 
  435: 	str = strdup(csDir);
  436: 	if (!str) {
  437: 		LOGERR;
  438: 		return cx;
  439: 	}
  440: 
  441: 	getcwd(szOld, MAXPATHLEN);
  442: 	if (*str == '/')
  443: 		chdir("/");
  444: 
  445: 	for (cx = 0, s = strtok_r(str, "/", &pbrk); s; s = strtok_r(NULL, "/", &pbrk)) {
  446: 		if (mkdir(s, mode) == -1) {
  447: 			if (errno != EEXIST) {
  448: 				LOGERR;
  449: 				cx = -1;
  450: 				goto end;
  451: 			}
  452: 		} else
  453: 			cx++;
  454: 
  455: 		if (chdir(s) == -1) {
  456: 			LOGERR;
  457: 			cx = -1;
  458: 			goto end;
  459: 		}
  460: 	}
  461: end:
  462: 	chdir(szOld);
  463: 	xfree(str);
  464: 	return cx;
  465: }
  466: 
  467: /*
  468:  * ioWatchDirLoop() - Function for watching changes in directory and fire callback
  469:  *
  470:  * @csDir = Full directory path
  471:  * @callback = Callback if raise event! nOp -1 delete, 0 change/move, 1 create
  472:  * return: -1 error, !=-1 ok, number of total signaled events
  473: */
  474: int
  475: ioWatchDirLoop(const char *csDir, int (*callback)(const char *csName, int nOp))
  476: {
  477: 	glob_t g[2] = {{ 0 }, { 0 }};
  478: 	int d, kq, n = 0;
  479: 	register int j, i;
  480: 	struct kevent req, chg;
  481: 	char wrk[MAXPATHLEN * 2], str[MAXPATHLEN] = { 0 };
  482: 
  483: 	if (!csDir || !callback)
  484: 		return 0;
  485: 
  486: 	strlcpy(str, csDir, MAXPATHLEN);
  487: 	strlcat(str, "/*", MAXPATHLEN);
  488: 
  489: 	kq = kqueue();
  490: 	if (kq == -1) {
  491: 		LOGERR;
  492: 		return -1;
  493: 	}
  494: 	d = open(csDir, O_RDONLY);
  495: 	if (d == -1) {
  496: 		LOGERR;
  497: 		close(kq);
  498: 		return -1;
  499: 	}
  500: 
  501: 	EV_SET(&req, d, EVFILT_VNODE, EV_ADD | EV_CLEAR, NOTE_WRITE, 0, 0);
  502: 
  503: 	if ((n = glob(str, GLOB_NOCHECK, NULL, &g[0]))) {
  504: 		LOGERR;
  505: 		close(d);
  506: 		close(kq);
  507: 		return -1;
  508: 	} /*else
  509: 		ioDEBUG(3, "Start files %d in %s\n", g[0].gl_matchc, str);*/
  510: 
  511: 	while (kevent(kq, &req, 1, &chg, 1, NULL) > 0) {
  512: 		/*ioDEBUG(1, "Event:: req=0x%x -> chg=0x%x data=%x\n", req.fflags, chg.fflags, chg.data);*/
  513: 
  514: 		if (!glob(str, GLOB_NOCHECK, NULL, &g[1])) {
  515: 			/*ioDEBUG(3, "Diffs %d <> %d\n", g[0].gl_matchc, g[1].gl_matchc);*/
  516: 
  517: 			if (g[0].gl_matchc != g[1].gl_matchc) {
  518: 				/* find new items */
  519: 				for (j = 0; j < g[1].gl_matchc; j++) {
  520: 					for (i = 0; i < g[0].gl_matchc; i++)
  521: 						if (!strcmp(g[0].gl_pathv[i], g[1].gl_pathv[j]))
  522: 							break;
  523: 					if (i == g[0].gl_matchc) {
  524: 						if (callback(g[1].gl_pathv[j], 1) < 0)
  525: 							break;
  526: 						else
  527: 							n++;
  528: 					}
  529: 				}
  530: 				/* find del items */
  531: 				for (j = 0; j < g[0].gl_matchc; j++) {
  532: 					for (i = 0; i < g[1].gl_matchc; i++)
  533: 						if (!strcmp(g[1].gl_pathv[i], g[0].gl_pathv[j]))
  534: 							break;
  535: 					if (i == g[1].gl_matchc) {
  536: 						if (callback(g[0].gl_pathv[j], -1) < 0)
  537: 							break;
  538: 						else
  539: 							n++;
  540: 					}
  541: 				}
  542: 			} else {
  543: 				/* find chg from items */
  544: 				for (j = 0; j < g[0].gl_matchc; j++) {
  545: 					for (i = 0; i < g[1].gl_matchc; i++)
  546: 						if (!strcmp(g[1].gl_pathv[i], g[0].gl_pathv[j]))
  547: 							break;
  548: 					if (i == g[1].gl_matchc) {
  549: 						strlcpy(wrk, g[0].gl_pathv[j], sizeof wrk);
  550: 						strlcat(wrk, ":", sizeof wrk);
  551: 					}
  552: 				}
  553: 				/* find chg to items */
  554: 				for (j = 0; j < g[1].gl_matchc; j++) {
  555: 					for (i = 0; i < g[0].gl_matchc; i++)
  556: 						if (!strcmp(g[0].gl_pathv[i], g[1].gl_pathv[j]))
  557: 							break;
  558: 					if (i == g[0].gl_matchc) {
  559: 						strlcat(wrk, g[1].gl_pathv[j], sizeof wrk);
  560: 						if (callback(wrk, 0) < 0)
  561: 							break;
  562: 						else
  563: 							n++;
  564: 					}
  565: 				}
  566: 			}
  567: 
  568: 			globfree(&g[0]);
  569: 			g[0] = g[1];
  570: 		}
  571: 	}
  572: 
  573: 	globfree(&g[0]);
  574: 	close(d);
  575: 	close(kq);
  576: 	return n;
  577: }
  578: 
  579: /*
  580:  * ioCreatePIDFile() - Create PID file
  581:  *
  582:  * @csName = PID filename
  583:  * @ifExists = !=0 if filename exists return error
  584:  * return: -1 error or 0 ok
  585:  */
  586: inline int
  587: ioCreatePIDFile(const char *csName, int ifExists)
  588: {
  589: 	int fd;
  590: 	char str[STRSIZ] = { 0 };
  591: 
  592: 	if (!csName)
  593: 		return -1;
  594: 
  595: 	fd = open(csName, O_WRONLY | O_CREAT | (ifExists ? O_EXCL : 0), 0644);
  596: 	if (fd == -1) {
  597: 		LOGERR;
  598: 		return -1;
  599: 	}
  600: 	snprintf(str, sizeof str, "%d", getpid());
  601: 	write(fd, str, strlen(str));
  602: 	close(fd);
  603: 	return 0;
  604: }
  605: 
  606: 
  607: /*
  608:  * ioSendFile() - AITNET sendfile() userland implementation, not dependant from OS
  609:  *
  610:  * @s = socket
  611:  * @csFile = file for send
  612:  * @sendLen = bytes to send, if 0 send all data
  613:  * @offset = start file offset
  614:  * @sndbuf = SO_SNDBUF value, if 0 use default
  615:  * return: 0 error, >0 ok, sended bytes
  616:  */
  617: size_t
  618: ioSendFile(int s, const char *csFile, size_t sendLen, off_t offset, int sndbuf)
  619: {
  620: 	void *addr;
  621: 	int fd;
  622: 	size_t len = 0;
  623: 	register size_t off = 0;
  624: 
  625: 	if (!csFile)
  626: 		return 0;
  627: 
  628: 	if (sndbuf)
  629: 		if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof sndbuf) == -1) {
  630: 			LOGERR;
  631: 			return 0;
  632: 		}
  633: 
  634: 	fd = open(csFile, O_RDONLY);
  635: 	if (fd == -1) {
  636: 		LOGERR;
  637: 		return 0;
  638: 	}
  639: 	if (!sendLen) {
  640: 		sendLen = lseek(fd, 0, SEEK_END);
  641: 		if (sendLen == -1) {
  642: 			LOGERR;
  643: 			close(fd);
  644: 			return 0;
  645: 		}
  646: 	}
  647: 	addr = mmap(NULL, sendLen, PROT_READ, MAP_SHARED, fd, offset);
  648: 	if (addr == MAP_FAILED) {
  649: 		LOGERR;
  650: 		close(fd);
  651: 		return 0;
  652: 	} else
  653: 		close(fd);
  654: 
  655: 	while (off < sendLen && (len = write(s, addr + off, sendLen - off)) != -1)
  656: 		off += len;
  657: 	if (len == -1) {
  658: 		LOGERR;
  659: 		munmap(addr, sendLen);
  660: 		return 0;
  661: 	} else
  662: 		len = off;
  663: 
  664: 	if (len != sendLen) {
  665: 		io_SetErr(ECANCELED, "Different sizes - request %u bytes, actually sended %u bytes\n", 
  666: 				sendLen, len);
  667: 		len ^= len;
  668: 	}
  669: 
  670: 	munmap(addr, sendLen);
  671: 	return len;
  672: }
  673: 
  674: /*
  675:  * ioRecvFile() - Receive file from socket, fastest (zero-copy) way
  676:  *
  677:  * @s = socket
  678:  * @csFile = file for receive
  679:  * @recvLen = receive bytes
  680:  * @over = overwrite file if exists with mode like 0644
  681:  * @rcvbuf = SO_RCVBUF value, if 0 use default
  682:  * return: 0 error, >0 ok, received bytes
  683:  */
  684: size_t
  685: ioRecvFile(int s, const char *csFile, size_t recvLen, int over, int rcvbuf)
  686: {
  687: 	void *addr;
  688: 	int fd;
  689: 	size_t len = 0;
  690: 	register size_t off = 0;
  691: 	struct pollfd pfd = { s, POLLIN | POLLPRI, 0 };
  692: 
  693: 	if (!csFile || !recvLen)
  694: 		return 0;
  695: 	if (!over && !access(csFile, F_OK))
  696: 		return 0;
  697: 
  698: 	if (rcvbuf)
  699: 		if (setsockopt(s, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof rcvbuf) == -1) {
  700: 			LOGERR;
  701: 			return 0;
  702: 		}
  703: 
  704: 	fd = open(csFile, O_WRONLY | O_CREAT | O_TRUNC, over);
  705: 	if (fd == -1) {
  706: 		LOGERR;
  707: 		unlink(csFile);
  708: 		return 0;
  709: 	}
  710: 	if (ftruncate(fd, recvLen) == -1) {
  711: 		LOGERR;
  712: 		close(fd);
  713: 		unlink(csFile);
  714: 		return 0;
  715: 	}
  716: 	addr = mmap(NULL, recvLen, PROT_WRITE, MAP_SHARED, fd, 0);
  717: 	if (addr == MAP_FAILED) {
  718: 		LOGERR;
  719: 		close(fd);
  720: 		unlink(csFile);
  721: 		return 0;
  722: 	} else
  723: 		close(fd);
  724: 
  725: 	while (off < recvLen && poll(&pfd, 1, RECV_TIMEOUT) != -1)
  726: 		while (off < recvLen && (len = read(s, addr + off, recvLen - off)) != -1)
  727: 			off += len;
  728: 	if (len == -1) {
  729: 		LOGERR;
  730: 		munmap(addr, recvLen);
  731: 		unlink(csFile);
  732: 		return 0;
  733: 	} else
  734: 		len = off;
  735: 
  736: 	if (len != recvLen)
  737: 		io_SetErr(EAGAIN, "Different sizes - request %u bytes, actually received %u bytes\n", 
  738: 				recvLen, len);
  739: 
  740: 	munmap(addr, recvLen);
  741: 	return len;
  742: }

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