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