Annotation of libaitio/src/aitio.c, revision 1.10

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

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