This is a fun sample of creating your own extensible keyword. */
| 22 | |
| 23 | /* This is a fun sample of creating your own extensible keyword. */ |
| 24 | int fortune(call *call, MessageComponent *comp, char *buf, int len) |
| 25 | { |
| 26 | int pipes[2]; |
| 27 | char localbuf[SIPP_MAX_MSG_SIZE]; |
| 28 | char *p = localbuf; |
| 29 | int ret; |
| 30 | int written = 0; |
| 31 | |
| 32 | if (pipe(pipes) == -1) { |
| 33 | ERROR("Could not create pipes!"); |
| 34 | } |
| 35 | |
| 36 | switch (fork()) { |
| 37 | case -1: |
| 38 | ERROR("Fork failed: %s", strerror(errno)); |
| 39 | case 0: |
| 40 | /* We are the child. */ |
| 41 | close(pipes[0]); |
| 42 | dup2(pipes[1], fileno(stdout)); |
| 43 | dup2(pipes[1], fileno(stderr)); |
| 44 | close(fileno(stdin)); |
| 45 | system("/usr/bin/fortune"); |
| 46 | exit (127); |
| 47 | default: |
| 48 | /* We are the parent*/ |
| 49 | close(pipes[1]); |
| 50 | while ((ret = read(pipes[0], p, sizeof(localbuf) - (p - localbuf))) > 0) { |
| 51 | p += ret; |
| 52 | } |
| 53 | *p = '\0'; |
| 54 | close(pipes[0]); |
| 55 | |
| 56 | if (len > p - localbuf) { |
| 57 | len = p -localbuf; |
| 58 | } |
| 59 | |
| 60 | p = localbuf; |
| 61 | while(len-- > 0) { |
| 62 | if (*p == '\n') { |
| 63 | if (len < 3) { |
| 64 | break; |
| 65 | } |
| 66 | *buf++ = '\r'; |
| 67 | *buf++ = '\n'; |
| 68 | *buf++ = ' '; |
| 69 | written += 3; |
| 70 | p++; |
| 71 | } else { |
| 72 | *buf++ = *p++; |
| 73 | written++; |
| 74 | } |
| 75 | } |
| 76 | break; |
| 77 | } |
| 78 | |
| 79 | return written; |
| 80 | } |
| 81 |