repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
i-vishi/ds-and-algo
|
Sort - Selection/C/selectionSort.c
|
/* Author: <NAME>
* Created: 03-01-2021 22:02:06
*/
#include <stdio.h>
// function to sort an array using selection sort
void selectionSort(int a[], int n)
{
for (int i = 0; i < n - 1; i++)
{
int minIdx = i;
for (int j = i + 1; j < n; j++)
{
if (a[j] < a[minIdx])
minIdx = j;
}
if (minIdx != i)
{
int tmp = a[i];
a[i] = a[minIdx];
a[minIdx] = tmp;
}
}
}
// main function to test above function
int main()
{
int arr[] = {12, 58, 40, 16, 49, 26, 24};
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted Array :\t");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
|
i-vishi/ds-and-algo
|
Search - Linear/C/linearSearch.c
|
/* Author: <NAME>
* Created: 03-01-2021 21:09:12
*/
#include <stdio.h>
// function to search an element using linear seaching
int linearSearch(int a[], int n, int x)
{
for (int i = 0; i < n; i++)
{
if (a[i] == x)
return i;
}
return -1;
}
// main function to test above function
int main()
{
int arr[] = {45, 65, 85, 12, 35, 97, 1, 7, 19};
int n = sizeof(arr) / sizeof(arr[0]);
int x, res;
x = 19;
res = linearSearch(arr, n, x);
if (res >= 0)
printf("%d found at index %d\n", x, res);
else
printf("%d not found!\n", x);
x = 10;
res = linearSearch(arr, n, x);
if (res >= 0)
printf("%d found at index %d\n", x, res);
else
printf("%d not found!\n", x);
return 0;
}
|
i-vishi/ds-and-algo
|
Sort - Insertion/C/insertionSort.c
|
/* Author: <NAME>
* Created: 03-01-2021 21:47:23
*/
#include <stdio.h>
// function to sort an array using insertion sort
void insertionSort(int a[], int n)
{
for (int i = 1; i < n; i++)
{
for (int j = i; j > 0; j--)
{
if (a[j - 1] > a[j])
{
int tmp = a[j];
a[j] = a[j - 1];
a[j - 1] = tmp;
}
else
break;
}
}
}
// main function to test above function
int main()
{
int arr[] = {12, 58, 40, 16, 49, 26, 24};
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
printf("Sorted Array :\t");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
|
i-vishi/ds-and-algo
|
Search - Binary/C/binarySearch.c
|
/* Author: <NAME>
* Created: 02-01-2021 14:07:21
*/
#include <stdio.h>
// function to search an element using binary seaching
int binarySearch(int a[], int n, int x)
{
int st = 0, ed = n - 1;
while (st <= ed)
{
int mid = st + (ed - st) / 2;
if (a[mid] == x)
return mid;
if (a[mid] < x)
st = mid + 1;
else
ed = mid - 1;
}
return -1;
}
// main function to test above function
int main()
{
int arr[] = {11, 16, 25, 78, 89, 120};
int n = sizeof(arr) / sizeof(arr[0]);
int x, res;
x = 78;
res = binarySearch(arr, n, x);
if (res >= 0)
printf("%d found at index %d\n", x, res);
else
printf("%d not found!\n", x);
x = 10;
res = binarySearch(arr, n, x);
if (res >= 0)
printf("%d found at index %d\n", x, res);
else
printf("%d not found!\n", x);
return 0;
}
|
i-vishi/ds-and-algo
|
DP - Rod Cutting/C/rodCutting.c
|
/* Author: <NAME>
* Created: 04-01-2021 20:32:21
*/
#include <stdio.h>
// function to find best obtainable price
int rodCutting(int values[], int n)
{
int pro[n + 1];
pro[0] = 0;
for (int i = 1; i <= n; i++)
{
int mx = -1;
for (int j = 0; j < i; j++)
{
int sm = values[j] + pro[i - j - 1];
if (sm > mx)
mx = sm;
}
pro[i] = mx;
}
return pro[n];
}
// main function to test above function
int main()
{
int values[] = {3, 6, 8, 10, 14, 16};
int len = sizeof(values) / sizeof(values[0]);
printf("Maximum obtainable price would be %d\n", rodCutting(values, len));
return 0;
}
|
i-vishi/ds-and-algo
|
Sort - Bubble/C/bubbleSort.c
|
<reponame>i-vishi/ds-and-algo
/* Author: <NAME>
* Created: 01-01-2021 13:15:32
*/
#include <stdio.h>
// function to sort an array using bubble sort
void bubbleSort(int a[], int n)
{
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (a[j] > a[j + 1])
{
int tmp = a[j];
a[j] = a[j + 1];
a[j + 1] = tmp;
}
}
}
}
// main function to test above function
int main()
{
int arr[] = {31, 56, 25, 78, 19, 20};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted Array :\t");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
|
i-vishi/ds-and-algo
|
Hello World/C/hello.c
|
<gh_stars>1-10
/* Author: <NAME>
* Created: 01-01-2021 13:02:07
*/
#include <stdio.h>
int main()
{
printf("Hello World\n");
return 0;
}
|
i-vishi/ds-and-algo
|
GCD - Euclidean (Basic)/C/gcdEuclid.c
|
<reponame>i-vishi/ds-and-algo
/* Author: <NAME>
* Created: 23-01-2021 21:50:34
*/
#include <stdio.h>
// function to find GCD using Basic Euclidean Algorithm
int gcdEuclid(int a, int b)
{
if (a == 0)
return b;
else
return gcdEuclid(b % a, a);
}
// main function to test above function
int main()
{
int a, b, g;
a = 35, b = 217;
g = gcdEuclid(a, b);
printf("GCD of %d & %d is: %d\n", a, b, g);
a = 24, b = 5;
g = gcdEuclid(a, b);
printf("GCD of %d & %d is: %d\n", a, b, g);
return 0;
}
|
abs-tudelft/fletcher-snap
|
examples/stringwrite/sw/snap_stringwrite.c
|
<filename>examples/stringwrite/sw/snap_stringwrite.c
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <errno.h>
#include <malloc.h>
#include <unistd.h>
#include <sys/time.h>
#include <getopt.h>
#include <ctype.h>
#include <libsnap.h>
#include <snap_tools.h>
#include <snap_s_regs.h>
#include "snap_stringwrite.h"
#include <omp.h>
#define LOG(...) fprintf(log, __VA_ARGS__); fflush(log);
/* Structure to easily convert from 64-bit addresses to 2x32-bit registers */
typedef struct _lohi {
uint32_t lo;
uint32_t hi;
}
lohi;
typedef union _addr_lohi {
uint64_t full;
lohi half;
}
addr_lohi;
int initialize_snap(struct snap_card **device, struct snap_action **action, FILE *log) {
int rc = 0;
uint64_t cir;
char device_name[64];
int card_no = 0;
unsigned long ioctl_data;
snap_action_flag_t attach_flags = 0;
sprintf(device_name, "/dev/cxl/afu%d.0s", card_no);
*device = snap_card_alloc_dev(device_name, SNAP_VENDOR_ID_IBM, SNAP_DEVICE_ID_SNAP);
if (device == NULL) {
errno = ENODEV;
fprintf(log, "ERROR: snap_card_alloc_dev(%s)\n", device_name);
return -1;
}
/// Read Card Capabilities
snap_card_ioctl(*device, GET_CARD_TYPE, (unsigned long) &ioctl_data);
LOG("SNAP on ");
switch (ioctl_data) {
case 0:fprintf(log, "ADKU3");
break;
case 1:fprintf(log, "N250S");
break;
case 16:fprintf(log, "N250SP");
break;
default:fprintf(log, "Unknown");
break;
}
snap_card_ioctl(*device, GET_SDRAM_SIZE, (unsigned long) &ioctl_data);
LOG(" Card, %d MB of Card Ram avilable.\n", (int) ioctl_data);
snap_mmio_read64(*device, SNAP_S_CIR, &cir);
LOG("Read from MMIO. Attaching action.\n");
// Attach action
*action = snap_attach_action(*device, ACTION_TYPE_EXAMPLE, attach_flags, 100);
if (*action == NULL) {
errno = ENODEV;
fprintf(log, "ERROR: snap_attach_action(%s)\n", device_name);
return -1;
}
LOG("Action attached.\n");
return rc;
}
int terminate_snap(struct snap_card *device, struct snap_action *action, FILE *log) {
LOG("Detaching action...\n");
snap_detach_action(action);
LOG("Detaching freeing card...\n");
snap_card_free(device);
return 0;
}
int allocate_buffers(uint32_t **off_buf, char **val_buf, int num_strings, int strlen_max, FILE *log) {
int rc;
// Create offsets buffer
LOG("Allocating %lu for offsets buffer.\n", sizeof(uint32_t) * (num_strings + 1));
rc = posix_memalign((void **) off_buf, BURST_LENGTH, sizeof(uint32_t) * (num_strings + 1));
// Clear offset buffer
for (uint32_t i = 0; i < num_strings + 1; i++) {
(*off_buf)[i] = 0xDEADBEEF;
}
// Create value buffer
uint32_t num_chars = strlen_max * num_strings;
LOG("Allocated %lu for values buffer.\n", sizeof(char) * num_chars);
rc = posix_memalign((void **) val_buf, BURST_LENGTH, sizeof(char) * num_chars);
// Clear values buffer
for (uint32_t i = 0; i < num_chars; i++) {
(*val_buf)[i] = '\0';
}
return rc;
}
int main(int argc, char *argv[]) {
// Log to a file.
FILE *log = fopen("swlog.log", "w");
// Program parameters
uint32_t num_strings = 16; /// Number of rows (strings) in the recordbatch
uint32_t strlen_min = 0; /// Minimum string length
uint32_t strlen_mask = 255; /// Mask for PRNG unit, str length is strlen_min + [prng] & strlen_mask
uint32_t strlen_max = 256; /// Number of bytes to allocate per string
// Parse optional arguments
if (argc > 1) sscanf(argv[1], "%u", &num_strings);
if (argc > 2) sscanf(argv[2], "%u", &strlen_min);
if (argc > 3) sscanf(argv[3], "%u", &strlen_mask);
// Initialize SNAP platform.
int rc = 0;
struct snap_card *device = NULL;
struct snap_action *action = NULL;
rc = initialize_snap(&device, &action, log);
if (rc != 0) {
LOG("ERROR: initialize_snap failed. RC=%d\n", rc);
return (-1);
}
// Allocate Arrow buffers.
uint32_t *off_buf = NULL;
char *val_buf = NULL;
allocate_buffers(&off_buf, &val_buf, num_strings, strlen_max, log);
// Prepare addresses for registers.
addr_lohi off, val;
off.full = (uint64_t) off_buf;
val.full = (uint64_t) val_buf;
LOG("Offsets buffer @ %016lX\n", off.full);
LOG("Values buffer @ %016lX\n", val.full);
LOG("Setting control registers...\n");
snap_mmio_write32(device, REG_CONTROL, CONTROL_RESET);
snap_mmio_write32(device, REG_CONTROL, 0);
snap_mmio_write32(device, REG_OFF_ADDR_LO, off.half.lo);
snap_mmio_write32(device, REG_OFF_ADDR_HI, off.half.hi);
snap_mmio_write32(device, REG_UTF8_ADDR_LO, val.half.lo);
snap_mmio_write32(device, REG_UTF8_ADDR_HI, val.half.hi);
snap_mmio_write32(device, REG_FIRST_IDX, 0);
snap_mmio_write32(device, REG_LAST_IDX, num_strings);
snap_mmio_write32(device, REG_STRLEN_MIN, strlen_min);
snap_mmio_write32(device, REG_PRNG_MASK, strlen_mask);
LOG("Registers set, starting kernel and polling for completion...\n");
double start = omp_get_wtime();
// Starting occurs when control start bit was high, then goes low.
snap_mmio_write32(device, REG_CONTROL, CONTROL_START);
snap_mmio_write32(device, REG_CONTROL, CONTROL_STOP);
// Poll for completion.
uint32_t status = 0;
uint32_t last_off = 0xDEADBEEF;
do {
snap_mmio_read32(device, REG_STATUS, &status);
LOG("S: %08X\n", status);
sleep(1);
} while ((status & STATUS_DONE) != STATUS_DONE);
double stop = omp_get_wtime();
LOG("Time: %f\n", stop - start);
// Print offsets buffer.
for (uint32_t i = 0; i < num_strings + 1; i++) {
LOG("%8u: %u\n", i, off_buf[i]);
}
// Get the last offset
last_off = off_buf[num_strings];
LOG("Last offset: %d\n", last_off);
uint64_t total_bytes = num_strings * sizeof(uint32_t) + last_off;
double total_time = stop - start;
double gib = (double) (num_strings * sizeof(uint32_t) + last_off) / (double) (1 << 30);
double gbps = (double) total_bytes / total_time * 1E-9;
LOG("Total bytes written: %lu\n", num_strings * sizeof(uint32_t) + last_off);
LOG("%f GiB\n", gib);
LOG("Throughput: %f\n", (double) total_bytes / total_time);
LOG("%f GB/s\n", gbps);
LOG("Last char: %2X ... %c\n", (int) val_buf[last_off - 1], val_buf[last_off - 1]);
printf("%u, %u, %u, %u, %lu, %f, %f, %f\n",
strlen_min,
strlen_mask,
strlen_max,
num_strings,
total_bytes,
total_time,
gib,
gbps);
// print values buffer
for (uint32_t i = 0; i < last_off;) {
uint32_t j = i;
LOG("%8u: ", i);
for (j = i;
(j < i + 16) && (j < last_off); j++) {
LOG("%2X ", (int) val_buf[j]);
}
LOG(" ");
for (j = i;
(j < i + 16) && (j < last_off); j++) {
LOG("%c", val_buf[j]);
}
LOG("\n");
i = j;
}
terminate_snap(device, action, log);
LOG("Freeing offsets buffer...\n");
free(off_buf);
LOG("Freeing values buffer...\n");
free(val_buf);
return 0;
}
|
alexwinger/bottle_filler
|
FlowMeter.h
|
/*
*
*
*/
#ifndef _FLOW_METER_
#define _FLOW_METER_
class flow_meter
{
static flow_meter *instance;
int sensor_pin;
volatile int pulse_count;
static void count_pulses();
public:
flow_meter(int input_pin);
};
#endif
|
catroll/mailx
|
src/su/prime.c
|
/*@ Implementation of prime.h.
*
* Copyright (c) 2001 - 2020 <NAME>) Nurpmeso <<EMAIL>>.
* SPDX-License-Identifier: ISC
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#undef su_FILE
#define su_FILE su_prime
#define su_SOURCE
#define su_SOURCE_PRIME
#include "su/code.h"
#include "su/prime.h"
#include "su/code-in.h"
/* Collected & merged from 'GLIB 1's 'gprimes.c' and 'GNU STL's 'hashtable'
* (around Y2K+1 or so) */
static u32 const a_prime_lookup[] = {
0x00000002, 0x00000005, 0x0000000B,
0x00000017, 0x0000002F, 0x00000061, 0x0000009D,
0x0000011B, 0x0000022D, 0x00000337, 0x000004D5, 0x00000741, 0x00000AD9,
0x00001051, 0x00001867, 0x0000249B, 0x000036E9, 0x00005261, 0x00007B8B,
0x0000B947,
0x000115E7, 0x0001A0E1, 0x00027149, 0x0003A9E5, 0x00057EE3, 0x00083E39,
0x000C5D67,
0x00128C09, 0x001BD1FF, 0x0029BB13, 0x003E988B, 0x005DE4C1, 0x008CD721,
0x00D342AB,
0x01800013, 0x03000005, 0x06000017, 0x0C000013,
0x18000005
};
#define a_PRIME_FIRST &a_prime_lookup[0]
#define a_PRIME_MIDDLE &a_prime_lookup[NELEM(a_prime_lookup) / 2]
#define a_PRIME_LAST &a_prime_lookup[NELEM(a_prime_lookup) - 1]
static u64 const a_prime_max = su_U64_C(0xFFFFFFFFFFFFFFFD);
/* */
static boole a_prime_is_pseudo(u64 no);
static boole a_prime_is_real(u64 no);
/* */
static u64 a_prime_calc(u64 no, sz add, boole pseudo_ok);
static boole
a_prime_is_pseudo(u64 no){
boole rv;
NYD_IN;
switch(no){
case 2:
case 3:
case 5:
case 7:
rv = TRU1; break;
case 0:
case 1:
case 4:
case 6:
rv = FAL0; break;
default:
rv = ((no & 1) && (no % 3) && (no % 5) && (no % 7));
break;
}
NYD_OU;
return rv;
}
static boole
a_prime_is_real(u64 no){ /* TODO brute force yet (at least Miller-Rabin?) */
/* no is pseudo! */
union {uz x; u64 x64; boole rv;} u;
NYD_IN;
if(no < 2)
goto jfal;
if(no != 2)
for(u.x64 = 3; u.x64 < no; u.x64 += 2)
if(no % u.x64 == 0)
goto jfal;
u.rv = TRU1;
jleave:
NYD_OU;
return u.rv;
jfal:
u.rv = FAL0;
goto jleave;
}
static u64
a_prime_calc(u64 no, sz add, boole pseudo_ok){
NYD_IN;
/* Primes are all odd (except 2 but that is NEVER evaluated in here) */
if(!(no & 1)){
no += add;
add <<= 1;
goto jdiver;
}
add <<= 1;
for(;;){
no += add;
jdiver:
if(!a_prime_is_pseudo(no))
continue;
if(pseudo_ok || a_prime_is_real(no))
break;
}
NYD_OU;
return no;
}
boole
su_prime_is_prime(u64 no, boole allowpseudo){
boole rv;
NYD_IN;
rv = a_prime_is_pseudo(no);
if(rv && !allowpseudo)
rv = a_prime_is_real(no);
NYD_OU;
return rv;
}
u64
su_prime_get_former(u64 no, boole allowpseudo){
NYD_IN;
if(no <= 2 + 1)
no = 2;
else if(no > a_prime_max)
no = a_prime_max;
else
no = a_prime_calc(no, -1, allowpseudo);
NYD_OU;
return no;
}
u64
su_prime_get_next(u64 no, boole allowpseudo){
NYD_IN;
if(no < 2)
no = 2;
else if(no >= a_prime_max - 2)
no = a_prime_max;
else
no = a_prime_calc(no, +1, allowpseudo);
NYD_OU;
return no;
}
u32
su_prime_lookup_former(u32 no){
u32 const *cursor;
NYD_IN;
cursor = ((no < *a_PRIME_MIDDLE) ? a_PRIME_MIDDLE - 1 : a_PRIME_LAST);
while(*cursor >= no && --cursor > a_PRIME_FIRST)
;
NYD_OU;
return *cursor;
}
u32
su_prime_lookup_next(u32 no){
u32 const *cursor;
NYD_IN;
cursor = ((no > *a_PRIME_MIDDLE) ? a_PRIME_MIDDLE + 1 : a_PRIME_FIRST);
while(*cursor <= no && ++cursor < a_PRIME_LAST)
;
NYD_OU;
return *cursor;
}
#include "su/code-ou.h"
/* s-it-mode */
|
catroll/mailx
|
src/mx/imap-search.c
|
<filename>src/mx/imap-search.c
/*@ S-nail - a mail user agent derived from Berkeley Mail.
*@ Client-side implementation of the IMAP SEARCH command. This is used
*@ for folders not located on IMAP servers, or for IMAP servers that do
*@ not implement the SEARCH command.
*
* Copyright (c) 2000-2004 <NAME>, Freiburg i. Br., Germany.
* Copyright (c) 2012 - 2020 Steffen (Daode) Nurpmeso <<EMAIL>>.
* SPDX-License-Identifier: BSD-4-Clause
*/
/*
* Copyright (c) 2004
* <NAME>. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by <NAME>
* and his contributors.
* 4. Neither the name of <NAME> nor the names of his contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY GUNNAR RITTER AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL GUNNAR RITTER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#undef su_FILE
#define su_FILE imap_search
#define mx_SOURCE
#ifndef mx_HAVE_AMALGAMATION
# include "mx/nail.h"
#endif
su_EMPTY_FILE()
#ifdef mx_HAVE_IMAP_SEARCH
#include <su/cs.h>
#include <su/icodec.h>
#include <su/mem.h>
#include "mx/file-streams.h"
#include "mx/names.h"
/* TODO fake */
#include "su/code-in.h"
enum itoken {
ITBAD, ITEOD, ITBOL, ITEOL, ITAND, ITSET, ITALL, ITANSWERED,
ITBCC, ITBEFORE, ITBODY,
ITCC,
ITDELETED, ITDRAFT,
ITFLAGGED, ITFROM,
ITHEADER,
ITKEYWORD,
ITLARGER,
ITNEW, ITNOT,
ITOLD, ITON, ITOR,
ITRECENT,
ITSEEN, ITSENTBEFORE, ITSENTON, ITSENTSINCE, ITSINCE, ITSMALLER,
ITSUBJECT,
ITTEXT, ITTO,
ITUID, ITUNANSWERED, ITUNDELETED, ITUNDRAFT, ITUNFLAGGED, ITUNKEYWORD,
ITUNSEEN
};
struct itlex {
char const *s_string;
enum itoken s_token;
};
struct itnode {
enum itoken n_token;
uz n_n;
void *n_v;
void *n_w;
struct itnode *n_x;
struct itnode *n_y;
};
static struct itlex const _it_strings[] = {
{ "ALL", ITALL },
{ "ANSWERED", ITANSWERED },
{ "BCC", ITBCC },
{ "BEFORE", ITBEFORE },
{ "BODY", ITBODY },
{ "CC", ITCC },
{ "DELETED", ITDELETED },
{ "DRAFT", ITDRAFT },
{ "FLAGGED", ITFLAGGED },
{ "FROM", ITFROM },
{ "HEADER", ITHEADER },
{ "KEYWORD", ITKEYWORD },
{ "LARGER", ITLARGER },
{ "NEW", ITNEW },
{ "NOT", ITNOT },
{ "OLD", ITOLD },
{ "ON", ITON },
{ "OR", ITOR },
{ "RECENT", ITRECENT },
{ "SEEN", ITSEEN },
{ "SENTBEFORE", ITSENTBEFORE },
{ "SENTON", ITSENTON },
{ "SENTSINCE", ITSENTSINCE },
{ "SINCE", ITSINCE },
{ "SMALLER", ITSMALLER },
{ "SUBJECT", ITSUBJECT },
{ "TEXT", ITTEXT },
{ "TO", ITTO },
{ "UID", ITUID },
{ "UNANSWERED", ITUNANSWERED },
{ "UNDELETED", ITUNDELETED },
{ "UNDRAFT", ITUNDRAFT },
{ "UNFLAGGED", ITUNFLAGGED },
{ "UNKEYWORD", ITUNKEYWORD },
{ "UNSEEN", ITUNSEEN },
{ NULL, ITBAD }
};
static struct itnode *_it_tree;
static char *_it_begin;
static enum itoken _it_token;
static uz _it_number;
static void *_it_args[2];
static uz _it_need_headers;
static enum okay itparse(char const *spec, char const **xp, int sub);
static enum okay itscan(char const *spec, char const **xp);
static enum okay itsplit(char const *spec, char const **xp);
static enum okay itstring(void **tp, char const *spec, char const **xp);
static int itexecute(struct mailbox *mp, struct message *m,
uz c, struct itnode *n);
static time_t _imap_read_date(char const *cp);
static char * _imap_quotestr(char const *s);
static char * _imap_unquotestr(char const *s);
static boole matchfield(struct message *m, char const *field,
void const *what);
static int matchenvelope(struct message *m, char const *field,
void const *what);
static char * mkenvelope(struct mx_name *np);
static char const * around(char const *cp);
static enum okay
itparse(char const *spec, char const **xp, int sub)
{
int level = 0;
struct itnode n, *z, *ittree;
enum okay rv;
NYD_IN;
_it_tree = NULL;
while ((rv = itscan(spec, xp)) == OKAY && _it_token != ITBAD &&
_it_token != ITEOD) {
ittree = _it_tree;
su_mem_set(&n, 0, sizeof n);
spec = *xp;
switch (_it_token) {
case ITBOL:
++level;
continue;
case ITEOL:
if (--level == 0)
goto jleave;
if (level < 0) {
if (sub > 0) {
--(*xp);
goto jleave;
}
n_err(_("Excess in )\n"));
rv = STOP;
goto jleave;
}
continue;
case ITNOT:
/* <search-key> */
n.n_token = ITNOT;
if ((rv = itparse(spec, xp, sub + 1)) == STOP)
goto jleave;
spec = *xp;
if ((n.n_x = _it_tree) == NULL) {
n_err(_("Criterion for NOT missing: >>> %s <<<\n"), around(*xp));
rv = STOP;
goto jleave;
}
_it_token = ITNOT;
break;
case ITOR:
/* <search-key1> <search-key2> */
n.n_token = ITOR;
if ((rv = itparse(spec, xp, sub + 1)) == STOP)
goto jleave;
if ((n.n_x = _it_tree) == NULL) {
n_err(_("First criterion for OR missing: >>> %s <<<\n"),
around(*xp));
rv = STOP;
goto jleave;
}
spec = *xp;
if ((rv = itparse(spec, xp, sub + 1)) == STOP)
goto jleave;
spec = *xp;
if ((n.n_y = _it_tree) == NULL) {
n_err(_("Second criterion for OR missing: >>> %s <<<\n"),
around(*xp));
rv = STOP;
goto jleave;
}
break;
default:
n.n_token = _it_token;
n.n_n = _it_number;
n.n_v = _it_args[0];
n.n_w = _it_args[1];
}
_it_tree = ittree;
if (_it_tree == NULL) {
_it_tree = n_autorec_alloc(sizeof *_it_tree);
*_it_tree = n;
} else {
z = _it_tree;
_it_tree = n_autorec_alloc(sizeof *_it_tree);
_it_tree->n_token = ITAND;
_it_tree->n_x = z;
_it_tree->n_y = n_autorec_alloc(sizeof *_it_tree->n_y);
*_it_tree->n_y = n;
}
if (sub && level == 0)
break;
}
jleave:
NYD_OU;
return rv;
}
static enum okay
itscan(char const *spec, char const **xp)
{
int i, n;
enum okay rv = OKAY;
NYD_IN;
while (su_cs_is_space(*spec))
++spec;
if (*spec == '(') {
*xp = &spec[1];
_it_token = ITBOL;
goto jleave;
}
if (*spec == ')') {
*xp = &spec[1];
_it_token = ITEOL;
goto jleave;
}
while (su_cs_is_space(*spec))
++spec;
if (*spec == '\0') {
_it_token = ITEOD;
goto jleave;
}
#define __GO(C) ((C) != '\0' && (C) != '(' && (C) != ')' && !su_cs_is_space(C))
for (i = 0; _it_strings[i].s_string != NULL; ++i) {
n = su_cs_len(_it_strings[i].s_string);
if (!su_cs_cmp_case_n(spec, _it_strings[i].s_string, n) &&
!__GO(spec[n])) {
_it_token = _it_strings[i].s_token;
spec += n;
while (su_cs_is_space(*spec))
++spec;
rv = itsplit(spec, xp);
goto jleave;
}
}
if (su_cs_is_digit(*spec)) {
su_idec_uz_cp(&_it_number, spec, 10, xp);
if (!__GO(**xp)) {
_it_token = ITSET;
goto jleave;
}
}
n_err(_("Bad SEARCH criterion: "));
for (i = 0; __GO(spec[i]); ++i)
;
n_err(_("%.*s: >>> %s <<<\n"), i, spec, around(*xp));
#undef __GO
_it_token = ITBAD;
rv = STOP;
jleave:
NYD_OU;
return rv;
}
static enum okay
itsplit(char const *spec, char const **xp)
{
char const *cp;
time_t t;
enum okay rv;
NYD_IN;
switch (_it_token) {
case ITBCC:
case ITBODY:
case ITCC:
case ITFROM:
case ITSUBJECT:
case ITTEXT:
case ITTO:
/* <string> */
++_it_need_headers;
rv = itstring(_it_args, spec, xp);
break;
case ITSENTBEFORE:
case ITSENTON:
case ITSENTSINCE:
++_it_need_headers;
/*FALLTHRU*/
case ITBEFORE:
case ITON:
case ITSINCE:
/* <date> */
if ((rv = itstring(_it_args, spec, xp)) != OKAY)
break;
if ((t = _imap_read_date(_it_args[0])) == (time_t)-1) {
n_err(_("Invalid date %s: >>> %s <<<\n"),
(char*)_it_args[0], around(*xp));
rv = STOP;
break;
}
_it_number = t;
rv = OKAY;
break;
case ITHEADER:
/* <field-name> <string> */
++_it_need_headers;
if ((rv = itstring(_it_args, spec, xp)) != OKAY)
break;
spec = *xp;
if ((rv = itstring(_it_args + 1, spec, xp)) != OKAY)
break;
break;
case ITKEYWORD:
case ITUNKEYWORD:
/* <flag> */ /* TODO use table->flag map search instead */
if ((rv = itstring(_it_args, spec, xp)) != OKAY)
break;
if (!su_cs_cmp_case(_it_args[0], "\\Seen"))
_it_number = MREAD;
else if (!su_cs_cmp_case(_it_args[0], "\\Deleted"))
_it_number = MDELETED;
else if (!su_cs_cmp_case(_it_args[0], "\\Recent"))
_it_number = MNEW;
else if (!su_cs_cmp_case(_it_args[0], "\\Flagged"))
_it_number = MFLAGGED;
else if (!su_cs_cmp_case(_it_args[0], "\\Answered"))
_it_number = MANSWERED;
else if (!su_cs_cmp_case(_it_args[0], "\\Draft"))
_it_number = MDRAFT;
else
_it_number = 0;
break;
case ITLARGER:
case ITSMALLER:
/* <n> */
if ((rv = itstring(_it_args, spec, xp)) != OKAY)
break;
else{
su_idec_uz_cp(&_it_number, _it_args[0], 10, &cp);
}
if (su_cs_is_space(*cp) || *cp == '\0')
break;
n_err(_("Invalid size: >>> %s <<<\n"), around(*xp));
rv = STOP;
break;
case ITUID:
/* <message set> */
n_err(_("Searching for UIDs is not supported: >>> %s <<<\n"),
around(*xp));
rv = STOP;
break;
default:
*xp = spec;
rv = OKAY;
break;
}
NYD_OU;
return rv;
}
static enum okay
itstring(void **tp, char const *spec, char const **xp) /* XXX lesser derefs */
{
int inquote = 0;
char *ap;
enum okay rv = STOP;
NYD_IN;
while (su_cs_is_space(*spec))
++spec;
if (*spec == '\0' || *spec == '(' || *spec == ')') {
n_err(_("Missing string argument: >>> %s <<<\n"),
around(&(*xp)[spec - *xp]));
goto jleave;
}
ap = *tp = n_autorec_alloc(su_cs_len(spec) +1);
*xp = spec;
do {
if (inquote && **xp == '\\')
*ap++ = *(*xp)++;
else if (**xp == '"')
inquote = !inquote;
else if (!inquote &&
(su_cs_is_space(**xp) || **xp == '(' || **xp == ')')) {
*ap++ = '\0';
break;
}
*ap++ = **xp;
} while (*(*xp)++);
*tp = _imap_unquotestr(*tp);
rv = OKAY;
jleave:
NYD_OU;
return rv;
}
static int
itexecute(struct mailbox *mp, struct message *m, uz c, struct itnode *n)
{
struct search_expr se;
char *cp;
FILE *ibuf;
int rv;
NYD_IN;
if (n == NULL) {
n_err(_("Internal error: Empty node in SEARCH tree\n"));
rv = 0;
goto jleave;
}
switch (n->n_token) {
case ITBEFORE:
case ITON:
case ITSINCE:
if (m->m_time == 0 && !(m->m_flag & MNOFROM) &&
(ibuf = setinput(mp, m, NEED_HEADER)) != NULL) {
char *line;
uz linesize;
mx_fs_linepool_aquire(&line, &linesize);
if (readline_restart(ibuf, &line, &linesize, 0) > 0)
m->m_time = unixtime(line);
mx_fs_linepool_release(line, linesize);
}
break;
case ITSENTBEFORE:
case ITSENTON:
case ITSENTSINCE:
if (m->m_date == 0)
if ((cp = hfield1("date", m)) != NULL)
m->m_date = rfctime(cp);
break;
default:
break;
}
switch (n->n_token) {
default:
n_err(_("Internal SEARCH error: Lost token %d\n"), n->n_token);
rv = 0;
break;
case ITAND:
rv = itexecute(mp, m, c, n->n_x) & itexecute(mp, m, c, n->n_y);
break;
case ITSET:
rv = (c == n->n_n);
break;
case ITALL:
rv = 1;
break;
case ITANSWERED:
rv = ((m->m_flag & MANSWERED) != 0);
break;
case ITBCC:
rv = matchenvelope(m, "bcc", n->n_v);
break;
case ITBEFORE:
rv = UCMP(z, m->m_time, <, n->n_n);
break;
case ITBODY:
su_mem_set(&se, 0, sizeof se);
se.ss_field = "body";
se.ss_body = n->n_v;
rv = message_match(m, &se, FAL0);
break;
case ITCC:
rv = matchenvelope(m, "cc", n->n_v);
break;
case ITDELETED:
rv = ((m->m_flag & MDELETED) != 0);
break;
case ITDRAFT:
rv = ((m->m_flag & MDRAFTED) != 0);
break;
case ITFLAGGED:
rv = ((m->m_flag & MFLAGGED) != 0);
break;
case ITFROM:
rv = matchenvelope(m, "from", n->n_v);
break;
case ITHEADER:
rv = matchfield(m, n->n_v, n->n_w);
break;
case ITKEYWORD:
rv = ((m->m_flag & n->n_n) != 0);
break;
case ITLARGER:
rv = (m->m_xsize > n->n_n);
break;
case ITNEW:
rv = ((m->m_flag & (MNEW | MREAD)) == MNEW);
break;
case ITNOT:
rv = !itexecute(mp, m, c, n->n_x);
break;
case ITOLD:
rv = !(m->m_flag & MNEW);
break;
case ITON:
rv = (UCMP(z, m->m_time, >=, n->n_n) &&
UCMP(z, m->m_time, <, n->n_n + 86400));
break;
case ITOR:
rv = itexecute(mp, m, c, n->n_x) | itexecute(mp, m, c, n->n_y);
break;
case ITRECENT:
rv = ((m->m_flag & MNEW) != 0);
break;
case ITSEEN:
rv = ((m->m_flag & MREAD) != 0);
break;
case ITSENTBEFORE:
rv = UCMP(z, m->m_date, <, n->n_n);
break;
case ITSENTON:
rv = (UCMP(z, m->m_date, >=, n->n_n) &&
UCMP(z, m->m_date, <, n->n_n + 86400));
break;
case ITSENTSINCE:
rv = UCMP(z, m->m_date, >=, n->n_n);
break;
case ITSINCE:
rv = UCMP(z, m->m_time, >=, n->n_n);
break;
case ITSMALLER:
rv = UCMP(z, m->m_xsize, <, n->n_n);
break;
case ITSUBJECT:
rv = matchfield(m, "subject", n->n_v);
break;
case ITTEXT:
su_mem_set(&se, 0, sizeof se);
se.ss_field = "text";
se.ss_body = n->n_v;
rv = message_match(m, &se, TRU1);
break;
case ITTO:
rv = matchenvelope(m, "to", n->n_v);
break;
case ITUNANSWERED:
rv = !(m->m_flag & MANSWERED);
break;
case ITUNDELETED:
rv = !(m->m_flag & MDELETED);
break;
case ITUNDRAFT:
rv = !(m->m_flag & MDRAFTED);
break;
case ITUNFLAGGED:
rv = !(m->m_flag & MFLAGGED);
break;
case ITUNKEYWORD:
rv = !(m->m_flag & n->n_n);
break;
case ITUNSEEN:
rv = !(m->m_flag & MREAD);
break;
}
jleave:
NYD_OU;
return rv;
}
static time_t
_imap_read_date(char const *cp)
{
time_t t;
s32 year, month, day, i;
char const *xp, *yp;
NYD_IN;
if (*cp == '"')
++cp;
su_idec_s32_cp(&day, cp, 10, &xp);
if (day <= 0 || day > 31 || *xp++ != '-')
goto jerr;
for (i = 0;;) {
if (!su_cs_cmp_case_n(xp, n_month_names[i], 3))
break;
if (n_month_names[++i][0] == '\0')
goto jerr;
}
month = i + 1;
if (xp[3] != '-')
goto jerr;
su_idec_s32_cp(&year, &xp[4], 10, &yp);
if (year < 1970 || year > 2037 || PCMP(yp, !=, xp + 8))
goto jerr;
if (yp[0] != '\0' && (yp[1] != '"' || yp[2] != '\0'))
goto jerr;
if((t = combinetime(year, month, day, 0, 0, 0)) == (time_t)-1)
goto jleave/*jerr*/;
t += n_time_tzdiff(t, NIL, NIL);
jleave:
NYD_OU;
return t;
jerr:
t = (time_t)-1;
goto jleave;
}
static char *
_imap_quotestr(char const *s)
{
char *n, *np;
NYD2_IN;
np = n = n_autorec_alloc(2 * su_cs_len(s) + 3);
*np++ = '"';
while (*s) {
if (*s == '"' || *s == '\\')
*np++ = '\\';
*np++ = *s++;
}
*np++ = '"';
*np = '\0';
NYD2_OU;
return n;
}
static char *
_imap_unquotestr(char const *s)
{
char *n, *np;
NYD2_IN;
if (*s != '"') {
n = savestr(s);
goto jleave;
}
np = n = n_autorec_alloc(su_cs_len(s) + 1);
while (*++s) {
if (*s == '\\')
s++;
else if (*s == '"')
break;
*np++ = *s;
}
*np = '\0';
jleave:
NYD2_OU;
return n;
}
static boole
matchfield(struct message *m, char const *field, void const *what)
{
struct str in, out;
boole rv = FAL0;
NYD_IN;
if ((in.s = hfieldX(field, m)) == NULL)
goto jleave;
in.l = su_cs_len(in.s);
mime_fromhdr(&in, &out, TD_ICONV);
rv = substr(out.s, what);
n_free(out.s);
jleave:
NYD_OU;
return rv;
}
static int
matchenvelope(struct message *m, char const *field, void const *what)
{
struct mx_name *np;
char *cp;
int rv = 0;
NYD_IN;
if ((cp = hfieldX(field, m)) == NULL)
goto jleave;
for (np = lextract(cp, GFULL); np != NULL; np = np->n_flink) {
if (!substr(np->n_name, what) && !substr(mkenvelope(np), what))
continue;
rv = 1;
break;
}
jleave:
NYD_OU;
return rv;
}
static char *
mkenvelope(struct mx_name *np)
{
uz epsize;
char *ep, *realnam = NULL, /**sourceaddr = NULL,*/ *localpart,
*domainpart, *cp, *rp, *xp, *ip;
struct str in, out;
int level = 0;
boole hadphrase = FAL0;
NYD_IN;
in.s = np->n_fullname;
in.l = su_cs_len(in.s);
mime_fromhdr(&in, &out, TD_ICONV);
rp = ip = n_lofi_alloc(su_cs_len(out.s) + 1);
for (cp = out.s; *cp; cp++) {
switch (*cp) {
case '"':
while (*cp) {
if (*++cp == '"')
break;
if (cp[0] == '\\' && cp[1] != '\0')
++cp;
*rp++ = *cp;
}
break;
case '<':
while (cp > out.s && su_cs_is_blank(cp[-1]))
--cp;
rp = ip;
xp = out.s;
if (PCMP(xp, <, cp - 1) && *xp == '"' && cp[-1] == '"') {
++xp;
--cp;
}
while (xp < cp)
*rp++ = *xp++;
hadphrase = TRU1;
goto jdone;
case '(':
if (level++)
goto jdfl;
if (!hadphrase)
rp = ip;
hadphrase = TRU1;
break;
case ')':
if (--level)
goto jdfl;
break;
case '\\':
if (level && cp[1] != '\0')
cp++;
goto jdfl;
default:
jdfl:
*rp++ = *cp;
}
}
jdone:
*rp = '\0';
if (hadphrase)
realnam = ip;
n_free(out.s);
localpart = savestr(np->n_name);
if ((cp = su_cs_rfind_c(localpart, '@')) != NULL) {
*cp = '\0';
domainpart = cp + 1;
}else
domainpart = NULL;
ep = n_autorec_alloc(epsize = su_cs_len(np->n_fullname) * 2 + 40);
snprintf(ep, epsize, "(%s %s %s %s)",
realnam ? _imap_quotestr(realnam) : "NIL",
/*sourceaddr ? _imap_quotestr(sourceaddr) :*/ "NIL",
_imap_quotestr(localpart),
domainpart ? _imap_quotestr(domainpart) : "NIL");
n_lofi_free(ip);
NYD_OU;
return ep;
}
#define SURROUNDING 16
static char const *
around(char const *cp)
{
static char ab[2 * SURROUNDING +1];
uz i;
NYD_IN;
for (i = 0; i < SURROUNDING && cp > _it_begin; ++i)
--cp;
for (i = 0; i < sizeof(ab) -1; ++i)
ab[i] = *cp++;
ab[i] = '\0';
NYD_OU;
return ab;
}
FL sz
imap_search(char const *spec, int f)
{
static char *lastspec;
char const *xp;
uz i;
sz rv;
NYD_IN;
if (su_cs_cmp(spec, "()")) {
if (lastspec != NULL)
n_free(lastspec);
i = su_cs_len(spec);
lastspec = su_cs_dup_cbuf(spec, i, 0);
} else if (lastspec == NULL) {
n_err(_("No last SEARCH criteria available\n"));
rv = -1;
goto jleave;
}
spec =
_it_begin = lastspec;
_it_need_headers = FAL0;
#ifdef mx_HAVE_IMAP
if ((rv = imap_search1(spec, f) == OKAY))
goto jleave;
#endif
if (itparse(spec, &xp, 0) == STOP){
rv = -1;
goto jleave;
}
rv = 0;
if (_it_tree == NULL)
goto jleave;
#ifdef mx_HAVE_IMAP
if (mb.mb_type == MB_IMAP && _it_need_headers)
imap_getheaders(1, msgCount);
#endif
srelax_hold();
for (i = 0; UCMP(z, i, <, msgCount); ++i) {
if (message[i].m_flag & MHIDDEN)
continue;
if (f == MDELETED || !(message[i].m_flag & MDELETED)) {
uz j = (int)(i + 1);
if (itexecute(&mb, message + i, j, _it_tree)){
mark((int)j, f);
++rv;
}
srelax();
}
}
srelax_rele();
jleave:
NYD_OU;
return rv;
}
#include "su/code-ou.h"
#endif /* mx_HAVE_IMAP_SEARCH */
/* s-it-mode */
|
catroll/mailx
|
src/mx/file-locks.c
|
/*@ S-nail - a mail user agent derived from Berkeley Mail.
*@ Implementation of file-locks.h.
*
* Copyright (c) 2015 - 2020 <NAME>) Nurpmeso <<EMAIL>>.
* SPDX-License-Identifier: ISC
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#undef su_FILE
#define su_FILE file_locks
#define mx_SOURCE
#define mx_SOURCE_FILE_LOCKS
#ifndef mx_HAVE_AMALGAMATION
# include "mx/nail.h"
#endif
#include <su/mem.h>
#ifdef mx_HAVE_DOTLOCK
# include <su/cs.h>
#endif
#include "mx/file-streams.h"
#include "mx/random.h"
#include "mx/sigs.h"
#include "mx/file-locks.h"
/* TODO fake */
#include "su/code-in.h"
/* XXX Our pipe_open() main() takes void, temporary global data store */
#ifdef mx_HAVE_DOTLOCK
static enum mx_file_lock_type a_filo_flt;
static int a_filo_fd;
struct mx_file_dotlock_info *a_filo_fdip;
#endif
/* Workhorse */
static boole a_filo_lock(int fd, enum mx_file_lock_type flt, off_t off,
off_t len);
/* main() of fork(2)ed dot file locker */
#ifdef mx_HAVE_DOTLOCK
static int a_filo_main(void);
#endif
#ifdef mx_HAVE_DOTLOCK
# include "mx/file-dotlock.h" /* $(MX_SRCDIR) */
#endif
static boole
a_filo_lock(int fd, enum mx_file_lock_type flt, off_t off, off_t len){
struct flock flp;
boole rv;
NYD2_IN;
su_mem_set(&flp, 0, sizeof flp);
switch(flt){
default:
case mx_FILE_LOCK_TYPE_READ: rv = F_RDLCK; break;
case mx_FILE_LOCK_TYPE_WRITE: rv = F_WRLCK; break;
}
flp.l_type = rv;
flp.l_start = off;
flp.l_whence = SEEK_SET;
flp.l_len = len;
if(!(rv = (fcntl(fd, F_SETLK, &flp) != -1)))
switch(su_err_no()){
case su_ERR_BADF:
case su_ERR_INVAL:
rv = TRUM1;
break;
}
NYD2_OU;
return rv;
}
#ifdef mx_HAVE_DOTLOCK
static int
a_filo_main(void){
/* Use PATH_MAX not NAME_MAX to catch those "we proclaim the minimum value"
* problems (SunOS), since the pathconf(3) value comes too late! */
char name[PATH_MAX +1];
struct mx_file_dotlock_info fdi;
struct stat stb, fdstb;
enum mx_file_dotlock_state fdls;
char const *cp;
int fd;
enum mx_file_lock_type flt;
NYD_IN;
/* Ignore SIGPIPE, we will see ERR_PIPE and "fall through" */
safe_signal(SIGPIPE, SIG_IGN);
/* Get the arguments "passed to us" */
flt = a_filo_flt;
fd = a_filo_fd;
UNUSED(fd);
fdi = *a_filo_fdip;
/* chdir(2)? */
jislink:
fdls = mx_FILE_DOTLOCK_STATE_CANT_CHDIR | mx_FILE_DOTLOCK_STATE_ABANDON;
if((cp = su_cs_rfind_c(fdi.fdi_file_name, '/')) != NIL){
char const *fname = cp + 1;
while(PCMP(cp - 1, >, fdi.fdi_file_name) && cp[-1] == '/')
--cp;
cp = savestrbuf(fdi.fdi_file_name, P2UZ(cp - fdi.fdi_file_name));
if(chdir(cp))
goto jmsg;
fdi.fdi_file_name = fname;
}
/* So we are here, but then again the file can be a symbolic link!
* This is however only true if we do not have realpath(3) available since
* that will have resolved the path already otherwise; nonetheless, let
* readlink(2) be a precondition for dotlocking and keep this code */
if(lstat(cp = fdi.fdi_file_name, &stb) == -1)
goto jmsg;
if(S_ISLNK(stb.st_mode)){
/* Use n_autorec_alloc() and hope we stay in built-in buffer.. */
char *x;
uz i;
sz sr;
for(x = NIL, i = PATH_MAX;; i += PATH_MAX){
x = n_autorec_alloc(i +1);
sr = readlink(cp, x, i);
if(sr <= 0){
fdls = mx_FILE_DOTLOCK_STATE_FISHY | mx_FILE_DOTLOCK_STATE_ABANDON;
goto jmsg;
}
if(UCMP(z, sr, <, i)){
x[sr] = '\0';
break;
}
}
fdi.fdi_file_name = x;
goto jislink;
}
fdls = mx_FILE_DOTLOCK_STATE_FISHY | mx_FILE_DOTLOCK_STATE_ABANDON;
/* Bail out if the file has changed its identity in the meanwhile */
if(fstat(fd, &fdstb) == -1 ||
fdstb.st_dev != stb.st_dev || fdstb.st_ino != stb.st_ino ||
fdstb.st_uid != stb.st_uid || fdstb.st_gid != stb.st_gid ||
fdstb.st_mode != stb.st_mode)
goto jmsg;
/* Be aware, even if the error is false! Note the shared code in
* file-dotlock.h *requires* that it is possible to create a filename
* at least one byte longer than di_lock_name! */
do/* while(0) breaker */{
# ifdef mx_HAVE_PATHCONF
long pc;
# endif
int i;
i = snprintf(name, sizeof name, "%s.lock", fdi.fdi_file_name);
if(i < 0 || UCMP(32, i, >=, sizeof name)){
jenametool:
fdls = mx_FILE_DOTLOCK_STATE_NAMETOOLONG |
mx_FILE_DOTLOCK_STATE_ABANDON;
goto jmsg;
}
/* fd is a file, not portable to use for _PC_NAME_MAX */
# ifdef mx_HAVE_PATHCONF
su_err_set_no(su_ERR_NONE);
if((pc = pathconf(".", _PC_NAME_MAX)) == -1){
/* su_err_no() unchanged: no limit */
if(su_err_no() == su_ERR_NONE)
break;
# endif
if(UCMP(z, NAME_MAX - 1, <, i))
goto jenametool;
# ifdef mx_HAVE_PATHCONF
}else if(pc - 1 >= i)
break;
else
goto jenametool;
# endif
}while(0);
fdi.fdi_lock_name = name;
/* We are in the directory of the mailbox for which we have to create
* a dotlock file for. Any symbolic links have been resolved.
* We do not know whether we have realpath(3) available,and manually
* resolving the path is due especially given that we support the special
* "%:" syntax to warp any file into a "system mailbox"; there may also be
* multiple system mailbox directories...
* So what we do is that we fstat(2) the mailbox and check its UID and
* GID against that of our own process: if any of those mismatch we must
* either assume a directory we are not allowed to write in, or that we run
* via -u/$USER/%USER as someone else, in which case we favour our
* privilege-separated dotlock process */
ASSERT(cp != NIL); /* Ugly: avoid a useless var and reuse that one */
if(access(".", W_OK)){
/* This may however also indicate a read-only filesystem, which is not
* really an error from our point of view since the mailbox will degrade
* to a readonly one for which no dotlock is needed, then, and errors
* may arise only due to actions which require box modifications */
if(su_err_no() == su_ERR_ROFS){
fdls = mx_FILE_DOTLOCK_STATE_ROFS | mx_FILE_DOTLOCK_STATE_ABANDON;
goto jmsg;
}
cp = NIL;
}
if(cp == NIL || stb.st_uid != n_user_id || stb.st_gid != n_group_id){
char itoabuf[64];
char const *args[13];
snprintf(itoabuf, sizeof itoabuf, "%" PRIuZ, fdi.fdi_pollmsecs);
args[ 0] = VAL_PS_DOTLOCK;
args[ 1] = (flt == mx_FILE_LOCK_TYPE_READ) ? "rdotlock" : "wdotlock";
args[ 2] = "mailbox"; args[ 3] = fdi.fdi_file_name;
args[ 4] = "name"; args[ 5] = fdi.fdi_lock_name;
args[ 6] = "hostname"; args[ 7] = fdi.fdi_hostname;
args[ 8] = "randstr"; args[ 9] = fdi.fdi_randstr;
args[10] = "pollmsecs"; args[11] = itoabuf;
args[12] = NIL;
execv(VAL_LIBEXECDIR "/" VAL_UAGENT "-dotlock", n_UNCONST(args));
fdls = mx_FILE_DOTLOCK_STATE_NOEXEC;
write(STDOUT_FILENO, &fdls, sizeof fdls);
/* But fall through and try it with normal privileges! */
}
/* So let's try and call it ourselves! Note we do not block signals just
* like our privsep child does, the user will anyway be able to remove his
* file again, and if we are in -u/$USER mode then we are allowed to access
* the user's box: shall we leave behind a stale dotlock then at least we
* start a friendly human conversation. Since we cannot handle SIGKILL and
* SIGSTOP malicious things could happen whatever we do */
safe_signal(SIGHUP, SIG_IGN);
safe_signal(SIGINT, SIG_IGN);
safe_signal(SIGQUIT, SIG_IGN);
safe_signal(SIGTERM, SIG_IGN);
NYD;
fdls = a_file_lock_dotlock_create(&fdi);
NYD;
/* Finally: notify our parent about the actual lock state.. */
jmsg:
write(STDOUT_FILENO, &fdls, sizeof fdls);
close(STDOUT_FILENO);
/* ..then eventually wait until we shall remove the lock again, which will
* be notified via the read returning */
if(fdls == mx_FILE_DOTLOCK_STATE_NONE){
read(STDIN_FILENO, &fdls, sizeof fdls);
unlink(name);
}
NYD_OU;
return n_EXIT_OK;
}
#endif /* mx_HAVE_DOTLOCK */
boole
mx_file_lock(int fd, enum mx_file_lock_type flt, off_t off, off_t len,
uz pollmsecs){
uz tries;
boole didmsg, rv;
NYD_IN;
if(pollmsecs == UZ_MAX)
pollmsecs = mx_FILE_LOCK_MILLIS;
UNINIT(rv, 0);
for(didmsg = FAL0, tries = 0; tries <= mx_FILE_LOCK_TRIES; ++tries){
rv = a_filo_lock(fd, flt, off, len);
if(rv == TRUM1){
rv = FAL0;
break;
}
if(rv || pollmsecs == 0)
break;
else{
if(!didmsg){
n_err(_("Failed to create a file lock, waiting %lu milliseconds "),
pollmsecs);
didmsg = TRU1;
}else
n_err(".");
n_msleep(pollmsecs, FAL0);
}
}
if(didmsg)
n_err(" %s\n", (rv ? _("ok") : _("failure")));
NYD_OU;
return rv;
}
FILE *
mx_file_dotlock(char const *fname, int fd, enum mx_file_lock_type flt,
off_t off, off_t len, uz pollmsecs){
#undef a_DOMSG
#define a_DOMSG() \
do if(!didmsg){\
didmsg = TRUM1;\
n_err(dmsg, dmsg_name);\
}while(0)
#ifdef mx_HAVE_DOTLOCK
sz cpipe[2];
struct mx_file_dotlock_info fdi;
enum mx_file_dotlock_state fdls;
char const *emsg;
#endif
char const *dmsg, *dmsg_name;
int serr;
union {uz tries; int (*ptf)(void); char const *sh; sz r;} u;
boole flocked, didmsg;
FILE *rv;
NYD_IN;
if(pollmsecs == UZ_MAX)
pollmsecs = mx_FILE_LOCK_MILLIS;
rv = NIL;
didmsg = FAL0;
UNINIT(serr, 0);
#ifdef mx_HAVE_DOTLOCK
emsg = NIL;
#endif
dmsg = _("Creating file (dot) lock for %s ");
dmsg_name = n_shexp_quote_cp(fname, FAL0);
if(n_poption & n_PO_D_VV)
a_DOMSG();
flocked = FAL0;
for(u.tries = 0; !mx_file_lock(fd, flt, off, len, 0);)
switch((serr = su_err_no())){
case su_ERR_ACCES:
case su_ERR_AGAIN:
case su_ERR_NOLCK:
if(pollmsecs > 0 && ++u.tries < mx_FILE_LOCK_TRIES){
a_DOMSG();
n_err(".");
n_msleep(pollmsecs, FAL0);
continue;
}
/* FALLTHRU */
default:
goto jleave;
}
flocked = TRU1;
#ifndef mx_HAVE_DOTLOCK
jleave:
if(didmsg == TRUM1)
n_err("\n");
if(flocked)
rv = (FILE*)-1;
else
su_err_set_no(serr);
NYD_OU;
return rv;
#else
if(ok_blook(dotlock_disable)){
rv = R(FILE*,-1);
goto jleave;
}
/* Create control-pipe for our dot file locker process, which will remove
* the lock and terminate once the pipe is closed, for whatever reason */
if(!mx_fs_pipe_cloexec(cpipe)){
serr = su_err_no();
emsg = N_(" Cannot create dotlock file control pipe\n");
goto jemsg;
}
/* And the locker process itself; it will be a (rather cheap) thread only
* unless the lock has to be placed in the system spool and we have our
* privilege-separated dotlock program available, in which case that will be
* executed and do "it" */
fdi.fdi_file_name = fname;
fdi.fdi_pollmsecs = pollmsecs;
/* Initialize some more stuff; query the two strings in the parent in order
* to cache the result of the former and anyway minimalize child page-ins.
* Especially uname(3) may hang for multiple seconds when it is called the
* first time! */
fdi.fdi_hostname = n_nodename(FAL0);
fdi.fdi_randstr = mx_random_create_cp(16, NIL);
a_filo_flt = flt;
a_filo_fd = fd;
a_filo_fdip = &fdi;
u.ptf = &a_filo_main;
rv = mx_fs_pipe_open(R(char*,-1), "W", u.sh, NIL, cpipe[1]);
serr = su_err_no();
close(S(int,cpipe[1]));
if(rv == NIL){
close(S(int,cpipe[0]));
emsg = N_(" Cannot create file lock process\n");
goto jemsg;
}
/* Let's check whether we were able to create the dotlock file */
for(;;){
u.r = read(S(int,cpipe[0]), &fdls, sizeof fdls);
if(UCMP(z, u.r, !=, sizeof fdls)){
serr = (u.r != -1) ? su_ERR_AGAIN : su_err_no();
fdls = mx_FILE_DOTLOCK_STATE_DUNNO | mx_FILE_DOTLOCK_STATE_ABANDON;
}else
serr = su_ERR_NONE;
if(fdls == mx_FILE_DOTLOCK_STATE_NONE ||
(fdls & mx_FILE_DOTLOCK_STATE_ABANDON))
close(S(int,cpipe[0]));
switch(fdls & ~mx_FILE_DOTLOCK_STATE_ABANDON){
case mx_FILE_DOTLOCK_STATE_NONE:
goto jleave;
case mx_FILE_DOTLOCK_STATE_CANT_CHDIR:
if(n_poption & n_PO_D_V)
emsg = N_(" Cannot change directory, please check permissions\n");
serr = su_ERR_ACCES;
break;
case mx_FILE_DOTLOCK_STATE_NAMETOOLONG:
emsg = N_("Resulting dotlock filename would be too long\n");
serr = su_ERR_ACCES;
break;
case mx_FILE_DOTLOCK_STATE_ROFS:
ASSERT(fdls & mx_FILE_DOTLOCK_STATE_ABANDON);
if(n_poption & n_PO_D_V)
emsg = N_(" Read-only filesystem, not creating lock file\n");
serr = su_ERR_ROFS;
break;
case mx_FILE_DOTLOCK_STATE_NOPERM:
if((n_psonce & n_PSO_INTERACTIVE) || (n_poption & n_PO_D_V))
emsg = N_(" Cannot create a dotlock file, "
"please check permissions\n");
serr = su_ERR_ACCES;
break;
case mx_FILE_DOTLOCK_STATE_NOEXEC:
if((n_psonce & (n_PSO_INTERACTIVE | n_PSO_PS_DOTLOCK_NOTED)
) == n_PSO_INTERACTIVE || (n_poption & n_PO_D_V)){
n_psonce |= n_PSO_PS_DOTLOCK_NOTED;
emsg = N_(" Cannot find privilege-separated dotlock program\n");
}
serr = su_ERR_NOENT;
break;
case mx_FILE_DOTLOCK_STATE_PRIVFAILED:
emsg = N_(" Privilege-separated dotlock program cannot change "
"privileges\n");
serr = su_ERR_PERM;
break;
case mx_FILE_DOTLOCK_STATE_EXIST:
emsg = N_(" It seems there is a stale dotlock file?\n"
" Please remove the lock file manually, then retry\n");
serr = su_ERR_EXIST;
break;
case mx_FILE_DOTLOCK_STATE_FISHY:
emsg = N_(" Fishy! Is someone trying to \"steal\" foreign files?\n"
" Please check the mailbox file etc. manually, then retry\n");
serr = su_ERR_AGAIN; /* ? Hack to ignore *dotlock-ignore-error* xxx */
break;
default:
case mx_FILE_DOTLOCK_STATE_DUNNO:
emsg = N_(" Unspecified dotlock file control process error.\n"
" Like broken I/O pipe; this one is unlikely to happen\n");
if(serr != su_ERR_AGAIN)
serr = su_ERR_INVAL;
break;
case mx_FILE_DOTLOCK_STATE_PING:
a_DOMSG();
n_err(".");
continue;
}
if(emsg != NIL){
boole b;
a_DOMSG();
b = ((fdls & mx_FILE_DOTLOCK_STATE_ABANDON) != 0);
n_err(_(". failed\n%s%s"), V_(emsg),
(b ? su_empty : _("Trying different policy ")));
if(b)
didmsg = TRU1;
emsg = NIL;
}
if(fdls & mx_FILE_DOTLOCK_STATE_ABANDON){
mx_fs_pipe_close(rv, FAL0);
rv = NIL;
break;
}
}
jleave:
if(didmsg == TRUM1)
n_err(". %s\n", (rv != NIL ? _("ok") : _("failed")));
if(rv == NIL){
if(flocked){
if(serr == su_ERR_ROFS)
rv = R(FILE*,-1);
else if(serr != su_ERR_AGAIN && serr != su_ERR_EXIST &&
ok_blook(dotlock_ignore_error)){
n_OBSOLETE(_("*dotlock-ignore-error*: please use "
"*dotlock-disable* instead"));
if(n_poption & n_PO_D_V)
n_err(_(" *dotlock-ignore-error* set: continuing\n"));
rv = R(FILE*,-1);
}else{
n_err(_(" (Set *dotlock-disable* to bypass dotlocking)\n"));
goto jserr;
}
}else
jserr:
su_err_set_no(serr);
}
NYD_OU;
return rv;
jemsg:
a_DOMSG();
n_err("\n");
n_err(V_(emsg));
didmsg = TRU1;
goto jleave;
#endif /* mx_HAVE_DOTLOCK */
#undef a_DOMSG
}
#include "su/code-ou.h"
/* s-it-mode */
|
catroll/mailx
|
include/mx/mime-type.h
|
<gh_stars>1-10
/*@ S-nail - a mail user agent derived from Berkeley Mail.
*@ MIME types: handlers, `mimetype', etc.
*
* Copyright (c) 2012 - 2020 Steffen (Daode) Nurpmeso <<EMAIL>>.
* SPDX-License-Identifier: ISC
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef mx_MIME_TYPE_H
#define mx_MIME_TYPE_H
#include <mx/nail.h>
#define mx_HEADER
#include <su/code-in.h>
struct mx_mimetype_handler;
enum mx_mimetype{
mx_MIMETYPE_UNKNOWN, /* unknown */
mx_MIMETYPE_SUBHDR, /* inside a multipart subheader */
mx_MIMETYPE_822, /* message/rfc822 */
mx_MIMETYPE_MESSAGE, /* other message/ */
mx_MIMETYPE_TEXT_PLAIN, /* text/plain */
mx_MIMETYPE_TEXT_HTML, /* text/html */
mx_MIMETYPE_TEXT, /* other text/ */
mx_MIMETYPE_ALTERNATIVE, /* multipart/alternative */
mx_MIMETYPE_RELATED, /* mime/related (RFC 2387) */
mx_MIMETYPE_DIGEST, /* multipart/digest */
mx_MIMETYPE_SIGNED, /* multipart/signed */
mx_MIMETYPE_ENCRYPTED, /* multipart/encrypted */
mx_MIMETYPE_MULTI, /* other multipart/ */
mx_MIMETYPE_PKCS7, /* PKCS7 */
mx_MIMETYPE_DISCARD /* is discarded */
};
enum mx_mimetype_handler_flags{
mx_MIMETYPE_HDL_NIL, /* No pipe- mimetype handler, go away */
mx_MIMETYPE_HDL_CMD, /* Normal command */
mx_MIMETYPE_HDL_MSG, /* Display msg (returned as command string) */
mx_MIMETYPE_HDL_PTF, /* A special pointer-to-function handler */
mx_MIMETYPE_HDL_TEXT, /* ? special cmd to force treatment as text */
mx_MIMETYPE_HDL_TYPE_MASK = 7u,
/* compose, composetyped, edit, print */
mx_MIMETYPE_HDL_ASYNC = 1u<<8, /* Should run asynchronously */
mx_MIMETYPE_HDL_COPIOUSOUTPUT = 1u<<9, /* _CMD output directly usable */
mx_MIMETYPE_HDL_NEEDSTERM = 1u<<10, /* Takes over terminal */
mx_MIMETYPE_HDL_NOQUOTE = 1u<<11, /* No MIME for quoting */
mx_MIMETYPE_HDL_TMPF = 1u<<12, /* Create temporary file (zero-sized) */
mx_MIMETYPE_HDL_TMPF_FILL = 1u<<13, /* Fill in the msg body content */
mx_MIMETYPE_HDL_TMPF_UNLINK = 1u<<14, /* Delete it later again */
/* Handler with _HDL_TMPF has a .mth_tmpf_nametmpl.. */
mx_MIMETYPE_HDL_TMPF_NAMETMPL = 1u<<15,
mx_MIMETYPE_HDL_TMPF_NAMETMPL_SUFFIX = 1u<<16 /* ..to be used as suffix */
/* xxx textualnewlines */
};
enum {mx_MIMETYPE_HDL_MAX = mx_MIMETYPE_HDL_TMPF_NAMETMPL_SUFFIX};
struct mx_mimetype_handler{
BITENUM_IS(u32,mx_mime_handler_flags) mth_flags;
su_64( u8 mth__dummy[4]; )
char const *mth_tmpf_nametmpl; /* Only with _HDL_TMPF_NAMETMPL */
/* XXX union{} the following? */
char const *mth_shell_cmd; /* For MIMETYPE_HDL_CMD */
int (*mth_ptf)(void); /* PTF main() for MIMETYPE_HDL_PTF */
struct str mth_msg; /* Message describing this command */
};
/* `(un)?mimetype' commands */
EXPORT int c_mimetype(void *vp);
EXPORT int c_unmimetype(void *vp);
/* Check whether name is correct according to RFC 4288, 4.2.
* With t_a_subt, check for valid TYPE/SUBTYPE.
* With subt_wildcard_ok, allow * as a SUBTYPE. */
EXPORT boole mx_mimetype_is_valid(char const *name, boole t_a_subt,
boole subt_wildcard_ok);
/* Check whether the Content-Type name is internally known */
EXPORT boole mx_mimetype_is_known(char const *name);
/* Return a Content-Type matching the name, or NIL if none could be found */
EXPORT char *mx_mimetype_classify_filename(char const *name);
/* Classify content of *fp* as necessary and fill in arguments; **charset* is
* set to *charset-7bit* or charset_iter_or_fallback() if NIL.
* no_mboxo states whether 7BIT/8BIT is acceptable if only existence of
* a ^From_ would otherwise enforce QP/BASE64 */
/* TODO this should take a carrier and only fill that in with what has been
* TODO detected/classified, and suggest hints; rest up to caller!
* TODO This is not only more correct (no_mboxo crux++), it simplifies a lot */
EXPORT enum conversion mx_mimetype_classify_file(FILE *fp,
char const **content_type, char const **charset, boole *do_iconv,
boole no_mboxo);
/* Dependent on *mime-counter-evidence* mpp->m_ct_type_usr_ovwr will be set,
* but otherwise mpp is const. for_user_context rather maps 1:1 to
* MIME_PARSE_FOR_USER_CONTEXT */
EXPORT enum mx_mimetype mx_mimetype_classify_part(struct mimepart *mpp,
boole for_user_context);
/* Query handler for a part, return the plain type (& MIMETYPE_HDL_TYPE_MASK).
* mthp is anyway initialized (.mth_flags, .mth_msg) */
EXPORT enum mx_mimetype_handler_flags mx_mimetype_handler(
struct mx_mimetype_handler *mthp, struct mimepart const *mpp,
enum sendaction action);
#include <su/code-ou.h>
#endif /* mx_MIME_TYPE_H */
/* s-it-mode */
|
catroll/mailx
|
src/mx/accmacvar.c
|
<gh_stars>1-10
/*@ S-nail - a mail user agent derived from Berkeley Mail.
*@ Account, macro and variable handling; `vexpr' and `vpospar'.
*@ HOWTO add a new non-dynamic boolean or value option:
*@ - add an entry to nail.h:enum okeys
*@ - run make-okey-map.pl (which is highly related..)
*@ - update the manual!
*@ TODO . Drop the VIP stuff. Allow PTF callbacks to be specified, call them.
*@ TODO . `localopts' should act like an automatic permanent `scope' command
*@ TODO modifier! We need an OnScopeLeaveEvent, then.
*@ TODO Also see the a_GO_SPLICE comment in go.c.
*@ TODO . Optimize: with the dynamic hashmaps, and the object based approach
*@ TODO it should become possible to strip down the implementation again.
*@ TODO E.g., FREEZE is much too complicated: use an overlay object ptr,
*@ TODO UNLIKELY() it, and add a OnProgramStartupCompletedEvent to
*@ TODO incorporate what it tracks, then drop it. Etc.
*@ TODO Global -> Scope -> Local, all "overlay" objects.
*
* Copyright (c) 2000-2004 <NAME>, Freiburg i. Br., Germany.
* Copyright (c) 2012 - 2020 Steffen (Daode) Nurpmeso <<EMAIL>>.
* SPDX-License-Identifier: BSD-3-Clause
*/
/*
* Copyright (c) 1980, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#undef su_FILE
#define su_FILE accmacvar
#define mx_SOURCE
#ifndef mx_HAVE_AMALGAMATION
# include "mx/nail.h"
#endif
#include <su/cs.h>
#include <su/cs-dict.h>
#include <su/icodec.h>
#include <su/mem.h>
#include <su/sort.h>
#include "mx/cmd.h"
#include "mx/file-streams.h"
#include "mx/iconv.h"
#include "mx/names.h"
#include "mx/sigs.h"
#include "mx/ui-str.h"
#include "mx/url.h"
/* TODO fake */
#include "su/code-in.h"
#if !defined mx_HAVE_SETENV && !defined mx_HAVE_PUTENV
# error Exactly one of mx_HAVE_SETENV and mx_HAVE_PUTENV
#endif
/* Positional parameter maximum (macro arguments, `vexpr' "splitifs") */
#define a_AMV_POSPAR_MAX S16_MAX
/* Special "pseudo macro" that stabs you from the back */
#define a_AMV_MACKY_MACK ((struct a_amv_mac*)-1)
/* Note: changing the hash function must be reflected in `vexpr' "hash32",
* because that is used by the hashtable creator scripts! */
#define a_AMV_PRIME 23 /* TODO cs_dict! */
#define a_AMV_NAME2HASH(N) ((u32)su_cs_hash(N))
#define a_AMV_HASH2PRIME(H) ((H) % a_AMV_PRIME)
enum a_amv_mac_flags{
a_AMV_MF_NONE = 0,
a_AMV_MF_ACCOUNT = 1u<<0, /* This macro is an `account' */
a_AMV_MF_TYPE_MASK = a_AMV_MF_ACCOUNT,
a_AMV_MF_UNDEF = 1u<<1, /* Unlink after lookup */
a_AMV_MF_DELETE = 1u<<7, /* Delete in progress, free once refcnt==0 */
a_AMV_MF__MAX = 0xFFu
};
enum a_amv_loflags{
a_AMV_LF_NONE = 0,
a_AMV_LF_SCOPE = 1u<<0, /* Current scope `localopts' on */
a_AMV_LF_SCOPE_FIXATE = 1u<<1, /* Ditto, but fixated */
a_AMV_LF_SCOPE_MASK = a_AMV_LF_SCOPE | a_AMV_LF_SCOPE_FIXATE,
a_AMV_LF_CALL = 1u<<2, /* `localopts' on for `call'ed scopes */
a_AMV_LF_CALL_FIXATE = 1u<<3, /* Ditto, but fixated */
a_AMV_LF_CALL_MASK = a_AMV_LF_CALL | a_AMV_LF_CALL_FIXATE,
a_AMV_LF_CALL_TO_SCOPE_SHIFT = 2
};
/* make-okey-map.pl ensures that _VIRT implies _RDONLY and _NODEL, and that
* _IMPORT implies _ENV; it doesn't verify anything...
* More description at nail.h:enum okeys */
enum a_amv_var_flags{
a_AMV_VF_NONE = 0,
/* The basic set of flags, also present in struct a_amv_var_map.avm_flags */
a_AMV_VF_BOOL = 1u<<0, /* ok_b_* */
a_AMV_VF_CHAIN = 1u<<1, /* Has -HOST and/or -USER@HOST variants */
a_AMV_VF_VIRT = 1u<<2, /* "Stateless" automatic variable */
a_AMV_VF_VIP = 1u<<3, /* Wants _var_check_vips() evaluation */
a_AMV_VF_RDONLY = 1u<<4, /* May not be set by user */
a_AMV_VF_NODEL = 1u<<5, /* May not be deleted */
a_AMV_VF_I3VAL = 1u<<6, /* Has an initial value */
a_AMV_VF_DEFVAL = 1u<<7, /* Has a default value */
a_AMV_VF_IMPORT = 1u<<8, /* Import ONLY from env (pre n_PSO_STARTED) */
a_AMV_VF_ENV = 1u<<9, /* Update environment on change */
a_AMV_VF_NOLOPTS = 1u<<10, /* May not be tracked by `localopts' */
a_AMV_VF_NOTEMPTY = 1u<<11, /* May not be assigned an empty value */
/* TODO _VF_NUM, _VF_POSNUM: we also need 64-bit limit numbers! */
a_AMV_VF_NUM = 1u<<12, /* Value must be a 32-bit number */
a_AMV_VF_POSNUM = 1u<<13, /* Value must be positive 32-bit number */
a_AMV_VF_LOWER = 1u<<14, /* Values will be stored in lowercase version */
a_AMV_VF_OBSOLETE = 1u<<15, /* Is obsolete? */
a_AMV_VF__MASK = (1u<<(15+1)) - 1,
/* Extended flags, not part of struct a_amv_var_map.avm_flags */
/* This flag indicates the instance is actually a variant of a _VF_CHAIN,
* it thus uses the a_amv_var_map of the base variable, but it is not the
* base itself and therefore care must be taken */
a_AMV_VF_EXT_CHAIN = 1u<<22,
a_AMV_VF_EXT_LOCAL = 1u<<23, /* `local' */
a_AMV_VF_EXT_LINKED = 1u<<24, /* `environ' link'ed */
a_AMV_VF_EXT_FROZEN = 1u<<25, /* Has been set by -S,.. */
a_AMV_VF_EXT_FROZEN_UNSET = 1u<<26, /* ..and was used to unset a variable */
a_AMV_VF_EXT__FROZEN_MASK = a_AMV_VF_EXT_FROZEN | a_AMV_VF_EXT_FROZEN_UNSET,
a_AMV_VF_EXT__MASK = (1u<<(26+1)) - 1
};
enum a_amv_var_lookup_flags{
a_AMV_VLOOK_NONE = 0,
a_AMV_VLOOK_LOCAL = 1u<<0, /* Query `local' layer first */
a_AMV_VLOOK_LOCAL_ONLY = 1u<<1, /* MUST be a `local' variable */
/* Do not allocate new var for _I3VAL, see _var_lookup() for more */
a_AMV_VLOOK_I3VAL_NONEW = 1u<<2,
a_AMV_VLOOK_I3VAL_NONEW_REPORT = 1u<<3,
/* And then we must be able to detect endless recursion, for example if
* $TMPDIR is set to non-existent we can use the VAL_TMPDIR config default,
* but if this also fails (filesystem read-only for example), then all bets
* are off, and we must not enter an endless loop */
a_AMV_VLOOK_BELLA_CIAO_CIAO_CIAO = 1u<<29,
/* #ifndef a_AMV_VAR_HAS_OBSOLETE temporarily defined to _VLOOK_NONE! */
a_AMV_VLOOK_LOG_OBSOLETE = 1u<<30
};
enum a_amv_var_setclr_flags{
a_AMV_VSETCLR_NONE = 0,
a_AMV_VSETCLR_LOCAL = 1u<<0, /* Use `local' variables only */
/* XXX Maybe something for only non-local? */
a_AMV_VSETCLR_ENV = 1u<<1 /* `environ' or otherwise environ */
};
/* We support some special parameter names for one(+)-letter variable names;
* note these have counterparts in the code that manages shell expansion!
* All these special variables are solely backed by n_var_vlook(), and besides
* there is only a_amv_var_revlookup() which knows about them */
enum a_amv_var_special_category{
a_AMV_VSC_NONE, /* Normal variable, no special treatment */
a_AMV_VSC_GLOBAL, /* ${[?!]} are specially mapped, but global */
a_AMV_VSC_MULTIPLEX, /* ${^.*} circumflex accent multiplexer */
a_AMV_VSC_POSPAR, /* ${[1-9][0-9]*} positional parameters */
a_AMV_VSC_POSPAR_ENV /* ${[*@#]} positional parameter support variables */
};
enum a_amv_var_special_type{
/* _VSC_GLOBAL */
a_AMV_VST_QM, /* ? */
a_AMV_VST_EM, /* ! */
/* _VSC_MULTIPLEX */
/* This is special in that it is a multiplex indicator, the ^ is followed by
* a normal variable */
a_AMV_VST_CACC, /* ^ (circumflex accent) */
/* _VSC_POSPAR_ENV */
a_AMV_VST_STAR, /* * */
a_AMV_VST_AT, /* @ */
a_AMV_VST_NOSIGN /* # */
};
enum a_amv_var_vip_mode{
a_AMV_VIP_SET_PRE,
a_AMV_VIP_SET_POST,
a_AMV_VIP_CLEAR
};
struct a_amv_pospar{
u16 app_maxcount; /* == slots in .app_dat */
u16 app_count; /* Maximum a_AMV_POSPAR_MAX */
u16 app_idx; /* `shift' moves this one, decs .app_count */
boole app_not_heap; /* .app_dat stuff not dynamically allocated */
u8 app__dummy[1];
char const **app_dat; /* NULL terminated (for "$@" explosion support) */
};
CTA(a_AMV_POSPAR_MAX <= S16_MAX, "Limit exceeds datatype capabilities");
struct a_amv_mac{
struct a_amv_mac *am_next;
u32 am_maxlen; /* of any line in .am_line_dat */
u32 am_line_cnt; /* of *.am_line_dat (but NULL terminated) */
struct a_amv_mac_line **am_line_dat; /* TODO use deque? */
struct a_amv_var *am_lopts; /* `localopts' unroll list */
u32 am_refcnt; /* 0-based for `un{account,define}' purposes */
u8 am_flags; /* enum a_amv_mac_flags */
char am_name[VFIELD_SIZE(3)]; /* of this macro */
};
CTA(a_AMV_MF__MAX <= U8_MAX, "Enumeration excesses storage datatype");
struct a_amv_mac_line{
u32 aml_len;
u32 aml_prespc; /* Number of leading SPACEs, for display purposes */
char aml_dat[VFIELD_SIZE(0)];
};
struct a_amv_mac_call_args{
char const *amca_name; /* For MACKY_MACK, this is *0*! */
struct a_amv_mac *amca_amp; /* "const", but for am_refcnt */
struct a_amv_var **amca_unroller;
void (*amca_hook_pre)(void *);
void *amca_hook_arg;
u8 amca_loflags;
boole amca_ps_hook_mask;
boole amca_no_xcall; /* XXX We want n_GO_INPUT_NO_XCALL for this */
boole amca_ignerr; /* XXX Use n_GO_INPUT_IGNERR for evaluating commands */
u8 amca__pad[4];
struct a_amv_var *(*amca_local_vars)[a_AMV_PRIME]; /* `local's, or NULL */
struct a_amv_pospar amca_pospar;
};
struct a_amv_lostack{
struct a_amv_lostack *as_global_saved; /* Saved global XXX due to jump */
struct a_amv_mac_call_args *as_amcap;
struct a_amv_lostack *as_up; /* Outer context */
struct a_amv_var *as_lopts;
u8 as_loflags; /* enum a_amv_mac_loflags */
u8 avs__pad[7];
};
struct a_amv_var{
struct a_amv_var *av_link;
char *av_value;
#ifdef mx_HAVE_PUTENV
char *av_env; /* Actively managed putenv(3) memory, or NULL */
#endif
u32 av_flags; /* enum a_amv_var_flags inclusive extended bits */
char av_name[VFIELD_SIZE(4)];
};
CTA(a_AMV_VF_EXT__MASK <= U32_MAX, "Enumeration excesses storage datatype");
/* After inclusion of gen-okeys.h we ASSERT keyoff fits in 16-bit */
struct a_amv_var_map{
u32 avm_hash;
u16 avm_keyoff;
u16 avm_flags; /* enum a_amv_var_flags without extended bits */
};
CTA(a_AMV_VF__MASK <= U16_MAX, "Enumeration excesses storage datatype");
/* XXX Since there is no indicator character used for variable chains, we just
* XXX cannot do better than using some s....y detection.
* The length of avcmb_prefix is highly hardwired with make-okey-map.pl etc. */
struct a_amv_var_chain_map_bsrch{
char avcmb_prefix[4];
u16 avcmb_chain_map_off;
u16 avcmb_chain_map_eokey; /* This is an enum okey */
};
/* Use 16-bit for enum okeys, which should always be sufficient; all around
* here we use 32-bit for it instead, but that owed to faster access (?) */
struct a_amv_var_chain_map{
u16 avcm_keyoff;
u16 avcm_okey;
};
CTA(n_OKEYS_MAX <= U16_MAX, "Enumeration excesses storage datatype");
struct a_amv_var_virt{
u32 avv_okey;
u8 avv__dummy[4];
struct a_amv_var const *avv_var;
};
struct a_amv_var_defval{
u32 avdv_okey;
u8 avdv__pad[4];
char const *avdv_value; /* Only for !BOOL (otherwise plain existence) */
};
struct a_amv_var_carrier{
char const *avc_name;
u32 avc_hash;
u32 avc_prime;
struct a_amv_var *avc_var;
struct a_amv_var_map const *avc_map;
enum okeys avc_okey;
boole avc_is_chain_variant; /* Base is a chain, this a variant thereof */
u8 avc_special_cat;
/* Numerical parameter name if .avc_special_cat=a_AMV_VSC_POSPAR,
* otherwise a enum a_amv_var_special_type */
u16 avc_special_prop;
};
/* Include constant make-okey-map.pl output, and the generated version data */
#include "mx/gen-version.h" /* - */
#include "mx/gen-okeys.h" /* $(MX_SRCDIR) */
/* As above */
#ifndef a_AMV_VAR_HAS_OBSOLETE
# define a_AMV_VLOOK_LOG_OBSOLETE a_AMV_VLOOK_NONE
#endif
/* As promised above, CTAs to protect our structures */
CTA(a_AMV_VAR_NAME_KEY_MAXOFF <= U16_MAX,
"Enumeration excesses storage datatype");
/* The currently active account */
static struct a_amv_mac *a_amv_acc_curr;
static struct a_amv_mac *a_amv_macs[a_AMV_PRIME]; /* TODO dynamically spaced */
/* Unroll list of currently running macro stack */
static struct a_amv_lostack *a_amv_lopts;
static struct a_amv_var *a_amv_vars[a_AMV_PRIME]; /* TODO dynamically spaced */
/* Global (i.e., non-local) a_AMV_VSC_POSPAR stack */
static struct a_amv_pospar a_amv_pospar;
/* TODO We really deserve localopts support for *folder-hook*s, so hack it in
* TODO today via a static lostack, it should be a field in mailbox, once that
* TODO is a real multi-instance object */
static struct a_amv_var *a_amv_folder_hook_lopts;
/* TODO Rather ditto (except for storage -> cmd_ctx), compose hooks */
static struct a_amv_var *a_amv_compose_lopts;
/* Lookup for macros/accounts: if newamp is not NULL it will be linked in the
* map, if _MF_UNDEF is set a possibly existing entry will be removed (first).
* Returns NULL if a lookup failed, or if newamp was set, the found entry in
* plain lookup cases or when _UNDEF was performed on a currently active entry
* (the entry will have been unlinked, and the _MF_DELETE will be honoured once
* the reference count reaches 0), and (*)-1 if an _UNDEF was performed */
static struct a_amv_mac *a_amv_mac_lookup(char const *name,
struct a_amv_mac *newamp, enum a_amv_mac_flags amf);
/* `call', `call_if' (and `xcall' via go.c -> c_call()) */
static int a_amv_mac_call(void *v, boole silent_nexist);
/* Execute a macro; amcap must reside in LOFI memory */
static boole a_amv_mac_exec(struct a_amv_mac_call_args *amcap);
static void a_amv_mac__finalize(void *vp);
/* User display helpers */
static boole a_amv_mac_show(enum a_amv_mac_flags amf);
/* _def() returns error for faulty definitions and already existing * names,
* _undef() returns error if a named thing doesn't exist */
static boole a_amv_mac_def(char const *name, enum a_amv_mac_flags amf);
static boole a_amv_mac_undef(char const *name, enum a_amv_mac_flags amf);
/* */
static void a_amv_mac_free(struct a_amv_mac *amp);
/* Update replay-log */
static void a_amv_lopts_add(struct a_amv_lostack *alp, char const *name,
struct a_amv_var *oavp);
static void a_amv_lopts_unroll(struct a_amv_var **avpp);
/* Special cased value string allocation */
static char *a_amv_var_copy(char const *str);
static void a_amv_var_free(char *cp);
/* Check for special housekeeping. _VIP_SET_POST and _VIP_CLEAR do not fail
* (or propagate errors), _VIP_SET_PRE may and should case abortion */
static boole a_amv_var_check_vips(enum a_amv_var_vip_mode avvm,
enum okeys okey, char const **val);
/* _VF_NUM / _VF_POSNUM */
static boole a_amv_var_check_num(char const *val, boole posnum);
/* Verify that the given name is an acceptable variable name */
static boole a_amv_var_check_name(char const *name, boole forenviron);
/* Try to reverse lookup a name to an enum okeys mapping, zeroing avcp.
* Updates .avc_name and .avc_hash; .avc_map is NULL if none found.
* We may try_harder to identify name: it may be an extended chain.
* That test only is actually performed by the latter(, then) */
static boole a_amv_var_revlookup(struct a_amv_var_carrier *avcp,
char const *name, boole try_harder);
static boole a_amv_var_revlookup_chain(struct a_amv_var_carrier *avcp,
char const *name);
/* Lookup a variable from .avc_(map|name|hash), return whether it was found.
* Sets .avc_prime; .avc_var is NULL if not found.
* Here it is where we care for _I3VAL and _DEFVAL.
* An _I3VAL will be "consumed" as necessary anyway, but it won't be used to
* create a new variable if _VLOOK_I3VAL_NONEW is set; if
* _VLOOK_I3VAL_NONEW_REPORT is set then we set .avc_var to -1 and return true
* if that was the case, otherwise we'll return FAL0, then! */
static boole a_amv_var_lookup(struct a_amv_var_carrier *avcp,
enum a_amv_var_lookup_flags avlf);
/* Lookup functions for special category variables, _pospar drives all
* positional parameter etc. special categories */
static char const *a_amv_var_vsc_global(struct a_amv_var_carrier *avcp);
static char const *a_amv_var_vsc_multiplex(struct a_amv_var_carrier *avcp);
static char const *a_amv_var_vsc_pospar(struct a_amv_var_carrier *avcp);
/* Set var from .avc_(map|name|hash), return success */
static boole a_amv_var_set(struct a_amv_var_carrier *avcp, char const *value,
enum a_amv_var_setclr_flags avscf);
static boole a_amv_var__putenv(struct a_amv_var_carrier *avcp,
struct a_amv_var *avp);
/* Clear var from .avc_(map|name|hash); sets .avc_var=NULL, return success */
static boole a_amv_var_clear(struct a_amv_var_carrier *avcp,
enum a_amv_var_setclr_flags avscf);
static boole a_amv_var__clearenv(char const *name, struct a_amv_var *avp);
/* List all variables */
static void a_amv_var_show_all(void);
/* Actually do print one, return number of lines written */
static uz a_amv_var_show(char const *name, FILE *fp, struct n_string *msgp);
/* Shared c_set() and c_environ():set impl, return success */
static boole a_amv_var_c_set(char **ap,
BITENUM_IS(u32,a_amv_var_setclr_flags) avscf);
/* */
#ifdef a_AMV_VAR_HAS_OBSOLETE
static void a_amv_var_obsolete(char const *name);
#endif
static struct a_amv_mac *
a_amv_mac_lookup(char const *name, struct a_amv_mac *newamp,
enum a_amv_mac_flags amf){
struct a_amv_mac *amp, **ampp;
u32 h;
enum a_amv_mac_flags save_amf;
NYD2_IN;
save_amf = amf;
amf &= a_AMV_MF_TYPE_MASK;
h = a_AMV_NAME2HASH(name);
h = a_AMV_HASH2PRIME(h);
ampp = &a_amv_macs[h];
for(amp = *ampp; amp != NULL; ampp = &(*ampp)->am_next, amp = amp->am_next){
if((amp->am_flags & a_AMV_MF_TYPE_MASK) == amf &&
!su_cs_cmp(amp->am_name, name)){
if(LIKELY((save_amf & a_AMV_MF_UNDEF) == 0))
goto jleave;
*ampp = amp->am_next;
if(amp->am_refcnt > 0){
amp->am_flags |= a_AMV_MF_DELETE;
if(n_poption & n_PO_D_V)
n_err(_("Delayed deletion of currently active %s: %s\n"),
(amp->am_flags & a_AMV_MF_ACCOUNT ? "account" : "define"),
name);
}else{
a_amv_mac_free(amp);
amp = (struct a_amv_mac*)-1;
}
break;
}
}
if(newamp != NULL){
ampp = &a_amv_macs[h];
newamp->am_next = *ampp;
*ampp = newamp;
amp = NULL;
}
jleave:
NYD2_OU;
return amp;
}
static int
a_amv_mac_call(void *v, boole silent_nexist){
struct a_amv_mac *amp;
int rv;
char const *name;
struct mx_cmd_arg_ctx *cacp;
NYD_IN;
cacp = v;
name = cacp->cac_arg->ca_arg.ca_str.s;
if(UNLIKELY(cacp->cac_no > a_AMV_POSPAR_MAX)){
n_err(_("Too many arguments to macro `call': %s\n"), name);
n_pstate_err_no = su_ERR_OVERFLOW;
rv = 1;
}else if(UNLIKELY((amp = a_amv_mac_lookup(name, NULL, a_AMV_MF_NONE)
) == NULL)){
if(!silent_nexist)
n_err(_("Undefined macro called: %s\n"),
n_shexp_quote_cp(name, FAL0));
n_pstate_err_no = su_ERR_NOENT;
rv = 1;
}else{
char const **argv;
struct a_amv_mac_call_args *amcap;
uz argc;
argc = cacp->cac_no + 1;
amcap = n_lofi_alloc(sizeof *amcap + (argc * sizeof *argv));
argv = (void*)&amcap[1];
for(argc = 0; (cacp->cac_arg = cacp->cac_arg->ca_next) != NULL; ++argc)
argv[argc] = cacp->cac_arg->ca_arg.ca_str.s;
argv[argc] = NULL;
su_mem_set(amcap, 0, sizeof *amcap);
amcap->amca_name = name;
amcap->amca_amp = amp;
if(a_amv_lopts != NULL)
amcap->amca_loflags = (a_amv_lopts->as_loflags & a_AMV_LF_CALL_MASK
) >> a_AMV_LF_CALL_TO_SCOPE_SHIFT;
if(argc > 0){
amcap->amca_pospar.app_count = (u16)argc;
amcap->amca_pospar.app_not_heap = TRU1;
amcap->amca_pospar.app_dat = argv;
}
(void)a_amv_mac_exec(amcap);
rv = n_pstate_ex_no;
}
NYD_OU;
return rv;
}
static boole
a_amv_mac_exec(struct a_amv_mac_call_args *amcap){
struct a_amv_lostack *losp;
struct a_amv_mac_line **amlp;
char **args_base, **args;
struct a_amv_mac *amp;
boole rv;
NYD2_IN;
amp = amcap->amca_amp;
ASSERT(amp != NULL && amp != a_AMV_MACKY_MACK);
++amp->am_refcnt;
/* XXX Unfortunately we yet need to dup the macro lines! :( */
args_base = args = n_alloc(sizeof(*args) * (amp->am_line_cnt +1));
for(amlp = amp->am_line_dat; *amlp != NULL; ++amlp)
*(args++) = su_cs_dup_cbuf((*amlp)->aml_dat, (*amlp)->aml_len, 0);
*args = NULL;
losp = n_lofi_alloc(sizeof *losp);
losp->as_global_saved = a_amv_lopts;
if((losp->as_amcap = amcap)->amca_unroller == NULL){
losp->as_up = losp->as_global_saved;
losp->as_lopts = NULL;
}else{
losp->as_up = NULL;
losp->as_lopts = *amcap->amca_unroller;
}
losp->as_loflags = amcap->amca_loflags;
a_amv_lopts = losp;
if(amcap->amca_hook_pre != NULL)
n_PS_ROOT_BLOCK((*amcap->amca_hook_pre)(amcap->amca_hook_arg));
rv = n_go_macro((n_GO_INPUT_NONE |
(amcap->amca_no_xcall ? n_GO_INPUT_NO_XCALL : 0) |
(amcap->amca_ignerr ? n_GO_INPUT_IGNERR : 0)),
amp->am_name, args_base, &a_amv_mac__finalize, losp);
NYD2_OU;
return rv;
}
static void
a_amv_mac__finalize(void *vp){
struct a_amv_mac *amp;
struct a_amv_mac_call_args *amcap;
struct a_amv_lostack *losp;
NYD2_IN;
losp = vp;
a_amv_lopts = losp->as_global_saved;
amcap = losp->as_amcap;
/* Delete positional parameter stack */
if(!amcap->amca_pospar.app_not_heap && amcap->amca_pospar.app_maxcount > 0){
u16 i;
for(i = amcap->amca_pospar.app_maxcount; i-- != 0;)
n_free(n_UNCONST(amcap->amca_pospar.app_dat[i]));
n_free(amcap->amca_pospar.app_dat);
}
/* `local' variable hashmap. These have no environment map, never */
if(amcap->amca_local_vars != NULL){
struct a_amv_var **avpp_base, **avpp, *avp;
for(avpp_base = *amcap->amca_local_vars, avpp = &avpp_base[a_AMV_PRIME];
avpp-- != avpp_base;)
while((avp = *avpp)){
ASSERT((avp->av_flags & (a_AMV_VF_NOLOPTS | a_AMV_VF_EXT_LOCAL)) ==
(a_AMV_VF_NOLOPTS | a_AMV_VF_EXT_LOCAL));
ASSERT(!(avp->av_flags &
((a_AMV_VF__MASK | a_AMV_VF_EXT__MASK) &
~(a_AMV_VF_NOLOPTS | a_AMV_VF_EXT_LOCAL))));
*avpp = avp->av_link;
a_amv_var_free(avp->av_value);
n_free(avp);
}
n_free(avpp_base);
}
/* Unroll `localopts', if applicable */
if(amcap->amca_unroller == NULL){
if(losp->as_lopts != NULL)
a_amv_lopts_unroll(&losp->as_lopts);
}else
*amcap->amca_unroller = losp->as_lopts;
if(amcap->amca_ps_hook_mask)
n_pstate &= ~n_PS_HOOK_MASK;
if((amp = amcap->amca_amp) != a_AMV_MACKY_MACK && amp != NULL &&
--amp->am_refcnt == 0 && (amp->am_flags & a_AMV_MF_DELETE))
a_amv_mac_free(amp);
n_lofi_free(losp);
n_lofi_free(amcap);
NYD2_OU;
}
static boole
a_amv_mac_show(enum a_amv_mac_flags amf){
uz lc, mc, ti, i;
char const *typestr;
FILE *fp;
boole rv;
NYD2_IN;
rv = FAL0;
if((fp = mx_fs_tmp_open("deflist", (mx_FS_O_RDWR | mx_FS_O_UNLINK |
mx_FS_O_REGISTER), NIL)) == NIL)
fp = n_stdout;
amf &= a_AMV_MF_TYPE_MASK;
typestr = (amf & a_AMV_MF_ACCOUNT) ? "account" : "define";
for(lc = mc = ti = 0; ti < a_AMV_PRIME; ++ti){
struct a_amv_mac *amp;
for(amp = a_amv_macs[ti]; amp != NULL; amp = amp->am_next){
if((amp->am_flags & a_AMV_MF_TYPE_MASK) == amf){
struct a_amv_mac_line **amlpp;
if(++mc > 1){
putc('\n', fp);
++lc;
}
++lc;
fprintf(fp, "%s %s {\n", typestr, amp->am_name);
for(amlpp = amp->am_line_dat; *amlpp != NULL; ++lc, ++amlpp){
for(i = (*amlpp)->aml_prespc; i > 0; --i)
putc(' ', fp);
fputs((*amlpp)->aml_dat, fp);
putc('\n', fp);
}
fputs("}\n", fp);
++lc;
}
}
}
if(fp != n_stdout){
if(mc > 0)
page_or_print(fp, lc);
rv = (ferror(fp) == 0);
mx_fs_close(fp);
}else{
clearerr(fp);
rv = TRU1;
}
NYD2_OU;
return rv;
}
static boole
a_amv_mac_def(char const *name, enum a_amv_mac_flags amf){
struct str line;
u32 line_cnt, maxlen;
struct linelist{
struct linelist *ll_next;
struct a_amv_mac_line *ll_amlp;
} *llp, *ll_head, *ll_tail;
union {uz s; int i; u32 ui; uz l;} n;
struct a_amv_mac *amp;
boole rv;
NYD2_IN;
mx_fs_linepool_aquire(&line.s, &line.l);
rv = FAL0;
amp = NIL;
/* TODO We should have our input state machine which emits Line events,
* TODO and hook different consumers dependent on our content, as stated
* TODO in i think lex_input: like this local macros etc. would become
* TODO possible from the input side */
/* Read in the lines which form the macro content */
for(ll_tail = ll_head = NULL, line_cnt = maxlen = 0;;){
u32 leaspc;
char *cp;
n.i = n_go_input(n_GO_INPUT_CTX_DEFAULT | n_GO_INPUT_NL_ESC, n_empty,
&line.s, &line.l, NULL, NULL);
if(n.ui == 0)
continue;
if(n.i < 0){
n_err(_("Unterminated %s definition: %s\n"),
(amf & a_AMV_MF_ACCOUNT ? "account" : "macro"), name);
goto jerr;
}
/* Trim WS, remember amount of leading spaces for display purposes */
for(cp = line.s, leaspc = 0; n.ui > 0; ++cp, --n.ui)
if(*cp == '\t')
leaspc = (leaspc + 8u) & ~7u;
else if(*cp == ' ')
++leaspc;
else
break;
for(; n.ui > 0 && su_cs_is_space(cp[n.ui - 1]); --n.ui)
;
if(n.ui == 0)
continue;
maxlen = MAX(maxlen, n.ui);
cp[n.ui++] = '\0';
/* Is is the closing brace? */
if(*cp == '}')
break;
if(LIKELY(++line_cnt < U32_MAX)){
struct a_amv_mac_line *amlp;
llp = n_autorec_alloc(sizeof *llp);
if(ll_head == NULL)
ll_head = llp;
else
ll_tail->ll_next = llp;
ll_tail = llp;
llp->ll_next = NULL;
llp->ll_amlp = amlp = n_alloc(VSTRUCT_SIZEOF(struct a_amv_mac_line,
aml_dat) + n.ui);
amlp->aml_len = n.ui -1;
amlp->aml_prespc = leaspc;
su_mem_copy(amlp->aml_dat, cp, n.ui);
}else{
n_err(_("Too much content in %s definition: %s\n"),
(amf & a_AMV_MF_ACCOUNT ? "account" : "macro"), name);
goto jerr;
}
}
/* Create the new macro */
n.s = su_cs_len(name) +1;
amp = n_alloc(VSTRUCT_SIZEOF(struct a_amv_mac, am_name) + n.s);
su_mem_set(amp, 0, VSTRUCT_SIZEOF(struct a_amv_mac, am_name));
amp->am_maxlen = maxlen;
amp->am_line_cnt = line_cnt;
amp->am_flags = amf;
su_mem_copy(amp->am_name, name, n.s);
/* C99 */{
struct a_amv_mac_line **amlpp;
amp->am_line_dat = amlpp = n_alloc(sizeof(*amlpp) * ++line_cnt);
for(llp = ll_head; llp != NULL; llp = llp->ll_next)
*amlpp++ = llp->ll_amlp;
*amlpp = NULL;
}
/* Create entry, replace a yet existing one as necessary */
a_amv_mac_lookup(name, amp, amf | a_AMV_MF_UNDEF);
rv = TRU1;
jleave:
mx_fs_linepool_release(line.s, line.l);
NYD2_OU;
return rv;
jerr:
for(llp = ll_head; llp != NULL; llp = llp->ll_next)
n_free(llp->ll_amlp);
/*
* if(amp != NULL){
* n_free(amp->am_line_dat);
* n_free(amp);
*}*/
goto jleave;
}
static boole
a_amv_mac_undef(char const *name, enum a_amv_mac_flags amf){
struct a_amv_mac *amp;
boole rv;
NYD2_IN;
rv = TRU1;
if(LIKELY(name[0] != '*' || name[1] != '\0')){
if((amp = a_amv_mac_lookup(name, NULL, amf | a_AMV_MF_UNDEF)) == NULL){
n_err(_("%s not defined: %s\n"),
(amf & a_AMV_MF_ACCOUNT ? "Account" : "Macro"), name);
rv = FAL0;
}
}else{
struct a_amv_mac **ampp, *lamp;
for(ampp = a_amv_macs; PCMP(ampp, <, &a_amv_macs[NELEM(a_amv_macs)]);
++ampp)
for(lamp = NULL, amp = *ampp; amp != NULL;){
if((amp->am_flags & a_AMV_MF_TYPE_MASK) == amf){
/* xxx Expensive but rare: be simple */
a_amv_mac_lookup(amp->am_name, NULL, amf | a_AMV_MF_UNDEF);
amp = (lamp == NULL) ? *ampp : lamp->am_next;
}else{
lamp = amp;
amp = amp->am_next;
}
}
}
NYD2_OU;
return rv;
}
static void
a_amv_mac_free(struct a_amv_mac *amp){
struct a_amv_mac_line **amlpp;
NYD2_IN;
for(amlpp = amp->am_line_dat; *amlpp != NULL; ++amlpp)
n_free(*amlpp);
n_free(amp->am_line_dat);
n_free(amp);
NYD2_OU;
}
static void
a_amv_lopts_add(struct a_amv_lostack *alp, char const *name,
struct a_amv_var *oavp){
struct a_amv_var *avp;
uz nl, vl;
NYD2_IN;
/* Propagate unrolling up the stack, as necessary */
ASSERT(alp != NULL);
for(;;){
if(alp->as_loflags & a_AMV_LF_SCOPE_MASK)
break;
if((alp = alp->as_up) == NULL)
goto jleave;
}
/* Check whether this variable is handled yet XXX Boost: ID check etc.!! */
for(avp = alp->as_lopts; avp != NULL; avp = avp->av_link)
if(!su_cs_cmp(avp->av_name, name))
goto jleave;
nl = su_cs_len(name) +1;
vl = (oavp != NULL) ? su_cs_len(oavp->av_value) +1 : 0;
avp = n_calloc(1, VSTRUCT_SIZEOF(struct a_amv_var, av_name) + nl + vl);
avp->av_link = alp->as_lopts;
alp->as_lopts = avp;
if(vl != 0){
avp->av_value = &avp->av_name[nl];
avp->av_flags = oavp->av_flags;
su_mem_copy(avp->av_value, oavp->av_value, vl);
}
su_mem_copy(avp->av_name, name, nl);
jleave:
NYD2_OU;
}
static void
a_amv_lopts_unroll(struct a_amv_var **avpp){
struct a_amv_lostack *save_alp;
struct a_amv_var *x, *avp;
NYD2_IN;
avp = *avpp;
*avpp = NULL;
save_alp = a_amv_lopts;
a_amv_lopts = NULL;
while(avp != NULL){
x = avp;
avp = avp->av_link;
n_PS_ROOT_BLOCK(n_var_vset(x->av_name, (up)x->av_value));
n_free(x);
}
a_amv_lopts = save_alp;
NYD2_OU;
}
static char *
a_amv_var_copy(char const *str){
char *news;
uz len;
NYD2_IN;
if(*str == '\0')
news = n_UNCONST(n_empty);
else if(str[1] == '\0'){
if(str[0] == '1')
news = n_UNCONST(n_1);
else if(str[0] == '0')
news = n_UNCONST(n_0);
else
goto jheap;
}else if(str[2] == '\0' && str[0] == '-' && str[1] == '1')
news = n_UNCONST(n_m1);
else{
jheap:
len = su_cs_len(str) +1;
news = n_alloc(len);
su_mem_copy(news, str, len);
}
NYD2_OU;
return news;
}
static void
a_amv_var_free(char *cp){
NYD2_IN;
if(cp[0] != '\0' && cp != n_0 && cp != n_1 && cp != n_m1)
n_free(cp);
NYD2_OU;
}
static boole
a_amv_var_check_vips(enum a_amv_var_vip_mode avvm, enum okeys okey,
char const **val){
char const *emsg;
boole ok;
NYD2_IN;
ok = TRU1;
emsg = NIL;
if(avvm == a_AMV_VIP_SET_PRE){
switch(okey){
default:
break;
case ok_v_charset_7bit:
case ok_v_charset_8bit:
case ok_v_charset_unknown_8bit:
case ok_v_ttycharset:
if((*val = n_iconv_normalize_name(*val)) == NULL)
ok = FAL0;
break;
case ok_v_customhdr:{
char const *vp;
char *buf;
struct n_header_field *hflp, **hflpp, *hfp;
buf = savestr(*val);
hflp = NIL;
hflpp = &hflp;
while((vp = su_cs_sep_escable_c(&buf, ',', TRU1)) != NULL){
if(!n_header_add_custom(hflpp, vp, TRU1)){
emsg = N_("Invalid *customhdr* entry: %s\n");
break;
}
hflpp = &(*hflpp)->hf_next;
}
hflpp = (emsg == NIL) ? &n_customhdr_list : &hflp;
while((hfp = *hflpp) != NULL){
*hflpp = hfp->hf_next;
n_free(hfp);
}
if(emsg)
goto jerr;
n_customhdr_list = hflp;
}break;
case ok_v_from:
case ok_v_sender:{
struct mx_name *np;
np = (okey == ok_v_sender ? n_extract_single : lextract
)(*val, GEXTRA | GFULL);
if(np == NIL){
jefrom:
emsg = N_("*from* / *sender*: invalid address(es): %s\n");
goto jerr;
}else for(; np != NIL; np = np->n_flink)
if(is_addr_invalid(np, EACM_STRICT | EACM_NOLOG | EACM_NONAME))
goto jefrom;
}break;
case ok_v_HOME:
/* Note this gets called from main.c during initialization, and they
* simply set this to pw_dir as a fallback: don't verify _that_ call.
* See main.c! */
if(!(n_pstate & n_PS_ROOT) && !n_is_dir(*val, TRUM1)){
emsg = N_("$HOME is not a directory or not accessible: %s\n");
goto jerr;
}
break;
case ok_v_hostname:
case ok_v_smtp_hostname:
#ifdef mx_HAVE_IDNA
if(**val != '\0'){
struct n_string cnv;
n_string_creat_auto(&cnv);
if(!n_idna_to_ascii(&cnv, *val, UZ_MAX)){
/*n_string_gut(&res);*/
emsg = N_("*hostname*/*smtp_hostname*: "
"IDNA encoding failed: %s\n");
goto jerr;
}
*val = n_string_cp(&cnv);
/*n_string_drop_ownership(&cnv);*/
}
#endif
break;
case ok_v_quote_chars:{
char c;
char const *cp;
for(cp = *val; (c = *cp++) != '\0';)
if(!su_cs_is_ascii(c) || su_cs_is_space(c)){
ok = FAL0;
break;
}
}break;
case ok_v_sendcharsets:{
struct n_string s_b, *s = &s_b;
char *csv, *cp;
s = n_string_creat_auto(s);
csv = savestr(*val);
while((cp = su_cs_sep_c(&csv, ',', TRU1)) != NULL){
if((cp = n_iconv_normalize_name(cp)) == NULL){
ok = FAL0;
break;
}
if(s->s_len > 0)
s = n_string_push_c(s, ',');
s = n_string_push_cp(s, cp);
}
*val = n_string_cp(s);
/* n_string_drop_ownership(so); */
}break;
case ok_v_TMPDIR:
if(!n_is_dir(*val, TRU1)){
emsg = N_("$TMPDIR is not a directory or not accessible: %s\n");
goto jerr;
}
break;
case ok_v_umask:
if(**val != '\0'){
u64 uib;
su_idec_u64_cp(&uib, *val, 0, NULL);
if(uib & ~0777u){ /* (is valid _VF_POSNUM) */
emsg = N_("Invalid *umask* setting: %s\n");
goto jerr;
}
}
break;
case ok_v_verbose:{
u64 uib;
/* Initially a boolean variable, we want to keep compat forever */
if(**val != '\0')
su_idec_u64_cp(&uib, *val, 0, NIL);
else switch(n_poption & n_PO_V_MASK){
case 0: uib = 1; break;
case n_PO_V: uib = 2; break;
default: uib = 3; break;
}
switch(uib){
case 0: *val = su_empty; break;
case 1: *val = n_1; break;
case 2: *val = "2"; break;
default: *val = "3"; break;
}
}break;
}
}else if(avvm == a_AMV_VIP_SET_POST){
switch(okey){
default:
break;
case ok_b_ask:
ok_bset(asksub);
break;
case ok_v_bind_timeout: /* v15-compat: drop this */
n_OBSOLETE("*bind-timeout*: please set *bind-inter-byte-timeout*, "
"doing this for you");
n_PS_ROOT_BLOCK(ok_vset(bind_inter_byte_timeout, *val));
break;
case ok_b_debug:
n_poption |= n_PO_D;
su_log_set_level(su_LOG_DEBUG);
# define a_DEBUG_MEMCONF su_MEM_CONF_DEBUG | su_MEM_CONF_LINGER_FREE
su_DBG( su_mem_set_conf(a_DEBUG_MEMCONF, TRU1); )
break;
case ok_v_HOME:
/* Invalidate any resolved folder then, too
* FALLTHRU */
case ok_v_folder:
n_PS_ROOT_BLOCK(ok_vclear(folder_resolved));
break;
case ok_v_ifs:{
char *x_b, *x, c;
char const *cp;
cp = *val;
x_b = x = n_autorec_alloc(su_cs_len(cp) +1);
while((c = *cp++) != '\0')
if(su_cs_is_space(c))
*x++ = c;
*x = '\0';
n_PS_ROOT_BLOCK(ok_vset(ifs_ws, x_b));
}break;
#ifdef mx_HAVE_SETLOCALE
case ok_v_LANG:
case ok_v_LC_ALL:
case ok_v_LC_CTYPE:
n_locale_init();
break;
#endif
case ok_b_memdebug:
su_DBG( su_mem_set_conf(a_DEBUG_MEMCONF |
su_MEM_CONF_ON_ERROR_EMERG, TRU1); )
break;
case ok_b_POSIXLY_CORRECT: /* <-> *posix* */
if(!(n_pstate & n_PS_ROOT))
n_PS_ROOT_BLOCK(ok_bset(posix));
break;
case ok_b_posix: /* <-> $POSIXLY_CORRECT */
if(!(n_pstate & n_PS_ROOT))
n_PS_ROOT_BLOCK(ok_bset(POSIXLY_CORRECT));
break;
case ok_b_skipemptybody:
n_poption |= n_PO_E_FLAG;
break;
case ok_v_SOCKS5_PROXY: /* <-> *socks-proxy* */
if(!(n_pstate & n_PS_ROOT))
n_PS_ROOT_BLOCK(ok_vset(socks_proxy, *val));
break;
case ok_v_socks_proxy: /* <-> $SOCKS5_PROXY */
if(!(n_pstate & n_PS_ROOT))
n_PS_ROOT_BLOCK(ok_vset(SOCKS5_PROXY, *val));
break;
case ok_b_typescript_mode:
ok_bset(colour_disable);
ok_bset(line_editor_disable);
if(!(n_psonce & n_PSO_STARTED))
ok_bset(termcap_disable);
break;
case ok_v_umask:
if(**val != '\0'){
u64 uib;
su_idec_u64_cp(&uib, *val, 0, NULL);
umask((mode_t)uib);
}
break;
case ok_v_verbose:{
/* Work out what the PRE VIP did */
u32 i;
/* Initially a boolean variable, we want to keep compat forever */
i = 0;
switch(**val){
default: i |= n_PO_VVV; /* FALLTHRU */
case '2': i |= n_PO_VV; /* FALLTHRU */
case '1': i |= n_PO_V; /* FALLTHRU */
case '\0': break;
}
if(i != 0){
n_poption &= ~n_PO_V_MASK;
n_poption |= i;
if(!(n_poption & n_PO_D))
su_log_set_level(su_LOG_INFO);
}else
ok_vclear(verbose);
}break;
}
}else{
switch(okey){
default:
break;
case ok_b_ask:
ok_bclear(asksub);
break;
case ok_b_debug:
n_poption &= ~n_PO_D;
su_log_set_level((n_poption & n_PO_V) ? su_LOG_INFO : n_LOG_LEVEL);
su_DBG( if(!ok_blook(memdebug))
su_mem_set_conf(a_DEBUG_MEMCONF, FAL0); )
break;
case ok_v_customhdr:{
struct n_header_field *hfp;
while((hfp = n_customhdr_list) != NULL){
n_customhdr_list = hfp->hf_next;
n_free(hfp);
}
}break;
case ok_v_HOME:
/* Invalidate any resolved folder then, too
* FALLTHRU */
case ok_v_folder:
n_PS_ROOT_BLOCK(ok_vclear(folder_resolved));
break;
case ok_b_memdebug:
su_DBG( su_mem_set_conf((ok_blook(debug) ? 0 : a_DEBUG_MEMCONF) |
su_MEM_CONF_ON_ERROR_EMERG, FAL0); )
#undef a_DEBUG_MEMCONF
break;
case ok_b_POSIXLY_CORRECT: /* <-> *posix* */
if(!(n_pstate & n_PS_ROOT))
n_PS_ROOT_BLOCK(ok_bclear(posix));
break;
case ok_b_posix: /* <-> $POSIXLY_CORRECT */
if(!(n_pstate & n_PS_ROOT))
n_PS_ROOT_BLOCK(ok_bclear(POSIXLY_CORRECT));
break;
case ok_b_skipemptybody:
n_poption &= ~n_PO_E_FLAG;
break;
case ok_v_SOCKS5_PROXY: /* <-> *socks-proxy* */
if(!(n_pstate & n_PS_ROOT))
n_PS_ROOT_BLOCK(ok_vclear(socks_proxy));
break;
case ok_v_socks_proxy: /* <-> $SOCKS5_PROXY */
if(!(n_pstate & n_PS_ROOT))
n_PS_ROOT_BLOCK(ok_vclear(SOCKS5_PROXY));
break;
case ok_v_verbose:
n_poption &= ~n_PO_V_MASK;
if(!(n_poption & n_PO_D))
su_log_set_level(n_LOG_LEVEL);
break;
}
}
jleave:
NYD2_OU;
return ok;
jerr:
emsg = V_(emsg);
n_err(emsg, n_shexp_quote_cp(*val, FAL0));
ok = FAL0;
goto jleave;
}
static boole
a_amv_var_check_num(char const *val, boole posnum){
/* TODO The internal/environment variables which are num= or posnum= should
* TODO gain special lookup functions, or the return should be void* and
* TODO castable to integer; i.e. no more strtoX() should be needed.
* TODO I.e., the result of this function should instead be stored */
boole rv;
NYD2_IN;
rv = TRU1;
if(*val != '\0'){ /* Would be _VF_NOTEMPTY if not allowed */
u64 uib;
enum su_idec_state ids;
ids = su_idec_cp(&uib, val, 0,
(su_IDEC_MODE_LIMIT_32BIT |
(posnum ? su_IDEC_MODE_SIGNED_TYPE : su_IDEC_MODE_NONE)), NULL);
if((ids & (su_IDEC_STATE_EMASK | su_IDEC_STATE_CONSUMED)
) != su_IDEC_STATE_CONSUMED)
rv = FAL0;
/* TODO Unless we store integers we need to look and forbid, because
* TODO callee may not be able to swallow, e.g., "-1" */
if(posnum && (ids & su_IDEC_STATE_SEEN_MINUS))
rv = FAL0;
}
NYD2_OU;
return rv;
}
static boole
a_amv_var_check_name(char const *name, boole forenviron){
char c;
char const *cp;
boole rv;
NYD2_IN;
rv = TRU1;
/* Empty name not tested, as documented */
for(cp = name; (c = *cp) != '\0'; ++cp)
if(c == '=' || su_cs_is_space(c) || su_cs_is_cntrl(c)){
n_err(_("Variable names may not contain =, space or control "
"characters: %s\n"), n_shexp_quote_cp(name, TRU1));
rv = FAL0;
goto jleave;
}
if(rv && forenviron && !(rv = n_shexp_is_valid_varname(name, TRU1)))
n_err(_("Invalid environment variable: %s\n"),
n_shexp_quote_cp(name, TRU1));
jleave:
NYD2_OU;
return rv;
}
static boole
a_amv_var_revlookup(struct a_amv_var_carrier *avcp, char const *name,
boole try_harder){
u32 hash, i, j;
struct a_amv_var_map const *avmp;
char c;
NYD2_IN;
su_mem_set(avcp, 0, sizeof *avcp); /* XXX overkill, just set chain */
/* It may be a special a.k.a. macro-local or one-letter parameter */
c = name[0];
if(UNLIKELY(su_cs_is_digit(c))){
/* (Inline dec. atoi, ugh) */
for(j = (u8)c - '0', i = 1;; ++i){
c = name[i];
if(c == '\0')
break;
if(!su_cs_is_digit(c))
goto jno_special_param;
j = j * 10 + (u8)c - '0';
}
if(j <= a_AMV_POSPAR_MAX){
avcp->avc_special_cat = a_AMV_VSC_POSPAR;
goto jspecial_param;
}
}else if(UNLIKELY(name[1] == '\0')){
switch(c){
case '?':
case '!':
avcp->avc_special_cat = a_AMV_VSC_GLOBAL;
j = (c == '?') ? a_AMV_VST_QM : a_AMV_VST_EM;
goto jspecial_param;
case '^':
goto jmultiplex;
case '*':
avcp->avc_special_cat = a_AMV_VSC_POSPAR_ENV;
j = a_AMV_VST_STAR;
goto jspecial_param;
case '@':
avcp->avc_special_cat = a_AMV_VSC_POSPAR_ENV;
j = a_AMV_VST_AT;
goto jspecial_param;
case '#':
avcp->avc_special_cat = a_AMV_VSC_POSPAR_ENV;
j = a_AMV_VST_NOSIGN;
goto jspecial_param;
default:
break;
}
}else if(c == '^'){
jmultiplex:
avcp->avc_special_cat = a_AMV_VSC_MULTIPLEX;
j = a_AMV_VST_CACC;
goto jspecial_param;
}
/* This is nothing special, but a plain variable */
jno_special_param:
ASSERT(a_AMV_VSC_NONE == 0);/*avcp->avc_special_cat = a_AMV_VSC_NONE;*/
avcp->avc_name = name;
avcp->avc_hash = hash = a_AMV_NAME2HASH(name);
/* Is it a known okey? Walk over the hashtable */
for(i = hash % a_AMV_VAR_REV_PRIME, j = 0; j <= a_AMV_VAR_REV_LONGEST; ++j){
u32 x;
if((x = a_amv_var_revmap[i]) == a_AMV_VAR_REV_ILL)
break;
avmp = &a_amv_var_map[x];
if(avmp->avm_hash == hash &&
!su_cs_cmp(&a_amv_var_names[avmp->avm_keyoff], name)){
avcp->avc_map = avmp;
avcp->avc_okey = (enum okeys)x;
goto jleave;
}
if(++i == a_AMV_VAR_REV_PRIME){
#ifdef a_AMV_VAR_REV_WRAPAROUND
i = 0;
#else
break;
#endif
}
}
/* Not a known key, but it may be a chain extension of one.
* We possibly want to know for a variety of reasons */
if(try_harder && a_amv_var_revlookup_chain(avcp, name))
goto jleave;
ASSERT(avcp->avc_map == NULL);/*avcp->avc_map = NULL;*/
avcp = NULL;
jleave:
ASSERT(avcp == NULL || avcp->avc_map != NULL ||
avcp->avc_special_cat == a_AMV_VSC_NONE);
NYD2_OU;
return (avcp != NULL);
/* All these are mapped to *--special-param* */
jspecial_param:
avcp->avc_name = name;
avcp->avc_special_prop = (u16)j;
avmp = &a_amv_var_map[a_AMV_VAR__SPECIAL_PARAM_MAP_IDX];
avcp->avc_hash = avmp->avm_hash;
avcp->avc_map = avmp;
avcp->avc_okey = ok_v___special_param;
goto jleave;
}
static boole
a_amv_var_revlookup_chain(struct a_amv_var_carrier *avcp, char const *name){
uz i;
struct a_amv_var_chain_map_bsrch const *avcmbp, *avcmbp_x;
NYD_IN;
if(su_cs_len(name) <
su_FIELD_SIZEOF(struct a_amv_var_chain_map_bsrch, avcmb_prefix)){
avcp = NULL;
goto jleave;
}
avcmbp = &a_amv_var_chain_map_bsrch[0];
i = a_AMV_VAR_CHAIN_MAP_BSRCH_CNT - 0;
do{
int cres;
avcmbp_x = &avcmbp[i >> 1];
cres = su_mem_cmp(name, avcmbp_x->avcmb_prefix,
su_FIELD_SIZEOF(struct a_amv_var_chain_map_bsrch, avcmb_prefix));
if(cres != 0){
/* Go right instead? */
if(cres > 0){
avcmbp = ++avcmbp_x;
--i;
}
}else{
/* Once the binary search found the right prefix we have to use
* a linear walk from then on, because there is no "trigger"
* character: anything could be something free-form or
* a chain-extension, we just do not know. Unfortunately.
* Luckily cramping the walk to a small window is possible */
struct a_amv_var_chain_map const *avcmp, *avcmp_hit;
avcmp = &a_amv_var_chain_map[avcmbp_x->avcmb_chain_map_off];
avcmp_hit = NULL;
do{
char c;
char const *cp, *ncp;
cp = &a_amv_var_names[avcmp->avcm_keyoff +
su_FIELD_SIZEOF(struct a_amv_var_chain_map_bsrch,
avcmb_prefix)];
ncp = &name[su_FIELD_SIZEOF(struct a_amv_var_chain_map_bsrch,
avcmb_prefix)];
for(;; ++ncp, ++cp)
if(*ncp != (c = *cp) || c == '\0')
break;
/* Is it a chain extension of this key? */
if(c == '\0' && *ncp == '-')
avcmp_hit = avcmp;
else if(avcmp_hit != NULL)
break;
}while((avcmp++)->avcm_okey < avcmbp_x->avcmb_chain_map_eokey);
if(avcmp_hit != NULL){
avcp->avc_map = &a_amv_var_map[avcp->avc_okey =
(enum okeys)avcmp_hit->avcm_okey];
avcp->avc_is_chain_variant = TRU1;
goto jleave;
}
break;
}
}while((i >>= 1) > 0);
avcp = NULL;
jleave:
NYD_OU;
return (avcp != NULL);
}
static boole
a_amv_var_lookup(struct a_amv_var_carrier *avcp, /* XXX too complicated! */
enum a_amv_var_lookup_flags avlf){
uz i;
char const *cp;
u32 f;
struct a_amv_var_map const *avmp;
struct a_amv_var *avp;
NYD2_IN;
ASSERT(!(avlf & a_AMV_VLOOK_LOCAL_ONLY) || (avlf & a_AMV_VLOOK_LOCAL));
ASSERT(!(avlf & a_AMV_VLOOK_I3VAL_NONEW_REPORT) ||
(avlf & a_AMV_VLOOK_I3VAL_NONEW));
ASSERT(!(avlf & a_AMV_VLOOK_BELLA_CIAO_CIAO_CIAO));
/* C99 */{
struct a_amv_var **avpp, *lavp;
avcp->avc_prime = a_AMV_HASH2PRIME(avcp->avc_hash);
/* Optionally macro-`local' variables first */
if(avlf & a_AMV_VLOOK_LOCAL){
if(a_amv_lopts != NULL &&
(avpp = *a_amv_lopts->as_amcap->amca_local_vars) != NULL){
avpp += avcp->avc_prime;
for(lavp = NULL, avp = *avpp; avp != NULL;
lavp = avp, avp = avp->av_link)
if(!su_cs_cmp(avp->av_name, avcp->avc_name)){
/* Relink as head, hope it "sorts on usage" over time.
* The code relies on this behaviour! */
if(lavp != NULL){
lavp->av_link = avp->av_link;
avp->av_link = *avpp;
*avpp = avp;
}
goto jleave;
}
}
if(avlf & a_AMV_VLOOK_LOCAL_ONLY)
goto jerr;
}
/* Global variable map */
avpp = &a_amv_vars[avcp->avc_prime];
for(lavp = NULL, avp = *avpp; avp != NULL;
lavp = avp, avp = avp->av_link)
if(!su_cs_cmp(avp->av_name, avcp->avc_name)){
/* Relink as head, hope it "sorts on usage" over time.
* The code relies on this behaviour! */
if(lavp != NULL){
lavp->av_link = avp->av_link;
avp->av_link = *avpp;
*avpp = avp;
}
/* If this setting has been established via -S and we still have
* not reached the _STARTED_CONFIG program state, it may have been
* an explicit "clearance" that is to be treated as unset.
* Because that is a special condition that (has been hacked in
* later and) needs to be encapsulated in lower levels, but not
* of interest if _set() or _clear() called us */
switch(avp->av_flags & a_AMV_VF_EXT__FROZEN_MASK){
case a_AMV_VF_EXT_FROZEN | a_AMV_VF_EXT_FROZEN_UNSET:
if(!(avlf & a_AMV_VLOOK_I3VAL_NONEW)){
avcp->avc_var = avp;
avp = NULL;
goto j_leave;
}
/* FALLTHRU */
default:
break;
}
goto jleave;
}
}
/* If this is not an assembled variable we need to consider some special
* initialization cases and eventually create the variable anew */
if(LIKELY((avmp = avcp->avc_map) != NULL)){
f = avmp->avm_flags;
/* Does it have an import-from-environment flag? */
if(UNLIKELY((f & (a_AMV_VF_IMPORT | a_AMV_VF_ENV)) != 0)){
if(LIKELY((cp = getenv(avcp->avc_name)) != NULL)){
/* May be better not to use that one, though? */
/* TODO Outsource the tests into a _shared_ test function! */
boole isempty, isbltin;
isempty = (*cp == '\0' && (f & a_AMV_VF_NOTEMPTY) != 0);
isbltin = ((f & (a_AMV_VF_I3VAL | a_AMV_VF_DEFVAL)) != 0);
if(UNLIKELY(isempty)){
n_err(_("Environment variable must not be empty: %s\n"),
avcp->avc_name);
if(!isbltin)
goto jerr;
}else if(LIKELY(*cp != '\0')){
if(UNLIKELY((f & a_AMV_VF_NUM) &&
!a_amv_var_check_num(cp, FAL0))){
n_err(_("Environment variable value not a number "
"or out of range: %s\n"), avcp->avc_name);
goto jerr;
}
if(UNLIKELY((f & a_AMV_VF_POSNUM) &&
!a_amv_var_check_num(cp, TRU1))){
n_err(_("Environment variable value not a number, "
"negative or out of range: %s\n"), avcp->avc_name);
goto jerr;
}
goto jnewval;
}else
goto jnewval;
}
}
/* A first-time init switch is to be handled now and here */
if(UNLIKELY((f & a_AMV_VF_I3VAL) != 0)){
static struct a_amv_var_defval const **arr,
*arr_base[a_AMV_VAR_I3VALS_CNT +1];
if(UNLIKELY(arr == NULL)){
arr = &arr_base[0];
arr[i = a_AMV_VAR_I3VALS_CNT] = NULL;
while(i-- > 0)
arr[i] = &a_amv_var_i3vals[i];
}
for(i = 0; arr[i] != NULL; ++i)
if(arr[i]->avdv_okey == avcp->avc_okey){
cp = (f & a_AMV_VF_BOOL) ? n_1 : arr[i]->avdv_value;
/* Remove this entry, hope entire block becomes no-op asap */
do
arr[i] = arr[i + 1];
while(arr[i++] != NULL);
if(!(avlf & a_AMV_VLOOK_I3VAL_NONEW))
goto jnewval;
if(avlf & a_AMV_VLOOK_I3VAL_NONEW_REPORT)
avp = (struct a_amv_var*)-1;
goto jleave;
}
}
/* */
jdefval:
if(UNLIKELY(f & a_AMV_VF_DEFVAL) != 0){
for(i = 0; i < a_AMV_VAR_DEFVALS_CNT; ++i)
if(a_amv_var_defvals[i].avdv_okey == avcp->avc_okey){
cp = (f & a_AMV_VF_BOOL) ? n_1
: a_amv_var_defvals[i].avdv_value;
goto jnewval;
}
}
/* The virtual variables */
if(UNLIKELY((f & a_AMV_VF_VIRT) != 0)){
for(i = 0; i < a_AMV_VAR_VIRTS_CNT; ++i)
if(a_amv_var_virts[i].avv_okey == avcp->avc_okey){
avp = n_UNCONST(a_amv_var_virts[i].avv_var);
goto jleave;
}
/* Not reached */
}
}
jerr:
avp = NULL;
jleave:
avcp->avc_var = avp;
j_leave:
#ifdef a_AMV_VAR_HAS_OBSOLETE
if(UNLIKELY((avmp = avcp->avc_map) != NIL &&
(avmp->avm_flags & a_AMV_VF_OBSOLETE) != 0) &&
((avlf & a_AMV_VLOOK_LOG_OBSOLETE) ||
(avp != NIL && avp != R(struct a_amv_var*,-1))))
a_amv_var_obsolete(avcp->avc_name);
#endif
if(UNLIKELY(!(avlf & a_AMV_VLOOK_I3VAL_NONEW)) &&
UNLIKELY(n_poption & n_PO_VVV) &&
avp != (struct a_amv_var*)-1 && avcp->avc_okey != ok_v_log_prefix){
/* I18N: Variable "name" is set to "value" */
n_err(_("*%s* is %s\n"),
n_shexp_quote_cp(avcp->avc_name, FAL0),
(avp == NULL ? _("not set")
: ((avp->av_flags & a_AMV_VF_BOOL) ? _("boolean set")
: n_shexp_quote_cp(avp->av_value, FAL0))));
}
NYD2_OU;
return (avp != NULL);
jnewval:
ASSERT(avmp != NULL);
ASSERT(f == avmp->avm_flags);
/* E.g., $TMPDIR may be set to non-existent, so we need to be able to catch
* that and redirect to a possible default value */
if((f & a_AMV_VF_VIP) &&
!a_amv_var_check_vips(a_AMV_VIP_SET_PRE, avcp->avc_okey, &cp)){
#ifdef mx_HAVE_SETENV
if(f & (a_AMV_VF_IMPORT | a_AMV_VF_ENV))
unsetenv(avcp->avc_name);
#endif
if(UNLIKELY(f & a_AMV_VF_DEFVAL) != 0){
if(avlf & a_AMV_VLOOK_BELLA_CIAO_CIAO_CIAO)
n_panic(_("Cannot set *%s* to default value: %s"),
n_shexp_quote_cp(avcp->avc_name, FAL0),
n_shexp_quote_cp((cp == NIL ? su_empty : cp), FAL0));
avlf |= a_AMV_VLOOK_BELLA_CIAO_CIAO_CIAO;
goto jdefval;
}
goto jerr;
}else{
struct a_amv_var **avpp;
uz l;
l = su_cs_len(avcp->avc_name) +1;
avcp->avc_var =
avp = n_calloc(1, VSTRUCT_SIZEOF(struct a_amv_var, av_name) + l);
avp->av_link = *(avpp = &a_amv_vars[avcp->avc_prime]);
*avpp = avp;
ASSERT(!avcp->avc_is_chain_variant);
avp->av_flags = f;
avp->av_value = a_amv_var_copy(cp);
su_mem_copy(avp->av_name, avcp->avc_name, l);
if(f & a_AMV_VF_ENV)
a_amv_var__putenv(avcp, avp);
if(f & a_AMV_VF_VIP)
a_amv_var_check_vips(a_AMV_VIP_SET_POST, avcp->avc_okey, &cp);
goto jleave;
}
}
static char const *
a_amv_var_vsc_global(struct a_amv_var_carrier *avcp){
char iencbuf[su_IENC_BUFFER_SIZE];
char const *rv;
s32 *ep;
struct a_amv_var_map const *avmp;
NYD2_IN;
/* Not function local, TODO but lazy evaluated for now */
if(avcp->avc_special_prop == a_AMV_VST_QM){
avmp = &a_amv_var_map[a_AMV_VAR__QM_MAP_IDX];
avcp->avc_okey = ok_v___qm;
ep = &n_pstate_ex_no;
}else{
avmp = &a_amv_var_map[a_AMV_VAR__EM_MAP_IDX];
avcp->avc_okey = ok_v___em;
ep = &n_pstate_err_no;
}
/* XXX Oh heaven, we are responsible to ensure that $?/! is up-to-date
* TODO we could num=1 ok_v___[qe]m, but the thing is still a string
* TODO and thus conversion takes places over and over again; also
* TODO for now that would have to occur before we set _that_ value
* TODO so let's special treat it until we store ints as such */
switch(*ep){
case 0: rv = n_0; break;
case 1: rv = n_1; break;
default:
rv = su_ienc(iencbuf, *ep, 10, su_IENC_MODE_SIGNED_TYPE);
break;
}
n_PS_ROOT_BLOCK(n_var_okset(avcp->avc_okey, (up)rv));
avcp->avc_hash = avmp->avm_hash;
avcp->avc_map = avmp;
rv = a_amv_var_lookup(avcp, a_AMV_VLOOK_NONE)
? avcp->avc_var->av_value : NULL;
NYD2_OU;
return rv;
}
static char const *
a_amv_var_vsc_multiplex(struct a_amv_var_carrier *avcp){
char iencbuf[su_IENC_BUFFER_SIZE];
s32 e;
uz i;
char const *rv;
NYD2_IN;
i = su_cs_len(rv = &avcp->avc_name[1]);
/* ERR, ERRDOC, ERRNAME, plus *-NAME variants.
* As well as ERRQUEUE-. */
if(rv[0] == 'E' && i >= 3 && rv[1] == 'R' && rv[2] == 'R'){
if(i == 3){
e = n_pstate_err_no;
goto jeno;
}else if(rv[3] == '-'){
e = su_err_from_name(&rv[4]);
jeno:
switch(e){
case 0: rv = n_0; break;
case 1: rv = n_1; break;
default:
/* XXX Need to convert number to string yet */
rv = savestr(su_ienc(iencbuf, e, 10, su_IENC_MODE_SIGNED_TYPE));
break;
}
goto jleave;
}else if(i >= 6){
if(!su_mem_cmp(&rv[3], "DOC", 3)){
rv += 6;
switch(*rv){
case '\0': e = n_pstate_err_no; break;
case '-': e = su_err_from_name(&rv[1]); break;
default: goto jerr;
}
rv = su_err_doc(e);
goto jleave;
}else if(i >= 7 && !su_mem_cmp(&rv[3], "NAME", 4)){
rv += 7;
switch(*rv){
case '\0': e = n_pstate_err_no; break;
case '-': e = su_err_from_name(&rv[1]); break;
default: goto jerr;
}
rv = su_err_name(e);
goto jleave;
}else if(i >= 14){
if(!su_mem_cmp(&rv[3], "QUEUE-COUNT", 11)){
if(rv[14] == '\0'){
e = 0
#ifdef mx_HAVE_ERRORS
| n_pstate_err_cnt
#endif
;
goto jeno;
}
}else if(i >= 15 && !su_mem_cmp(&rv[3], "QUEUE-EXISTS", 12)){
if(rv[15] == '\0'){
#ifdef mx_HAVE_ERRORS
if(n_pstate_err_cnt != 0)
rv = V_(n_error);
else
#endif
rv = su_empty;
goto jleave;
}
}
}
}
}
jerr:
rv = NULL;
jleave:
NYD2_OU;
return rv;
}
static char const *
a_amv_var_vsc_pospar(struct a_amv_var_carrier *avcp){
uz i, j;
u16 argc;
char const *rv, **argv;
NYD2_IN;
rv = NULL;
/* If in a macro/xy.. */
if(a_amv_lopts != NULL){
boole ismacky;
struct a_amv_mac_call_args *amcap;
amcap = a_amv_lopts->as_amcap;
argc = amcap->amca_pospar.app_count;
argv = amcap->amca_pospar.app_dat;
argv += amcap->amca_pospar.app_idx;
/* ..in a `call'ed macro only, to be exact. Or in a_AMV_MACKY_MACK */
if(!(ismacky = (amcap->amca_amp == a_AMV_MACKY_MACK)) &&
(amcap->amca_ps_hook_mask ||
(amcap->amca_amp->am_flags & a_AMV_MF_TYPE_MASK
) == a_AMV_MF_ACCOUNT))
goto jleave;
if(avcp->avc_special_cat == a_AMV_VSC_POSPAR){
if(avcp->avc_special_prop > 0){
if(argc >= avcp->avc_special_prop)
rv = argv[avcp->avc_special_prop - 1];
}else if(ismacky)
rv = amcap->amca_name;
else
rv = (a_amv_lopts->as_up != NULL
? a_amv_lopts->as_up->as_amcap->amca_name : n_empty);
goto jleave;
}
/* MACKY_MACK doesn't know about [*@#] */
/*else*/ if(ismacky){
if(n_poption & n_PO_D_V)
n_err(_("Cannot use $*/$@/$# in this context: %s\n"),
n_shexp_quote_cp(avcp->avc_name, FAL0));
goto jleave;
}
}else{
argc = a_amv_pospar.app_count;
argv = a_amv_pospar.app_dat;
argv += a_amv_pospar.app_idx;
if(avcp->avc_special_cat == a_AMV_VSC_POSPAR){
if(avcp->avc_special_prop > 0){
if(argc >= avcp->avc_special_prop)
rv = argv[avcp->avc_special_prop - 1];
}else
rv = su_program;
goto jleave;
}
}
switch(avcp->avc_special_prop){ /* XXX OPTIMIZE */
case a_AMV_VST_STAR:{
char sep;
sep = *ok_vlook(ifs);
if(0){
case a_AMV_VST_AT:
sep = ' ';
}
for(i = j = 0; i < argc; ++i)
j += su_cs_len(argv[i]) + 1;
if(j == 0)
rv = n_empty;
else{
char *cp;
rv = cp = n_autorec_alloc(j);
for(i = j = 0; i < argc; ++i){
j = su_cs_len(argv[i]);
su_mem_copy(cp, argv[i], j);
cp += j;
if(sep != '\0')
*cp++ = sep;
}
if(sep != '\0')
--cp;
*cp = '\0';
}
}break;
case a_AMV_VST_NOSIGN:{
char iencbuf[su_IENC_BUFFER_SIZE];
rv = savestr(su_ienc(iencbuf, argc, 10, su_IENC_MODE_NONE));
}break;
default:
rv = n_empty;
break;
}
jleave:
NYD2_OU;
return rv;
}
static boole
a_amv_var_set(struct a_amv_var_carrier *avcp, char const *value,
enum a_amv_var_setclr_flags avscf){
struct a_amv_var *avp;
char *oval;
struct a_amv_var_map const *avmp;
boole rv;
NYD2_IN;
if(value == NIL){
rv = a_amv_var_clear(avcp, avscf);
goto jleave;
}
if((avmp = avcp->avc_map) != NIL){
u32 f;
rv = FAL0;
f = avmp->avm_flags;
#ifdef a_AMV_VAR_HAS_OBSOLETE
if(UNLIKELY((f & a_AMV_VF_OBSOLETE) != 0))/* TODO v15compat only D_V */
a_amv_var_obsolete(avcp->avc_name);
#endif
/* Validity checks */
if(UNLIKELY((f & a_AMV_VF_RDONLY) != 0 && !(n_pstate & n_PS_ROOT))){
value = N_("Variable is read-only: %s\n");
goto jeavmp;
}
if(UNLIKELY((f & a_AMV_VF_NOTEMPTY) && *value == '\0')){
value = N_("Variable must not be empty: %s\n");
goto jeavmp;
}
if(UNLIKELY((f & a_AMV_VF_NUM) && !a_amv_var_check_num(value, FAL0))){
value = N_("Variable value not a number or out of range: %s\n");
goto jeavmp;
}
if(UNLIKELY((f & a_AMV_VF_POSNUM) && !a_amv_var_check_num(value, TRU1))){
value = _("Variable value not a number, negative, "
"or out of range: %s\n");
goto jeavmp;
}
if(UNLIKELY((f & a_AMV_VF_IMPORT) != 0 &&
!(n_psonce & n_PSO_STARTED) && !(n_pstate & n_PS_ROOT))){
value = N_("Variable cannot be set in a resource file: %s\n");
goto jeavmp;
}
/* Any more complicated inter-dependency? */
if(UNLIKELY((f & a_AMV_VF_VIP) != 0 &&
!a_amv_var_check_vips(a_AMV_VIP_SET_PRE, avcp->avc_okey, &value))){
value = N_("Assignment of variable aborted: %s\n");
jeavmp:
n_err(V_(value), avcp->avc_name);
goto jleave;
}
/* Transformations */
if(UNLIKELY(f & a_AMV_VF_LOWER)){
char c;
oval = savestr(value);
value = oval;
for(; (c = *oval) != '\0'; ++oval)
*oval = su_cs_to_lower(c);
}
}
/* Lookup possibly existing var. For */
rv = TRU1;
a_amv_var_lookup(avcp, (a_AMV_VLOOK_I3VAL_NONEW |
((avscf & a_AMV_VSETCLR_LOCAL)
? (a_AMV_VLOOK_LOCAL | a_AMV_VLOOK_LOCAL_ONLY)
: a_AMV_VLOOK_LOCAL)));
avp = avcp->avc_var;
/* A `local' setting is never covered by `localopts' nor frozen */
if((avscf & a_AMV_VSETCLR_LOCAL) ||
(avp != NIL && (avp->av_flags & a_AMV_VF_EXT_LOCAL)))
goto jislocal;
/* If this setting had been established via -S and we still have not reached
* the _STARTED_CONFIG program state, silently ignore request! */
if(UNLIKELY(avp != NULL) &&
UNLIKELY((avp->av_flags & a_AMV_VF_EXT__FROZEN_MASK) != 0)){
if(!(n_psonce & n_PSO_STARTED_CONFIG)){
if((n_pstate & n_PS_ROOT) ||
(!(n_psonce & n_PSO_STARTED_GETOPT) &&
(n_poption & n_PO_S_FLAG_TEMPORARY)))
goto joval_and_go;
if(n_poption & n_PO_D_VV)
n_err(_("Temporarily frozen by -S, not `set'ing: %s\n"),
avcp->avc_name);
goto jleave;
}
/* Otherwise, if -S freezing was an `unset' request, be very simple and
* avoid tampering with that very special case we are not really prepared
* for just one more line of code: throw the old thing away! */
if(!(avp->av_flags & a_AMV_VF_EXT_FROZEN_UNSET))
avp->av_flags &= ~a_AMV_VF_EXT__FROZEN_MASK;
else{
ASSERT(avp->av_value == n_empty);
ASSERT(a_amv_vars[avcp->avc_prime] == avp);
a_amv_vars[avcp->avc_prime] = avp->av_link;
n_free(avp);
avcp->avc_var = avp = NULL;
}
}
/* Optionally cover by `localopts' */
if(UNLIKELY(a_amv_lopts != NULL) &&
(avmp == NULL || !(avmp->avm_flags & a_AMV_VF_NOLOPTS)))
a_amv_lopts_add(a_amv_lopts, avcp->avc_name, avcp->avc_var);
jislocal:
if(avp != NULL)
joval_and_go:
oval = avp->av_value;
else{
uz l;
struct a_amv_var **avpp;
if(avscf & a_AMV_VSETCLR_LOCAL){
if((avpp = *a_amv_lopts->as_amcap->amca_local_vars) == NULL)
avpp = *(a_amv_lopts->as_amcap->amca_local_vars =
n_calloc(1,
sizeof(*a_amv_lopts->as_amcap->amca_local_vars)));
avpp += avcp->avc_prime;
}else
avpp = &a_amv_vars[avcp->avc_prime];
l = su_cs_len(avcp->avc_name) +1;
avcp->avc_var = avp = n_calloc(1,
VSTRUCT_SIZEOF(struct a_amv_var, av_name) + l);
avp->av_link = *avpp;
*avpp = avp;
avp->av_flags = (((avscf & a_AMV_VSETCLR_LOCAL)
? a_AMV_VF_NOLOPTS | a_AMV_VF_EXT_LOCAL
: ((avmp != NULL) ? avmp->avm_flags : 0)) |
(avcp->avc_is_chain_variant ? a_AMV_VF_EXT_CHAIN : a_AMV_VF_NONE));
su_mem_copy(avp->av_name, avcp->avc_name, l);
oval = n_UNCONST(n_empty);
}
if(avmp == NULL)
avp->av_value = a_amv_var_copy(value);
else{
ASSERT(!(avscf & a_AMV_VSETCLR_LOCAL));
/* Via `set' etc. the user may give even boolean options non-boolean
* values, ignore that and force boolean */
if(!(avp->av_flags & a_AMV_VF_BOOL))
avp->av_value = a_amv_var_copy(value);
else{
if(!(n_pstate & n_PS_ROOT) && (n_poption & n_PO_D_V) &&
*value != '\0')
n_err(_("Ignoring value of boolean variable: %s: %s\n"),
avcp->avc_name, value);
avp->av_value = n_UNCONST(n_1);
}
}
/* A `local' setting can skip all the crude special things */
if(!(avscf & a_AMV_VSETCLR_LOCAL)){
u32 f;
f = avp->av_flags;
if((avscf & a_AMV_VSETCLR_ENV) && !(f & a_AMV_VF_ENV))
f |= a_AMV_VF_EXT_LINKED;
if(f & (a_AMV_VF_ENV | a_AMV_VF_EXT_LINKED))
rv = a_amv_var__putenv(avcp, avp);
if(f & a_AMV_VF_VIP)
a_amv_var_check_vips(a_AMV_VIP_SET_POST, avcp->avc_okey, &value);
f &= ~a_AMV_VF_EXT__FROZEN_MASK;
if(!(n_psonce & n_PSO_STARTED_GETOPT) &&
(n_poption & n_PO_S_FLAG_TEMPORARY) != 0)
f |= a_AMV_VF_EXT_FROZEN;
avp->av_flags = f;
}
a_amv_var_free(oval);
jleave:
NYD2_OU;
return rv;
}
static boole
a_amv_var__putenv(struct a_amv_var_carrier *avcp, struct a_amv_var *avp){
#ifndef mx_HAVE_SETENV
char *cp;
#endif
boole rv;
NYD2_IN;
#ifdef mx_HAVE_SETENV
rv = (setenv(avcp->avc_name, avp->av_value, 1) == 0);
#else
cp = su_cs_dup(savecatsep(avcp->avc_name, '=', avp->av_value), 0);
if((rv = (putenv(cp) == 0))){
char *ocp;
ocp = avp->av_env;
avp->av_env = cp;
cp = ocp;
}
if(cp != NULL)
n_free(cp);
#endif
NYD2_OU;
return rv;
}
static boole
a_amv_var_clear(struct a_amv_var_carrier *avcp,
enum a_amv_var_setclr_flags avscf){
struct a_amv_var **avpp, *avp;
u32 f;
struct a_amv_var_map const *avmp;
boole rv;
NYD2_IN;
rv = FAL0;
f = 0;
if(LIKELY((avmp = avcp->avc_map) != NULL)){
f = avmp->avm_flags;
#ifdef a_AMV_VAR_HAS_OBSOLETE
if(UNLIKELY((f & a_AMV_VF_OBSOLETE) != 0))/* TODO v15compat only D_V */
a_amv_var_obsolete(avcp->avc_name);
#endif
/* Validity checks */
if(UNLIKELY((f & a_AMV_VF_NODEL) != 0 && !(n_pstate & n_PS_ROOT))){
n_err(_("Variable may not be unset: %s\n"), avcp->avc_name);
goto jleave;
}
if(UNLIKELY((f & a_AMV_VF_VIP) != 0 &&
!a_amv_var_check_vips(a_AMV_VIP_CLEAR, avcp->avc_okey, NULL))){
n_err(_("Clearance of variable aborted: %s\n"), avcp->avc_name);
goto jleave;
}
}
rv = TRU1;
if(UNLIKELY(!a_amv_var_lookup(avcp,
(((avscf & a_AMV_VSETCLR_LOCAL)
? (a_AMV_VLOOK_LOCAL | a_AMV_VLOOK_LOCAL_ONLY)
: a_AMV_VLOOK_LOCAL) |
a_AMV_VLOOK_I3VAL_NONEW | a_AMV_VLOOK_I3VAL_NONEW_REPORT)))){
ASSERT(avcp->avc_var == NULL);
/* This may be a clearance request from the command line, via -S, and we
* need to keep track of that! Unfortunately we are not prepared for
* this, really, so we need to create a fake entry that is known and
* handled correctly by the lowermost variable layer! However, all
* this cannot happen for plain unset of `local' variables */
if(avscf & a_AMV_VSETCLR_LOCAL)
goto jleave;
if(UNLIKELY(!(n_psonce & n_PSO_STARTED_GETOPT)) &&
(n_poption & n_PO_S_FLAG_TEMPORARY)) Jfreeze:{
uz l;
l = su_cs_len(avcp->avc_name) +1;
avp = n_calloc(1, VSTRUCT_SIZEOF(struct a_amv_var, av_name) + l);
avp->av_link = *(avpp = &a_amv_vars[avcp->avc_prime]);
*avpp = avp;
avp->av_value = n_UNCONST(n_empty); /* Sth. covered by _var_free()! */
ASSERT(f == (avmp != NULL ? avmp->avm_flags : 0));
avp->av_flags = f | a_AMV_VF_EXT_FROZEN | a_AMV_VF_EXT_FROZEN_UNSET;
su_mem_copy(avp->av_name, avcp->avc_name, l);
if((avscf & a_AMV_VSETCLR_ENV) || (f & a_AMV_VF_ENV))
a_amv_var__clearenv(avcp->avc_name, NULL);
}else if(avscf & a_AMV_VSETCLR_ENV){
jforce_env:
if(!(rv = a_amv_var__clearenv(avcp->avc_name, NULL)))
goto jerr_env_unset;
}else{
/* TODO "cannot unset undefined variable" not echoed in "ROBOT" state,
* TODO should only be like that with "ignerr"! */
jerr_env_unset:
if(!(n_pstate & (n_PS_ROOT | n_PS_ROBOT)) && (n_poption & n_PO_D_V))
n_err(_("Cannot unset undefined variable: %s\n"), avcp->avc_name);
}
goto jleave;
}else if((avp = avcp->avc_var) == (struct a_amv_var*)-1){
/* Clearance request from command line, via -S? As above.. */
if(UNLIKELY(!(n_psonce & n_PSO_STARTED_GETOPT) &&
(n_poption & n_PO_S_FLAG_TEMPORARY) != 0))
goto Jfreeze;
avcp->avc_var = NULL;
if(avscf & a_AMV_VSETCLR_ENV)
goto jforce_env;
goto jleave;
}
ASSERT(avcp->avc_var != NULL);
/* `local' variables bypass "frozen" checks and `localopts' coverage etc. */
if((f = avp->av_flags) & a_AMV_VF_EXT_LOCAL)
goto jdefault_path;
/* If this setting has been established via -S and we still have not reached
* the _STARTED_CONFIG program state, silently ignore request!
* XXX All this is very complicated for the tenth of a second */
/*else*/ if(UNLIKELY((f & a_AMV_VF_EXT__FROZEN_MASK) != 0)){
if(!(n_psonce & n_PSO_STARTED_CONFIG)){
if((n_pstate & n_PS_ROOT) ||
(!(n_psonce & n_PSO_STARTED_GETOPT) &&
(n_poption & n_PO_S_FLAG_TEMPORARY))){
/* Be aware this may turn a set into an unset! */
if(!(f & a_AMV_VF_EXT_FROZEN_UNSET)){
if(f & a_AMV_VF_DEFVAL)
goto jdefault_path;
a_amv_var_free(avp->av_value);
f |= a_AMV_VF_EXT_FROZEN_UNSET;
avp->av_flags = f;
avp->av_value = n_UNCONST(n_empty); /* _var_free() covered */
if(f & (a_AMV_VF_ENV | a_AMV_VF_EXT_LINKED))
goto jforce_env;
}
goto jleave;
}
if(n_poption & n_PO_D_VV)
n_err(_("Temporarily frozen by -S, not `unset'ting: %s\n"),
avcp->avc_name);
goto jleave;
}
f &= ~a_AMV_VF_EXT__FROZEN_MASK;
avp->av_flags = f;
}
if(UNLIKELY(a_amv_lopts != NULL) &&
(avmp == NULL || !(avmp->avm_flags & a_AMV_VF_NOLOPTS)))
a_amv_lopts_add(a_amv_lopts, avcp->avc_name, avcp->avc_var);
jdefault_path:
ASSERT(avp == avcp->avc_var);
avcp->avc_var = NULL;
avpp = &(((f = avp->av_flags) & a_AMV_VF_EXT_LOCAL)
? *a_amv_lopts->as_amcap->amca_local_vars : a_amv_vars
)[avcp->avc_prime];
ASSERT(*avpp == avp); /* (always listhead after lookup()) */
*avpp = (*avpp)->av_link;
if(f & (a_AMV_VF_ENV | a_AMV_VF_EXT_LINKED))
rv = a_amv_var__clearenv(avp->av_name, avp);
a_amv_var_free(avp->av_value);
n_free(avp);
/* XXX Fun part, extremely simple-minded for now: if this variable has
* XXX a default value, immediately reinstantiate it! TODO Heh? */
/* xxx Simply assuming we will never have default values for actual
* xxx -HOST or -USER@HOST chain extensions */
if(UNLIKELY(avmp != NULL && (avmp->avm_flags & a_AMV_VF_DEFVAL) != 0)){
a_amv_var_lookup(avcp, a_AMV_VLOOK_I3VAL_NONEW);
if(UNLIKELY(!(n_psonce & n_PSO_STARTED_GETOPT)) &&
(n_poption & n_PO_S_FLAG_TEMPORARY))
avcp->avc_var->av_flags |= a_AMV_VF_EXT_FROZEN;
}
jleave:
NYD2_OU;
return rv;
}
static boole
a_amv_var__clearenv(char const *name, struct a_amv_var *avp){
extern char **environ;
char **ecpp;
boole rv;
NYD2_IN;
UNUSED(avp);
rv = FAL0;
ecpp = environ;
#ifndef mx_HAVE_SETENV
if(avp != NULL && avp->av_env != NULL){
for(; *ecpp != NULL; ++ecpp)
if(*ecpp == avp->av_env){
do
ecpp[0] = ecpp[1];
while(*ecpp++ != NULL);
n_free(avp->av_env);
avp->av_env = NULL;
rv = TRU1;
break;
}
}else
#endif
{
uz l;
if((l = su_cs_len(name)) > 0){
for(; *ecpp != NULL; ++ecpp)
if(!strncmp(*ecpp, name, l) && (*ecpp)[l] == '='){
#ifdef mx_HAVE_SETENV
unsetenv(name);
#else
do
ecpp[0] = ecpp[1];
while(*ecpp++ != NULL);
#endif
rv = TRU1;
break;
}
}
}
NYD2_OU;
return rv;
}
static void
a_amv_var_show_all(void){
struct n_string msg, *msgp;
FILE *fp;
uz no, i;
struct a_amv_var *avp;
char const **vacp, **cap;
NYD2_IN;
if((fp = mx_fs_tmp_open("setlist", (mx_FS_O_RDWR | mx_FS_O_UNLINK |
mx_FS_O_REGISTER), NIL)) == NIL)
fp = n_stdout;
/* We need to instantiate first-time-inits and default values here, so that
* they will be regular members of our _vars[] table */
for(i = a_AMV_VAR_I3VALS_CNT; i-- > 0;)
n_var_oklook(a_amv_var_i3vals[i].avdv_okey);
for(i = a_AMV_VAR_DEFVALS_CNT; i-- > 0;)
n_var_oklook(a_amv_var_defvals[i].avdv_okey);
for(no = i = 0; i < a_AMV_PRIME; ++i)
for(avp = a_amv_vars[i]; avp != NULL; avp = avp->av_link)
++no;
no += a_AMV_VAR_VIRTS_CNT;
vacp = n_autorec_alloc(no * sizeof(*vacp));
for(cap = vacp, i = 0; i < a_AMV_PRIME; ++i)
for(avp = a_amv_vars[i]; avp != NULL; avp = avp->av_link)
*cap++ = avp->av_name;
for(i = a_AMV_VAR_VIRTS_CNT; i-- > 0;)
*cap++ = a_amv_var_virts[i].avv_var->av_name;
if(no > 1)
su_sort_shell_vpp(su_S(void const**,vacp), no, su_cs_toolbox.tb_compare);
msgp = &msg;
msgp = n_string_reserve(n_string_creat(msgp), 80);
for(i = 0, cap = vacp; no != 0; ++cap, --no)
i += a_amv_var_show(*cap, fp, msgp);
n_string_gut(&msg);
if(fp != n_stdout){
page_or_print(fp, i);
mx_fs_close(fp);
}else
clearerr(fp);
NYD2_OU;
}
static uz
a_amv_var_show(char const *name, FILE *fp, struct n_string *msgp){
/* XXX a_amv_var_show(): if we iterate over all the actually set variables
* XXX via a_amv_var_show_all() there is no need to call
* XXX a_amv_var_revlookup() at all! Revisit this call chain */
struct a_amv_var_carrier avc;
char const *quote;
struct a_amv_var *avp;
boole isset;
uz i;
NYD2_IN;
msgp = n_string_trunc(msgp, 0);
i = 0;
a_amv_var_revlookup(&avc, name, TRU1);
isset = a_amv_var_lookup(&avc, a_AMV_VLOOK_NONE);
avp = avc.avc_var;
if(n_poption & n_PO_D_V){
if(avc.avc_map == NULL){
msgp = n_string_push_cp(msgp, "#assembled variable with value");
i = 1;
}else{
struct{
u16 flag;
char msg[22];
} const tbase[] = {
{a_AMV_VF_CHAIN, "variable chain"},
{a_AMV_VF_VIRT, "virtual"},
{a_AMV_VF_RDONLY, "read-only"},
{a_AMV_VF_NODEL, "nodelete"},
{a_AMV_VF_I3VAL, "initial-value"},
{a_AMV_VF_DEFVAL, "default-value"},
{a_AMV_VF_IMPORT, "import-environ-first\0"}, /* \0 fits longest */
{a_AMV_VF_ENV, "sync-environ"},
{a_AMV_VF_NOLOPTS, "no-localopts"},
{a_AMV_VF_NOTEMPTY, "notempty"},
{a_AMV_VF_NUM, "number"},
{a_AMV_VF_POSNUM, "positive-number"},
{a_AMV_VF_OBSOLETE, "obsoleted"},
}, *tp;
ASSERT(!isset || ((avp->av_flags & a_AMV_VF__MASK) ==
(avc.avc_map->avm_flags & a_AMV_VF__MASK)));
for(tp = tbase; PCMP(tp, <, &tbase[NELEM(tbase)]); ++tp)
if(isset ? (avp->av_flags & tp->flag)
: (avc.avc_map->avm_flags & tp->flag)){
msgp = n_string_push_c(msgp, (i++ == 0 ? '#' : ','));
msgp = n_string_push_cp(msgp, tp->msg);
if(isset){
if((tp->flag == a_AMV_VF_CHAIN) &&
(avp->av_flags & a_AMV_VF_EXT_CHAIN))
msgp = n_string_push_cp(msgp, " (extension)");
}
}
}
if(isset){
if(avp->av_flags & a_AMV_VF_EXT_FROZEN){
msgp = n_string_push_c(msgp, (i++ == 0 ? '#' : ','));
msgp = n_string_push_cp(msgp, "(un)?set via -S");
}
}
if(i > 0)
msgp = n_string_push_cp(msgp, "\n ");
}
/* (Read-only variables are generally shown via comments..) */
if(!isset || (avp->av_flags & a_AMV_VF_RDONLY)){
msgp = n_string_push_c(msgp, n_ns[0]);
if(!isset){
if(avc.avc_map != NULL && (avc.avc_map->avm_flags & a_AMV_VF_BOOL))
msgp = n_string_push_cp(msgp, "boolean; ");
msgp = n_string_push_cp(msgp, "variable not set: ");
msgp = n_string_push_cp(msgp, n_shexp_quote_cp(name, FAL0));
goto jleave;
}
}
UNINIT(quote, NULL);
if(!(avp->av_flags & a_AMV_VF_BOOL)){
quote = n_shexp_quote_cp(avp->av_value, TRU1);
if(su_cs_cmp(quote, avp->av_value))
msgp = n_string_push_cp(msgp, "wysh ");
}else if(n_poption & n_PO_D_V)
msgp = n_string_push_cp(msgp, "wysh "); /* (for shell-style comment) */
if(avp->av_flags & a_AMV_VF_EXT_LINKED)
msgp = n_string_push_cp(msgp, "environ ");
msgp = n_string_push_cp(msgp, "set ");
msgp = n_string_push_cp(msgp, name);
if(!(avp->av_flags & a_AMV_VF_BOOL)){
msgp = n_string_push_c(msgp, '=');
msgp = n_string_push_cp(msgp, quote);
}else if(n_poption & n_PO_D_V)
msgp = n_string_push_cp(msgp, " #boolean");
jleave:
msgp = n_string_push_c(msgp, '\n');
fputs(n_string_cp(msgp), fp);
NYD2_OU;
return (i > 0 ? 2 : 1);
}
static boole
a_amv_var_c_set(char **ap, BITENUM_IS(u32,a_amv_var_setclr_flags) avscf){
char *cp, *cp2, *varbuf, c;
uz errs;
NYD2_IN;
for(errs = 0; (cp = *ap++) != NIL;){
/* Isolate key */
cp2 = varbuf = n_autorec_alloc(su_cs_len(cp) +1);
for(; (c = *cp) != '=' && c != '\0'; ++cp)
*cp2++ = c;
*cp2 = '\0';
if(c == '\0')
cp = UNCONST(char*,n_empty);
else
++cp;
if(varbuf == cp2){
n_err(_("Empty variable name ignored\n"));
++errs;
}else if(!a_amv_var_check_name(varbuf,
((avscf & a_AMV_VSETCLR_ENV) != 0))){
/* Log done */
++errs;
}else{
struct a_amv_var_carrier avc;
u8 loflags_;
BITENUM_IS(u32,a_amv_var_setclr_flags) avscf_;
boole isunset, xreset;
if((isunset = (varbuf[0] == 'n' && varbuf[1] == 'o'))){
if(c != '\0')
n_err(_("Un`set'ting via \"no\" takes no value: %s=%s\n"),
varbuf, n_shexp_quote_cp(cp, FAL0));
varbuf = &varbuf[2];
}
a_amv_var_revlookup(&avc, varbuf, TRU1);
if((xreset = ((avscf & a_AMV_VSETCLR_LOCAL) && avc.avc_map != NIL))){
ASSERT(a_amv_lopts != NIL);
avscf_ = avscf;
avscf ^= a_AMV_VSETCLR_LOCAL;
loflags_ = a_amv_lopts->as_loflags;
a_amv_lopts->as_loflags = a_AMV_LF_SCOPE;
}
if(isunset)
errs += !a_amv_var_clear(&avc, avscf);
else
errs += !a_amv_var_set(&avc, cp, avscf);
if(xreset){
avscf = avscf_;
a_amv_lopts->as_loflags = loflags_;
}
}
}
NYD2_OU;
return (errs == 0);
}
#ifdef a_AMV_VAR_HAS_OBSOLETE
static void
a_amv_var_obsolete(char const *name){
static struct su_cs_dict a_csd__obsol, *a_csd_obsol;
NYD2_IN;
if(!su_state_has(su_STATE_REPRODUCIBLE)){
if(UNLIKELY(a_csd_obsol == NIL)) /* XXX atexit cleanup */
a_csd_obsol = su_cs_dict_set_treshold_shift(
su_cs_dict_create(&a_csd__obsol, (su_CS_DICT_POW2_SPACED |
su_CS_DICT_HEAD_RESORT | su_CS_DICT_ERR_PASS), NIL), 2);
if(UNLIKELY(!su_cs_dict_has_key(a_csd_obsol, name))){
su_cs_dict_insert(a_csd_obsol, name, NIL);
n_err(_("Warning: variable superseded or obsoleted: %s\n"), name);
}
}
NYD2_OU;
}
#endif
FL int
c_define(void *v){
int rv;
char **args;
NYD_IN;
rv = 1;
if((args = v)[0] == NULL){
rv = (a_amv_mac_show(a_AMV_MF_NONE) == FAL0);
goto jleave;
}
if(args[1] == NULL || args[1][0] != '{' || args[1][1] != '\0' ||
args[2] != NULL){
mx_cmd_print_synopsis(mx_cmd_firstfit("define"), NIL);
goto jleave;
}
rv = (a_amv_mac_def(args[0], a_AMV_MF_NONE) == FAL0);
jleave:
NYD_OU;
return rv;
}
FL int
c_undefine(void *v){
int rv;
char **args;
NYD_IN;
rv = 0;
args = v;
do
rv |= !a_amv_mac_undef(*args, a_AMV_MF_NONE);
while(*++args != NULL);
NYD_OU;
return rv;
}
FL int
c_call(void *vp){
int rv;
NYD_IN;
rv = a_amv_mac_call(vp, FAL0);
NYD_OU;
return rv;
}
FL int
c_call_if(void *vp){
int rv;
NYD_IN;
rv = a_amv_mac_call(vp, TRU1);
NYD_OU;
return rv;
}
FL void
mx_account_leave(void){
/* Note no care for *account* here */
struct a_amv_mac_call_args *amcap;
struct a_amv_mac *amp;
char const *cp;
char *var;
NYD_IN;
if(a_amv_acc_curr != NIL){
/* Is there a cleanup hook? */
var = savecat("on-account-cleanup-", a_amv_acc_curr->am_name);
if((cp = n_var_vlook(var, FAL0)) != NIL ||
(cp = ok_vlook(on_account_cleanup)) != NIL){
if((amp = a_amv_mac_lookup(cp, NIL, a_AMV_MF_NONE)) != NIL){
amcap = n_lofi_calloc(sizeof *amcap);
amcap->amca_name = cp;
amcap->amca_amp = amp;
amcap->amca_unroller = &a_amv_acc_curr->am_lopts;
amcap->amca_loflags = a_AMV_LF_SCOPE_FIXATE;
amcap->amca_no_xcall = TRU1;
n_pstate |= n_PS_HOOK;
(void)a_amv_mac_exec(amcap);
n_pstate &= ~n_PS_HOOK_MASK;
}else
n_err(_("*on-account-leave* hook %s does not exist\n"),
n_shexp_quote_cp(cp, FAL0));
}
/* `localopts'? */
if(a_amv_acc_curr->am_lopts != NIL)
a_amv_lopts_unroll(&a_amv_acc_curr->am_lopts);
/* For accounts this lingers */
--a_amv_acc_curr->am_refcnt;
if(a_amv_acc_curr->am_flags & a_AMV_MF_DELETE)
a_amv_mac_free(a_amv_acc_curr);
}
NYD_OU;
}
FL int
c_account(void *v){
struct a_amv_mac_call_args *amcap;
struct a_amv_mac *amp;
char **args;
int rv, i, oqf, nqf;
NYD_IN;
rv = 1;
if((args = v)[0] == NULL){
rv = (a_amv_mac_show(a_AMV_MF_ACCOUNT) == FAL0);
goto jleave;
}
if(args[1] && args[1][0] == '{' && args[1][1] == '\0'){
if(args[2] != NULL){
mx_cmd_print_synopsis(mx_cmd_firstfit("account"), NIL);
goto jleave;
}
if(!su_cs_cmp_case(args[0], ACCOUNT_NULL)){
n_err(_("account: cannot use reserved name: %s\n"),
ACCOUNT_NULL);
goto jleave;
}
rv = (a_amv_mac_def(args[0], a_AMV_MF_ACCOUNT) == FAL0);
goto jleave;
}
if(n_pstate & n_PS_HOOK_MASK){
n_err(_("account: cannot change account from within a hook\n"));
goto jleave;
}
save_mbox_for_possible_quitstuff();
amp = NULL;
if(su_cs_cmp_case(args[0], ACCOUNT_NULL) != 0 &&
(amp = a_amv_mac_lookup(args[0], NULL, a_AMV_MF_ACCOUNT)) == NULL){
n_err(_("account: account does not exist: %s\n"), args[0]);
goto jleave;
}
oqf = savequitflags();
/* Shutdown the active account */
if(a_amv_acc_curr != NULL)
mx_account_leave();
a_amv_acc_curr = amp;
/* And switch to any non-"null" account */
if(amp != NULL){
ASSERT(amp->am_lopts == NULL);
n_PS_ROOT_BLOCK(ok_vset(account, amp->am_name));
amcap = n_lofi_calloc(sizeof *amcap);
amcap->amca_name = amp->am_name;
amcap->amca_amp = amp;
amcap->amca_unroller = &->am_lopts;
amcap->amca_loflags = a_AMV_LF_SCOPE_FIXATE;
amcap->amca_no_xcall = TRU1;
++amp->am_refcnt; /* We may not run 0 to avoid being deleted! */
if(!a_amv_mac_exec(amcap) || n_pstate_ex_no != 0){
/* XXX account switch incomplete, unroll? */
mx_account_leave();
n_PS_ROOT_BLOCK(ok_vclear(account));
n_err(_("account: failed to switch to account: %s\n"), amp->am_name);
goto jleave;
}
}else
n_PS_ROOT_BLOCK(ok_vclear(account));
/* Otherwise likely initial setfile() in a_main_rcv_mode() will pick up */
if(n_psonce & n_PSO_STARTED){
ASSERT(!(n_pstate & n_PS_HOOK_MASK));
nqf = savequitflags(); /* TODO obsolete (leave -> void -> new box!) */
restorequitflags(oqf);
i = setfile("%", FEDIT_SYSBOX | FEDIT_ACCOUNT);
restorequitflags(nqf);
if(i < 0)
goto jleave;
temporary_folder_hook_check(FAL0);
if(i != 0 && !ok_blook(emptystart)) /* Avoid annoying "double message" */
goto jleave;
n_folder_announce(n_ANNOUNCE_CHANGE);
}
rv = 0;
jleave:
NYD_OU;
return rv;
}
FL int
c_unaccount(void *v){
int rv;
char **args;
NYD_IN;
rv = 0;
args = v;
do
rv |= !a_amv_mac_undef(*args, a_AMV_MF_ACCOUNT);
while(*++args != NULL);
NYD_OU;
return rv;
}
FL int
c_localopts(void *vp){
enum a_amv_loflags alf, alm;
char const **argv;
int rv;
NYD_IN;
rv = 1;
if(a_amv_lopts == NULL){
n_err(_("Cannot use `localopts' in this context\n"));
goto jleave;
}
if((argv = vp)[1] == NULL || su_cs_starts_with_case("scope", (++argv)[-1]))
alf = alm = a_AMV_LF_SCOPE;
else if(su_cs_starts_with_case("call", argv[-1]))
alf = a_AMV_LF_CALL, alm = a_AMV_LF_CALL_MASK;
else if(su_cs_starts_with_case("call-fixate", argv[-1]))
alf = a_AMV_LF_CALL_FIXATE, alm = a_AMV_LF_CALL_MASK;
else{
jesynopsis:
mx_cmd_print_synopsis(mx_cmd_firstfit("localopts"), NIL);
goto jleave;
}
if(alf == a_AMV_LF_SCOPE &&
(a_amv_lopts->as_loflags & a_AMV_LF_SCOPE_FIXATE)){
if(n_poption & n_PO_D_V)
n_err(_("Cannot turn off `localopts', setting is fixated\n"));
goto jleave;
}
if((rv = n_boolify(*argv, UZ_MAX, FAL0)) < FAL0)
goto jesynopsis;
a_amv_lopts->as_loflags &= ~alm;
if(rv > FAL0)
a_amv_lopts->as_loflags |= alf;
rv = 0;
jleave:
NYD_OU;
return rv;
}
FL int
c_shift(void *vp){ /* xxx move to bottom, not in macro part! */
struct a_amv_pospar *appp;
u16 i;
int rv;
NYD_IN;
rv = 1;
if((vp = *(char**)vp) == NULL)
i = 1;
else{
s16 sib;
if((su_idec_s16_cp(&sib, vp, 10, NULL
) & (su_IDEC_STATE_EMASK | su_IDEC_STATE_CONSUMED)
) != su_IDEC_STATE_CONSUMED || sib < 0){
n_err(_("shift: invalid argument: %s\n"), vp);
goto jleave;
}
i = (u16)sib;
}
/* If in in a macro/xy */
if(a_amv_lopts != NULL){
struct a_amv_mac const *amp;
struct a_amv_mac_call_args *amcap;
/* Explicitly do allow `vpospar' created things! */
amp = (amcap = a_amv_lopts->as_amcap)->amca_amp;
if((amp == NULL || amcap->amca_ps_hook_mask ||
(amp->am_flags & a_AMV_MF_TYPE_MASK) == a_AMV_MF_ACCOUNT) &&
amcap->amca_pospar.app_not_heap){
n_err(_("Cannot use `shift' in `account's or hook macros etc.\n"));
goto jleave;
}
appp = &amcap->amca_pospar;
}else
appp = &a_amv_pospar;
if(i > appp->app_count){
n_err(_("shift: cannot shift %hu of %hu parameters\n"),
i, appp->app_count);
goto jleave;
}else{
appp->app_idx += i;
appp->app_count -= i;
rv = 0;
}
jleave:
NYD_OU;
return rv;
}
FL int
c_return(void *vp){ /* TODO the exit status should be m_si64! */
int rv;
NYD_IN;
if(a_amv_lopts != NULL){
char const **argv;
n_go_input_force_eof();
n_pstate_err_no = su_ERR_NONE;
rv = 0;
if((argv = vp)[0] != NULL){
s32 i;
if((su_idec_s32_cp(&i, argv[0], 10, NULL
) & (su_IDEC_STATE_EMASK | su_IDEC_STATE_CONSUMED)
) == su_IDEC_STATE_CONSUMED && i >= 0)
rv = (int)i;
else{
n_err(_("return: return value argument is invalid: %s\n"),
argv[0]);
n_pstate_err_no = su_ERR_INVAL;
rv = 1;
}
if(argv[1] != NULL){
if((su_idec_s32_cp(&i, argv[1], 10, NULL
) & (su_IDEC_STATE_EMASK | su_IDEC_STATE_CONSUMED)
) == su_IDEC_STATE_CONSUMED && i >= 0)
n_pstate_err_no = i;
else{
n_err(_("return: error number argument is invalid: %s\n"),
argv[1]);
n_pstate_err_no = su_ERR_INVAL;
rv = 1;
}
}
}
}else{
n_err(_("Can only use `return' in a macro\n"));
n_pstate_err_no = su_ERR_OPNOTSUPP;
rv = 1;
}
NYD_OU;
return rv;
}
FL void
temporary_on_xy_hook_caller(char const *hname, char const *mac,
boole sigs_held){
struct a_amv_mac_call_args *amcap;
struct a_amv_mac *amp;
NYD_IN;
if(mac != NIL){
if((amp = a_amv_mac_lookup(mac, NIL, a_AMV_MF_NONE)) != NIL){
if(sigs_held)
mx_sigs_all_rele();
amcap = n_lofi_calloc(sizeof *amcap);
amcap->amca_name = mac;
amcap->amca_amp = amp;
amcap->amca_ps_hook_mask = TRU1;
amcap->amca_no_xcall = TRU1;
n_pstate &= ~n_PS_HOOK_MASK;
n_pstate |= n_PS_HOOK;
a_amv_mac_exec(amcap);
if(sigs_held)
mx_sigs_all_holdx();
}else
n_err(_("*%s* macro does not exist: %s\n"), hname, mac);
}
NYD_OU;
}
FL boole
temporary_folder_hook_check(boole nmail){ /* TODO temporary, v15: drop */
struct a_amv_mac_call_args *amcap;
struct a_amv_mac *amp;
uz len;
char const *cp;
char *var;
boole rv;
NYD_IN;
rv = TRU1;
var = n_autorec_alloc(len = su_cs_len(mailname) +
sizeof("folder-hook-") -1 +1);
/* First try the fully resolved path */
snprintf(var, len, "folder-hook-%s", mailname);
if((cp = n_var_vlook(var, FAL0)) != NULL)
goto jmac;
/* If we are under *folder*, try the usual +NAME syntax, too */
if(displayname[0] == '+'){
char *x;
for(x = &mailname[len]; x != mailname; --x)
if(x[-1] == '/'){
snprintf(var, len, "folder-hook-+%s", x);
if((cp = n_var_vlook(var, FAL0)) != NULL)
goto jmac;
break;
}
}
/* Plain *folder-hook* is our last try */
if((cp = ok_vlook(folder_hook)) == NULL)
goto jleave;
jmac:
if((amp = a_amv_mac_lookup(cp, NULL, a_AMV_MF_NONE)) == NULL){
n_err(_("Cannot call *folder-hook* for %s: macro does not exist: %s\n"),
n_shexp_quote_cp(displayname, FAL0), cp);
rv = FAL0;
goto jleave;
}
amcap = n_lofi_calloc(sizeof *amcap);
amcap->amca_name = cp;
amcap->amca_amp = amp;
n_pstate &= ~n_PS_HOOK_MASK;
if(nmail){
amcap->amca_unroller = NULL;
n_pstate |= n_PS_HOOK_NEWMAIL;
}else{
amcap->amca_unroller = &a_amv_folder_hook_lopts;
n_pstate |= n_PS_HOOK;
}
amcap->amca_loflags = a_AMV_LF_SCOPE_FIXATE;
amcap->amca_ps_hook_mask = TRU1;
amcap->amca_no_xcall = TRU1;
rv = a_amv_mac_exec(amcap);
n_pstate &= ~n_PS_HOOK_MASK;
jleave:
NYD_OU;
return rv;
}
FL void
temporary_folder_hook_unroll(void){ /* XXX intermediate hack */
NYD_IN;
if(a_amv_folder_hook_lopts != NULL){
void *save = a_amv_lopts;
a_amv_lopts = NULL;
a_amv_lopts_unroll(&a_amv_folder_hook_lopts);
ASSERT(a_amv_folder_hook_lopts == NULL);
a_amv_lopts = save;
}
NYD_OU;
}
FL void
temporary_compose_mode_hook_call(char const *macname,
void (*hook_pre)(void *), void *hook_arg){
/* TODO compose_mode_hook_call() temporary, v15: generalize; see a_GO_SPLICE
* TODO comment in go.c for the right way of doing things! */
static struct a_amv_lostack *cmh_losp;
struct a_amv_mac_call_args *amcap;
struct a_amv_mac *amp;
NYD_IN;
amp = NULL;
if(macname == (char*)-1){
a_amv_mac__finalize(cmh_losp);
cmh_losp = NULL;
}else if(macname != NULL &&
(amp = a_amv_mac_lookup(macname, NULL, a_AMV_MF_NONE)) == NULL)
n_err(_("Cannot call *on-compose-**: macro does not exist: %s\n"),
macname);
else{
amcap = n_lofi_calloc(sizeof *amcap);
amcap->amca_name = (macname != NULL) ? macname
: "*on-compose-splice(-shell)?*";
amcap->amca_amp = amp;
amcap->amca_unroller = &a_amv_compose_lopts;
amcap->amca_hook_pre = hook_pre;
amcap->amca_hook_arg = hook_arg;
amcap->amca_loflags = a_AMV_LF_SCOPE_FIXATE;
amcap->amca_ps_hook_mask = TRU1;
amcap->amca_no_xcall = TRU1;
n_pstate &= ~n_PS_HOOK_MASK;
n_pstate |= n_PS_HOOK;
if(macname != NULL)
a_amv_mac_exec(amcap);
else{
cmh_losp = n_lofi_calloc(sizeof *cmh_losp);
cmh_losp->as_global_saved = a_amv_lopts;
cmh_losp->as_lopts = *(cmh_losp->as_amcap = amcap)->amca_unroller;
cmh_losp->as_loflags = a_AMV_LF_SCOPE_FIXATE;
a_amv_lopts = cmh_losp;
}
}
NYD_OU;
}
FL void
temporary_compose_mode_hook_unroll(void){ /* XXX intermediate hack */
NYD_IN;
if(a_amv_compose_lopts != NULL){
void *save = a_amv_lopts;
a_amv_lopts = NULL;
a_amv_lopts_unroll(&a_amv_compose_lopts);
ASSERT(a_amv_compose_lopts == NULL);
a_amv_lopts = save;
}
NYD_OU;
}
#ifdef mx_HAVE_HISTORY
FL boole
temporary_addhist_hook(char const *ctx, char const *gabby_type,
char const *histent){
/* XXX temporary_addhist_hook(): intermediate hack */
struct a_amv_mac_call_args *amcap;
s32 perrn, pexn;
struct a_amv_mac *amp;
char const *macname, *argv[4];
boole rv;
NYD_IN;
if((macname = ok_vlook(on_history_addition)) == NULL)
rv = TRUM1;
else if((amp = a_amv_mac_lookup(macname, NULL, a_AMV_MF_NONE)) == NULL){
n_err(_("Cannot call *on-history-addition*: macro does not exist: %s\n"),
macname);
rv = TRUM1;
}else{
perrn = n_pstate_err_no;
pexn = n_pstate_ex_no;
argv[0] = ctx;
argv[1] = gabby_type;
argv[2] = histent;
argv[3] = NULL;
amcap = n_lofi_calloc(sizeof *amcap);
amcap->amca_name = macname;
amcap->amca_amp = amp;
amcap->amca_loflags = a_AMV_LF_SCOPE_FIXATE;
amcap->amca_no_xcall = amcap->amca_ignerr = TRU1;
amcap->amca_pospar.app_count = 3;
amcap->amca_pospar.app_not_heap = TRU1;
amcap->amca_pospar.app_dat = argv;
if(!a_amv_mac_exec(amcap))
rv = TRUM1;
else
rv = (n_pstate_ex_no == 0);
n_pstate_err_no = perrn;
n_pstate_ex_no = pexn;
}
NYD_OU;
return rv;
}
#endif /* mx_HAVE_HISTORY */
#ifdef mx_HAVE_REGEX
FL char *
temporary_pospar_access_hook(char const *name, char const **argv, u32 argc,
char *(*hook)(void *uservp), void *uservp){
struct a_amv_lostack los;
struct a_amv_mac_call_args amca;
char *rv;
NYD_IN;
su_mem_set(&amca, 0, sizeof amca);
amca.amca_name = name;
amca.amca_amp = a_AMV_MACKY_MACK;
amca.amca_pospar.app_count = argc;
amca.amca_pospar.app_not_heap = TRU1;
amca.amca_pospar.app_dat = argv;
su_mem_set(&los, 0, sizeof los);
mx_sigs_all_holdx(); /* TODO DISLIKE! */
los.as_global_saved = a_amv_lopts;
los.as_amcap = &amca;
los.as_up = los.as_global_saved;
a_amv_lopts = &los;
rv = (*hook)(uservp);
a_amv_lopts = los.as_global_saved;
mx_sigs_all_rele(); /* TODO DISLIKE! */
NYD_OU;
return rv;
}
#endif /* mx_HAVE_REGEX */
FL void
n_var_setup_batch_mode(void){
NYD2_IN;
n_pstate |= n_PS_ROBOT; /* (be silent unsetting undefined variables) */
n_poption |= n_PO_S_FLAG_TEMPORARY;
ok_vset(MAIL, n_path_devnull);
ok_vset(MBOX, n_path_devnull);
ok_bset(emptystart);
ok_bclear(errexit);
ok_bclear(header);
ok_vset(inbox, n_path_devnull);
ok_bclear(posix);
ok_bset(quiet);
ok_vset(sendwait, su_empty);
ok_bset(typescript_mode);
n_poption &= ~n_PO_S_FLAG_TEMPORARY;
n_pstate &= ~n_PS_ROBOT;
NYD2_OU;
}
FL boole
n_var_is_user_writable(char const *name){
struct a_amv_var_carrier avc;
struct a_amv_var_map const *avmp;
boole rv;
NYD_IN;
a_amv_var_revlookup(&avc, name, TRU1);
if((avmp = avc.avc_map) == NULL)
rv = TRU1;
else
rv = ((avmp->avm_flags & (a_AMV_VF_BOOL | a_AMV_VF_RDONLY)) == 0);
NYD_OU;
return rv;
}
FL char *
n_var_oklook(enum okeys okey){
struct a_amv_var_carrier avc;
char *rv;
struct a_amv_var_map const *avmp;
NYD_IN;
su_mem_set(&avc, 0, sizeof avc);
avc.avc_map = avmp = &a_amv_var_map[okey];
avc.avc_name = &a_amv_var_names[avmp->avm_keyoff];
avc.avc_hash = avmp->avm_hash;
avc.avc_okey = okey;
if(a_amv_var_lookup(&avc, a_AMV_VLOOK_NONE))
rv = avc.avc_var->av_value;
else
rv = NULL;
NYD_OU;
return rv;
}
FL boole
n_var_okset(enum okeys okey, up val){
struct a_amv_var_carrier avc;
boole ok;
struct a_amv_var_map const *avmp;
NYD_IN;
su_mem_set(&avc, 0, sizeof avc);
avc.avc_map = avmp = &a_amv_var_map[okey];
avc.avc_name = &a_amv_var_names[avmp->avm_keyoff];
avc.avc_hash = avmp->avm_hash;
avc.avc_okey = okey;
ok = a_amv_var_set(&avc, (val == 0x1 ? n_empty : (char const*)val),
a_AMV_VSETCLR_NONE);
NYD_OU;
return ok;
}
FL boole
n_var_okclear(enum okeys okey){
struct a_amv_var_carrier avc;
boole rv;
struct a_amv_var_map const *avmp;
NYD_IN;
su_mem_set(&avc, 0, sizeof avc);
avc.avc_map = avmp = &a_amv_var_map[okey];
avc.avc_name = &a_amv_var_names[avmp->avm_keyoff];
avc.avc_hash = avmp->avm_hash;
avc.avc_okey = okey;
rv = a_amv_var_clear(&avc, a_AMV_VSETCLR_NONE);
NYD_OU;
return rv;
}
FL char const *
n_var_vlook(char const *vokey, boole try_getenv){
struct a_amv_var_carrier avc;
char const *rv;
NYD_IN;
a_amv_var_revlookup(&avc, vokey, FAL0);
switch((enum a_amv_var_special_category)avc.avc_special_cat){
default: /* silence CC */
case a_AMV_VSC_NONE:
rv = NULL;
if(a_amv_var_lookup(&avc, (a_AMV_VLOOK_LOCAL |
(try_getenv ? a_AMV_VLOOK_LOG_OBSOLETE : a_AMV_VLOOK_NONE))))
rv = avc.avc_var->av_value;
/* Only check the environment for something that is otherwise unknown */
else if(try_getenv && avc.avc_map == NULL &&
!a_amv_var_revlookup_chain(&avc, vokey))
rv = getenv(vokey);
break;
case a_AMV_VSC_GLOBAL:
rv = a_amv_var_vsc_global(&avc);
break;
case a_AMV_VSC_MULTIPLEX:
rv = a_amv_var_vsc_multiplex(&avc);
break;
case a_AMV_VSC_POSPAR:
case a_AMV_VSC_POSPAR_ENV:
rv = a_amv_var_vsc_pospar(&avc);
break;
}
NYD_OU;
return rv;
}
FL boole
n_var_vexplode(void const **cookie){
struct a_amv_pospar *appp;
NYD_IN;
appp = (a_amv_lopts != NULL) ? &a_amv_lopts->as_amcap->amca_pospar
: &a_amv_pospar;
*cookie = (appp->app_count > 0) ? &appp->app_dat[appp->app_idx] : NULL;
NYD_OU;
return (*cookie != NULL);
}
FL boole
n_var_vset(char const *vokey, up val){
struct a_amv_var_carrier avc;
boole ok;
NYD_IN;
a_amv_var_revlookup(&avc, vokey, TRU1);
ok = a_amv_var_set(&avc, (val == 0x1 ? n_empty : (char const*)val),
a_AMV_VSETCLR_NONE);
NYD_OU;
return ok;
}
FL boole
n_var_vclear(char const *vokey){
struct a_amv_var_carrier avc;
boole ok;
NYD_IN;
a_amv_var_revlookup(&avc, vokey, FAL0);
ok = a_amv_var_clear(&avc, a_AMV_VSETCLR_NONE);
NYD_OU;
return ok;
}
#ifdef mx_HAVE_NET
FL char *
n_var_xoklook(enum okeys okey, struct mx_url const *urlp,
enum okey_xlook_mode oxm){
struct a_amv_var_carrier avc;
struct str const *usp;
uz nlen;
char *nbuf, *rv;
NYD_IN;
ASSERT(oxm & (OXM_PLAIN | OXM_H_P | OXM_U_H_P));
/* For simplicity: allow this case too */
if(!(oxm & (OXM_H_P | OXM_U_H_P))){
nbuf = NULL;
goto jplain;
}
su_mem_set(&avc, 0, sizeof avc);
avc.avc_name = &a_amv_var_names[(avc.avc_map = &a_amv_var_map[okey]
)->avm_keyoff];
avc.avc_okey = okey;
avc.avc_is_chain_variant = TRU1;
usp = (oxm & OXM_U_H_P) ? &urlp->url_u_h_p : &urlp->url_h_p;
nlen = su_cs_len(avc.avc_name);
nbuf = n_lofi_alloc(nlen + 1 + usp->l +1);
su_mem_copy(nbuf, avc.avc_name, nlen);
/* One of .url_u_h_p and .url_h_p we test in here */
nbuf[nlen++] = '-';
su_mem_copy(&nbuf[nlen], usp->s, usp->l +1);
avc.avc_name = nbuf;
avc.avc_hash = a_AMV_NAME2HASH(avc.avc_name);
if(a_amv_var_lookup(&avc, a_AMV_VLOOK_NONE))
goto jvar;
/* The second */
if((oxm & (OXM_U_H_P | OXM_H_P)) == (OXM_U_H_P | OXM_H_P)){
usp = &urlp->url_h_p;
su_mem_copy(&nbuf[nlen], usp->s, usp->l +1);
avc.avc_name = nbuf;
avc.avc_hash = a_AMV_NAME2HASH(avc.avc_name);
if(a_amv_var_lookup(&avc, a_AMV_VLOOK_NONE)){
jvar:
rv = avc.avc_var->av_value;
goto jleave;
}
}
jplain:
/*avc.avc_is_chain_variant = FAL0;*/
rv = (oxm & OXM_PLAIN) ? n_var_oklook(okey) : NULL;
jleave:
if(nbuf != NULL)
n_lofi_free(nbuf);
NYD_OU;
return rv;
}
#endif /* mx_HAVE_NET */
FL int
c_set(void *vp){
int err;
char **ap;
NYD_IN;
if(*(ap = vp) == NULL){
a_amv_var_show_all();
err = 0;
}else{
enum a_amv_var_setclr_flags avscf;
if(!(n_pstate & n_PS_ARGMOD_LOCAL))
avscf = a_AMV_VSETCLR_NONE;
else{
if(a_amv_lopts == NULL){
n_err(_("set: cannot use `local' in this context\n"));
err = 1;
goto jleave;
}
avscf = a_AMV_VSETCLR_LOCAL;
}
err = !a_amv_var_c_set(ap, avscf);
}
jleave:
NYD_OU;
return err;
}
FL int
c_unset(void *vp){
struct a_amv_var_carrier avc;
u8 loflags_;
boole xreset;
char **ap;
int err;
BITENUM_IS(u32,a_amv_var_setclr_flags) avscf, avscf_;
NYD_IN;
if(!(n_pstate & n_PS_ARGMOD_LOCAL))
avscf = a_AMV_VSETCLR_NONE;
else{
if(a_amv_lopts == NULL){
n_err(_("unset: cannot use `local' in this context\n"));
err = 1;
goto jleave;
}
avscf = a_AMV_VSETCLR_LOCAL;
}
for(err = 0, ap = vp; *ap != NULL; ++ap){
if(!a_amv_var_check_name(*ap, FAL0)){
err |= 1;
continue;
}
a_amv_var_revlookup(&avc, *ap, FAL0);
if((xreset = ((avscf & a_AMV_VSETCLR_LOCAL) && avc.avc_map != NIL))){
ASSERT(a_amv_lopts != NIL);
avscf_ = avscf;
avscf ^= a_AMV_VSETCLR_LOCAL;
loflags_ = a_amv_lopts->as_loflags;
a_amv_lopts->as_loflags = a_AMV_LF_SCOPE;
}
err |= !a_amv_var_clear(&avc, avscf);
if(xreset){
avscf = avscf_;
a_amv_lopts->as_loflags = loflags_;
}
}
jleave:
NYD_OU;
return err;
}
FL int
c_varshow(void *v){
char **ap;
NYD_IN;
if(*(ap = v) == NULL)
v = NULL;
else{
struct n_string msg, *msgp = &msg;
msgp = n_string_creat(msgp);
for(; *ap != NULL; ++ap)
if(a_amv_var_check_name(*ap, FAL0))
a_amv_var_show(*ap, n_stdout, msgp);
n_string_gut(msgp);
}
NYD_OU;
return (v == NULL ? !STOP : !OKAY); /* xxx 1:bad 0:good -- do some */
}
FL int
c_environ(void *v){
struct a_amv_var_carrier avc;
int err;
char **ap;
boole islnk;
NYD_IN;
if((islnk = su_cs_starts_with_case("link", *(ap = v))) ||
su_cs_starts_with_case("unlink", *ap)){
for(err = 0; *++ap != NIL;){
if(!a_amv_var_check_name(*ap, TRU1)){
err = 1;
continue;
}
a_amv_var_revlookup(&avc, *ap, TRU1);
if(a_amv_var_lookup(&avc, (a_AMV_VLOOK_NONE |
a_AMV_VLOOK_LOG_OBSOLETE)) && (islnk ||
(avc.avc_var->av_flags & a_AMV_VF_EXT_LINKED))){
if(!islnk){
avc.avc_var->av_flags &= ~a_AMV_VF_EXT_LINKED;
continue;
}else if(avc.avc_var->av_flags &
(a_AMV_VF_ENV | a_AMV_VF_EXT_LINKED)){
if(n_poption & n_PO_D_V)
n_err(_("environ: link: already established: %s\n"), *ap);
continue;
}
avc.avc_var->av_flags |= a_AMV_VF_EXT_LINKED;
if(!(avc.avc_var->av_flags & a_AMV_VF_ENV))
a_amv_var__putenv(&avc, avc.avc_var);
}else if(!islnk){
n_err(_("environ: unlink: no link established: %s\n"), *ap);
err = 1;
}else{
char const *evp = getenv(*ap);
if(evp != NULL)
err |= !a_amv_var_set(&avc, evp, a_AMV_VSETCLR_ENV);
else{
n_err(_("environ: link: cannot link to non-existent: %s\n"),
*ap);
err = 1;
}
}
}
}else if(su_cs_starts_with_case("set", *ap))
err = !a_amv_var_c_set(++ap, a_AMV_VSETCLR_ENV);
else if(su_cs_starts_with_case("unset", *ap)){
for(err = 0; *++ap != NIL;){
if(!a_amv_var_check_name(*ap, TRU1)){
err = 1;
continue;
}
a_amv_var_revlookup(&avc, *ap, FAL0);
if(!a_amv_var_clear(&avc, a_AMV_VSETCLR_ENV))
err = 1;
}
}else{
mx_cmd_print_synopsis(mx_cmd_firstfit("environ"), NIL);
err = 1;
}
NYD_OU;
return err;
}
FL int
c_vpospar(void *v){
struct mx_cmd_arg *cap;
uz i;
struct a_amv_pospar *appp;
enum{
a_NONE = 0,
a_ERR = 1u<<0,
a_SET = 1u<<1,
a_CLEAR = 1u<<2,
a_QUOTE = 1u<<3
} f;
char const *varres;
struct mx_cmd_arg_ctx *cacp;
NYD_IN;
n_pstate_err_no = su_ERR_NONE;
UNINIT(varres, n_empty);
cacp = v;
cap = cacp->cac_arg;
if(su_cs_starts_with_case("set", cap->ca_arg.ca_str.s))
f = a_SET;
else if(su_cs_starts_with_case("clear", cap->ca_arg.ca_str.s))
f = a_CLEAR;
else if(su_cs_starts_with_case("quote", cap->ca_arg.ca_str.s))
f = a_QUOTE;
else{
n_err(_("vpospar: invalid subcommand: %s\n"),
n_shexp_quote_cp(cap->ca_arg.ca_str.s, FAL0));
mx_cmd_print_synopsis(mx_cmd_firstfit("vpospar"), NIL);
n_pstate_err_no = su_ERR_INVAL;
f = a_ERR;
goto jleave;
}
--cacp->cac_no;
if((f & (a_CLEAR | a_QUOTE)) && cap->ca_next != NULL){
n_err(_("vpospar: %s: takes no argument\n"), cap->ca_arg.ca_str.s);
n_pstate_err_no = su_ERR_INVAL;
f = a_ERR;
goto jleave;
}
cap = cap->ca_next;
/* If in a macro, we need to overwrite the local instead of global argv */
appp = (a_amv_lopts != NULL) ? &a_amv_lopts->as_amcap->amca_pospar
: &a_amv_pospar;
if(f & (a_SET | a_CLEAR)){
if(cacp->cac_vput != NULL)
n_err(_("vpospar: `vput' only supported for `quote' subcommand\n"));
if(!appp->app_not_heap && appp->app_maxcount > 0){
for(i = appp->app_maxcount; i-- != 0;)
n_free(n_UNCONST(appp->app_dat[i]));
n_free(appp->app_dat);
}
su_mem_set(appp, 0, sizeof *appp);
if(f & a_SET){
if((i = cacp->cac_no) > a_AMV_POSPAR_MAX){
n_err(_("vpospar: overflow: %" PRIuZ " arguments!\n"), i);
n_pstate_err_no = su_ERR_OVERFLOW;
f = a_ERR;
goto jleave;
}
su_mem_set(appp, 0, sizeof *appp);
if(i > 0){
appp->app_maxcount = appp->app_count = (u16)i;
/* XXX Optimize: store it all in one chunk! */
++i;
i *= sizeof *appp->app_dat;
appp->app_dat = n_alloc(i);
for(i = 0; cap != NULL; ++i, cap = cap->ca_next){
appp->app_dat[i] = n_alloc(cap->ca_arg.ca_str.l +1);
su_mem_copy(n_UNCONST(appp->app_dat[i]), cap->ca_arg.ca_str.s,
cap->ca_arg.ca_str.l +1);
}
appp->app_dat[i] = NULL;
}
}
}else{
if(appp->app_count == 0)
varres = n_empty;
else{
struct str in;
struct n_string s_b, *s;
char sep1, sep2;
s = n_string_creat_auto(&s_b);
sep1 = *ok_vlook(ifs);
sep2 = *ok_vlook(ifs_ws);
if(sep1 == sep2)
sep2 = '\0';
if(sep1 == '\0')
sep1 = ' ';
for(i = 0; i < appp->app_count; ++i){
if(s->s_len){
if(!n_string_can_book(s, 2))
goto jeover;
s = n_string_push_c(s, sep1);
if(sep2 != '\0')
s = n_string_push_c(s, sep2);
}
in.l = su_cs_len(in.s =
n_UNCONST(appp->app_dat[i + appp->app_idx]));
if(!n_string_can_book(s, in.l)){
jeover:
n_err(_("vpospar: overflow: string too long!\n"));
n_pstate_err_no = su_ERR_OVERFLOW;
f = a_ERR;
goto jleave;
}
s = n_shexp_quote(s, &in, TRU1);
}
varres = n_string_cp(s);
}
if(cacp->cac_vput == NULL){
if(fprintf(n_stdout, "%s\n", varres) < 0){
n_pstate_err_no = su_err_no();
f |= a_ERR;
}
}else if(!n_var_vset(cacp->cac_vput, (up)varres)){
n_pstate_err_no = su_ERR_NOTSUP;
f |= a_ERR;
}
}
jleave:
NYD_OU;
return (f & a_ERR) ? 1 : 0;
}
#undef a_AMV_VLOOK_LOG_OBSOLETE
#include "su/code-ou.h"
/* s-it-mode */
|
catroll/mailx
|
include/mx/nailfuns.h
|
/*@ S-nail - a mail user agent derived from Berkeley Mail.
*@ Function prototypes and function-alike macros.
*@ TODO Should be split in myriads of FEATURE-GROUP.h headers.
*
* Copyright (c) 2000-2004 <NAME>, Freiburg i. Br., Germany.
* Copyright (c) 2012 - 2020 <NAME> <<EMAIL>>.
* SPDX-License-Identifier: BSD-3-Clause TODO ISC
*/
/*
* Copyright (c) 1980, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
struct mx_attachment;
struct mx_cmd_arg;
struct su_cs_dict;
struct quoteflt;
/*
* TODO Convert optional utility+ functions to n_*(); ditto
* TODO else use generic module-specific prefixes: str_(), am[em]_, sm[em]_, ..
*/
/* TODO s-it-mode: not really (docu, funnames, funargs, etc) */
#undef FL
#ifndef mx_HAVE_AMALGAMATION
# define FL extern
#else
# define FL static
#endif
/*
* Macro-based generics
*/
/* RFC 822, 3.2. */
#define fieldnamechar(c) \
(su_cs_is_ascii(c) && (c) > 040 && (c) != 0177 && (c) != ':')
/* Single-threaded, use unlocked I/O */
#ifdef mx_HAVE_PUTC_UNLOCKED
# undef getc
# define getc(c) getc_unlocked(c)
# undef putc
# define putc(c, f) putc_unlocked(c, f)
#endif
/* There are problems with dup()ing of file-descriptors for child processes.
* We have to somehow accomplish that the FILE* fp makes itself comfortable
* with the *real* offset of the underlying file descriptor.
* POSIX Issue 7 overloaded fflush(3): if used on a readable stream, then
*
* if the file is not already at EOF, and the file is one capable of
* seeking, the file offset of the underlying open file description shall
* be set to the file position of the stream */
#if !su_OS_OPENBSD &&\
defined _POSIX_VERSION && _POSIX_VERSION + 0 >= 200809L
# define n_real_seek(FP,OFF,WH) (fseek(FP, OFF, WH) != -1 && fflush(FP) != EOF)
# define really_rewind(stream) \
do{\
rewind(stream);\
fflush(stream);\
}while(0)
#else
# define n_real_seek(FP,OFF,WH) \
(fseek(FP, OFF, WH) != -1 && fflush(FP) != EOF &&\
lseek(fileno(FP), OFF, WH) != -1)
# define really_rewind(stream) \
do{\
rewind(stream);\
fflush(stream);\
lseek(fileno(stream), 0, SEEK_SET);\
}while(0)
#endif
/* fflush() and rewind() */
#define fflush_rewind(stream) \
do{\
fflush(stream);\
rewind(stream);\
}while(0)
/* Truncate a file to the last character written. This is useful just before
* closing an old file that was opened for read/write */
#define ftrunc(stream) \
do{\
off_t off;\
fflush(stream);\
off = ftell(stream);\
if(off >= 0)\
ftruncate(fileno(stream), off);\
}while(0)
/*
* accmacvar.c
*/
/* Macros: `define', `undefine', `call', `call_if' */
FL int c_define(void *v);
FL int c_undefine(void *v);
FL int c_call(void *v);
FL int c_call_if(void *v);
/* Accounts: `account', `unaccount' */
FL void mx_account_leave(void);
FL int c_account(void *v);
FL int c_unaccount(void *v);
/* `localopts', `shift', `return' */
FL int c_localopts(void *vp);
FL int c_shift(void *vp);
FL int c_return(void *vp);
/* TODO - Main loop on tick event: mx_sigs_all_holdx() is active
* TODO - main.c *on-program-exit*
* mac must not be NIL */
FL void temporary_on_xy_hook_caller(char const *hname, char const *mac,
boole sigs_held);
/* TODO Check whether a *folder-hook* exists for currently active mailbox */
FL boole temporary_folder_hook_check(boole nmail);
FL void temporary_folder_hook_unroll(void); /* XXX im. hack */
/* TODO v15 drop Invoke compose hook macname */
FL void temporary_compose_mode_hook_call(char const *macname,
void (*hook_pre)(void *), void *hook_arg);
FL void temporary_compose_mode_hook_unroll(void);
#ifdef mx_HAVE_HISTORY
/* TODO *on-history-addition* */
FL boole temporary_addhist_hook(char const *ctx, char const *gabby_type,
char const *histent);
#endif
/* TODO v15 drop: let shexp_parse_token take a carrier with positional
* TODO params, then let callers use that as such!!
* Call hook in a recursed environment named name where positional params are
* setup according to argv/argc. NOTE: all signals blocked! */
#ifdef mx_HAVE_REGEX
FL char *temporary_pospar_access_hook(char const *name, char const **argv,
u32 argc, char *(*hook)(void *uservp), void *uservp);
#endif
/* Setting up batch mode, variable-handling side */
FL void n_var_setup_batch_mode(void);
/* Can name freely be used as a variable by users? */
FL boole n_var_is_user_writable(char const *name);
/* Don't use n_var_* unless you *really* have to! */
/* Constant option key look/(un)set/clear */
FL char *n_var_oklook(enum okeys okey);
#define ok_blook(C) (n_var_oklook(su_CONCAT(ok_b_, C)) != NULL)
#define ok_vlook(C) n_var_oklook(su_CONCAT(ok_v_, C))
FL boole n_var_okset(enum okeys okey, up val);
#define ok_bset(C) \
n_var_okset(su_CONCAT(ok_b_, C), (up)TRU1)
#define ok_vset(C,V) \
n_var_okset(su_CONCAT(ok_v_, C), (up)(V))
FL boole n_var_okclear(enum okeys okey);
#define ok_bclear(C) n_var_okclear(su_CONCAT(ok_b_, C))
#define ok_vclear(C) n_var_okclear(su_CONCAT(ok_v_, C))
/* Variable option key lookup/(un)set/clear.
* If try_getenv is true we will getenv(3) _if_ vokey is not a known enum okey;
* it will also cause obsoletion messages only for doing lookup (once).
* _vexplode() is to be used by the shell expansion stuff when encountering
* ${@} in double-quotes, in order to provide sh(1)ell compatible behaviour;
* it returns whether there are any elements in argv (*cookie) */
FL char const *n_var_vlook(char const *vokey, boole try_getenv);
FL boole n_var_vexplode(void const **cookie);
FL boole n_var_vset(char const *vokey, up val);
FL boole n_var_vclear(char const *vokey);
/* Special case to handle the typical [xy-USER@HOST,] xy-HOST and plain xy
* variable chains; oxm is a bitmix which tells which combinations to test */
#ifdef mx_HAVE_NET
FL char *n_var_xoklook(enum okeys okey, struct mx_url const *urlp,
enum okey_xlook_mode oxm);
# define xok_BLOOK(C,URL,M) (n_var_xoklook(C, URL, M) != NULL)
# define xok_VLOOK(C,URL,M) n_var_xoklook(C, URL, M)
# define xok_blook(C,URL,M) xok_BLOOK(su_CONCAT(ok_b_, C), URL, M)
# define xok_vlook(C,URL,M) xok_VLOOK(su_CONCAT(ok_v_, C), URL, M)
#endif
/* User variable access: `set', `local' and `unset' */
FL int c_set(void *vp);
FL int c_unset(void *vp);
/* `varshow' */
FL int c_varshow(void *v);
/* `environ' */
FL int c_environ(void *v);
/* `vpospar' */
FL int c_vpospar(void *v);
/*
* auxlily.c
*/
/* Compute *screen* size */
FL uz n_screensize(void);
/* In n_PSO_INTERACTIVE, we want to go over $PAGER.
* These are specialized version of fs_pipe_open()/fs_pipe_close() which also
* encapsulate error message printing, terminal handling etc. additionally */
FL FILE *mx_pager_open(void);
FL boole mx_pager_close(FILE *fp);
/* Use a pager or STDOUT to print *fp*; if *lines* is 0, they'll be counted */
FL void page_or_print(FILE *fp, uz lines);
/* Parse name and guess at the required protocol.
* If check_stat is true then stat(2) will be consulted - a TODO c..p hack
* TODO that together with *newfolders*=maildir adds Maildir support; sigh!
* If try_hooks is set check_stat is implied and if the stat(2) fails all
* file-hook will be tried in order to find a supported version of name.
* If adjusted_or_null is not NULL it will be set to the final version of name
* this function knew about: a %: FEDIT_SYSBOX prefix is forgotten, in case
* a hook is needed the "real" filename will be placed.
* TODO This c..p should be URL::from_string()->protocol() or something! */
FL enum protocol which_protocol(char const *name, boole check_stat,
boole try_hooks, char const **adjusted_or_null);
/* Hexadecimal itoa (NUL terminates) / atoi (-1 on error) */
FL char * n_c_to_hex_base16(char store[3], char c);
FL s32 n_c_from_hex_base16(char const hex[2]);
/* Return the name of the dead.letter file */
FL char const * n_getdeadletter(void);
/* Detect and query the hostname to use */
FL char *n_nodename(boole mayoverride);
/* Convert from / to *ttycharset* */
#ifdef mx_HAVE_IDNA
FL boole n_idna_to_ascii(struct n_string *out, char const *ibuf, uz ilen);
/*TODO FL boole n_idna_from_ascii(struct n_string *out, char const *ibuf,
uz ilen);*/
#endif
/* Check whether the argument string is a TRU1 or FAL0 boolean, or an invalid
* string, in which case TRUM1 is returned.
* If the input buffer is empty emptyrv is used as the return: if it is GE
* FAL0 it will be made a binary boolean, otherwise TRU2 is returned.
* inlen may be UZ_MAX to force su_cs_len() detection */
FL boole n_boolify(char const *inbuf, uz inlen, boole emptyrv);
/* Dig a "quadoption" in inbuf, possibly going through getapproval() in
* interactive mode, in which case prompt is printed first if set.
. Just like n_boolify() otherwise */
FL boole n_quadify(char const *inbuf, uz inlen, char const *prompt,
boole emptyrv);
/* Is the argument "all" (case-insensitive) or "*" */
FL boole n_is_all_or_aster(char const *name);
/* Get seconds since epoch, return pointer to static struct.
* Unless force_update is true we may use the event-loop tick time */
FL struct n_timespec const *n_time_now(boole force_update);
#define n_time_epoch() ((time_t)n_time_now(FAL0)->ts_sec)
/* Update *tc* to now; only .tc_time updated unless *full_update* is true */
FL void time_current_update(struct time_current *tc,
boole full_update);
/* TZ difference in seconds.
* secsepoch is only used if any of the tm's is NIL. */
FL s32 n_time_tzdiff(s64 secsepoch, struct tm const *utcp_or_nil,
struct tm const *localp_or_nil);
/* ctime(3), but do ensure 26 byte limit, do not crash XXX static buffer.
* NOTE: no trailing newline */
FL char *n_time_ctime(s64 secsepoch, struct tm const *localtime_or_nil);
/* Returns 0 if fully slept, number of millis left if ignint is true and we
* were interrupted. Actual resolution may be second or less.
* Note in case of mx_HAVE_SLEEP this may be SIGALARM based. */
FL uz n_msleep(uz millis, boole ignint);
/* Our error print series.. Note: these reverse scan format in order to know
* whether a newline was included or not -- this affects the output!
* xxx Prototype changes to be reflected in src/su/core-code. (for now) */
FL void n_err(char const *format, ...);
FL void n_errx(boole allow_multiple, char const *format, ...);
FL void n_verr(char const *format, va_list ap);
FL void n_verrx(boole allow_multiple, char const *format, va_list ap);
/* ..(for use in a signal handler; to be obsoleted..).. */
FL void n_err_sighdl(char const *format, ...);
/* Our perror(3); if errval is 0 su_err_no() is used; newline appended */
FL void n_perr(char const *msg, int errval);
/* Announce a fatal error (and die); newline appended */
FL void n_alert(char const *format, ...);
FL void n_panic(char const *format, ...);
/* `errors' */
#ifdef mx_HAVE_ERRORS
FL int c_errors(void *vp);
#endif
/* */
#ifdef mx_HAVE_REGEX
FL char const *n_regex_err_to_doc(const regex_t *rep, int e);
#endif
/* Shared code for c_unxy() which base upon su_cs_dict, e.g., `shortcut' */
FL su_boole mx_unxy_dict(char const *cmdname, struct su_cs_dict *dp, void *vp);
/* Sort all keys of dp, iterate over them, call the given hook ptf for each
* key/data pair, place any non-NIL returned in the *result list.
* A non-NIL *result will not be updated, but be appended to.
* tailpp_or_nil can be set to speed up follow runs.
* The boole return states error, *result may be NIL even upon success,
* e.g., if dp is NIL or empty */
FL boole mx_xy_dump_dict(char const *cmdname, struct su_cs_dict *dp,
struct n_strlist **result, struct n_strlist **tailpp_or_nil,
struct n_strlist *(*ptf)(char const *cmdname, char const *key,
void const *dat));
/* Default callback which can be used when dat is in fact a char const* */
FL struct n_strlist *mx_xy_dump_dict_gen_ptf(char const *cmdname,
char const *key, void const *dat);
/* page_or_print() all members of slp, one line per node.
* If slp is NIL print a line that no cmdname are registered.
* If cnt_lines is FAL0 then each slp entry is assumed to be one line without
* a trailing newline character, otherwise these characters are counted and
* a trailing such is put as necessary */
FL boole mx_page_or_print_strlist(char const *cmdname,
struct n_strlist *slp, boole cnt_lines);
/*
* cmd-cnd.c
*/
/* if.elif.else.endif conditional execution */
FL int c_if(void *v);
FL int c_elif(void *v);
FL int c_else(void *v);
FL int c_endif(void *v);
/* Whether an `if' block exists (TRU1) / is in a whiteout condition (TRUM1) */
FL boole n_cnd_if_exists(void);
/* An execution context is teared down, and it finds to have an if stack */
FL void n_cnd_if_stack_del(struct n_go_data_ctx *gdcp);
/*
* cmd-folder.c
*/
/* `file' (`folder') and `File' (`Folder') */
FL int c_file(void *v);
FL int c_File(void *v);
/* 'newmail' command: Check for new mail without writing old mail back */
FL int c_newmail(void *v);
/* noop */
FL int c_noop(void *v);
/* Remove mailbox */
FL int c_remove(void *v);
/* Rename mailbox */
FL int c_rename(void *v);
/* List the folders the user currently has */
FL int c_folders(void *v);
/*
* cmd-head.c
*/
/* `headers' (show header group, possibly after setting dot) */
FL int c_headers(void *v);
/* Like c_headers(), but pre-prepared message vector */
FL int print_header_group(int *vector);
/* Scroll to the next/previous screen */
FL int c_scroll(void *v);
FL int c_Scroll(void *v);
/* Move the dot up or down by one message */
FL int c_dotmove(void *v);
/* Print out the headlines for each message in the passed message list */
FL int c_from(void *v);
/* Print all messages in msgvec visible and either only_marked is false or they
* are MMARKed.
* TODO If subject_thread_compress is true then a subject will not be printed
* TODO if it equals the subject of the message "above"; as this only looks
* TODO in the thread neighbour and NOT in the "visible" neighbour, the caller
* TODO has to ensure the result will look sane; DROP + make it work (tm) */
FL void print_headers(int const *msgvec, boole only_marked,
boole subject_thread_compress);
/*
* cmd-msg.c
*/
/* Paginate messages, honour/don't honour ignored fields, respectively */
FL int c_more(void *v);
FL int c_More(void *v);
/* Type out messages, honour/don't honour ignored fields, respectively */
FL int c_type(void *v);
FL int c_Type(void *v);
/* Show raw message content */
FL int c_show(void *v);
/* `mimeview' */
FL int c_mimeview(void *vp);
/* Pipe messages, honour/don't honour ignored fields, respectively */
FL int c_pipe(void *vp);
FL int c_Pipe(void *vp);
/* Print the first *toplines* of each desired message */
FL int c_top(void *v);
FL int c_Top(void *v);
/* If any arguments were given, go to the next applicable argument following
* dot, otherwise, go to the next applicable message. If given as first
* command with no arguments, print first message */
FL int c_next(void *v);
/* `=': print out the value(s) of <msglist> (or dot) */
FL int c_pdot(void *vp);
/* Print the size of each message */
FL int c_messize(void *v);
/* Delete messages */
FL int c_delete(void *v);
/* Delete messages, then type the new dot */
FL int c_deltype(void *v);
/* Undelete the indicated messages */
FL int c_undelete(void *v);
/* Touch all the given messages so that they will get mboxed */
FL int c_stouch(void *v);
/* Make sure all passed messages get mboxed */
FL int c_mboxit(void *v);
/* Preserve messages, so that they will be sent back to the system mailbox */
FL int c_preserve(void *v);
/* Mark all given messages as unread */
FL int c_unread(void *v);
/* Mark all given messages as read */
FL int c_seen(void *v);
/* Message flag manipulation */
FL int c_flag(void *v);
FL int c_unflag(void *v);
FL int c_answered(void *v);
FL int c_unanswered(void *v);
FL int c_draft(void *v);
FL int c_undraft(void *v);
/*
* cmd-misc.c
*/
/* `!': process a shell escape by saving signals, ignoring signals and sh -c */
FL int c_shell(void *v);
/* `shell': fork an interactive shell */
FL int c_dosh(void *v);
/* `cwd': print user's working directory */
FL int c_cwd(void *v);
/* `chdir': change user's working directory */
FL int c_chdir(void *v);
/* `echo' series: expand file names like echo (to stdout/stderr, with/out
* trailing newline) */
FL int c_echo(void *v);
FL int c_echoerr(void *v);
FL int c_echon(void *v);
FL int c_echoerrn(void *v);
/* `read', `readsh' */
FL int c_read(void *vp);
FL int c_readsh(void *vp);
/* `readall' */
FL int c_readall(void *vp);
/* `version', and generic support for the shared initial version line, which
* appends to sp the UA name, version etc., and a \n LF */
FL struct n_string *n_version(struct n_string *sp);
FL int c_version(void *vp);
/*
* cmd-resend.c
*/
/* All thinkable sorts of `reply' / `respond' and `followup'.. */
FL int c_reply(void *vp);
FL int c_replyall(void *vp); /* v15-compat */
FL int c_replysender(void *vp); /* v15-compat */
FL int c_Reply(void *vp);
FL int c_followup(void *vp);
FL int c_followupall(void *vp); /* v15-compat */
FL int c_followupsender(void *vp); /* v15-compat */
FL int c_Followup(void *vp);
/* ..and a mailing-list reply and followup */
FL int c_Lreply(void *vp);
FL int c_Lfollowup(void *vp);
/* 'forward' / `Forward' */
FL int c_forward(void *vp);
FL int c_Forward(void *vp);
/* Resend a message list to a third person.
* The latter does not add the Resent-* header series */
FL int c_resend(void *vp);
FL int c_Resend(void *vp);
/*
* cmd-write.c
*/
/* Save a message in a file. Mark the message as saved so we can discard when
* the user quits */
FL int c_save(void *vp);
FL int c_Save(void *vp);
/* Copy a message to a file without affected its saved-ness */
FL int c_copy(void *vp);
FL int c_Copy(void *vp);
/* Move a message to a file */
FL int c_move(void *vp);
FL int c_Move(void *vp);
/* Decrypt and copy a message to a file. Like plain `copy' at times */
FL int c_decrypt(void *vp);
FL int c_Decrypt(void *vp);
/* Write the indicated messages at the end of the passed file name, minus
* header and trailing blank line. This is the MIME save function */
FL int c_write(void *vp);
/*
* collect.c
*/
/* temporary_compose_mode_hook_call() etc. setter hook */
FL void n_temporary_compose_hook_varset(void *arg);
/* If quotefile is (char*)-1, stdin will be used, caller has to verify that
* we're not running in interactive mode */
FL FILE *n_collect(enum n_mailsend_flags msf, struct header *hp,
struct message *mp, char const *quotefile, s8 *checkaddr_err);
/*
* folder.c
*/
/* Set up editing on the given file name.
* If the first character of name is %, we are considered to be editing the
* file, otherwise we are reading our mail which has signficance for mbox and
* so forth */
FL int setfile(char const *name, enum fedit_mode fm);
FL int newmailinfo(int omsgCount);
/* Set the size of the message vector used to construct argument lists to
* message list functions */
FL void setmsize(int sz);
/* Logic behind -H / -L invocations */
FL void print_header_summary(char const *Larg);
/* Announces the current folder as indicated.
* Is responsible for updating "dot" (after a folder change). */
FL void n_folder_announce(enum n_announce_flags af);
FL int getmdot(int nmail);
FL void initbox(char const *name);
/* Determine and expand the current *folder* name, return it (with trailing
* solidus) or the empty string also in case of errors: since POSIX mandates
* a default of CWD if not set etc., that seems to be a valid fallback, then */
FL char const *n_folder_query(void);
/* Prepare the seekable O_APPEND MBOX fout for appending of another message.
* If st_or_null is not NULL it is assumed to point to an up-to-date status of
* fout, otherwise an internal fstat(2) is performed as necessary.
* Returns su_err_no() of error */
FL int n_folder_mbox_prepare_append(FILE *fout, struct stat *st_or_null);
/*
* go.c
* Program input of all sorts, input lexing, event loops, command evaluation.
* Also alias handling.
*/
/* Setup the run environment; this i *only* for main() */
FL void n_go_init(void);
/* Interpret user commands. If stdin is not a tty, print no prompt; return
* whether last processed command returned error; this is *only* for main()! */
FL boole n_go_main_loop(void);
/* Actual cmd input */
/* */
FL void n_go_input_clearerr(void);
/* Force n_go_input() to read EOF next */
FL void n_go_input_force_eof(void);
/* Returns true if force_eof() has been set -- it is set automatically if
* an input context enters EOF state (rather than error, as in ferror(3)) */
FL boole n_go_input_is_eof(void);
/* Are there any go_input_inject()ions pending? */
FL boole n_go_input_have_injections(void);
/* Force n_go_input() to read that buffer next.
* If n_GO_INPUT_INJECT_COMMIT is not set the line editor is reentered with buf
* as the default/initial line content */
FL void n_go_input_inject(enum n_go_input_inject_flags giif, char const *buf,
uz len);
/* Read a complete line of input, with editing if interactive and possible.
* string_or_nil is the optional initial line content if in interactive
* mode, otherwise this argument is ignored for reproducibility.
* If histok_or_nil is set it will be updated to FAL0 if input shall not be
* placed in history.
* Return number of octets or a value <0 on error.
* Note: may use the currently `source'd file stream instead of stdin!
* Manages the n_PS_READLINE_NL hack
* TODO We need an OnReadLineCompletedEvent and drop this function */
FL int n_go_input(enum n_go_input_flags gif, char const *prompt_or_nil,
char **linebuf, uz *linesize, char const *string_or_nil,
boole *histok_or_nil su_DBG_LOC_ARGS_DECL);
#ifdef su_HAVE_DBG_LOC_ARGS
# define n_go_input(A,B,C,D,E,F) n_go_input(A,B,C,D,E,F su_DBG_LOC_ARGS_INJ)
#endif
/* Like go_input(), but return savestr()d result or NIL in case of errors or if
* an empty line would be returned.
* This may only be called from toplevel (not during n_PS_ROBOT) */
FL char *n_go_input_cp(enum n_go_input_flags gif, char const *prompt_or_nil,
char const *string_or_nil);
/* Deal with loading of resource files and dealing with a stack of files for
* the source command */
/* Load a file of user system startup resources.
* *Only* for main(), returns whether program shall continue */
FL boole n_go_load_rc(char const *name);
/* "Load" or go_inject() command line option "cmd" arguments in order.
* *Only* for main(), returns whether program shall continue unless injectit is
* set, in which case this function does not fail.
* If lines is NIL the builtin RC file is used, and errors are ignored */
FL boole n_go_load_lines(boole injectit, char const **lines, uz cnt);
/* Pushdown current input file and switch to a new one. */
FL int c_source(void *v);
FL int c_source_if(void *v);
/* Evaluate a complete macro / a single command. For the former lines will
* be free()d, for the latter cmd will always be duplicated internally */
FL boole n_go_macro(enum n_go_input_flags gif, char const *name, char **lines,
void (*on_finalize)(void*), void *finalize_arg);
FL boole n_go_command(enum n_go_input_flags gif, char const *cmd);
/* XXX See a_GO_SPLICE in source */
FL void n_go_splice_hack(char const *cmd, FILE *new_stdin, FILE *new_stdout,
u32 new_psonce, void (*on_finalize)(void*), void *finalize_arg);
FL void n_go_splice_hack_remove_after_jump(void);
/* XXX Hack: may we release our (interactive) (terminal) control to a different
* XXX program, e.g., a $PAGER? */
FL boole n_go_may_yield_control(void);
/* `eval' */
FL int c_eval(void *vp);
/* `xcall' */
FL int c_xcall(void *vp);
/* `exit' and `quit' commands */
FL int c_exit(void *vp);
FL int c_quit(void *vp);
/* `readctl' */
FL int c_readctl(void *vp);
/*
* header.c
*/
/* Return the user's From: address(es) */
FL char const * myaddrs(struct header *hp);
/* Boil the user's From: addresses down to a single one, or use *sender* */
FL char const * myorigin(struct header *hp);
/* See if the passed line buffer, which may include trailing newline (sequence)
* is a mail From_ header line according to POSIX ("From ").
* If check_rfc4155 is true we'll return TRUM1 instead if the From_ line
* matches POSIX but is _not_ compatible to RFC 4155 */
FL boole is_head(char const *linebuf, uz linelen,
boole check_rfc4155);
/* Return pointer to first non-header, non-space character, or NIL if invalid.
* If lead_ws is true leading whitespace is allowed and skipped.
* If cramp_or_nil is not NIL it will be set to the valid header name itself */
FL char const *mx_header_is_valid(char const *name, boole lead_ws,
struct str *cramp_or_nil);
/* Print hp "to user interface" fp for composing purposes xxx what a sigh */
FL boole n_header_put4compose(FILE *fp, struct header *hp);
/* Extract some header fields (see e.g. -t documentation) from a message.
* This calls expandaddr() on some headers and sets checkaddr_err_or_null if
* that is set -- note it explicitly allows EAF_NAME because aliases are not
* expanded when this is called! */
FL void n_header_extract(enum n_header_extract_flags hef, FILE *fp,
struct header *hp, s8 *checkaddr_err_or_null);
/* Return the desired header line from the passed message
* pointer (or NULL if the desired header field is not available).
* If mult is zero, return the content of the first matching header
* field only, the content of all matching header fields else */
FL char * hfield_mult(char const *field, struct message *mp, int mult);
#define hfieldX(a, b) hfield_mult(a, b, 1)
#define hfield1(a, b) hfield_mult(a, b, 0)
/* Check whether the passed line is a header line of the desired breed.
* If qm_suffix_or_nil is set then the field?[MOD]: syntax is supported, the
* suffix substring range of linebuf will be stored in there, then, or NIL;
* this logically casts away the const.
* Return the field body, or NULL */
FL char const *n_header_get_field(char const *linebuf, char const *field,
struct str *qm_suffix_or_nil);
/* Start of a "comment". Ignore it */
FL char const * skip_comment(char const *cp);
/* Return the start of a route-addr (address in angle brackets), if present */
FL char const * routeaddr(char const *name);
/* Query *expandaddr*, parse it and return flags.
* Flags are already adjusted for n_PSO_INTERACTIVE, n_PO_TILDE_FLAG etc. */
FL enum expand_addr_flags expandaddr_to_eaf(void);
/* Check if an address is invalid, either because it is malformed or, if not,
* according to eacm. Return FAL0 when it looks good, TRU1 if it is invalid
* but the error condition was not covered by a 'hard "fail"ure', else -1 */
FL s8 is_addr_invalid(struct mx_name *np,
enum expand_addr_check_mode eacm);
/* Does *NP* point to a file or pipe addressee? */
#define is_fileorpipe_addr(NP) \
(((NP)->n_flags & mx_NAME_ADDRSPEC_ISFILEORPIPE) != 0)
/* Skin an address according to the RFC 822 interpretation of "host-phrase" */
FL char * skin(char const *name);
/* Skin *name* and extract *addr-spec* according to RFC 5322 and enum gfield.
* Store the result in .ag_skinned and also fill in those .ag_ fields that have
* actually been seen.
* Return NULL on error, or name again, but which may have been replaced by
* a version with fixed quotation etc.! */
FL char const *n_addrspec_with_guts(struct n_addrguts *agp, char const *name,
u32 gfield);
/* `addrcodec' */
FL int c_addrcodec(void *vp);
/* Fetch the real name from an internet mail address field */
FL char * realname(char const *name);
/* Look for a RFC 2369 List-Post: header, return NIL if none was found, -1 if
* the one found forbids posting to the list, a header otherwise.
* .n_type needs to be set to something desired still */
FL struct mx_name *mx_header_list_post_of(struct message *mp);
/* Get the sender (From: or Sender:) of this message, or NIL.
* If gf is 0 GFULL|GSKIN is used (no senderfield beside that) */
FL struct mx_name *mx_header_sender_of(struct message *mp, u32 gf);
/* Get header_sender_of(), or From_ line from this message.
* The return value may be empty and needs lextract()ion */
FL char *n_header_senderfield_of(struct message *mp);
/* Trim away all leading Re: etc., return pointer to plain subject.
* Note it doesn't perform any MIME decoding by itself */
FL char const *subject_re_trim(char const *cp);
FL int msgidcmp(char const *s1, char const *s2);
/* Fake Sender for From_ lines if missing, e. g. with POP3 */
FL char const * fakefrom(struct message *mp);
/* From username Fri Jan 2 20:13:51 2004
* | | | | |
* 0 5 10 15 20 */
#if defined mx_HAVE_IMAP_SEARCH || defined mx_HAVE_IMAP
FL time_t unixtime(char const *from);
#endif
FL time_t rfctime(char const *date);
FL time_t combinetime(int year, int month, int day,
int hour, int minute, int second);
/* Determine the date to print in faked 'From ' lines */
FL void substdate(struct message *m);
/* Create ready-to-go environment taking into account *datefield* etc.,
* and return a result in auto-reclaimed storage.
* TODO hack *color_tag_or_null could be set to n_COLOUR_TAG_SUM_OLDER.
* time_current is used for comparison and must thus be up-to-date */
FL char *n_header_textual_date_info(struct message *mp,
char const **color_tag_or_null);
/* Create ready-to-go sender name of a message in *cumulation_or_null, the
* addresses only in *addr_or_null, the real names only in *name_real_or_null,
* and the full names in *name_full_or_null, taking account for *showname*.
* If *is_to_or_null is set, *showto* and n_is_myname() are taken into account
* when choosing which names to use.
* The list as such is returned, or NULL if there is really none (empty strings
* will be stored, then).
* All results are in auto-reclaimed storage, but may point to the same string.
* TODO *is_to_or_null could be set to whether we actually used To:, or not.
* TODO n_header_textual_sender_info(): should only create a list of matching
* TODO name objects, which the user can iterate over and o->to_str().. */
FL struct mx_name *n_header_textual_sender_info(struct message *mp,
char **cumulation_or_null, char **addr_or_null,
char **name_real_or_null, char **name_full_or_null,
boole *is_to_or_null);
/* TODO Weird thing that tries to fill in From: and Sender: */
FL void setup_from_and_sender(struct header *hp);
/* Note: returns 0x1 if both args were NULL */
FL struct mx_name const *check_from_and_sender(struct mx_name const *fromfield,
struct mx_name const *senderfield);
#ifdef mx_HAVE_XTLS
FL char * getsender(struct message *m);
#endif
/* This returns NULL if hp is NULL or when no information is available.
* hp remains unchanged (->h_in_reply_to is not set!) */
FL struct mx_name *n_header_setup_in_reply_to(struct header *hp);
/* Fill in / reedit the desired header fields */
FL int grab_headers(enum n_go_input_flags gif, struct header *hp,
enum gfield gflags, int subjfirst);
/* Check whether sep->ss_sexpr (or ->ss_sregex) matches any header of mp.
* If sep->s_where (or >s_where_wregex) is set, restrict to given headers */
FL boole n_header_match(struct message *mp, struct search_expr const *sep);
/* Verify whether len (UZ_MAX=su_cs_len) bytes of name form a standard or
* otherwise known header name (that must not be used as a custom header).
* Return the (standard) header name, or NULL */
FL char const *n_header_is_known(char const *name, uz len);
/* Add a custom header to the given list, in auto-reclaimed or heap memory */
FL boole n_header_add_custom(struct n_header_field **hflp, char const *dat,
boole heap);
/*
* ignore.c
*/
/* `(un)?headerpick' */
FL int c_headerpick(void *vp);
FL int c_unheaderpick(void *vp);
/* TODO Compat variants of the c_(un)?h*() series,
* except for `retain' and `ignore', which are standardized */
FL int c_retain(void *vp);
FL int c_ignore(void *vp);
FL int c_unretain(void *vp);
FL int c_unignore(void *vp);
FL int c_saveretain(void *v);
FL int c_saveignore(void *v);
FL int c_unsaveretain(void *v);
FL int c_unsaveignore(void *v);
FL int c_fwdretain(void *v);
FL int c_fwdignore(void *v);
FL int c_unfwdretain(void *v);
FL int c_unfwdignore(void *v);
/* Ignore object lifecycle. (Most of the time this interface deals with
* special n_IGNORE_* objects, e.g., n_IGNORE_TYPE, though.)
* isauto: whether auto-reclaimed storage is to be used for allocations;
* if so, _del() needn't be called */
FL struct n_ignore *n_ignore_new(boole isauto);
FL void n_ignore_del(struct n_ignore *self);
/* Are there just _any_ user settings covered by self? */
FL boole n_ignore_is_any(struct n_ignore const *self);
/* Set an entry to retain (or ignore).
* Returns FAL0 if dat is not a valid header field name or an invalid regular
* expression, TRU1 if insertion took place, and TRUM1 if already set */
FL boole n_ignore_insert(struct n_ignore *self, boole retain,
char const *dat, uz len);
#define n_ignore_insert_cp(SELF,RT,CP) n_ignore_insert(SELF, RT, CP, UZ_MAX)
/* Returns TRU1 if retained, TRUM1 if ignored, FAL0 if not covered */
FL boole n_ignore_lookup(struct n_ignore const *self, char const *dat,
uz len);
#define n_ignore_lookup_cp(SELF,CP) n_ignore_lookup(SELF, CP, UZ_MAX)
#define n_ignore_is_ign(SELF,FDAT,FLEN) \
(n_ignore_lookup(SELF, FDAT, FLEN) == TRUM1)
/*
* imap-search.c
*/
/* Return -1 on invalid spec etc., the number of matches otherwise */
#ifdef mx_HAVE_IMAP_SEARCH
FL sz imap_search(char const *spec, int f);
#endif
/*
* maildir.c
*/
#ifdef mx_HAVE_MAILDIR
FL int maildir_setfile(char const *who, char const *name, enum fedit_mode fm);
FL boole maildir_quit(boole hold_sigs_on);
FL enum okay maildir_append(char const *name, FILE *fp, long offset);
FL enum okay maildir_remove(char const *name);
#endif /* mx_HAVE_MAILDIR */
/*
* (Former memory.c, now SU TODO get rid of compat macros)
* Heap memory and automatically reclaimed storage, plus pseudo "alloca"
*
*/
/* Generic heap memory */
#define n_alloc su_MEM_ALLOC
#define n_realloc su_MEM_REALLOC
#define n_calloc(NO,SZ) su_MEM_CALLOC_N(SZ, NO)
#define n_free su_MEM_FREE
/* Auto-reclaimed storage */
#define n_autorec_relax_create() \
su_mem_bag_auto_relax_create(n_go_data->gdc_membag)
#define n_autorec_relax_gut() \
su_mem_bag_auto_relax_gut(n_go_data->gdc_membag)
#define n_autorec_relax_unroll() \
su_mem_bag_auto_relax_unroll(n_go_data->gdc_membag)
/* (Even older obsolete names!) */
#define srelax_hold n_autorec_relax_create
#define srelax_rele n_autorec_relax_gut
#define srelax n_autorec_relax_unroll
#define n_autorec_alloc su_MEM_BAG_SELF_AUTO_ALLOC
#define n_autorec_calloc(NO,SZ) su_MEM_BAG_SELF_AUTO_CALLOC_N(SZ, NO)
/* Pseudo alloca (and also auto-reclaimed) */
#define n_lofi_alloc su_MEM_BAG_SELF_LOFI_ALLOC
#define n_lofi_calloc su_MEM_BAG_SELF_LOFI_CALLOC
#define n_lofi_free su_MEM_BAG_SELF_LOFI_FREE
#define n_lofi_snap_create() su_mem_bag_lofi_snap_create(n_go_data->gdc_membag)
#define n_lofi_snap_unroll(COOKIE) \
su_mem_bag_lofi_snap_unroll(n_go_data->gdc_membag, COOKIE)
/*
* message.c
*/
/* Return a file buffer all ready to read up the passed message pointer */
FL FILE * setinput(struct mailbox *mp, struct message *m,
enum needspec need);
/* */
FL enum okay get_body(struct message *mp);
/* Reset (free) the global message array */
FL void message_reset(void);
/* Append the passed message descriptor onto the message array; if mp is NULL,
* NULLify the entry at &[msgCount-1] */
FL void message_append(struct message *mp);
/* Append a NULL message */
FL void message_append_null(void);
/* Check whether sep->ss_sexpr (or ->ss_sregex) matches mp. If with_headers is
* true then the headers will also be searched (as plain text) */
FL boole message_match(struct message *mp, struct search_expr const *sep,
boole with_headers);
/* */
FL struct message * setdot(struct message *mp);
/* Touch the named message by setting its MTOUCH flag. Touched messages have
* the effect of not being sent back to the system mailbox on exit */
FL void touch(struct message *mp);
/* Convert user message spec. to message numbers and store them in vector,
* which should be capable to hold msgCount+1 entries (n_msgvec ASSERTs this).
* flags is cmd_arg_ctx.cac_msgflag==cmd_desc.cd_mflags_o_minargs==enum mflag.
* If capp_or_null is not NULL then the last (string) token is stored in here
* and not interpreted as a message specification; in addition, if only one
* argument remains and this is the empty string, 0 is returned (*vector=0;
* this is used to implement CMD_ARG_DESC_MSGLIST_AND_TARGET).
* A NUL *buf input results in a 0 return, *vector=0, [*capp_or_null=NULL].
* Returns the count of messages picked up or -1 on error */
FL int n_getmsglist(char const *buf, int *vector, int flags,
struct mx_cmd_arg **capp_or_null);
/* Find the first message whose flags&m==f and return its message number */
FL int first(int f, int m);
/* Mark the named message by setting its mark bit */
FL void mark(int mesg, int f);
/*
* mime.c
*/
/* *sendcharsets* .. *charset-8bit* iterator; *a_charset_to_try_first* may be
* used to prepend a charset to this list (e.g., for *reply-in-same-charset*).
* The returned boolean indicates charset_iter_is_valid().
* Without mx_HAVE_ICONV, this "iterates" over *ttycharset* only */
FL boole charset_iter_reset(char const *a_charset_to_try_first);
FL boole charset_iter_next(void);
FL boole charset_iter_is_valid(void);
FL char const * charset_iter(void);
/* And this is (xxx temporary?) which returns the iterator if that is valid and
* otherwise either *charset-8bit* or *ttycharset*, dep. on mx_HAVE_ICONV */
FL char const * charset_iter_or_fallback(void);
FL void charset_iter_recurse(char *outer_storage[2]); /* TODO LEGACY */
FL void charset_iter_restore(char *outer_storage[2]); /* TODO LEGACY */
/* Check whether our headers will need MIME conversion */
#ifdef mx_HAVE_ICONV
FL char const * need_hdrconv(struct header *hp);
#endif
/* Convert header fields from RFC 1522 format */
FL void mime_fromhdr(struct str const *in, struct str *out,
enum tdflags flags);
/* Interpret MIME strings in parts of an address field */
FL char * mime_fromaddr(char const *name);
/* fwrite(3) performing the given MIME conversion */
FL sz mime_write(char const *ptr, uz size, FILE *f,
enum conversion convert, enum tdflags dflags,
struct quoteflt *qf, struct str *outrest,
struct str *inrest);
FL sz xmime_write(char const *ptr, uz size, /* TODO LEGACY */
FILE *f, enum conversion convert, enum tdflags dflags,
struct str *outrest, struct str *inrest);
/*
* mime-enc.c
* Content-Transfer-Encodings as defined in RFC 2045 (and RFC 2047):
* - Quoted-Printable, section 6.7
* - Base64, section 6.8
* TODO For now this is pretty mixed up regarding this external interface
* TODO (and due to that the code is, too).
* TODO In v15.0 CTE will be filter based, and explicit conversion will
* TODO gain clear error codes
*/
/* Default MIME Content-Transfer-Encoding: as via *mime-encoding*.
* Cannot be MIMEE_BIN nor MIMEE_7B (i.e., only B64, QP, 8B) */
FL enum mime_enc mime_enc_target(void);
/* Map from a Content-Transfer-Encoding: header body (which may be NULL) */
FL enum mime_enc mime_enc_from_ctehead(char const *hbody);
/* XXX Try to get rid of that */
FL char const * mime_enc_from_conversion(enum conversion const convert);
/* How many characters of (the complete body) ln need to be quoted.
* Only MIMEEF_ISHEAD and MIMEEF_ISENCWORD are understood */
FL uz mime_enc_mustquote(char const *ln, uz lnlen,
enum mime_enc_flags flags);
/* How much space is necessary to encode len bytes in QP, worst case.
* Includes room for terminator, UZ_MAX on overflow */
FL uz qp_encode_calc_size(uz len);
/* If flags includes QP_ISHEAD these assume "word" input and use special
* quoting rules in addition; soft line breaks are not generated.
* Otherwise complete input lines are assumed and soft line breaks are
* generated as necessary. Return NULL on error (overflow) */
FL struct str * qp_encode(struct str *out, struct str const *in,
enum qpflags flags);
#ifdef notyet
FL struct str * qp_encode_cp(struct str *out, char const *cp,
enum qpflags flags);
FL struct str * qp_encode_buf(struct str *out, void const *vp, uz vp_len,
enum qpflags flags);
#endif
/* The buffers of out and *rest* will be managed via n_realloc().
* If inrest_or_null is needed but NULL an error occurs, otherwise tolerant.
* Return FAL0 on error; caller is responsible to free buffers */
FL boole qp_decode_header(struct str *out, struct str const *in);
FL boole qp_decode_part(struct str *out, struct str const *in,
struct str *outrest, struct str *inrest_or_null);
/* How much space is necessary to encode len bytes in Base64, worst case.
* Includes room for (CR/LF/CRLF and) terminator, UZ_MAX on overflow */
FL uz b64_encode_calc_size(uz len);
/* Note these simply convert all the input (if possible), including the
* insertion of NL sequences if B64_CRLF or B64_LF is set (and multiple thereof
* if B64_MULTILINE is set).
* Thus, in the B64_BUF case, better call b64_encode_calc_size() first.
* Return NULL on error (overflow; cannot happen for B64_BUF) */
FL struct str * b64_encode(struct str *out, struct str const *in,
enum b64flags flags);
FL struct str * b64_encode_buf(struct str *out, void const *vp, uz vp_len,
enum b64flags flags);
#ifdef notyet
FL struct str * b64_encode_cp(struct str *out, char const *cp,
enum b64flags flags);
#endif
/* The _{header,part}() variants are failure tolerant, the latter requires
* outrest to be set; due to the odd 4:3 relation inrest_or_null should be
* given, _then_, it is an error if it is needed but not set.
* TODO pre v15 callers should ensure that no endless loop is entered because
* TODO the inrest cannot be converted and ends up as inrest over and over:
* TODO give NULL to stop such loops.
* The buffers of out and possibly *rest* will be managed via n_realloc().
* Returns FAL0 on error; caller is responsible to free buffers.
* XXX FAL0 is effectively not returned for _part*() variants,
* XXX (instead replacement characters are produced for invalid data.
* XXX _Unless_ operation could EOVERFLOW.)
* XXX I.e. this is bad and is tolerant for text and otherwise not */
FL boole b64_decode(struct str *out, struct str const *in);
FL boole b64_decode_header(struct str *out, struct str const *in);
FL boole b64_decode_part(struct str *out, struct str const *in,
struct str *outrest, struct str *inrest_or_null);
/*
* mime-param.c
*/
/* Get a mime style parameter from a header body */
FL char * mime_param_get(char const *param, char const *headerbody);
/* Format parameter name to have value, autorec_alloc() it or NULL in result.
* 0 on error, 1 or -1 on success: the latter if result contains \n newlines,
* which it will if the created param requires more than MIME_LINELEN bytes;
* there is never a trailing newline character */
/* TODO mime_param_create() should return a StrList<> or something.
* TODO in fact it should take a HeaderField* and append HeaderFieldParam*! */
FL s8 mime_param_create(struct str *result, char const *name,
char const *value);
/* Get the boundary out of a Content-Type: multipart/xyz header field, return
* autorec_alloc()ed copy of it; store su_cs_len() in *len if set */
FL char * mime_param_boundary_get(char const *headerbody, uz *len);
/* Create a autorec_alloc()ed MIME boundary */
FL char * mime_param_boundary_create(void);
/*
* mime-parse.c
*/
/* Create MIME part object tree for and of mp */
FL struct mimepart * mime_parse_msg(struct message *mp,
enum mime_parse_flags mpf);
/*
* path.c
*/
/* Test to see if the passed file name is a directory, return true if it is.
* If check_access is set, we also access(2): if it is TRUM1 only X_OK|R_OK is
* tested, otherwise X_OK|R_OK|W_OK. */
FL boole n_is_dir(char const *name, boole check_access);
/* Recursively create a directory */
FL boole n_path_mkdir(char const *name);
/* Delete a file, but only if the file is a plain file; return FAL0 on system
* error and TRUM1 if name is not a plain file, return TRU1 on success */
FL boole n_path_rm(char const *name);
/* A get-wd..restore-wd approach */
FL enum okay cwget(struct cw *cw);
FL enum okay cwret(struct cw *cw);
FL void cwrelse(struct cw *cw);
/*
* quit.c
*/
/* Save all of the undetermined messages at the top of "mbox". Save all
* untouched messages back in the system mailbox. Remove the system mailbox,
* if none saved there.
* TODO v15 Note: assumes hold_sigs() has been called _and_ can be temporarily
* TODO dropped via a single rele_sigs() if hold_sigs_on */
FL boole quit(boole hold_sigs_on);
/* Adjust the message flags in each message */
FL int holdbits(void);
/* Create another temporary file and copy user's mbox file darin. If there is
* no mbox, copy nothing. If he has specified "append" don't copy his mailbox,
* just copy saveable entries at the end */
FL enum okay makembox(void);
FL void save_mbox_for_possible_quitstuff(void); /* TODO DROP IF U CAN */
FL int savequitflags(void);
FL void restorequitflags(int);
/*
* send.c
*/
/* Send message described by the passed pointer to the passed output buffer.
* Return -1 on error. Adjust the status: field if need be. If doitp is
* given, suppress ignored header fields. prefix is a string to prepend to
* each output line. action = data destination
* (SEND_MBOX,_TOFILE,_TODISP,_QUOTE,_DECRYPT). stats[0] is line count,
* stats[1] is character count. stats may be NULL. Note that stats[0] is
* valid for SEND_MBOX only */
FL int sendmp(struct message *mp, FILE *obuf,
struct n_ignore const *doitp,
char const *prefix, enum sendaction action, u64 *stats);
/*
* sendout.c
*/
/* Check whether outgoing transport is via SMTP/SUBMISSION etc.
* It handles all the *mta* (v15-compat: +*smtp*) cases.
* Returns TRU1 if yes and URL parsing succeeded, TRUM1 if *mta* is file:// or
* test:// based, and FAL0 on failure.
* TODO It will assign CPROTO_NONE and only set urlp->url_input for file-based
* TODO and test protos, .url_portno is 0 for the former, U16_MAX for latter.
* TODO Should simply leave all that up to URL, is URL_PROTO_FILExy then). */
FL boole mx_sendout_mta_url(struct mx_url *urlp);
/* For main() only: interface between the command line argument list and the
* mail1 routine which does all the dirty work */
FL int n_mail(enum n_mailsend_flags msf, struct mx_name *to,
struct mx_name *cc, struct mx_name *bcc, char const *subject,
struct mx_attachment *attach, char const *quotefile);
/* `mail' and `Mail' commands, respectively */
FL int c_sendmail(void *v);
FL int c_Sendmail(void *v);
/* Mail a message on standard input to the people indicated in the passed
* header, applying all the address massages first. (Internal interface) */
FL enum okay n_mail1(enum n_mailsend_flags flags, struct header *hp,
struct message *quote, char const *quotefile);
/* Create a Date: header field.
* We compare the localtime() and gmtime() results to get the timezone, because
* numeric timezones are easier to read and because $TZ isn't always set.
* Return number of bytes written of -1 */
FL int mkdate(FILE *fo, char const *field);
/* Dump the to, subject, cc header on the passed file buffer.
* nosend_msg tells us not to dig to deep but to instead go for compose mode or
* editing a message (yet we're stupid and cannot do it any better) - if it is
* TRUM1 then we're really in compose mode and will produce some fields for
* easier filling in (see n_run_editor() proto for this hack) */
FL boole n_puthead(boole nosend_msg, struct header *hp, FILE *fo,
enum gfield w, enum sendaction action,
enum conversion convert, char const *contenttype,
char const *charset);
/* Note: hp->h_to must already have undergone address massage(s), it is taken
* as-is; h_cc and h_bcc are asserted to be NIL. urlp must have undergone
* mx_sendout_mta_url() processing */
FL enum okay n_resend_msg(struct message *mp, struct mx_url *urlp,
struct header *hp, boole add_resent);
/* *save* / $DEAD */
FL void savedeadletter(FILE *fp, boole fflush_rewind_first);
/*
* shexp.c
*/
/* Evaluate the string given as a new mailbox name. Supported meta characters:
* . % for my system mail box
* . %user for user's system mail box
* . # for previous file
* . & invoker's mbox file
* . +file file in folder directory
* . any shell meta character (except for FEXP_NSHELL).
* a poor man's vis(3), on name before calling this (and showing the user).
* If FEXP_MULTIOK is set we return an array of terminated strings, the (last)
* result string is terminated via \0\0 and n_PS_EXPAND_MULTIRESULT is set.
* Returns the file name as an auto-reclaimed string */
FL char *fexpand(char const *name, BITENUM_IS(u32,fexp_mode) fexpm);
/* Parse the next shell token from input (->s and ->l are adjusted to the
* remains, data is constant beside that; ->s may be NULL if ->l is 0, if ->l
* EQ UZ_MAX su_cs_len(->s) is used) and append the resulting output to store.
* If cookie is not NULL and we're in double-quotes then ${@} will be exploded
* just as known from the sh(1)ell in that case */
FL BITENUM_IS(u32,n_shexp_state) n_shexp_parse_token(
BITENUM_IS(u32,n_shexp_parse_flags) flags, struct n_string *store,
struct str *input, void const **cookie);
/* Quick+dirty simplified : if an error occurs, returns a copy of *cp and set
* *cp to NULL, otherwise advances *cp to over the parsed token */
FL char *n_shexp_parse_token_cp(BITENUM_IS(u32,n_shexp_parse_flags) flags,
char const **cp);
/* Another variant of parse_token_cp(): unquote the argument, ensure the result
* is "alone": after WS/IFS trimming STATE_STOP must be set, returns TRUM1 if
* not, TRU1 if STATE_OUTPUT is set, TRU2 if not, FAL0 on error */
FL boole n_shexp_unquote_one(struct n_string *store, char const *input);
/* Quote input in a way that can, in theory, be fed into parse_token() again.
* ->s may be NULL if ->l is 0, if ->l EQ UZ_MAX su_cs_len(->s) is used.
* If rndtrip is true we try to make the resulting string "portable" (by
* converting Unicode to \u etc.), otherwise we produce something to be
* consumed "now", i.e., to display for the user.
* Resulting output is _appended_ to store.
* TODO Note: last resort, since \u and $ expansions etc. are necessarily
* TODO already expanded and can thus not be reverted, but ALL we have */
FL struct n_string *n_shexp_quote(struct n_string *store,
struct str const *input, boole rndtrip);
FL char *n_shexp_quote_cp(char const *cp, boole rndtrip);
/* Can name be used as a variable name (for the process environment)?
* I.e., this returns false for special parameter names like $# etc. */
FL boole n_shexp_is_valid_varname(char const *name, boole forenviron);
/* `shcodec' */
FL int c_shcodec(void *vp);
/*
* spam.c
*/
#ifdef mx_HAVE_SPAM
/* Direct mappings of the various spam* commands */
FL int c_spam_clear(void *v);
FL int c_spam_set(void *v);
FL int c_spam_forget(void *v);
FL int c_spam_ham(void *v);
FL int c_spam_rate(void *v);
FL int c_spam_spam(void *v);
#endif
/*
* strings.c
*/
/* Return a pointer to a dynamic copy of the argument */
FL char *savestr(char const *str su_DBG_LOC_ARGS_DECL);
FL char *savestrbuf(char const *sbuf, uz slen su_DBG_LOC_ARGS_DECL);
#ifdef su_HAVE_DBG_LOC_ARGS
# define savestr(CP) savestr(CP su_DBG_LOC_ARGS_INJ)
# define savestrbuf(CBP,CBL) savestrbuf(CBP, CBL su_DBG_LOC_ARGS_INJ)
#endif
/* Concatenate cp2 onto cp1 (if not NULL), separated by sep (if not '\0') */
FL char *savecatsep(char const *cp1, char sep, char const *cp2
su_DBG_LOC_ARGS_DECL);
#ifdef su_HAVE_DBG_LOC_ARGS
# define savecatsep(S1,SEP,S2) savecatsep(S1, SEP, S2 su_DBG_LOC_ARGS_INJ)
#endif
/* Make copy of argument incorporating old one, if set, separated by space */
#define save2str(S,O) savecatsep(O, ' ', S)
/* strcat */
#define savecat(S1,S2) savecatsep(S1, '\0', S2)
/* */
FL struct str * str_concat_csvl(struct str *self, ...);
/* */
FL struct str *str_concat_cpa(struct str *self, char const * const *cpa,
char const *sep_o_null su_DBG_LOC_ARGS_DECL);
#ifdef su_HAVE_DBG_LOC_ARGS
# define str_concat_cpa(S,A,N) str_concat_cpa(S, A, N su_DBG_LOC_ARGS_INJ)
#endif
/* Plain char* support, not auto-reclaimed (unless noted) */
/* Could the string contain a regular expression?
* NOTE: on change: manual contains several occurrences of this string! */
#define n_is_maybe_regex(S) n_is_maybe_regex_buf(S, su_UZ_MAX)
FL boole n_is_maybe_regex_buf(char const *buf, uz len);
/* Convert a string to lowercase, in-place and with multibyte-aware */
FL void makelow(char *cp);
/* Is *sub* a substring of *str*, case-insensitive and multibyte-aware? */
FL boole substr(char const *str, char const *sub);
/* struct str related support funs TODO _cp->_cs! */
/* *self->s* is n_realloc()ed */
#define n_str_dup(S, T) n_str_assign_buf((S), (T)->s, (T)->l)
/* *self->s* is n_realloc()ed; if buflen==UZ_MAX su_cs_len() is called unless
* buf is NULL; buf may be NULL if buflen is 0 */
FL struct str *n_str_assign_buf(struct str *self, char const *buf, uz buflen
su_DBG_LOC_ARGS_DECL);
#define n_str_assign(S, T) n_str_assign_buf(S, (T)->s, (T)->l)
#define n_str_assign_cp(S, CP) n_str_assign_buf(S, CP, UZ_MAX)
/* *self->s* is n_realloc()ed, *self->l* incremented; if buflen==UZ_MAX
* su_cs_len() is called unless buf is NULL; buf may be NULL if buflen is 0 */
FL struct str *n_str_add_buf(struct str *self, char const *buf, uz buflen
su_DBG_LOC_ARGS_DECL);
#define n_str_add(S, T) n_str_add_buf(S, (T)->s, (T)->l)
#define n_str_add_cp(S, CP) n_str_add_buf(S, CP, UZ_MAX)
#ifdef su_HAVE_DBG_LOC_ARGS
# define n_str_assign_buf(S,B,BL) \
n_str_assign_buf(S, B, BL su_DBG_LOC_ARGS_INJ)
# define n_str_add_buf(S,B,BL) n_str_add_buf(S, B, BL su_DBG_LOC_ARGS_INJ)
#endif
/* Remove leading and trailing su_cs_is_space()s and *ifs-ws*, respectively.
* The ->s and ->l of the string will be adjusted, but no NUL termination will
* be applied to a possibly adjusted buffer!
* If dofaults is set, " \t\n" is always trimmed (in addition).
* Note trimming does not copy, it only adjusts the pointer/length */
FL struct str *n_str_trim(struct str *self, enum n_str_trim_flags stf);
FL struct str *n_str_trim_ifs(struct str *self, boole dodefaults);
/* struct n_string
* May have NIL buffer, may contain embedded NULs */
FL struct n_string *n__string_clear(struct n_string *self);
/* Lifetime. n_string_gut() is optional for _creat_auto() strings */
INLINE struct n_string *
n_string_creat(struct n_string *self){
self->s_dat = NIL;
self->s_len = self->s_auto = self->s_size = 0;
return self;
}
INLINE struct n_string *
n_string_creat_auto(struct n_string *self){
self->s_dat = NIL;
self->s_len = self->s_auto = self->s_size = 0;
self->s_auto = TRU1;
return self;
}
INLINE void n_string_gut(struct n_string *self){
if(self->s_dat != NIL)
n__string_clear(self);
}
INLINE struct n_string *
n_string_trunc(struct n_string *self, uz len){
ASSERT(UCMP(z, len, <=, self->s_len));
self->s_len = S(u32,len);
return self;
}
INLINE struct n_string *
n_string_take_ownership(struct n_string *self, char *buf, u32 size, u32 len){
ASSERT(self->s_dat == NIL);
ASSERT(size == 0 || buf != NIL);
ASSERT(len == 0 || len < size);
self->s_dat = buf;
self->s_size = size;
self->s_len = len;
return self;
}
INLINE struct n_string *
n_string_drop_ownership(struct n_string *self){
self->s_dat = NIL;
self->s_len = self->s_size = 0;
return self;
}
INLINE struct n_string *
n_string_clear(struct n_string *self){
if(self->s_size > 0)
self = n__string_clear(self);
return self;
}
/* Check whether a buffer of Len bytes can be inserted into S(elf) */
INLINE boole n_string_get_can_book(uz len){
return (S(uz,S32_MAX) - Z_ALIGN(1) > len);
}
INLINE boole n_string_can_book(struct n_string *self, uz len){
return (n_string_get_can_book(len) &&
S(uz,S32_MAX) - Z_ALIGN(1) - len > self->s_len);
}
/* Reserve room for noof additional bytes, but don't adjust length (yet) */
FL struct n_string *n_string_reserve(struct n_string *self, uz noof
su_DBG_LOC_ARGS_DECL);
#define n_string_book n_string_reserve
/* Resize to exactly nlen bytes; any new storage isn't initialized */
FL struct n_string *n_string_resize(struct n_string *self, uz nlen
su_DBG_LOC_ARGS_DECL);
#ifdef su_HAVE_DBG_LOC_ARGS
# define n_string_reserve(S,N) (n_string_reserve)(S, N su_DBG_LOC_ARGS_INJ)
# define n_string_resize(S,N) (n_string_resize)(S, N su_DBG_LOC_ARGS_INJ)
#endif
/* */
FL struct n_string *n_string_push_buf(struct n_string *self, char const *buf,
uz buflen su_DBG_LOC_ARGS_DECL);
#define n_string_push(S, T) n_string_push_buf(S, (T)->s_len, (T)->s_dat)
#define n_string_push_cp(S,CP) n_string_push_buf(S, CP, UZ_MAX)
FL struct n_string *n_string_push_c(struct n_string *self, char c
su_DBG_LOC_ARGS_DECL);
#define n_string_assign(S,T) ((S)->s_len = 0, n_string_push(S, T))
#define n_string_assign_c(S,C) ((S)->s_len = 0, n_string_push_c(S, C))
#define n_string_assign_cp(S,CP) ((S)->s_len = 0, n_string_push_cp(S, CP))
#define n_string_assign_buf(S,B,BL) \
((S)->s_len = 0, n_string_push_buf(S, B, BL))
#ifdef su_HAVE_DBG_LOC_ARGS
# define n_string_push_buf(S,B,BL) \
(n_string_push_buf)(S, B, BL su_DBG_LOC_ARGS_INJ)
# define n_string_push_c(S,C) (n_string_push_c)(S, C su_DBG_LOC_ARGS_INJ)
#endif
/* */
FL struct n_string *n_string_unshift_buf(struct n_string *self,
char const *buf, uz buflen su_DBG_LOC_ARGS_DECL);
#define n_string_unshift(S,T) \
n_string_unshift_buf(S, (T)->s_len, (T)->s_dat)
#define n_string_unshift_cp(S,CP) \
n_string_unshift_buf(S, CP, UZ_MAX)
FL struct n_string *n_string_unshift_c(struct n_string *self, char c
su_DBG_LOC_ARGS_DECL);
#ifdef su_HAVE_DBG_LOC_ARGS
# define n_string_unshift_buf(S,B,BL) \
(n_string_unshift_buf)(S, B, BL su_DBG_LOC_ARGS_INJ)
# define n_string_unshift_c(S,C) \
(n_string_unshift_c)(S, C su_DBG_LOC_ARGS_INJ)
#endif
/* */
FL struct n_string *n_string_insert_buf(struct n_string *self, uz idx,
char const *buf, uz buflen su_DBG_LOC_ARGS_DECL);
#define n_string_insert(S,I,T) \
n_string_insert_buf(S, I, (T)->s_len, (T)->s_dat)
#define n_string_insert_cp(S,I,CP) \
n_string_insert_buf(S, I, CP, UZ_MAX)
FL struct n_string *n_string_insert_c(struct n_string *self, uz idx,
char c su_DBG_LOC_ARGS_DECL);
#ifdef su_HAVE_DBG_LOC_ARGS
# define n_string_insert_buf(S,I,B,BL) \
(n_string_insert_buf)(S, I, B, BL su_DBG_LOC_ARGS_INJ)
# define n_string_insert_c(S,I,C) \
(n_string_insert_c)(S, I, C su_DBG_LOC_ARGS_INJ)
#endif
/* */
FL struct n_string *n_string_cut(struct n_string *self, uz idx,
uz len);
/* Ensure self has a - NUL terminated - buffer, and return that.
* The latter may return the pointer to an internal empty RODATA instead */
FL char *n_string_cp(struct n_string *self su_DBG_LOC_ARGS_DECL);
FL char const *n_string_cp_const(struct n_string const *self);
#ifdef su_HAVE_DBG_LOC_ARGS
# define n_string_cp(S) (n_string_cp)(S su_DBG_LOC_ARGS_INJ)
#endif
/*
* thread.c
*/
/* */
FL int c_thread(void *vp);
/* */
FL int c_unthread(void *vp);
/* */
FL struct message * next_in_thread(struct message *mp);
FL struct message * prev_in_thread(struct message *mp);
FL struct message * this_in_thread(struct message *mp, long n);
/* Sorted mode is internally just a variant of threaded mode with all m_parent
* and m_child links being NULL */
FL int c_sort(void *vp);
/* */
FL int c_collapse(void *v);
FL int c_uncollapse(void *v);
/* */
FL void uncollapse1(struct message *mp, int always);
/*
* tls.c
*/
#ifdef mx_HAVE_TLS
/* */
FL void n_tls_set_verify_level(struct mx_url const *urlp);
/* */
FL boole n_tls_verify_decide(void);
/* */
FL boole mx_smime_split(FILE *ip, FILE **hp, FILE **bp, long xcount,
boole keep);
/* */
FL FILE * smime_sign_assemble(FILE *hp, FILE *bp, FILE *sp,
char const *message_digest);
/* */
FL FILE * smime_encrypt_assemble(FILE *hp, FILE *yp);
/* hp and bp are NOT closed */
FL struct message *mx_smime_decrypt_assemble(struct message *mp, FILE *hp,
FILE *bp);
/* `certsave' */
FL int c_certsave(void *vp);
/* */
FL boole n_tls_rfc2595_hostname_match(char const *host, char const *pattern);
/* `tls' */
FL int c_tls(void *vp);
#endif /* mx_HAVE_TLS */
/*
* xtls.c
*/
#ifdef mx_HAVE_XTLS
/* Our wrapper for RAND_bytes(3); the implementation exists only when
* HAVE_RANDOM is RANDOM_IMPL_TLS, though */
FL void mx_tls_rand_bytes(void *buf, uz blen);
/* Will fill in a non-NULL *urlp->url_cert_fprint with auto-reclaimed
* buffer on success, otherwise urlp is constant */
FL boole n_tls_open(struct mx_url *urlp, struct mx_socket *sp);
/* */
FL void ssl_gen_err(char const *fmt, ...);
/* */
FL int c_verify(void *vp);
/* */
FL FILE * smime_sign(FILE *ip, char const *addr);
/* */
FL FILE * smime_encrypt(FILE *ip, char const *certfile, char const *to);
FL struct message * smime_decrypt(struct message *m, char const *to,
char const *cc, boole is_a_verify_call);
/* */
FL enum okay smime_certsave(struct message *m, int n, FILE *op);
#endif /* mx_HAVE_XTLS */
/*
* obs-imap.c
*/
#ifdef mx_HAVE_IMAP
FL void n_go_onintr_for_imap(void);
/* The former returns the input again if no conversion is necessary */
FL char const *imap_path_encode(char const *path, boole *err_or_null);
FL char *imap_path_decode(char const *path, boole *err_or_null);
FL char const * imap_fileof(char const *xcp);
FL enum okay imap_noop(void);
FL enum okay imap_select(struct mailbox *mp, off_t *size, int *count,
const char *mbx, enum fedit_mode fm);
FL int imap_setfile(char const *who, const char *xserver, enum fedit_mode fm);
FL enum okay imap_header(struct message *m);
FL enum okay imap_body(struct message *m);
FL void imap_getheaders(int bot, int top);
FL boole imap_quit(boole hold_sigs_on);
FL enum okay imap_undelete(struct message *m, int n);
FL enum okay imap_unread(struct message *m, int n);
FL int c_imapcodec(void *vp);
FL int c_imap_imap(void *vp);
FL int imap_newmail(int nmail);
FL enum okay imap_append(const char *xserver, FILE *fp, long offset);
FL int imap_folders(const char *name, int strip);
FL enum okay imap_copy(struct message *m, int n, const char *name);
# ifdef mx_HAVE_IMAP_SEARCH
FL sz imap_search1(const char *spec, int f);
# endif
FL int imap_thisaccount(const char *cp);
FL enum okay imap_remove(const char *name);
FL enum okay imap_rename(const char *old, const char *new);
FL enum okay imap_dequeue(struct mailbox *mp, FILE *fp);
FL int c_connect(void *vp);
FL int c_disconnect(void *vp);
FL int c_cache(void *vp);
FL int disconnected(const char *file);
FL void transflags(struct message *omessage, long omsgCount,
int transparent);
FL time_t imap_read_date_time(const char *cp);
FL const char * imap_make_date_time(time_t t);
/* Extract the protocol base and return a duplicate */
FL char *protbase(char const *cp su_DBG_LOC_ARGS_DECL);
# ifdef su_HAVE_DBG_LOC_ARGS
# define protbase(CP) (protbase)(CP su_DBG_LOC_ARGS_INJ)
# endif
#endif /* mx_HAVE_IMAP */
/*
* obs-imap-cache.c
*/
#ifdef mx_HAVE_IMAP
FL enum okay getcache1(struct mailbox *mp, struct message *m,
enum needspec need, int setflags);
FL enum okay getcache(struct mailbox *mp, struct message *m,
enum needspec need);
FL void putcache(struct mailbox *mp, struct message *m);
FL void initcache(struct mailbox *mp);
FL void purgecache(struct mailbox *mp, struct message *m, long mc);
FL void delcache(struct mailbox *mp, struct message *m);
FL enum okay cache_setptr(enum fedit_mode fm, int transparent);
FL enum okay cache_list(struct mailbox *mp, char const *base, int strip,
FILE *fp);
FL enum okay cache_remove(char const *name);
FL enum okay cache_rename(char const *old, char const *new);
FL u64 cached_uidvalidity(struct mailbox *mp);
FL FILE * cache_queue(struct mailbox *mp);
FL enum okay cache_dequeue(struct mailbox *mp);
#endif /* mx_HAVE_IMAP */
/*
* obs-lzw.c
*/
#ifdef mx_HAVE_IMAP
FL int zwrite(void *cookie, const char *wbp, int num);
FL int zfree(void *cookie);
FL int zread(void *cookie, char *rbp, int num);
FL void * zalloc(FILE *fp);
#endif /* mx_HAVE_IMAP */
#ifndef mx_HAVE_AMALGAMATION
# undef FL
# define FL
#endif
/* s-it-mode */
|
catroll/mailx
|
src/mx/cmd-vexpr.c
|
<filename>src/mx/cmd-vexpr.c
/*@ S-nail - a mail user agent derived from Berkeley Mail.
*@ Implementation of cmd-vexpr.h.
*@ TODO - better commandline parser that can dive into subcommands could
*@ TODO get rid of a lot of ERR_SYNOPSIS cruft.
*@ TODO - use su_regex (and if it's a wrapper only)
*@ TODO - use su_path_info instead of stat(2)
*@ TODO - yet needs OPT_CMD_CSOP for compat byte string operation call-out
*@ TODO - _VEXPR -> _CVEXPR
*
* Copyright (c) 2017 - 2020 Steffen (Daode) Nurpmeso <<EMAIL>>.
* SPDX-License-Identifier: ISC
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#undef su_FILE
#define su_FILE cmd_vexpr
#define mx_SOURCE
#define mx_SOURCE_CMD_VEXPR
#ifndef mx_HAVE_AMALGAMATION
# include "mx/nail.h"
#endif
su_EMPTY_FILE()
#ifdef mx_HAVE_CMD_VEXPR
#include <sys/types.h> /* TODO su_path_info */
#include <sys/stat.h> /* TODO su_path_info */
#include <unistd.h> /* TODO su_path_info */
#ifdef mx_HAVE_REGEX
# include <regex.h> /* TODO su_regex */
#endif
#include <su/cs.h>
#include <su/icodec.h>
#include <su/mem.h>
#include "mx/cmd.h"
/* v15compat: csop.h */
#include "mx/cmd-csop.h"
#include "mx/random.h"
#include "mx/ui-str.h"
#include "mx/cmd-vexpr.h"
#include "su/code-in.h"
enum a_vexpr_cmd{
a_VEXPR_CMD_NUM__MIN,
a_VEXPR_CMD_NUM_EQUAL = a_VEXPR_CMD_NUM__MIN,
a_VEXPR_CMD_NUM_NOT,
a_VEXPR_CMD_NUM_PLUS,
a_VEXPR_CMD_NUM_MINUS,
a_VEXPR_CMD_NUM_MUL,
a_VEXPR_CMD_NUM_DIV,
a_VEXPR_CMD_NUM_MOD,
a_VEXPR_CMD_NUM_OR,
a_VEXPR_CMD_NUM_AND,
a_VEXPR_CMD_NUM_XOR,
a_VEXPR_CMD_NUM_LSHIFT,
a_VEXPR_CMD_NUM_RSHIFT,
a_VEXPR_CMD_NUM_URSHIFT,
a_VEXPR_CMD_NUM_PBASE,
a_VEXPR_CMD_NUM__MAX,
a_VEXPR_CMD_AGN__MIN = a_VEXPR_CMD_NUM__MAX,
a_VEXPR_CMD_AGN_DATE_UTC = a_VEXPR_CMD_AGN__MIN,
a_VEXPR_CMD_AGN_DATE_STAMP_UTC,
a_VEXPR_CMD_AGN_EPOCH,
a_VEXPR_CMD_AGN_FILE_EXPAND,
a_VEXPR_CMD_AGN_FILE_STAT,
a_VEXPR_CMD_AGN_FILE_LSTAT,
a_VEXPR_CMD_AGN_RANDOM,
a_VEXPR_CMD_AGN__MAX,
a_VEXPR_CMD_STR__MIN = a_VEXPR_CMD_AGN__MAX,
a_VEXPR_CMD_STR_MAKEPRINT = a_VEXPR_CMD_STR__MIN,
#ifdef mx_HAVE_REGEX
a_VEXPR_CMD_STR_REGEX,
a_VEXPR_CMD_STR_IREGEX, /* v15compat */
#endif
a_VEXPR_CMD_STR__MAX,
/* v15compat: vexpr byte operations -> csop */
a_VEXPR_CMD_BYTE__MIN = a_VEXPR_CMD_STR__MAX,
a_VEXPR_CMD_BYTE_LENGTH = a_VEXPR_CMD_BYTE__MIN,
a_VEXPR_CMD_BYTE_HASH32,
a_VEXPR_CMD_BYTE_HASH,
a_VEXPR_CMD_BYTE_FIND,
a_VEXPR_CMD_BYTE_IFIND,
a_VEXPR_CMD_BYTE_SUBSTRING,
a_VEXPR_CMD_BYTE_TRIM,
a_VEXPR_CMD_BYTE_TRIM_FRONT,
a_VEXPR_CMD_BYTE_TRIM_END,
a_VEXPR_CMD_BYTE__MAX,
a_VEXPR_CMD__MAX
};
enum a_vexpr_err{
a_VEXPR_ERR_NONE,
a_VEXPR_ERR_SYNOPSIS,
a_VEXPR_ERR_SUBCMD,
a_VEXPR_ERR_MOD_NOT_ALLOWED,
a_VEXPR_ERR_MOD_NOT_SUPPORTED,
a_VEXPR_ERR_NUM_RANGE,
a_VEXPR_ERR_NUM_OVERFLOW,
a_VEXPR_ERR_STR_NUM_RANGE,
a_VEXPR_ERR_STR_OVERFLOW,
a_VEXPR_ERR_STR_NODATA,
a_VEXPR_ERR_STR_GENERIC
};
enum {a_VEXPR_ERR__MAX = a_VEXPR_ERR_STR_GENERIC};
CTA(S(uz,a_VEXPR_CMD__MAX | a_VEXPR_ERR__MAX) <= 0x7Fu, "Bit range excess");
enum a_vexpr_flags{
a_VEXPR_NONE,
a_VEXPR_ERR = 1u<<0, /* There was an error */
a_VEXPR_MOD_SATURATED = 1u<<1, /* Saturated / case-insensitive / XY */
a_VEXPR_MOD_CASE = 1u<<2, /* Saturated / case-insensitive / XY */
a_VEXPR_MOD_MASK = a_VEXPR_MOD_SATURATED | a_VEXPR_MOD_CASE,
a_VEXPR_ISNUM = 1u<<3,
a_VEXPR_ISDECIMAL = 1u<<4, /* Print only decimal result */
a_VEXPR_UNSIGNED_OP = 1u<<5, /* Force unsigned interpretation */
a_VEXPR_SOFTOVERFLOW = 1u<<6,
a_VEXPR_PBASE = 1u<<7, /* Print additional number base */
a_VEXPR_PBASE_FORCE_UNSIGNED = 1u<<8, /* We saw an u prefix for it */
a_VEXPR__FMASK = 0x1FFu,
a_VEXPR__FSHIFT = 9u,
a_VEXPR__FCMDMASK = 0xFE00u,
a_VEXPR__TMP = 1u<<30
};
/* .vc_cmderr=8-bit, and so a_vexpr_subcmd can store CMD+MOD flags in 16-bit */
CTA(((S(u32,a_VEXPR_CMD__MAX | a_VEXPR_ERR__MAX) << a_VEXPR__FSHIFT) &
~a_VEXPR__FCMDMASK) == 0, "Bit ranges overlap");
struct a_vexpr_ctx{
u32 vc_flags;
u8 vc_cmderr; /* On input, a_vexpr_cmd, on output (maybe) a_vexpr_err */
u8 vc_pbase;
u8 vc__pad[2];
char const **vc_argv;
char const *vc_cmd_name;
char const *vc_varname; /* VPUT support */
char const *vc_varres;
char const *vc_arg; /* The current arg (_ERR: which caused failure) */
s64 vc_lhv;
s64 vc_rhv;
char vc_iencbuf[2+1/* BASE# prefix*/ + su_IENC_BUFFER_SIZE + 1];
};
struct a_vexpr_subcmd{
u16 vs_mpv;
char vs_name[14];
};
static struct a_vexpr_subcmd const a_vexpr_subcmds[] = {
#undef a_X
#define a_X(C,F) (S(u16,C) << a_VEXPR__FSHIFT) | F
{a_X(a_VEXPR_CMD_NUM_EQUAL, a_VEXPR_MOD_SATURATED), "="},
{a_X(a_VEXPR_CMD_NUM_NOT, a_VEXPR_MOD_SATURATED), "~"},
{a_X(a_VEXPR_CMD_NUM_PLUS, a_VEXPR_MOD_SATURATED), "+"},
{a_X(a_VEXPR_CMD_NUM_MINUS, a_VEXPR_MOD_SATURATED), "-"},
{a_X(a_VEXPR_CMD_NUM_MUL, a_VEXPR_MOD_SATURATED), "*"},
{a_X(a_VEXPR_CMD_NUM_DIV, a_VEXPR_MOD_SATURATED), "/"},
{a_X(a_VEXPR_CMD_NUM_MOD, a_VEXPR_MOD_SATURATED), "%"},
{a_X(a_VEXPR_CMD_NUM_OR, a_VEXPR_MOD_SATURATED), "|"},
{a_X(a_VEXPR_CMD_NUM_AND, a_VEXPR_MOD_SATURATED), "&"},
{a_X(a_VEXPR_CMD_NUM_XOR, a_VEXPR_MOD_SATURATED), "^"},
{a_X(a_VEXPR_CMD_NUM_LSHIFT, a_VEXPR_MOD_SATURATED), "<<"},
{a_X(a_VEXPR_CMD_NUM_RSHIFT, a_VEXPR_MOD_SATURATED), ">>"},
{a_X(a_VEXPR_CMD_NUM_URSHIFT, a_VEXPR_MOD_SATURATED), ">>>"},
{a_X(a_VEXPR_CMD_NUM_PBASE, a_VEXPR_MOD_SATURATED), "pbase\0"},
{a_X(a_VEXPR_CMD_AGN_DATE_UTC, 0), "date-utc"},
{a_X(a_VEXPR_CMD_AGN_DATE_STAMP_UTC, 0), "date-stamp-utc"},
{a_X(a_VEXPR_CMD_AGN_EPOCH, 0), "epoch"},
{a_X(a_VEXPR_CMD_AGN_FILE_EXPAND, 0), "file-expand\0"},
{a_X(a_VEXPR_CMD_AGN_FILE_STAT, 0), "file-stat"},
{a_X(a_VEXPR_CMD_AGN_FILE_LSTAT, 0), "file-lstat"},
{a_X(a_VEXPR_CMD_AGN_RANDOM, 0), "random"},
{a_X(a_VEXPR_CMD_STR_MAKEPRINT, 0), "makeprint"},
#ifdef mx_HAVE_REGEX
{a_X(a_VEXPR_CMD_STR_REGEX, a_VEXPR_MOD_CASE), "regex"},
{a_X(a_VEXPR_CMD_STR_IREGEX, 0), "iregex"}, /* v15compat*/
#endif
/* v15compat: vexpr byte operations -> csop */
{a_X(a_VEXPR_CMD_BYTE_LENGTH, 0), "length"},
{a_X(a_VEXPR_CMD_BYTE_HASH, 0), "hash"},
{a_X(a_VEXPR_CMD_BYTE_HASH32, 0), "hash32"},
{a_X(a_VEXPR_CMD_BYTE_FIND, a_VEXPR_MOD_CASE), "find"},
{a_X(a_VEXPR_CMD_BYTE_IFIND, 0), "ifind"}, /* v15compat */
{a_X(a_VEXPR_CMD_BYTE_SUBSTRING, 0), "substring"},
{a_X(a_VEXPR_CMD_BYTE_TRIM, 0), "trim"},
{a_X(a_VEXPR_CMD_BYTE_TRIM_FRONT, 0), "trim-front\0"},
{a_X(a_VEXPR_CMD_BYTE_TRIM_END, 0), "trim-end"},
#undef a_X
};
/* Entered with .vc_flags=NONE(|MOD)? */
static void a_vexpr_numeric(struct a_vexpr_ctx *vcp);
static void a_vexpr_agnostic(struct a_vexpr_ctx *vcp);
static void a_vexpr_string(struct a_vexpr_ctx *vcp);
#ifdef mx_HAVE_REGEX
static char *a_vexpr__regex_replace(void *uservp);
#endif
static void
a_vexpr_numeric(struct a_vexpr_ctx *vcp){
u8 cmd;
u32 idecs, idecm;
s64 lhv, rhv;
char const *cp;
u32 f;
NYD2_IN;
lhv = rhv = 0;
f = vcp->vc_flags;
f |= a_VEXPR_ISNUM;
if((cp = vcp->vc_argv[0]) == NIL){
f |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_SYNOPSIS;
goto jleave;
}
jlhv_redo:
if(*cp == '\0')
lhv = 0;
else{
vcp->vc_arg = cp;
idecm = (((*cp == 'u' || *cp == 'U')
? (f |= a_VEXPR_PBASE_FORCE_UNSIGNED, ++cp, su_IDEC_MODE_NONE)
: ((*cp == 's' || *cp == 'S')
? (++cp, su_IDEC_MODE_SIGNED_TYPE)
: su_IDEC_MODE_SIGNED_TYPE | su_IDEC_MODE_POW2BASE_UNSIGNED)
) |
su_IDEC_MODE_BASE0_NUMBER_SIGN_RESCAN);
if(((idecs = su_idec_cp(&lhv, cp, 0, idecm, NIL)
) & (su_IDEC_STATE_EMASK | su_IDEC_STATE_CONSUMED)
) != su_IDEC_STATE_CONSUMED){
if(!(idecs & su_IDEC_STATE_EOVERFLOW) ||
!(f & a_VEXPR_MOD_SATURATED)){
f |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_NUM_RANGE;
}else
f |= a_VEXPR_SOFTOVERFLOW;
goto jleave;
}
}
switch((cmd = S(u8,vcp->vc_cmderr))){ /* break==goto jleave */
case a_VEXPR_CMD_NUM_NOT:
lhv = ~lhv;
/* FALLTHRU */
default:
case a_VEXPR_CMD_NUM_EQUAL:
if(vcp->vc_argv[1] != NIL){
f |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_SYNOPSIS;
}
break;
case a_VEXPR_CMD_NUM_PLUS:
if(vcp->vc_argv[1] == NIL){
lhv = +lhv;
break;
}
goto jbinop;
case a_VEXPR_CMD_NUM_MINUS:
if(vcp->vc_argv[1] == NIL){
lhv = -lhv;
break;
}
goto jbinop;
case a_VEXPR_CMD_NUM_MUL:
case a_VEXPR_CMD_NUM_DIV:
case a_VEXPR_CMD_NUM_MOD:
case a_VEXPR_CMD_NUM_OR:
case a_VEXPR_CMD_NUM_AND:
case a_VEXPR_CMD_NUM_XOR:
case a_VEXPR_CMD_NUM_LSHIFT:
case a_VEXPR_CMD_NUM_RSHIFT:
case a_VEXPR_CMD_NUM_URSHIFT:
jbinop:
if((cp = vcp->vc_argv[1]) == NIL ||
(vcp->vc_arg = cp, vcp->vc_argv[2] != NIL)){
f |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_SYNOPSIS;
break;
}
if(*cp == '\0')
rhv = 0;
else{
idecm = (((*cp == 'u' || *cp == 'U')
? (++cp, su_IDEC_MODE_NONE)
: ((*cp == 's' || *cp == 'S')
? (++cp, su_IDEC_MODE_SIGNED_TYPE)
: su_IDEC_MODE_SIGNED_TYPE |
su_IDEC_MODE_POW2BASE_UNSIGNED)) |
su_IDEC_MODE_BASE0_NUMBER_SIGN_RESCAN);
if(((idecs = su_idec_cp(&rhv, cp, 0, idecm, NIL)
) & (su_IDEC_STATE_EMASK | su_IDEC_STATE_CONSUMED)
) != su_IDEC_STATE_CONSUMED){
if(!(idecs & su_IDEC_STATE_EOVERFLOW) ||
!(f & a_VEXPR_MOD_SATURATED)){
f |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_NUM_RANGE;
}else
f |= a_VEXPR_SOFTOVERFLOW;
break;
}
}
jbinop_again:
switch(cmd){
default:
case a_VEXPR_CMD_NUM_PLUS:
if(rhv < 0){
if(rhv != S64_MIN){
rhv = -rhv;
cmd = a_VEXPR_CMD_NUM_MINUS;
goto jbinop_again;
}else if(lhv < 0)
goto jenum_plusminus;
else if(lhv == 0){
lhv = rhv;
break;
}
}else if(S64_MAX - rhv < lhv)
goto jenum_plusminus;
lhv += rhv;
break;
case a_VEXPR_CMD_NUM_MINUS:
if(rhv < 0){
if(rhv != S64_MIN){
rhv = -rhv;
cmd = a_VEXPR_CMD_NUM_PLUS;
goto jbinop_again;
}else if(lhv > 0)
goto jenum_plusminus;
else if(lhv == 0){
lhv = rhv;
break;
}
}else if(S64_MIN + rhv > lhv){
jenum_plusminus:
if(!(f & a_VEXPR_MOD_SATURATED)){
f |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_NUM_OVERFLOW;
break;
}
f |= a_VEXPR_SOFTOVERFLOW;
lhv = (lhv < 0 || cmd == a_VEXPR_CMD_NUM_MINUS)
? S64_MIN : S64_MAX;
break;
}
lhv -= rhv;
break;
case a_VEXPR_CMD_NUM_MUL:
/* Will the result be positive? */
if((lhv < 0) == (rhv < 0)){
if(lhv > 0){
lhv = -lhv;
rhv = -rhv;
}
if(rhv != 0 && lhv != 0 && S64_MAX / rhv > lhv){
if(!(f & a_VEXPR_MOD_SATURATED)){
f |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_NUM_OVERFLOW;
break;
}
f |= a_VEXPR_SOFTOVERFLOW;
lhv = S64_MAX;
}else
lhv *= rhv;
}else{
if(rhv > 0){
if(lhv != 0 && S64_MIN / lhv < rhv){
if(!(f & a_VEXPR_MOD_SATURATED)){
f |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_NUM_OVERFLOW;
break;
}
f |= a_VEXPR_SOFTOVERFLOW;
lhv = S64_MIN;
}else
lhv *= rhv;
}else{
if(rhv != 0 && lhv != 0 && S64_MIN / rhv < lhv){
if(!(f & a_VEXPR_MOD_SATURATED)){
f |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_NUM_OVERFLOW;
}
f |= a_VEXPR_SOFTOVERFLOW;
lhv = S64_MIN;
}else
lhv *= rhv;
}
}
break;
case a_VEXPR_CMD_NUM_DIV:
if(rhv == 0){
if(!(f & a_VEXPR_MOD_SATURATED)){
f |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_NUM_RANGE;
break;
}
f |= a_VEXPR_SOFTOVERFLOW;
lhv = S64_MAX;
}else
lhv /= rhv;
break;
case a_VEXPR_CMD_NUM_MOD:
if(rhv == 0){
if(!(f & a_VEXPR_MOD_SATURATED)){
f |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_NUM_RANGE;
break;
}
f |= a_VEXPR_SOFTOVERFLOW;
lhv = S64_MAX;
}else
lhv %= rhv;
break;
case a_VEXPR_CMD_NUM_OR:
lhv |= rhv;
break;
case a_VEXPR_CMD_NUM_AND:
lhv &= rhv;
break;
case a_VEXPR_CMD_NUM_XOR:
lhv ^= rhv;
break;
case a_VEXPR_CMD_NUM_LSHIFT:
case a_VEXPR_CMD_NUM_RSHIFT:
case a_VEXPR_CMD_NUM_URSHIFT:{
u8 sv;
if(S(u64,rhv) <= 63) /* xxx 63? */
sv = S(u8,rhv);
else if(!(f & a_VEXPR_MOD_SATURATED)){
f |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_NUM_OVERFLOW;
break;
}else
sv = 63;
if(cmd == a_VEXPR_CMD_NUM_LSHIFT)
lhv <<= sv;
else if(cmd == a_VEXPR_CMD_NUM_RSHIFT)
lhv >>= sv;
else
lhv = S(u64,lhv) >> sv;
}break;
}
break;
case a_VEXPR_CMD_NUM_PBASE:
/* Have been here already? */
if(f & a_VEXPR_PBASE)
break;
if((cp = vcp->vc_argv[1]) == NIL || vcp->vc_argv[2] != NIL){
f |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_SYNOPSIS;
break;
}
if(lhv < 2 || lhv > 36){
f |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_NUM_RANGE;
break;
}
f |= a_VEXPR_PBASE;
vcp->vc_pbase = S(u8,lhv);
goto jlhv_redo;
}
jleave:
vcp->vc_flags = f;
vcp->vc_lhv = lhv;
vcp->vc_rhv = rhv;
NYD2_OU;
}
static void
a_vexpr_agnostic(struct a_vexpr_ctx *vcp){
struct stat st;
struct n_string s_b, *s;
NYD2_IN;
switch(vcp->vc_cmderr){
case a_VEXPR_CMD_AGN_DATE_UTC:
if(vcp->vc_argv[0] != NIL){
vcp->vc_flags |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_SYNOPSIS;
}else{
struct time_current tc;
time_current_update(&tc, TRU1);
s = n_string_book(n_string_creat_auto(&s_b), 31);
s = n_string_push_cp(s, "dutc_year=");
s = n_string_push_cp(s,
su_ienc_s64(vcp->vc_iencbuf, tc.tc_gm.tm_year + 1900, 10));
s = n_string_push_c(s, ' ');
s = n_string_push_cp(s, "dutc_month=");
s = n_string_push_cp(s,
su_ienc_s64(vcp->vc_iencbuf, tc.tc_gm.tm_mon + 1, 10));
s = n_string_push_c(s, ' ');
s = n_string_push_cp(s, "dutc_day=");
s = n_string_push_cp(s,
su_ienc_s64(vcp->vc_iencbuf, tc.tc_gm.tm_mday, 10));
s = n_string_push_c(s, ' ');
s = n_string_push_cp(s, "dutc_hour=");
s = n_string_push_cp(s,
su_ienc_s64(vcp->vc_iencbuf, tc.tc_gm.tm_hour, 10));
s = n_string_push_c(s, ' ');
s = n_string_push_cp(s, "dutc_min=");
s = n_string_push_cp(s,
su_ienc_s64(vcp->vc_iencbuf, tc.tc_gm.tm_min, 10));
s = n_string_push_c(s, ' ');
s = n_string_push_cp(s, "dutc_sec=");
s = n_string_push_cp(s,
su_ienc_s64(vcp->vc_iencbuf, tc.tc_gm.tm_sec, 10));
vcp->vc_varres = n_string_cp(s);
/* n_string_gut(n_string_drop_ownership(s)); */
}
break;
default:
case a_VEXPR_CMD_AGN_DATE_STAMP_UTC:
if(vcp->vc_argv[0] != NIL){
vcp->vc_flags |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_SYNOPSIS;
}else{
struct time_current tc;
time_current_update(&tc, TRU1);
(void)snprintf(vcp->vc_iencbuf, sizeof(vcp->vc_iencbuf),
"%04d-%02d-%02dT%02d:%02d:%02dZ",
tc.tc_gm.tm_year + 1900, tc.tc_gm.tm_mon + 1, tc.tc_gm.tm_mday,
tc.tc_gm.tm_hour, tc.tc_gm.tm_min, tc.tc_gm.tm_sec);
vcp->vc_varres = vcp->vc_iencbuf;
}
break;
case a_VEXPR_CMD_AGN_EPOCH:
if(vcp->vc_argv[0] != NIL){
vcp->vc_flags |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_SYNOPSIS;
}else{
struct n_timespec const *tsp;
tsp = n_time_now(TRU1);
s = n_string_book(n_string_creat_auto(&s_b), 31);
s = n_string_push_cp(s, "epoch_sec=");
s = n_string_push_cp(s,
su_ienc_s64(vcp->vc_iencbuf, tsp->ts_sec, 10));
s = n_string_push_c(s, ' ');
s = n_string_push_cp(s, "epoch_nsec=");
s = n_string_push_cp(s,
su_ienc_s64(vcp->vc_iencbuf, tsp->ts_nsec, 10));
vcp->vc_varres = n_string_cp(s);
/* n_string_gut(n_string_drop_ownership(s)); */
}
break;
case a_VEXPR_CMD_AGN_FILE_EXPAND:
if(vcp->vc_argv[0] == NIL || vcp->vc_argv[1] != NIL){
vcp->vc_flags |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_SYNOPSIS;
break;
}
vcp->vc_arg = vcp->vc_argv[0];
if((vcp->vc_varres = fexpand(vcp->vc_arg, FEXP_NVAR | FEXP_NOPROTO)
) == NIL){
vcp->vc_flags |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_STR_NODATA;
}
break;
case a_VEXPR_CMD_AGN_FILE_LSTAT:
vcp->vc_flags |= a_VEXPR_MOD_MASK;
/* FALLTHRU */
case a_VEXPR_CMD_AGN_FILE_STAT:{
char c;
if(vcp->vc_argv[0] == NIL || vcp->vc_argv[1] != NIL){
vcp->vc_flags |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_SYNOPSIS;
break;
}
vcp->vc_arg = vcp->vc_argv[0];
if((vcp->vc_varres = fexpand(vcp->vc_arg, (/*FEXP_NOPROTO |*/
FEXP_LOCAL | FEXP_NVAR))) == NIL){
vcp->vc_flags |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_STR_NODATA;
break;
}
if(((vcp->vc_flags & a_VEXPR_MOD_MASK) ? lstat : stat
)(vcp->vc_varres, &st) != 0){
vcp->vc_flags |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_STR_NODATA;
break;
}
s = n_string_book(n_string_creat_auto(&s_b), 250);
s = n_string_push_cp(s, "st_file=");
s = n_string_push_cp(s, n_shexp_quote_cp(vcp->vc_varres, FAL0));
s = n_string_push_c(s, ' ');
s = n_string_push_cp(s, "st_type=");
if(S_ISDIR(st.st_mode)) c = '/';
else if(S_ISLNK(st.st_mode)) c = '@';
#ifdef S_ISBLK
else if(S_ISBLK(st.st_mode)) c = '#';
#endif
#ifdef S_ISCHR
else if(S_ISCHR(st.st_mode)) c = '%';
#endif
#ifdef S_ISFIFO
else if(S_ISFIFO(st.st_mode)) c = '|';
#endif
#ifdef S_ISSOCK
else if(S_ISSOCK(st.st_mode)) c = '=';
#endif
else c = '.';
s = n_string_push_c(s, c);
s = n_string_push_c(s, ' ');
s = n_string_push_cp(s, "st_nlink=");
s = n_string_push_cp(s, su_ienc_s64(vcp->vc_iencbuf, st.st_nlink, 10));
s = n_string_push_c(s, ' ');
s = n_string_push_cp(s, "st_size=");
s = n_string_push_cp(s, su_ienc_u64(vcp->vc_iencbuf, st.st_size, 10));
s = n_string_push_c(s, ' ');
s = n_string_push_cp(s, "st_mode=");
s = n_string_push_cp(s, su_ienc_s32(vcp->vc_iencbuf,
st.st_mode & 07777, 8));
s = n_string_push_c(s, ' ');
s = n_string_push_cp(s, "st_uid=");
s = n_string_push_cp(s, su_ienc_s64(vcp->vc_iencbuf, st.st_uid, 10));
s = n_string_push_c(s, ' ');
s = n_string_push_cp(s, "st_gid=");
s = n_string_push_cp(s, su_ienc_s64(vcp->vc_iencbuf, st.st_gid, 10));
s = n_string_push_c(s, ' ');
vcp->vc_varres = n_string_cp(s);
/* n_string_gut(n_string_drop_ownership(s)); */
}break;
case a_VEXPR_CMD_AGN_RANDOM:
if(vcp->vc_argv[0] == NIL || vcp->vc_argv[1] != NIL){
vcp->vc_flags |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_SYNOPSIS;
break;
}
vcp->vc_arg = vcp->vc_argv[0];
if((su_idec_s64_cp(&vcp->vc_lhv, vcp->vc_argv[0], 0, NIL
) & (su_IDEC_STATE_EMASK | su_IDEC_STATE_CONSUMED)
) != su_IDEC_STATE_CONSUMED ||
vcp->vc_lhv < 0 || vcp->vc_lhv > PATH_MAX){
vcp->vc_flags |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_STR_NUM_RANGE;
break;
}
if(vcp->vc_lhv == 0)
vcp->vc_lhv = NAME_MAX;
vcp->vc_varres = mx_random_create_cp(S(uz,vcp->vc_lhv), NIL);
break;
}
NYD2_OU;
}
static void
a_vexpr_string(struct a_vexpr_ctx *vcp){
NYD2_IN;
switch(vcp->vc_cmderr){
default:
case a_VEXPR_CMD_STR_MAKEPRINT:{
struct str sin, sout;
if(vcp->vc_argv[0] == NIL || vcp->vc_argv[1] != NIL){
vcp->vc_flags |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_SYNOPSIS;
break;
}
vcp->vc_arg = vcp->vc_argv[0];
/* XXX using su_cs_len for `vexpr makeprint' is wrong for UTF-16 */
sin.l = su_cs_len(sin.s = UNCONST(char*,vcp->vc_arg));
makeprint(&sin, &sout);
vcp->vc_varres = savestrbuf(sout.s, sout.l);
n_free(sout.s);
}break;
/* TODO `vexpr': (wide) string length, find, etc!! */
#ifdef mx_HAVE_REGEX
case a_VEXPR_CMD_STR_IREGEX:
n_OBSOLETE(_("vexpr: iregex: simply use regex?[case] instead, please"));
vcp->vc_flags |= a_VEXPR_MOD_CASE;
/* FALLTHRU */
case a_VEXPR_CMD_STR_REGEX:{
regmatch_t rema[1 + mx_VEXPR_REGEX_MAX];
regex_t re;
int reflrv;
vcp->vc_flags |= a_VEXPR_ISNUM | a_VEXPR_ISDECIMAL;
if(vcp->vc_argv[0] == NIL || vcp->vc_argv[1] == NIL ||
(vcp->vc_argv[2] != NIL && vcp->vc_argv[3] != NIL)){
vcp->vc_flags |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_SYNOPSIS;
break;
}
vcp->vc_arg = vcp->vc_argv[1];
reflrv = REG_EXTENDED;
if(vcp->vc_flags & a_VEXPR_MOD_CASE)
reflrv |= REG_ICASE;
if((reflrv = regcomp(&re, vcp->vc_arg, reflrv))){
n_err(_("vexpr: invalid regular expression: %s: %s\n"),
n_shexp_quote_cp(vcp->vc_arg, FAL0),
n_regex_err_to_doc(NIL, reflrv));
vcp->vc_flags |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_STR_GENERIC;
n_pstate_err_no = su_ERR_INVAL;
break;
}
reflrv = regexec(&re, vcp->vc_argv[0], NELEM(rema), rema, 0);
regfree(&re);
if(reflrv == REG_NOMATCH){
vcp->vc_flags |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_STR_NODATA;
break;
}
/* Search only? Else replace, which is a bit */
if(vcp->vc_argv[2] == NIL){
if(UCMP(64, rema[0].rm_so, >, S64_MAX)){
vcp->vc_flags |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_STR_OVERFLOW;
break;
}
vcp->vc_lhv = S(s64,rema[0].rm_so);
}else{
/* TODO We yet need to have a hook into generic pospar handling
* TODO instead of having a shexp_parse carrier which takes some
* TODO pospars directly */
char const *name, **argv, **ccpp;
uz i, argc;
name = savestrbuf(&vcp->vc_argv[0][rema[0].rm_so],
rema[0].rm_eo - rema[0].rm_so);
for(argc = i = 1; i < NELEM(rema); ++i)
if(rema[i].rm_so != -1)
argc = i;
argv = su_LOFI_TALLOC(char const*,argc +1);
for(ccpp = argv, i = 1; i <= argc; ++ccpp, ++i)
if(rema[i].rm_so != -1)
*ccpp = savestrbuf(&vcp->vc_argv[0][rema[i].rm_so],
rema[i].rm_eo - rema[i].rm_so);
else
*ccpp = su_empty;
*ccpp = NIL;
/* Logical unconst */
vcp->vc_varres = temporary_pospar_access_hook(name, argv, argc,
&a_vexpr__regex_replace, UNCONST(char*,vcp->vc_argv[2]));
su_LOFI_FREE(argv);
if(vcp->vc_varres == NIL){
vcp->vc_flags |= a_VEXPR_ERR;
vcp->vc_cmderr = a_VEXPR_ERR_STR_NODATA;
break;
}
vcp->vc_flags ^= (a_VEXPR_ISNUM | a_VEXPR_ISDECIMAL);
}
}break;
#endif /* mx_HAVE_REGEX */
}
NYD2_OU;
}
#ifdef mx_HAVE_REGEX
static char *
a_vexpr__regex_replace(void *uservp){
struct str templ;
struct n_string s_b;
char *rv;
BITENUM_IS(u32,n_shexp_state) shs;
NYD2_IN;
templ.s = S(char*,uservp);
templ.l = UZ_MAX;
shs = n_shexp_parse_token((n_SHEXP_PARSE_LOG |
n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_QUOTE_AUTO_FIXED |
n_SHEXP_PARSE_QUOTE_AUTO_DSQ),
n_string_creat_auto(&s_b), &templ, NIL);
if((shs & (n_SHEXP_STATE_ERR_MASK | n_SHEXP_STATE_STOP)
) == n_SHEXP_STATE_STOP){
rv = n_string_cp(&s_b);
n_string_drop_ownership(&s_b);
}else
rv = NIL;
NYD2_OU;
return rv;
}
#endif /* mx_HAVE_REGEX */
int
c_vexpr(void *vp){ /* TODO POSIX expr(1) comp. exit status */
struct a_vexpr_ctx vc;
char const *cp;
u32 f;
uz i, j;
NYD_IN;
/*DVL(*/ su_mem_set(&vc, 0xAA, sizeof vc); /*)*/
vc.vc_flags = a_VEXPR_ERR | a_VEXPR_ISNUM;
vc.vc_cmderr = a_VEXPR_ERR_SUBCMD;
vc.vc_argv = S(char const**,vp);
vc.vc_varname = (n_pstate & n_PS_ARGMOD_VPUT) ? *vc.vc_argv++ : NIL;
vc.vc_varres = su_empty;
vc.vc_arg =
vc.vc_cmd_name = *vc.vc_argv++;
if((cp = su_cs_find_c(vc.vc_cmd_name, '?')) != NIL){
j = P2UZ(cp - vc.vc_cmd_name);
if(cp[1] == '\0')
f = a_VEXPR_MOD_MASK;
else if(su_cs_starts_with_case("case", &cp[1]))
f = a_VEXPR_MOD_CASE;
else if(su_cs_starts_with_case("saturated", &cp[1]))
f = a_VEXPR_MOD_SATURATED;
else{
n_err(_("vexpr: invalid modifier: %s\n"),
n_shexp_quote_cp(vc.vc_cmd_name, FAL0));
f = a_VEXPR_ERR;
goto jleave;
}
}else{
f = a_VEXPR_NONE;
if(*vc.vc_cmd_name == '@'){ /* v15compat */
n_OBSOLETE2(_("vexpr: please use ? modifier suffix, "
"not @ prefix"), n_shexp_quote_cp(vc.vc_cmd_name, FAL0));
++vc.vc_cmd_name;
f = a_VEXPR_MOD_MASK;
}
j = su_cs_len(vc.vc_cmd_name);
}
for(i = 0; i < NELEM(a_vexpr_subcmds); ++i){
if(su_cs_starts_with_case_n(a_vexpr_subcmds[i].vs_name,
vc.vc_cmd_name, j)){
vc.vc_cmd_name = a_vexpr_subcmds[i].vs_name;
i = a_vexpr_subcmds[i].vs_mpv;
if(UNLIKELY(f & a_VEXPR_MOD_MASK)){
u32 f2;
f2 = f & a_VEXPR_MOD_MASK;
if(UNLIKELY(!(i & a_VEXPR_MOD_MASK))){
vc.vc_cmderr = a_VEXPR_ERR_MOD_NOT_ALLOWED;
break;
}else if(UNLIKELY(f2 != a_VEXPR_MOD_MASK &&
f2 != (i & a_VEXPR_MOD_MASK))){
vc.vc_cmderr = a_VEXPR_ERR_MOD_NOT_SUPPORTED;
break;
}
}
vc.vc_arg = vc.vc_cmd_name;
vc.vc_flags = f;
i = (i & a_VEXPR__FCMDMASK) >> a_VEXPR__FSHIFT;
if((vc.vc_cmderr = S(u8,i)) < a_VEXPR_CMD_NUM__MAX)
a_vexpr_numeric(&vc);
else if(i < a_VEXPR_CMD_AGN__MAX)
a_vexpr_agnostic(&vc);
else if(i < a_VEXPR_CMD_STR__MAX)
a_vexpr_string(&vc);
else /*if(i < a_VEXPR_CMD_BYTE__MAX)*/{
n_OBSOLETE2(_("vexpr: C-style string operations are now "
"handled via `csop' command (sorry)"), vc.vc_cmd_name);
f = (c_csop(vp) == 0) ? 0 : a_VEXPR_ERR;
goto jleave;
}
break;
}
}
f = vc.vc_flags;
if(LIKELY(!(f & a_VEXPR_ERR))){
n_pstate_err_no = (f & a_VEXPR_SOFTOVERFLOW)
? su_ERR_OVERFLOW : su_ERR_NONE;
}else switch(vc.vc_cmderr){
case a_VEXPR_ERR_NONE:
ASSERT(0);
break;
case a_VEXPR_ERR_SYNOPSIS:
mx_cmd_print_synopsis(mx_cmd_firstfit("vexpr"), NIL);
n_pstate_err_no = su_ERR_INVAL;
goto jenum;
case a_VEXPR_ERR_SUBCMD:
n_err(_("vexpr: invalid subcommand: %s\n"),
n_shexp_quote_cp(vc.vc_arg, FAL0));
n_pstate_err_no = su_ERR_INVAL;
goto jenum;
case a_VEXPR_ERR_MOD_NOT_ALLOWED:
n_err(_("vexpr: modifiers not allowed for subcommand: %s\n"),
n_shexp_quote_cp(vc.vc_arg, FAL0));
n_pstate_err_no = su_ERR_INVAL;
goto jenum;
case a_VEXPR_ERR_MOD_NOT_SUPPORTED:
n_err(_("vexpr: given modifier not supported for subcommand: %s\n"),
n_shexp_quote_cp(vc.vc_arg, FAL0));
n_pstate_err_no = su_ERR_INVAL;
goto jenum;
case a_VEXPR_ERR_NUM_RANGE:
n_err(_("vexpr: numeric argument invalid or out of range: %s\n"),
n_shexp_quote_cp(vc.vc_arg, FAL0));
n_pstate_err_no = su_ERR_RANGE;
goto jenum;
case a_VEXPR_ERR_NUM_OVERFLOW:
n_err(_("vexpr: expression overflows datatype: %" PRId64
" %s %" PRId64 "\n"),
vc.vc_lhv, vc.vc_cmd_name, vc.vc_rhv);
n_pstate_err_no = su_ERR_OVERFLOW;
goto jenum;
default:
jenum:
f = a_VEXPR_ERR | a_VEXPR_ISNUM | a_VEXPR_ISDECIMAL;
vc.vc_lhv = -1;
break;
case a_VEXPR_ERR_STR_NUM_RANGE:
n_err(_("vexpr: numeric argument invalid or out of range: %s\n"),
n_shexp_quote_cp(vc.vc_arg, FAL0));
n_pstate_err_no = su_ERR_RANGE;
goto jestr;
case a_VEXPR_ERR_STR_OVERFLOW:
n_err(_("vexpr: string length or offset overflows datatype\n"));
n_pstate_err_no = su_ERR_OVERFLOW;
goto jestr;
case a_VEXPR_ERR_STR_NODATA:
n_pstate_err_no = su_ERR_NODATA;
/* FALLTHRU*/
case a_VEXPR_ERR_STR_GENERIC:
jestr:
vc.vc_varres = su_empty;
f = a_VEXPR_ERR;
break;
}
/* Generate the variable value content for numerics.
* Anticipate in our handling below! (Avoid needless work) */
if((f & a_VEXPR_ISNUM) && ((f & (a_VEXPR_ISDECIMAL | a_VEXPR_PBASE)) ||
vc.vc_varname != NIL)){
cp = su_ienc(vc.vc_iencbuf, vc.vc_lhv,
((!(f & a_VEXPR_ERR) && (f & a_VEXPR_PBASE)) ? vc.vc_pbase : 10),
(((f & (a_VEXPR_PBASE | a_VEXPR_PBASE_FORCE_UNSIGNED)) ==
(a_VEXPR_PBASE | a_VEXPR_PBASE_FORCE_UNSIGNED))
? su_IENC_MODE_NONE : su_IENC_MODE_SIGNED_TYPE));
if(cp != NIL)
vc.vc_varres = cp;
else{
f |= a_VEXPR_ERR;
vc.vc_varres = su_empty;
}
}
if(vc.vc_varname == NIL){
/* If there was no error and we are printing a numeric result, print some
* more bases for the fun of it */
if((f & (a_VEXPR_ERR | a_VEXPR_ISNUM | a_VEXPR_ISDECIMAL)
) == a_VEXPR_ISNUM){
char binabuf[64 + 64 / 8 +1];
for(j = 1, i = 0; i < 64; ++i){
binabuf[63 + 64 / 8 -j - i] =
(vc.vc_lhv & (S(u64,1) << i)) ? '1' : '0';
if((i & 7) == 7 && i != 63){
++j;
binabuf[63 + 64 / 8 -j - i] = ' ';
}
}
binabuf[64 + 64 / 8 -1] = '\0';
if(fprintf(n_stdout,
"0b %s\n0%" PRIo64 " | 0x%" PRIX64 " | %" PRId64 "\n",
binabuf, S(u64,vc.vc_lhv), S(u64,vc.vc_lhv), vc.vc_lhv
) < 0 ||
((f & a_VEXPR_PBASE) &&
fprintf(n_stdout, "%s\n", vc.vc_varres) < 0)){
n_pstate_err_no = su_err_no();
f |= a_VEXPR_ERR;
}
}else if(vc.vc_varres != NIL &&
fprintf(n_stdout, "%s\n", vc.vc_varres) < 0){
n_pstate_err_no = su_err_no();
f |= a_VEXPR_ERR;
}
}else if(!n_var_vset(vc.vc_varname, S(up,vc.vc_varres))){
n_pstate_err_no = su_ERR_NOTSUP;
f |= a_VEXPR_ERR;
}
jleave:
NYD_OU;
return (f & a_VEXPR_ERR) ? 1 : 0;
}
#include "su/code-ou.h"
#endif /* mx_HAVE_CMD_VEXPR */
/* s-it-mode */
|
catroll/mailx
|
src/su/avopt.c
|
/*@ Implementation of avopt.h.
*
* Copyright (c) 2001 - 2020 <NAME> <<EMAIL>>.
* SPDX-License-Identifier: ISC
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#undef su_FILE
#define su_FILE su_avopt
#define su_SOURCE
#define su_SOURCE_AVOPT
#include "su/code.h"
#include "su/cs.h"
#include "su/mem.h"
#include "su/avopt.h"
#include "su/code-in.h"
enum a_avopt_flags{
a_AVOPT_NONE,
a_AVOPT_DONE = 1u<<0,
a_AVOPT_STOP = 1u<<1,
a_AVOPT_SHORT = 1u<<2,
a_AVOPT_LONG = 1u<<3,
a_AVOPT_FOLLOWUP = 1u<<4,
a_AVOPT_CURR_LONG = 1u<<5,
a_AVOPT_ERR_OPT = 1u<<6,
a_AVOPT_ERR_ARG = 1u<<7,
a_AVOPT_ROUND_MASK = a_AVOPT_CURR_LONG | a_AVOPT_ERR_OPT | a_AVOPT_ERR_ARG
};
char const su_avopt_fmt_err_arg[] = N_("option requires argument: %s\n");
char const su_avopt_fmt_err_opt[] = N_("invalid option: %s\n");
struct su_avopt *
su_avopt_setup(struct su_avopt *self, u32 argc, char const * const *argv,
char const *opts_short_or_nil, char const * const *opts_long_or_nil){
NYD_IN;
ASSERT(self);
su_mem_set(self, 0, sizeof *self);
ASSERT_NYD_EXEC(argc == 0 || argv != NIL, self->avo_flags = a_AVOPT_DONE);
ASSERT_NYD_EXEC(opts_short_or_nil != NIL || opts_long_or_nil != NIL,
self->avo_flags = a_AVOPT_DONE);
self->avo_flags = (argc == 0 ? a_AVOPT_DONE : a_AVOPT_NONE) |
(opts_short_or_nil != NIL ? a_AVOPT_SHORT : a_AVOPT_NONE) |
(opts_long_or_nil != NIL ? a_AVOPT_LONG : a_AVOPT_NONE);
self->avo_argc = argc;
self->avo_argv = argv;
self->avo_opts_short = opts_short_or_nil;
self->avo_opts_long = opts_long_or_nil;
/* Somewhat test the content of the option strings in debug code */
#if DVLOR(1, 0)
/* C99 */{
uz i;
char const *cp;
if(self->avo_flags & a_AVOPT_SHORT){
if((cp = self->avo_opts_short)[0] == '\0'){
self->avo_flags &= ~a_AVOPT_SHORT;
su_log_write(su_LOG_CRIT, "su_avopt_setup(): empty short option "
"string is unsupported\n");
}else do{
if(!su_cs_is_print(*cp)){
self->avo_flags &= ~a_AVOPT_SHORT;
su_log_write(su_LOG_CRIT, "su_avopt_setup(): invalid non-"
"printable bytes in short option string: %s\n",
self->avo_opts_short);
}else if(*cp == '-'){
self->avo_flags &= ~a_AVOPT_SHORT;
su_log_write(su_LOG_CRIT, "su_avopt_setup(): invalid "
"hyphen-minus in short option string: %s\n",
self->avo_opts_short);
}
}while(*++cp != '\0');
}
if(self->avo_flags & a_AVOPT_LONG){
if(self->avo_opts_long[0] == NIL){
self->avo_flags &= ~a_AVOPT_LONG;
su_log_write(su_LOG_CRIT, "su_avopt_setup(): empty long option "
"array is unsupported\n");
}else for(i = 0; (cp = self->avo_opts_long[i]) != NIL; ++i){
if(cp[0] == '\0'){
self->avo_flags &= ~a_AVOPT_LONG;
su_log_write(su_LOG_CRIT, "su_avopt_setup(): empty long option "
"strings are unsupported\n");
}else do{
if(*cp == ';'){
/* Empty option, or no equivalence? */
if(cp == self->avo_opts_long[i] || cp[1] == '\0'){
jelong_semicolon:
self->avo_flags &= ~a_AVOPT_LONG;
su_log_write(su_LOG_CRIT, "su_avopt_setup(): invalid "
"semicolon usage in long option string: %s\n",
self->avo_opts_long[i]);
}
/* Could only indicate documentation string, too */
else if(cp[1] == ';'){
;
}
/* Otherwise we require an equivalence, optionally followed
* by documentation */
else if(cp[2] != '\0' && cp[2] != ';'){
goto jelong_semicolon;
}else if(cp[1] == su_AVOPT_STATE_DONE ||
cp[1] == su_AVOPT_STATE_LONG ||
cp[1] == su_AVOPT_STATE_ERR_OPT ||
cp[1] == su_AVOPT_STATE_ERR_ARG){
self->avo_flags &= ~a_AVOPT_LONG;
su_log_write(su_LOG_CRIT, "su_avopt_setup(): long option "
"equivalence byte shadows enum su_avopt_state: %s\n",
self->avo_opts_long[i]);
}else if(self->avo_flags & a_AVOPT_SHORT){
char const *osp;
char sopt;
boole wantsopt;
wantsopt = (cp[-1] == ':');
sopt = cp[1];
for(osp = self->avo_opts_short; *osp != '\0'; ++osp){
if(*osp != sopt){
if(osp[1] == ':')
++osp;
}else{
if((osp[1] == ':') != wantsopt){
self->avo_flags &= ~a_AVOPT_LONG;
su_log_write(su_LOG_CRIT, "su_avopt_setup(): "
"long option %s argument, short does%s: %s\n",
(wantsopt ? "wants" : "does not want"),
(wantsopt ? " not" : su_empty),
self->avo_opts_long[i]);
}
break;
}
}
}
break;
}else if(*cp == ':'){
if(cp == self->avo_opts_long[i])
goto jelong_colon;
if(cp[1] != '\0'){
if(cp[1] == ';')
continue;
jelong_colon:
self->avo_flags &= ~a_AVOPT_LONG;
su_log_write(su_LOG_CRIT, "su_avopt_setup(): invalid "
"colon in long option string: %s\n",
self->avo_opts_long[i]);
}
break;
}else if(*cp == '='){
self->avo_flags &= ~a_AVOPT_LONG;
su_log_write(su_LOG_CRIT, "su_avopt_setup(): invalid "
"equal-sign in long option string: %s\n",
self->avo_opts_long[i]);
}else if(!su_cs_is_print(*cp)){
self->avo_flags &= ~a_AVOPT_LONG;
su_log_write(su_LOG_CRIT, "su_avopt_setup(): invalid non-"
"printable bytes in long option string: %s\n",
self->avo_opts_long[i]);
}
}while(*++cp != '\0');
}
}
if(!(self->avo_flags & (a_AVOPT_SHORT | a_AVOPT_LONG)))
self->avo_flags |= a_AVOPT_DONE;
}
#endif /* DVLOR(1,0) */
NYD_OU;
return self;
}
s8
su_avopt_parse(struct su_avopt *self){
u8 flags;
char const *opt, *curr;
s8 rv;
NYD_IN;
ASSERT(self);
rv = su_AVOPT_STATE_DONE;
curr = self->avo_curr;
if((flags = self->avo_flags) & a_AVOPT_DONE)
goto jleave;
flags &= ~(a_AVOPT_ROUND_MASK);
/* If follow up is set this necessarily is a short option */
if(flags & a_AVOPT_FOLLOWUP){
ASSERT(flags & a_AVOPT_SHORT);
goto jshort;
}
/* We need an argv entry */
if(self->avo_argc == 0){
flags |= a_AVOPT_DONE;
goto jleave;
}
/* Finished if not - or a plain -, which is to be kept in argc/argv!
* Otherwise we consume this argc/argv entry */
curr = *self->avo_argv;
if(*curr != '-' || *++curr == '\0'){
flags |= a_AVOPT_DONE;
goto jleave;
}
--self->avo_argc;
++self->avo_argv;
/* -- stops argument processing unless long options are enabled and
* anything non-NUL follows */
if(UNLIKELY(*curr == '-')){
if(!(flags & a_AVOPT_LONG) || *++curr == '\0'){
flags |= a_AVOPT_DONE | a_AVOPT_STOP;
goto jleave;
}else{
/* This is a long option */
char const * const *opta, *xcurr;
flags |= a_AVOPT_CURR_LONG;
rv = su_AVOPT_STATE_LONG;
opta = self->avo_opts_long;
for(;;){
jlong_outer:
if((opt = *opta++) == NIL)
goto jerropt;
if(*opt != *(xcurr = curr))
continue;
while(*++opt != '\0')
if(*opt == ':' || *opt == ';')
break;
else if(*opt != *++xcurr)
goto jlong_outer;
if(*++xcurr == '\0' || (*xcurr == '=' && *opt == ':'))
break;
}
/* Have it: argument? */
if(*opt == ':'){
++opt;
if(*xcurr == '=')
++xcurr;
else{
if(self->avo_argc == 0)
goto jerrarg;
--self->avo_argc;
xcurr = *self->avo_argv++;
}
}else
xcurr = NIL;
self->avo_current_arg = xcurr;
self->avo_current_long_idx = P2UZ(opta - self->avo_opts_long) - 1;
/* Short option equivalence instead of su_AVOPT_STATE_LONG? */
if(*opt == ';' && *++opt != ';')
rv = *opt;
}
}else if(UNLIKELY((flags & a_AVOPT_SHORT) == 0))
goto jerropt;
else{
/* A short option */
jshort:
opt = self->avo_opts_short;
rv = S(s8,*curr++);
while(UCMP(8, *opt, !=, rv)){
/* Skip argument spec. */
if(opt[1] == ':')
++opt;
/* If we do not know about this, skip entire ARGV entry! */
if(UNLIKELY(*++opt == '\0'))
goto jerropt;
}
/* Does this take an argument? */
flags &= ~a_AVOPT_FOLLOWUP;
if(opt[1] != ':'){
if(*curr != '\0')
flags |= a_AVOPT_FOLLOWUP;
opt = NIL;
}else{
if(*curr == '\0'){
if(self->avo_argc == 0)
goto jerrarg;
--self->avo_argc;
curr = *self->avo_argv++;
}
opt = curr;
}
self->avo_current_arg = opt;
}
jleave:
self->avo_curr = curr;
self->avo_current_opt = rv;
self->avo_current_opt =
(rv != su_AVOPT_STATE_DONE || !(flags & a_AVOPT_STOP)) ? rv
: su_AVOPT_STATE_STOP;
self->avo_flags = flags;
NYD_OU;
return rv;
jerropt:
if(flags & a_AVOPT_CURR_LONG)
self->avo_current_err_opt = curr;
else{
self->avo_current_err_opt = self->avo__buf;
self->avo__buf[0] = S(char,rv);
self->avo__buf[1] = '\0';
}
flags &= ~a_AVOPT_FOLLOWUP;
flags |= a_AVOPT_ERR_OPT;
rv = su_AVOPT_STATE_ERR_OPT;
goto jleave;
jerrarg:
ASSERT(!(flags & a_AVOPT_FOLLOWUP));
if(flags & a_AVOPT_CURR_LONG)
self->avo_current_err_opt = curr;
else{
self->avo_current_err_opt = self->avo__buf;
self->avo__buf[0] = S(char,rv);
self->avo__buf[1] = '\0';
}
flags |= a_AVOPT_ERR_ARG;
rv = su_AVOPT_STATE_ERR_ARG;
goto jleave;
}
boole
su_avopt_dump_doc(struct su_avopt const *self,
boole (*ptf)(up cookie, boole has_arg, char const *sopt,
char const *lopt, char const *doc), up cookie){
char s_so[8], s_lo[128];
char const * const *opta, *opt, *cp;
uz l;
boole rv;
NYD_IN;
ASSERT(self);
ASSERT_NYD_EXEC(ptf != NIL, rv = TRU1);
rv = TRU1;
if(self->avo_flags & a_AVOPT_LONG){
s_so[2] = '\0';
s_lo[0] = s_lo[1] = '-';
for(opta = self->avo_opts_long; (opt = *opta++) != NIL;){
cp = opt;
while(*++opt != '\0')
if(*opt == ':' || *opt == ';')
break;
l = P2UZ(opt - cp);
if(l > sizeof(s_lo) - 2 -1)
l = sizeof(s_lo) - 2 -1;
su_mem_copy(&s_lo[2], cp, l);
s_lo[l += 2] = '\0';
/* Have it: argument? */
if((rv = (*opt == ':')))
++opt;
/* (Actual) Short option equivalence? */
s_so[0] = '\0';
if(*opt == ';' && *++opt != ';'){
if(su_cs_is_print(*opt)){
s_so[0] = '-';
s_so[1] = *opt;
}
++opt;
}
/* Documentation? */
if(*opt == ';')
++opt;
else
opt = su_empty;
rv = (*ptf)(cookie, rv, s_so, s_lo, opt);
}
}
NYD_OU;
return rv;
}
#include "su/code-ou.h"
/* s-it-mode */
|
catroll/mailx
|
src/mx/main.c
|
/*@ S-nail - a mail user agent derived from Berkeley Mail.
*@ Startup and initialization.
*@ This file is also used to materialize externals.
*@ TODO we need a program wide global ctx; furtherly split main();
*@ TODO when arguments are parsed the a_main_ctx instance should be dropped
*
* Copyright (c) 2012 - 2020 <NAME>) Nurpmeso <<EMAIL>>.
* SPDX-License-Identifier: ISC
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#undef su_FILE
#define su_FILE main
#define mx_SOURCE
#define mx_SOURCE_MASTER
#include "mx/nail.h"
#include <pwd.h>
#include <su/avopt.h>
#include <su/cs.h>
#include <su/mem.h>
#include "mx/attachments.h"
#include "mx/file-streams.h"
#include "mx/iconv.h"
#include "mx/mime-type.h"
#include "mx/names.h"
#include "mx/sigs.h"
#include "mx/termcap.h"
#include "mx/termios.h"
#include "mx/tty.h"
#include "mx/ui-str.h"
/* TODO fake */
#include "su/code-in.h"
struct a_main_ctx{
uz mc_smopts_size; /* To manage n_smopts_cnt and n_smopts */
char const *mc_A;
struct a_main_aarg *mc_a_head;
struct a_main_aarg *mc_a_curr;
struct mx_attachment *mc_attach;
struct mx_name *mc_bcc;
struct mx_name *mc_cc;
char const *mc_folder;
char const *mc_L;
char const *mc_quote;
char const *mc_subject;
struct mx_name *mc_to;
char const *mc_u;
char const **mc_X;
uz mc_X_size;
uz mc_X_cnt;
char const **mc_Y;
uz mc_Y_size;
uz mc_Y_cnt;
};
struct a_main_aarg{
struct a_main_aarg *maa_next;
char const *maa_file;
};
/* (extern, but not with amalgamation, so define here) */
VL char const n_weekday_names[7 + 1][4] = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", ""
};
VL char const n_month_names[12 + 1][4] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ""
};
VL char const n_uagent[sizeof VAL_UAGENT] = VAL_UAGENT;
#ifdef mx_HAVE_UISTRINGS
VL char const n_error[sizeof n_ERROR] = N_(n_ERROR);
#endif
VL char const n_path_devnull[sizeof n_PATH_DEVNULL] = n_PATH_DEVNULL;
VL char const n_0[2] = "0";
VL char const n_1[2] = "1";
VL char const n_m1[3] = "-1";
VL char const n_em[2] = "!";
VL char const n_ns[2] = "#";
VL char const n_star[2] = "*";
VL char const n_hy[2] = "-";
VL char const n_qm[2] = "?";
VL char const n_at[2] = "@";
/* Perform basic startup initialization */
static void a_main_startup(void);
/* Grow a char** */
static uz a_main_grow_cpp(char const ***cpp, uz newsize, uz oldcnt);
/* Setup some variables which we require to be valid / verified */
static void a_main_setup_vars(void);
/* Ok, we are reading mail. Decide whether we are editing a mailbox or reading
* the system mailbox, and open up the right stuff */
static int a_main_rcv_mode(struct a_main_ctx *mcp);
/* Interrupt printing of the headers */
static void a_main_hdrstop(int signo);
/* SIGUSR1, then */
#if DVLOR(1, 0) && defined mx_HAVE_DEVEL && defined su_MEM_ALLOC_DEBUG
static void a_main_memtrace(int signo);
#endif
/* The _opt_ series returns an error message or NIL */
static char const *a_main_o_r(struct a_main_ctx *mcp, struct su_avopt *avop);
static char const *a_main_o_S(struct a_main_ctx *mcp, struct su_avopt *avop);
static void a_main_o_s(struct a_main_ctx *mcp, struct su_avopt *avop);
/* */
static void a_main_usage(FILE *fp);
static boole a_main_dump_doc(up cookie, boole has_arg, char const *sopt,
char const *lopt, char const *doc);
static void
a_main_startup(void){
struct passwd *pwuid;
char *cp;
NYD2_IN;
n_stdin = stdin;
n_stdout = stdout;
n_stderr = stderr;
if((cp = su_cs_rfind_c(su_program, '/')) != NIL)
su_program = ++cp;
/* XXX Due to n_err() mess the su_log config only applies to EMERG yet! */
su_state_set(su_STATE_LOG_SHOW_LEVEL | su_STATE_LOG_SHOW_PID
/* XXX | su_STATE_ERR_NOMEM | su_STATE_ERR_OVERFLOW */
);
su_log_set_level(n_LOG_LEVEL); /* XXX _EMERG is 0.. */
/* Change to reproducible mode asap */
if(ok_vlook(SOURCE_DATE_EPOCH) != NIL)
su_state_set(su_STATE_REPRODUCIBLE);
/* TODO This is wrong: interactive is STDIN/STDERR for a POSIX sh(1).
* TODO For now we get this wrong, all over the place, as this software
* TODO has always been developed with stdout as an output channel.
* TODO Start doing it right for at least explicit terminal-related things,
* TODO but v15 should use ONLY this, also for terminal input! */
if(isatty(STDIN_FILENO)){
n_psonce |= n_PSO_TTYIN;
/* We need a writable terminal descriptor then, anyway */
if((mx_tty_fp = fdopen(fileno(n_stdin), "w+")) != NIL)
setvbuf(mx_tty_fp, NIL, _IOLBF, 0);
}
if(isatty(STDOUT_FILENO))
n_psonce |= n_PSO_TTYOUT;
/* STDOUT is always line buffered from our point of view */
setvbuf(n_stdout, NIL, _IOLBF, 0);
if(mx_tty_fp == NIL)
mx_tty_fp = n_stdout;
/* Assume we are interactive, then.
* This state will become unset later for n_PO_QUICKRUN_MASK! */
if((n_psonce & n_PSO_TTYANY) == n_PSO_TTYANY)
n_psonce |= n_PSO_INTERACTIVE;
if(isatty(STDERR_FILENO))
n_psonce |= n_PSO_TTYERR;
/* Now that the basic I/O is accessible, initialize our main machinery,
* input, loop, child, termios, whatever */
n_go_init();
if(n_psonce & n_PSO_INTERACTIVE)
safe_signal(SIGPIPE, SIG_IGN);
#if DVLOR(1, 0)
# if defined mx_HAVE_DEVEL && defined su_MEM_ALLOC_DEBUG
safe_signal(SIGUSR1, &a_main_memtrace);
# endif
safe_signal(SIGUSR2, &mx__nyd_oncrash);
safe_signal(SIGABRT, &mx__nyd_oncrash);
# ifdef SIGBUS
safe_signal(SIGBUS, &mx__nyd_oncrash);
# endif
safe_signal(SIGFPE, &mx__nyd_oncrash);
safe_signal(SIGILL, &mx__nyd_oncrash);
safe_signal(SIGSEGV, &mx__nyd_oncrash);
#endif
/* -- >8 -- 8< -- */
n_locale_init();
#ifdef mx_HAVE_ICONV
iconvd = R(iconv_t,-1);
#endif
/*
* Ensure some variables get loaded and/or verified, I. (pre-getopt)
*/
/* Detect, verify and fixate our invoking user (environment) */
n_group_id = getgid();
if((pwuid = getpwuid(n_user_id = getuid())) == NIL)
n_panic(_("Cannot associate a name with uid %lu"), S(ul,n_user_id));
else{
char const *ep;
boole doenv;
/* Reset inherited diverging effective IDs, do not pass them along! */
if(n_user_id != 0 &&
(n_user_id != geteuid() || n_group_id != getegid())){
n_err(_("Warning: dropping diverging effective IDs (euid/egid)\n"));
setuid(n_user_id);
setgid(n_group_id);
}
/* */
if(!(doenv = (ep = ok_vlook(LOGNAME)) == NIL) &&
(doenv = (su_cs_cmp(pwuid->pw_name, ep) != 0)))
n_err(_("Warning: $LOGNAME (%s) not identical to user (%s)!\n"),
ep, pwuid->pw_name);
if(doenv){
n_pstate |= n_PS_ROOT;
ok_vset(LOGNAME, pwuid->pw_name);
n_pstate &= ~n_PS_ROOT;
}
/* BSD compat */
if((ep = ok_vlook(USER)) != NIL && su_cs_cmp(pwuid->pw_name, ep)){
n_err(_("Warning: $USER (%s) not identical to user (%s)!\n"),
ep, pwuid->pw_name);
n_pstate |= n_PS_ROOT;
ok_vset(USER, pwuid->pw_name);
n_pstate &= ~n_PS_ROOT;
}
/* XXX myfullname = pw->pw_gecos[OPTIONAL!] -> GUT THAT; TODO pw_shell */
}
/* This is not automated just as $TMPDIR is for the initial setting, since
* we have the pwuid at hand and can simply use it! See accmacvar.c! */
if(n_user_id == 0 || (cp = ok_vlook(HOME)) == NIL){
cp = pwuid->pw_dir;
n_pstate |= n_PS_ROOT;
ok_vset(HOME, cp);
n_pstate &= ~n_PS_ROOT;
}
/* XXX Perform lookup of environmental VIP variables which have a mapping
* XXX This should be local to the variable handling stuff or so! */
(void)ok_blook(POSIXLY_CORRECT);
#ifdef mx_HAVE_NET
(void)ok_vlook(SOCKS5_PROXY);
#endif
NYD2_OU;
}
static uz
a_main_grow_cpp(char const ***cpp, uz newsize, uz oldcnt){
/* Just use auto-reclaimed storage, it will be preserved */
char const **newcpp;
NYD2_IN;
newcpp = n_autorec_alloc(sizeof(char*) * (newsize + 1));
if(oldcnt > 0)
su_mem_copy(newcpp, *cpp, oldcnt * sizeof(char*));
*cpp = newcpp;
NYD2_OU;
return newsize;
}
static void
a_main_setup_vars(void){
NYD2_IN;
/*
* Ensure some variables get loaded and/or verified, II. (post getopt).
*/
/* Do not honour TMPDIR if root */
if(n_user_id == 0)
ok_vset(TMPDIR, NIL);
else
(void)ok_vlook(TMPDIR);
/* Are we in a reproducible-builds.org environment?
* That special mode bends some settings (again) */
if(su_state_has(su_STATE_REPRODUCIBLE)){
su_program = su_reproducible_build;
n_pstate |= n_PS_ROOT;
ok_vset(LOGNAME, su_reproducible_build);
/* Do not care about USER at all in this special mode! */
n_pstate &= ~n_PS_ROOT;
ok_vset(log_prefix, savecat(su_reproducible_build, ": "));
}
/* Finally set our terminal dimension */
mx_termios_controller_setup(mx_TERMIOS_SETUP_TERMSIZE);
NYD2_OU;
}
static sigjmp_buf a_main__hdrjmp; /* XXX */
static int
a_main_rcv_mode(struct a_main_ctx *mcp){
n_sighdl_t prevint;
int i;
NYD_IN;
i = (mcp->mc_A != NIL) ? FEDIT_ACCOUNT : FEDIT_NONE;
if(n_poption & n_PO_QUICKRUN_MASK)
i |= FEDIT_RDONLY;
if(mcp->mc_folder == NIL){
mcp->mc_folder = "%";
if(i & FEDIT_ACCOUNT)
i |= FEDIT_SYSBOX;
}
#ifdef mx_HAVE_IMAP
else if(*mcp->mc_folder == '@'){
/* This must be treated specially to make possible invocation like
* -A imap -f @mailbox */
char const *cp;
cp = n_folder_query();
if(which_protocol(cp, FAL0, FAL0, NIL) == PROTO_IMAP)
su_cs_pcopy_n(mailname, cp, sizeof mailname);
}
#endif
i = setfile(mcp->mc_folder, i);
if(i < 0){
n_exit_status = n_EXIT_ERR; /* error already reported */
goto jquit;
}
temporary_folder_hook_check(FAL0);
if(n_poption & n_PO_QUICKRUN_MASK){
n_exit_status = i;
if(i == n_EXIT_OK && (!(n_poption & n_PO_EXISTONLY) ||
(n_poption & n_PO_HEADERLIST)))
print_header_summary(mcp->mc_L);
goto jquit;
}
if(i > 0 && !ok_blook(emptystart)){
n_exit_status = n_EXIT_ERR;
goto jleave;
}
if(sigsetjmp(a_main__hdrjmp, 1) == 0){
if((prevint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
safe_signal(SIGINT, &a_main_hdrstop);
if(!ok_blook(quiet))
fprintf(n_stdout, _("%s version %s. Type `?' for help\n"),
n_uagent,
(su_state_has(su_STATE_REPRODUCIBLE)
? su_reproducible_build : ok_vlook(version)));
n_folder_announce(n_ANNOUNCE_MAIN_CALL | n_ANNOUNCE_CHANGE);
safe_signal(SIGINT, prevint);
}
/* Enter the command loop */
/* "load()" more commands given on command line */
if(mcp->mc_Y_cnt > 0 && !n_go_load_lines(TRU1, mcp->mc_Y, mcp->mc_Y_cnt))
n_exit_status = n_EXIT_ERR;
else
n_go_main_loop();
if(!(n_psonce & n_PSO_XIT)){
if(mb.mb_type == MB_FILE || mb.mb_type == MB_MAILDIR){
safe_signal(SIGHUP, SIG_IGN);
safe_signal(SIGINT, SIG_IGN);
safe_signal(SIGQUIT, SIG_IGN);
}
jquit:
save_mbox_for_possible_quitstuff();
quit(FAL0);
}
jleave:
NYD_OU;
return n_exit_status;
}
static void
a_main_hdrstop(int signo){
NYD; /* Signal handler */
UNUSED(signo);
fflush(n_stdout);
n_err_sighdl(_("\nInterrupt\n"));
siglongjmp(a_main__hdrjmp, 1);
}
#if DVLOR(1, 0) && defined mx_HAVE_DEVEL && defined su_MEM_ALLOC_DEBUG
static void
a_main_memtrace(int signo){
enum su_log_level lvl;
UNUSED(signo);
lvl = su_log_get_level();
su_log_set_level(su_LOG_INFO);
su_mem_trace();
su_log_set_level(lvl);
}
#endif
static char const *
a_main_o_r(struct a_main_ctx *mcp, struct su_avopt *avop){
struct mx_name *fap;
char const *rv;
NYD2_IN;
n_poption |= n_PO_r_FLAG;
rv = NIL;
if(avop->avo_current_arg[0] == '\0')
goto jleave;
fap = nalloc(avop->avo_current_arg, GSKIN | GFULL | GFULLEXTRA |
GNOT_A_LIST | GNULL_OK | GSHEXP_PARSE_HACK);
if(fap == NIL || is_addr_invalid(fap, EACM_STRICT | EACM_NOLOG)){
rv = N_("Invalid address argument with -r");
goto jleave;
}
n_poption_arg_r = fap;
/* TODO -r options is set in n_smopts, but may
* TODO be overwritten by setting from= in
* TODO an interactive session!
* TODO Maybe disable setting of from?
* TODO Warn user? Update manual!! */
avop->avo_current_arg = savecat("from=", fap->n_fullname);
rv = a_main_o_S(mcp, avop);
jleave:
NYD2_OU;
return rv;
}
static char const *
a_main_o_S(struct a_main_ctx *mcp, struct su_avopt *avop){
struct str sin;
struct n_string s_b, *s;
boole b;
char const *rv, *a[2];
NYD2_IN;
UNUSED(mcp);
rv = NIL;
/* May be called from _opt_r(), for example */
if(avop->avo_current_opt != 'S' || ok_vlook(v15_compat) == NIL){
a[0] = avop->avo_current_arg;
s = NIL;
}else{
BITENUM_IS(u32,n_shexp_state) shs;
n_autorec_relax_create();
s = n_string_creat_auto(&s_b);
sin.s = UNCONST(char*,avop->avo_current_arg);
sin.l = UZ_MAX;
shs = n_shexp_parse_token((n_SHEXP_PARSE_LOG |
n_SHEXP_PARSE_IGNORE_EMPTY |
n_SHEXP_PARSE_QUOTE_AUTO_FIXED |
n_SHEXP_PARSE_QUOTE_AUTO_DSQ), s, &sin, NIL);
if((shs & n_SHEXP_STATE_ERR_MASK) ||
!(shs & n_SHEXP_STATE_STOP)){
n_autorec_relax_gut();
goto je_S;
}
a[0] = n_string_cp_const(s);
}
a[1] = NIL;
n_poption |= n_PO_S_FLAG_TEMPORARY;
n_pstate |= n_PS_ROBOT;
b = (c_set(a) == n_EXIT_OK);
n_pstate &= ~n_PS_ROBOT;
n_poption &= ~n_PO_S_FLAG_TEMPORARY;
if(s != NIL)
n_autorec_relax_gut();
if(!b && (ok_blook(errexit) || ok_blook(posix))){
je_S:
rv = N_("-S failed to set variable");
}
NYD2_OU;
return rv;
}
static void
a_main_o_s(struct a_main_ctx *mcp, struct su_avopt *avop){
/* Take care for Debian #419840 and strip any \r and \n */
uz i;
char *cp;
NYD2_IN;
n_psonce |= n_PSO_SENDMODE;
mcp->mc_subject = cp = UNCONST(char*,avop->avo_current_arg);
if((i = su_cs_first_of(cp, "\n\r")) != UZ_MAX){
n_err(_("-s: normalizing away invalid ASCII NL / CR bytes\n"));
mcp->mc_subject = cp = savestr(cp);
for(cp = &cp[i]; *cp != '\0'; ++cp)
if(*cp == '\n' || *cp == '\r')
*cp = ' ';
}
NYD2_OU;
}
static char const *
a_main_o_T(struct a_main_ctx *mcp, struct su_avopt *avop){
struct str suffix;
struct mx_name **npp, *np;
BITENUM_IS(u32,gfield) gf;
char const *rv, *a;
NYD2_IN;
n_psonce |= n_PSO_SENDMODE;
rv = NIL;
if((a = n_header_get_field(avop->avo_current_arg, "to", &suffix)) != NIL){
gf = GTO | GSHEXP_PARSE_HACK | GFULL | GNULL_OK;
npp = &mcp->mc_to;
}else if((a = n_header_get_field(avop->avo_current_arg, "cc", &suffix)
) != NIL){
gf = GCC | GSHEXP_PARSE_HACK | GFULL | GNULL_OK;
npp = &mcp->mc_cc;
}else if((a = n_header_get_field(avop->avo_current_arg, "bcc", &suffix)
) != NIL){
gf = GBCC | GSHEXP_PARSE_HACK | GFULL | GNULL_OK;
npp = &mcp->mc_bcc;
}else if((a = n_header_get_field(avop->avo_current_arg, "fcc", su_NIL)
) != NIL){
gf = GBCC_IS_FCC;
npp = &mcp->mc_bcc;
}else{
ASSERT(suffix.s == NIL);
jeTuse:
rv = N_("-T: only supports to,cc,bcc (with ?single modifier) and fcc");
goto jleave;
}
if(suffix.s != NIL){
if(suffix.l > 0 &&
!su_cs_starts_with_case_n("single", suffix.s, suffix.l))
goto jeTuse;
gf |= GNOT_A_LIST;
}
if(!(gf & GBCC_IS_FCC))
np = lextract(a, gf);
else
np = nalloc_fcc(a);
if(np == NIL){
rv = N_("-T: invalid receiver (address)");
goto jleave;
}
*npp = cat(*npp, np);
jleave:
NYD2_OU;
return rv;
}
static void
a_main_usage(FILE *fp){
/* Stay in VAL_HEIGHT lines; On buf length change: verify visual output! */
char buf[7];
uz i;
NYD2_IN;
i = su_cs_len(su_program);
i = MIN(i, sizeof(buf) -1);
if(i > 0)
su_mem_set(buf, ' ', i);
buf[i] = '\0';
fprintf(fp, _("%s (%s %s): send and receive Internet mail\n"),
su_program, n_uagent, ok_vlook(version));
if(fp != n_stderr)
putc('\n', fp);
fprintf(fp, _(
"Send-only mode: send mail \"to-addr\"(ess) receiver(s):\n"
" %s [-DdEFinv~#] [-: spec] [-A account] [:-C \"field: body\":]\n"
" %s [:-a attachment:] [:-b bcc-addr:] [:-c cc-addr:]\n"
" %s [-M type | -m file | -q file | -t] [-r from-addr] "
"[:-S var[=value]:]\n"
" %s [-s subject] [-T \"arget: addr\"] [:-X/Y cmd:] [-.] :to-addr:\n"),
su_program, buf, buf, buf);
if(fp != n_stderr)
putc('\n', fp);
fprintf(fp, _(
"\"Receive\" mode, starting on [-u user], primary *inbox* or [$MAIL]:\n"
" %s [-DdEeHiNnRv~#] [-: spec] [-A account] [:-C \"field: body\":]\n"
" %s [-L spec] [-r from-addr] [:-S var[=value]:] [-u user] "
"[:-X/Y cmd:]\n"),
su_program, buf);
if(fp != n_stderr)
putc('\n', fp);
fprintf(fp, _(
"\"Receive\" mode, starting on -f (secondary $MBOX or [file]):\n"
" %s [-DdEeHiNnRv~#] [-: spec] [-A account] [:-C \"field: body\":] -f\n"
" %s [-L spec] [-r from-addr] [:-S var[=value]:] [:-X/Y cmd:] "
"[file]\n"),
su_program, buf);
if(fp != n_stderr)
putc('\n', fp);
/* (ISO C89 string length) */
fprintf(fp, _(
". -d sandbox, -:/ no .rc files, -. end options and force send-mode\n"
". -a attachment[=input-charset[#output-charset]]\n"
". -b, -c, -r, -T, to-addr: <EMAIL> or '(Lovely) Ex <<EMAIL>>'\n"
". -M, -m, -q, -t: special input (-t: template message on stdin)\n"
". -e only mail check, -H header summary; "
"both: message specification via -L\n"
". -S (un)sets variable, -X/-Y execute commands pre/post startup, "
"-#: batch mode\n"));
fprintf(fp, _(
". Features via \"$ %s -Xversion -Xx\"; there is --long-help\n"
". Bugs/Contact via "
"\"$ %s -Sexpandaddr=shquote '\\$contact-mail'\"\n"),
su_program, su_program);
NYD2_OU;
}
static boole
a_main_dump_doc(up cookie, boole has_arg, char const *sopt, char const *lopt,
char const *doc){
char const *x1, *x2;
NYD2_IN;
UNUSED(doc);
if(has_arg)
/* I18N: describing arguments to command line options */
x1 = (sopt[0] != '\0' ? _(" ARG, ") : sopt), x2 = _("=ARG");
else
/* I18N: separating command line options */
x1 = (sopt[0] != '\0' ? _(", ") : sopt), x2 = su_empty;
/* I18N: short option, "[ ARG], " separator, long option [=ARG], doc */
fprintf(S(FILE*,cookie), _("%s%s%s%s: %s\n"), sopt, x1, lopt, x2, V_(doc));
NYD2_OU;
return TRU1;
}
int
main(int argc, char *argv[]){
/* TODO Once v15 control flow/carrier rewrite took place main() should
* TODO be rewritten and option parsing++ should be outsourced.
* TODO Like so we can get rid of some stack locals etc.
* TODO Furthermore: the locals should be in a carrier, and once there
* TODO is the memory pool+page cache, that should go in LOFI memory,
* TODO and there should be two pools: one which is fixated() and remains,
* TODO and one with throw away data (-X, -Y args, temporary allocs, e.g.,
* TODO redo -S like so, etc.) */
enum a_rf_ids{
a_RF_NONE,
a_RF_SET = 1u<<0,
a_RF_SYSTEM = 1u<<1,
a_RF_USER = 1u<<2,
a_RF_BLTIN = 1u<<3,
a_RF_DEFAULT = a_RF_SYSTEM | a_RF_USER,
a_RF_MASK = a_RF_SYSTEM | a_RF_USER | a_RF_BLTIN
};
/* Keep in SYNC: ./nail.1:"SYNOPSIS, main() */
static char const a_sopts[] =
"::A:a:Bb:C:c:DdEeFfHhiL:M:m:NnO:q:Rr:S:s:T:tu:VvX:Y:~#.";
static char const * const a_lopts[] = {
"resource-files:;:;" N_("control loading of resource files"),
"account:;A;" N_("execute an `account' command"),
"attach:;a;" N_("attach a file to message to be sent"),
"bcc:;b;" N_("add blind carbon copy recipient"),
"custom-header:;C;" N_("create custom header (\"header-field: body\")"),
"cc:;c;" N_("add carbon copy recipient"),
"disconnected;D;" N_("identical to -Sdisconnected"),
"debug;d;" N_("identical to -Sdebug"),
"discard-empty-messages;E;" N_("identical to -Sskipemptybody"),
"check-and-exit;e;" N_("note mail presence (of -L) via exit status"),
"file;f;" N_("open secondary mailbox, or \"file\" last on command line"),
"header-summary;H;" N_("is to be displayed (for given file) only"),
"help;h;" N_("short help"),
"search:;L;" N_("like -H (or -e) for the given \"spec\" only"),
"no-header-summary;N;" N_("identical to -Snoheader"),
"quote-file:;q;" N_("initialize body of message to be sent with a file"),
"read-only;R;" N_("any mailbox file will be opened read-only"),
"from-address:;r;" N_("set source address used by MTAs (and -Sfrom)"),
"set:;S;" N_("set one of the INTERNAL VARIABLES (unset via \"noARG\")"),
"subject:;s;" N_("specify subject of message to be sent"),
"target:;T;" N_("add receiver(s) \"header-field: address\" as via -t"),
"template;t;" N_("message to be sent is read from standard input"),
"inbox-of:;u;" N_("initially open primary mailbox of the given user"),
"version;V;" N_("print version (more so with \"[-v] -Xversion -Xx\")"),
"verbose;v;" N_("equals -Sverbose (multiply for more verbosity)"),
"startup-cmd:;X;" N_("to be executed before normal operation"),
"cmd:;Y;" N_("to be executed under normal operation (is \"input\")"),
"enable-cmd-escapes;~;" N_("even in non-interactive compose mode"),
"batch-mode;#;" N_("more confined non-interactive setup"),
"end-options;.;" N_("force the end of options, and (enter) send mode"),
"long-help;\201;" N_("this listing"),
NIL
};
struct a_main_ctx mc;
struct su_avopt avo;
int i;
char const *emsg;
char *cp;
BITENUM_IS(u32,a_rf_ids) resfiles;
NYD_IN;
su_mem_set(&mc, 0, sizeof mc);
resfiles = a_RF_DEFAULT;
UNINIT(emsg, NIL);
/*
* Start our lengthy setup, finalize by setting n_PSO_STARTED
*/
su_program = argv[0];
a_main_startup();
/* Command line parsing.
* XXX We could parse silently to grasp the actual mode (send, receive
* XXX with/out -f, then use an according option array. This would ease
* XXX the interdependency checking necessities! */
su_avopt_setup(&avo, --argc, C(char const*const*,++argv), a_sopts, a_lopts);
while((i = su_avopt_parse(&avo)) != su_AVOPT_STATE_DONE){
switch(i){
case 'A':
/* Execute an account command later on */
mc.mc_A = avo.avo_current_arg;
break;
case 'a':{
/* Add an attachment */
struct a_main_aarg *nap;
n_psonce |= n_PSO_SENDMODE;
nap = n_autorec_alloc(sizeof(struct a_main_aarg));
if(mc.mc_a_head == NIL)
mc.mc_a_head = nap;
else
mc.mc_a_curr->maa_next = nap;
nap->maa_next = NIL;
nap->maa_file = avo.avo_current_arg;
mc.mc_a_curr = nap;
}break;
case 'B':
n_OBSOLETE(_("-B is obsolete, please use -# as necessary"));
break;
case 'b':
/* Add (a) blind carbon copy recipient (list) */
n_psonce |= n_PSO_SENDMODE;
mc.mc_bcc = cat(mc.mc_bcc, lextract(avo.avo_current_arg,
GBCC | GFULL | GNOT_A_LIST | GSHEXP_PARSE_HACK));
break;
case 'C':{
/* Create custom header (at list tail) */
struct n_header_field **hflpp;
if(*(hflpp = &n_poption_arg_C) != NIL){
while((*hflpp)->hf_next != NIL)
hflpp = &(*hflpp)->hf_next;
hflpp = &(*hflpp)->hf_next;
}
if(!n_header_add_custom(hflpp, avo.avo_current_arg, FAL0)){
emsg = N_("Invalid custom header data with -C");
goto jusage;
}
}break;
case 'c':
/* Add (a) carbon copy recipient (list) */
n_psonce |= n_PSO_SENDMODE;
mc.mc_cc = cat(mc.mc_cc, lextract(avo.avo_current_arg,
GCC | GFULL | GNOT_A_LIST | GSHEXP_PARSE_HACK));
break;
case 'D':
#ifdef mx_HAVE_IMAP
ok_bset(disconnected);
#endif
break;
case 'd':
ok_bset(debug);
break;
case 'E':
ok_bset(skipemptybody);
break;
case 'e':
/* Check if mail (matching -L) exists in given box, exit status */
n_poption |= n_PO_EXISTONLY;
n_psonce &= ~n_PSO_INTERACTIVE;
break;
case 'F':
/* Save msg in file named after local part of first recipient */
n_poption |= n_PO_F_FLAG;
n_psonce |= n_PSO_SENDMODE;
break;
case 'f':
/* User is specifying file to "edit" with Mail, as opposed to reading
* system mailbox. If no argument is given, we read his mbox file.
* Check for remaining arguments later */
n_poption |= n_PO_f_FLAG;
mc.mc_folder = "&";
break;
case 'H':
/* Display summary of headers, exit */
n_poption |= n_PO_HEADERSONLY;
n_psonce &= ~n_PSO_INTERACTIVE;
break;
case 'h':
case S(char,S(u8,'\201')):
a_main_usage(n_stdout);
if(i != 'h'){
fprintf(n_stdout, "\nLong options:\n");
(void)su_avopt_dump_doc(&avo, &a_main_dump_doc, S(up,n_stdout));
}
goto jleave;
case 'i':
/* Ignore interrupts */
ok_bset(ignore);
break;
case 'L':
/* Display summary of headers which match given spec, exit.
* In conjunction with -e, only test the given spec for existence */
n_poption |= n_PO_HEADERLIST;
n_psonce &= ~n_PSO_INTERACTIVE;
mc.mc_L = avo.avo_current_arg;
/* TODO list.c:listspec_check() */
if(*mc.mc_L == '"' || *mc.mc_L == '\''){
uz j;
j = su_cs_len(++mc.mc_L);
if(j > 0){
cp = savestrbuf(mc.mc_L, --j);
mc.mc_L = cp;
}
}
break;
case 'M':
/* Flag message body (standard input) with given MIME type */
if(mc.mc_quote != NIL && (!(n_poption & n_PO_Mm_FLAG) ||
mc.mc_quote != R(char*,-1)))
goto jeMmq;
n_poption_arg_Mm = avo.avo_current_arg;
mc.mc_quote = R(char*,-1);
if(0){
/* FALLTHRU*/
case 'm':
/* Flag the given file with MIME type and use as message body */
if(mc.mc_quote != NIL && (!(n_poption & n_PO_Mm_FLAG) ||
mc.mc_quote == R(char*,-1)))
goto jeMmq;
mc.mc_quote = avo.avo_current_arg;
}
n_poption |= n_PO_Mm_FLAG;
n_psonce |= n_PSO_SENDMODE;
break;
case 'N':
/* Avoid initial header printing */
ok_bclear(header);
break;
case 'n':
/* Don't source "unspecified system start-up file" */
if(resfiles & a_RF_SET){
emsg = N_("-n cannot be used in conjunction with -:");
goto jusage;
}
resfiles = a_RF_USER;
break;
case 'O':
/* Additional options to pass-through to MTA TODO v15-compat legacy */
if(n_smopts_cnt == mc.mc_smopts_size)
mc.mc_smopts_size = a_main_grow_cpp(&n_smopts,
mc.mc_smopts_size + 8, n_smopts_cnt);
n_smopts[n_smopts_cnt++] = avo.avo_current_arg;
break;
case 'q':
/* "Quote" file: use as message body (-t without headers etc.) */
/* XXX Traditional. Add -Q to initialize as *quote*d content? */
if(mc.mc_quote != NIL && (n_poption & n_PO_Mm_FLAG)){
jeMmq:
emsg = N_("Only one of -M, -m or -q may be given");
goto jusage;
}
n_psonce |= n_PSO_SENDMODE;
/* Allow, we have to special check validity of -q- later on! */
mc.mc_quote = ((avo.avo_current_arg[0] == '-' &&
avo.avo_current_arg[1] == '\0') ? R(char*,-1)
: avo.avo_current_arg);
break;
case 'R':
/* Open folders read-only */
n_poption |= n_PO_R_FLAG;
break;
case 'r':
/* Set From address. */
if((emsg = a_main_o_r(&mc, &avo)) != NIL)
goto jusage;
break;
case 'S':
/* Set variable */
if((emsg = a_main_o_S(&mc, &avo)) != NIL)
goto jusage;
break;
case 's':
/* Subject: */
a_main_o_s(&mc, &avo);
break;
case 'T':
/* Target mode: `digmsg header insert' from command line */
if((emsg = a_main_o_T(&mc, &avo)) != NIL)
goto jusage;
break;
case 't':
/* Use the given message as send template */
n_poption |= n_PO_t_FLAG;
n_psonce |= n_PSO_SENDMODE;
break;
case 'u':
/* Open primary mailbox of the given user */
mc.mc_u = savecat("%", avo.avo_current_arg);
break;
case 'V':{
struct n_string s;
fputs(n_string_cp_const(n_version(
n_string_book(n_string_creat_auto(&s), 120))), n_stdout);
n_exit_status = n_EXIT_OK;
}goto jleave;
case 'v':
/* Be verbose */
ok_vset(verbose, su_empty);
break;
case 'X':
/* Add to list of commands to exec before entering normal operation */
if(mc.mc_X_cnt == mc.mc_X_size)
mc.mc_X_size = a_main_grow_cpp(&mc.mc_X, mc.mc_X_size + 8,
mc.mc_X_cnt);
mc.mc_X[mc.mc_X_cnt++] = avo.avo_current_arg;
break;
case 'Y':
/* Add to list of commands to exec after entering normal operation */
if(mc.mc_Y_cnt == mc.mc_Y_size)
mc.mc_Y_size = a_main_grow_cpp(&mc.mc_Y, mc.mc_Y_size + 8,
mc.mc_Y_cnt);
mc.mc_Y[mc.mc_Y_cnt++] = avo.avo_current_arg;
break;
case ':':
/* Control which resource files shall be loaded */
if(!(resfiles & (a_RF_SET | a_RF_SYSTEM))){
emsg = N_("-n cannot be used in conjunction with -:");
goto jusage;
}
resfiles = a_RF_SET;
while((i = *avo.avo_current_arg++) != '\0')
switch(i){
case 'S': case 's': resfiles |= a_RF_SYSTEM; break;
case 'U': case 'u': resfiles |= a_RF_USER; break;
case 'X': case 'x': resfiles |= a_RF_BLTIN; break;
case '-': case '/': resfiles &= ~a_RF_MASK; break;
default:
emsg = N_("Invalid argument of -:");
goto jusage;
}
break;
case '~':
/* Enable command escapes even in non-interactive mode */
n_poption |= n_PO_TILDE_FLAG;
break;
case '#':
/* Work in batch mode, even if non-interactive */
if(!(n_psonce & n_PSO_INTERACTIVE))
setvbuf(n_stdin, NIL, _IOLBF, 0);
n_poption |= n_PO_TILDE_FLAG | n_PO_BATCH_FLAG;
mc.mc_folder = n_path_devnull;
n_var_setup_batch_mode();
break;
case '.':
/* Enforce send mode */
n_psonce |= n_PSO_SENDMODE;
goto jgetopt_done;
case su_AVOPT_STATE_ERR_ARG:
emsg = su_avopt_fmt_err_arg;
if(0){
/* FALLTHRU */
case su_AVOPT_STATE_ERR_OPT:
emsg = su_avopt_fmt_err_opt;
}
n_err(emsg, avo.avo_current_err_opt);
if(0){
jusage:
if(emsg != NIL)
n_err("%s\n", V_(emsg));
}
a_main_usage(n_stderr);
n_exit_status = n_EXIT_USE;
goto jleave;
}
}
jgetopt_done:
;
/* The normal arguments may be followed by MTA arguments after a "--";
* however, -f may take off an argument, too, and before that.
* Since MTA arguments after "--" require *expandargv*, delay parsing off
* those options until after the resource files are loaded... */
argc = avo.avo_argc;
argv = C(char**,avo.avo_argv);
if((cp = argv[i = 0]) == NIL || avo.avo_current_opt == su_AVOPT_STATE_STOP){
}else if(cp[0] == '-' && cp[1] == '-' && cp[2] == '\0')
++i;
/* n_PO_BATCH_FLAG sets to /dev/null, but -f can still be used and sets & */
else if(n_poption & n_PO_f_FLAG){
mc.mc_folder = cp;
if((cp = argv[++i]) != NIL){
if(cp[0] != '-' || cp[1] != '-' || cp[2] != '\0'){
emsg = N_("More than one file given with -f");
goto jusage;
}
++i;
}
}else{
n_psonce |= n_PSO_SENDMODE;
for(;;){
mc.mc_to = cat(mc.mc_to, lextract(cp, GTO | GFULL | GNOT_A_LIST |
GSHEXP_PARSE_HACK));
if((cp = argv[++i]) == NIL)
break;
if(cp[0] == '-' && cp[1] == '-' && cp[2] == '\0'){
++i;
break;
}
}
}
argc = i;
/* ...BUT, since we use n_autorec_alloc() for the MTA n_smopts storage we
* need to allocate the space for them before we fixate that storage! */
while(argv[i] != NIL)
++i;
if(n_smopts_cnt + i > mc.mc_smopts_size)
DBG(mc.mc_smopts_size =)
a_main_grow_cpp(&n_smopts, n_smopts_cnt + i + 1, n_smopts_cnt);
/* Check for inconsistent arguments, fix some temporaries */
if(n_psonce & n_PSO_SENDMODE){
/* XXX This is only because BATCH_FLAG sets *folder*=/dev/null
* XXX in order to function. Ideally that would not be needed */
if(mc.mc_folder != NIL && !(n_poption & n_PO_BATCH_FLAG)){
emsg = N_("Cannot give -f and people to send to.");
goto jusage;
}
if(mc.mc_u != NIL){
emsg = N_("The -u option cannot be used in send mode");
goto jusage;
}
if(!(n_poption & n_PO_t_FLAG) && mc.mc_to == NIL){
emsg = N_("Send options without primary recipient specified.");
goto jusage;
}
if((n_poption & n_PO_t_FLAG) && mc.mc_quote != NIL){
emsg = N_("The -M, -m, -q and -t options are mutual exclusive.");
goto jusage;
}
if(n_poption & (n_PO_EXISTONLY | n_PO_HEADERSONLY | n_PO_HEADERLIST)){
emsg = N_("The -e, -H and -L options cannot be used in send mode.");
goto jusage;
}
if(n_poption & n_PO_R_FLAG){
emsg = N_("The -R option is meaningless in send mode.");
goto jusage;
}
if(n_psonce & n_PSO_INTERACTIVE){
if(mc.mc_quote == R(char*,-1)){
if(!(n_poption & n_PO_Mm_FLAG))
emsg = N_("-q can't use standard input when interactive.\n");
goto jusage;
}
}
}else{
if(mc.mc_u != NIL && mc.mc_folder != NIL){
emsg = N_("The options -u and -f (and -#) are mutually exclusive");
goto jusage;
}
if((n_poption & (n_PO_EXISTONLY | n_PO_HEADERSONLY)) ==
(n_PO_EXISTONLY | n_PO_HEADERSONLY)){
emsg = N_("The options -e and -H are mutual exclusive");
goto jusage;
}
if((n_poption & (n_PO_HEADERSONLY | n_PO_HEADERLIST) /* TODO OBSOLETE */
) == (n_PO_HEADERSONLY | n_PO_HEADERLIST))
n_OBSOLETE(_("please use \"-e -L xy\" instead of \"-H -L xy\""));
if(mc.mc_u != NIL)
mc.mc_folder = mc.mc_u;
}
/*
* We have reached our second program state, the command line options have
* been worked and verified a bit, we are likely to go, perform more setup
*/
n_psonce |= n_PSO_STARTED_GETOPT;
ASSERT(!(n_poption & n_PO_QUICKRUN_MASK) ||
!(n_psonce & n_PSO_INTERACTIVE));
a_main_setup_vars();
/* Create memory pool snapshot; Memory is auto-reclaimed from now on */
su_mem_bag_fixate(n_go_data->gdc_membag);
/* load() any resource files */
if(resfiles & a_RF_MASK){
/* *expand() returns a savestr(), but load() only uses the file name
* for fopen(), so it is safe to do this */
if(resfiles & a_RF_SYSTEM){
boole nload;
if((nload = ok_blook(NAIL_NO_SYSTEM_RC)))
n_OBSOLETE(_("Please use $MAILX_NO_SYSTEM_RC instead of "
"$NAIL_NO_SYSTEM_RC"));
if(!nload && !ok_blook(MAILX_NO_SYSTEM_RC) &&
!n_go_load_rc(ok_vlook(system_mailrc)))
goto jleave;
}
if((resfiles & a_RF_USER) &&
(cp = fexpand(ok_vlook(MAILRC), (FEXP_NOPROTO | FEXP_LOCAL_FILE |
FEXP_NSHELL))) != NIL && !n_go_load_rc(cp))
goto jleave;
if((resfiles & a_RF_BLTIN) && !n_go_load_lines(FAL0, NIL, 0))
goto jleave;
}
if((cp = ok_vlook(NAIL_EXTRA_RC)) != NIL)
n_OBSOLETE(_("Please use *mailx-extra-rc*, not *NAIL_EXTRA_RC*"));
if((cp != NIL || (cp = ok_vlook(mailx_extra_rc)) != NIL) &&
(cp = fexpand(cp, (FEXP_NOPROTO | FEXP_LOCAL_FILE | FEXP_NSHELL))
) != NIL && !n_go_load_rc(cp))
goto jleave;
/* Cause possible umask(2) to be applied, now that any setting is
* established, and before we change accounts, evaluate commands etc. */
(void)ok_vlook(umask);
/* Additional options to pass-through to MTA, and allowed to do so? */
i = argc;
if((cp = ok_vlook(expandargv)) != NIL){
boole isfail, isrestrict;
isfail = !su_cs_cmp_case(cp, "fail");
isrestrict = (!isfail && !su_cs_cmp_case(cp, "restrict"));
if((n_poption & n_PO_D_V) && !isfail && !isrestrict && *cp != '\0')
n_err(_("Unknown *expandargv* value: %s\n"), cp);
if((cp = argv[i]) != NIL){
/* _TILDE_ is implied by _BATCH_ */
if(isfail || (isrestrict && !((n_poption & n_PO_TILDE_FLAG) ||
(n_psonce & n_PSO_INTERACTIVE)))){
je_expandargv:
n_err(_("*expandargv* doesn't allow MTA arguments; consider "
"using *mta-arguments*\n"));
n_exit_status = n_EXIT_USE | n_EXIT_SEND_ERROR;
goto jleave;
}
do{
ASSERT(n_smopts_cnt + 1 <= mc.mc_smopts_size);
n_smopts[n_smopts_cnt++] = cp;
}while((cp = argv[++i]) != NIL);
}
}else if(argv[i] != NIL)
goto je_expandargv;
/* We had to wait until the resource files are loaded and any command line
* setting has been restored, but get the termcap up and going before we
* switch account or running commands */
if(n_psonce & n_PSO_INTERACTIVE){
#ifdef mx_HAVE_TCAP
mx_termcap_init();
#endif
/* We have to fake some state of readiness in order to allow resolving of
* lazy `bind's (from config files); this is ok and allows one call to
* tty_init() (and one to tty_destroy()) instead of two according pairs
* for send and receive mode, which also had the ugly effect that -A
* account switch and -X commands ran without properly setup tty/MLE! */
n_psonce |= n_PSO_STARTED_CONFIG;
mx_tty_init();
n_psonce ^= n_PSO_STARTED_CONFIG;
}
/* Now we can set the account */
if(mc.mc_A != NIL){
char const *a[2];
a[0] = mc.mc_A;
a[1] = NIL;
if(c_account(a) && (!(n_psonce & n_PSO_INTERACTIVE) ||
ok_blook(errexit) || ok_blook(posix))){
n_exit_status = n_EXIT_USE | n_EXIT_SEND_ERROR;
goto jleave;
}
}
/*
* Almost setup, only -X commands are missing!
*/
n_psonce |= n_PSO_STARTED_CONFIG;
/* "load()" commands given on command line */
if(mc.mc_X_cnt > 0 && !n_go_load_lines(FAL0, mc.mc_X, mc.mc_X_cnt))
goto jleave_full;
/* Final tests */
if(n_poption & n_PO_Mm_FLAG){
if(mc.mc_quote == R(char*,-1)){
if(!mx_mimetype_is_known(n_poption_arg_Mm)){
n_err(_("Could not find `mimetype' for -M argument: %s\n"),
n_poption_arg_Mm);
n_exit_status = n_EXIT_ERR;
goto jleave_full;
}
}else if(/* XXX only to satisfy Coverity! */mc.mc_quote != NIL &&
(n_poption_arg_Mm = mx_mimetype_classify_filename(mc.mc_quote)
) == NIL){
n_err(_("Could not `mimetype'-classify -m argument: %s\n"),
n_shexp_quote_cp(mc.mc_quote, FAL0));
n_exit_status = n_EXIT_ERR;
goto jleave_full;
}else if(!su_cs_cmp_case(n_poption_arg_Mm, "text/plain")) /* TODO magic*/
n_poption_arg_Mm = NULL;
}
/*
* We are finally completely setup and ready to go!
*/
n_psonce |= n_PSO_STARTED;
/* TODO v15compat */
if((n_poption & n_PO_D_V) && ok_vlook(v15_compat) == NIL)
n_err("Warning -- v15-compat=yes will be default in v14.10.0!\n");
if(!(n_psonce & n_PSO_SENDMODE))
n_exit_status = a_main_rcv_mode(&mc);
else{
/* XXX This may use savestr(), but since we will not enter the command
* XXX loop we do not need to care about that */
for(; mc.mc_a_head != NIL; mc.mc_a_head = mc.mc_a_head->maa_next){
BITENUM_IS(u32,mx_attachments_error) aerr;
mc.mc_attach = mx_attachments_append(mc.mc_attach,
mc.mc_a_head->maa_file, &aerr, NIL);
if(aerr != mx_ATTACHMENTS_ERR_NONE){
n_exit_status = n_EXIT_ERR;
goto jleave_full;
}
}
/* "load()" more commands given on command line */
if(mc.mc_Y_cnt > 0 && !n_go_load_lines(TRU1, mc.mc_Y, mc.mc_Y_cnt))
n_exit_status = n_EXIT_ERR;
else
n_mail((((n_psonce & n_PSO_INTERACTIVE
) ? n_MAILSEND_HEADERS_PRINT : 0) |
(n_poption & n_PO_F_FLAG ? n_MAILSEND_RECORD_RECIPIENT : 0)),
mc.mc_to, mc.mc_cc, mc.mc_bcc, mc.mc_subject,
mc.mc_attach, mc.mc_quote);
}
jleave_full:/* C99 */{
char const *ccp;
boole was_xit;
i = n_exit_status;
was_xit = ((n_psonce & n_PSO_XIT) != 0);
n_psonce &= ~n_PSO_EXIT_MASK;
mx_account_leave();
if(n_psonce & n_PSO_INTERACTIVE){
mx_tty_destroy(was_xit);
#ifdef mx_HAVE_TCAP
mx_termcap_destroy();
#endif
}
n_psonce &= ~n_PSO_EXIT_MASK;
if((ccp = ok_vlook(on_program_exit)) != NIL)
temporary_on_xy_hook_caller("on-program-exit", ccp, FAL0);
n_exit_status = i;
}
jleave:
if(n_exit_status == n_EXIT_OK && (n_psonce & n_PSO_SEND_ERROR) &&
ok_blook(posix))
n_exit_status = n_EXIT_SEND_ERROR;
if(!mx_fs_flush(NIL)){
n_err(_("Flushing file output buffers failed: %s\n"),
su_err_doc(su_err_no()));
if(n_exit_status == n_EXIT_OK)
n_exit_status = n_EXIT_IOERR;
}
#ifdef su_HAVE_DEBUG
/* xxx call atexit handlers here */
su_mem_bag_gut(n_go_data->gdc_membag); /* Was init in go_init() */
su_mem_set_conf(su_MEM_CONF_LINGER_FREE_RELEASE, 0);
#endif
NYD_OU;
return n_exit_status;
}
#include "su/code-ou.h"
/* Source the others in that case! */
#ifdef mx_HAVE_AMALGAMATION
# include <mx/gen-config.h>
#endif
/* s-it-mode */
|
catroll/mailx
|
include/mx/gen-version.h
|
<gh_stars>0
#define mx_VERSION "v14.9.23"
#define mx_VERSION_DATE "2021-11-11"
#define mx_VERSION_MAJOR "14"
#define mx_VERSION_MINOR "9"
#define mx_VERSION_UPDATE "23"
#define mx_VERSION_HEXNUM "0x0E009017"
|
catroll/mailx
|
src/mx/random.c
|
<gh_stars>1-10
/*@ S-nail - a mail user agent derived from Berkeley Mail.
*@ Implementation of random.h.
*
* Copyright (c) 2015 - 2020 <NAME>) Nurpmeso <<EMAIL>>.
* SPDX-License-Identifier: ISC
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#undef su_FILE
#define su_FILE random
#define mx_SOURCE
#define mx_SOURCE_RANDOM
#ifndef mx_HAVE_AMALGAMATION
# include "mx/nail.h"
#endif
#include "mx/random.h"
#if mx_HAVE_RANDOM != mx_RANDOM_IMPL_ARC4 &&\
mx_HAVE_RANDOM != mx_RANDOM_IMPL_TLS
# define a_RAND_USE_BUILTIN
# if mx_HAVE_RANDOM == mx_RANDOM_IMPL_GETENTROPY
# include <unistd.h>
# elif mx_HAVE_RANDOM == mx_RANDOM_IMPL_GETRANDOM
# include mx_RANDOM_GETRANDOM_H
# endif
# ifdef mx_HAVE_SCHED_YIELD
# include <sched.h>
# endif
#endif
#include <su/mem.h>
#ifdef a_RAND_USE_BUILTIN
# include <su/prime.h>
#endif
/* Already: #include "mx/random.h" */
#include "su/code-in.h"
#ifdef a_RAND_USE_BUILTIN
union a_rand_state{
struct a_rand_arc4{
u8 _dat[256];
u8 _i;
u8 _j;
u8 __pad[6];
} a;
u8 b8[sizeof(struct a_rand_arc4)];
u32 b32[sizeof(struct a_rand_arc4) / sizeof(u32)];
};
#endif
#ifdef a_RAND_USE_BUILTIN
static union a_rand_state *a_rand;
#endif
/* Our ARC4 random generator with its completely unacademical pseudo
* initialization (shall /dev/urandom fail) */
#ifdef a_RAND_USE_BUILTIN
static void a_rand_init(void);
su_SINLINE u8 a_rand_get8(void);
static u32 a_rand_weak(u32 seed);
#endif
#ifdef a_RAND_USE_BUILTIN
static void
a_rand_init(void){
union {int fd; uz i;} u;
NYD2_IN;
a_rand = n_alloc(sizeof *a_rand);
# if mx_HAVE_RANDOM == mx_RANDOM_IMPL_GETENTROPY ||\
mx_HAVE_RANDOM == mx_RANDOM_IMPL_GETRANDOM
/* getentropy(3)/getrandom(2) guarantee 256 without su_ERR_INTR..
* However, support sequential reading to avoid possible hangs that have
* been reported on the ML (2017-08-22, s-nail/s-mailx freezes when
* mx_HAVE_GETRANDOM is #defined) */
LCTA(sizeof(a_rand->a._dat) <= 256,
"Buffer too large to be served without su_ERR_INTR error");
LCTA(sizeof(a_rand->a._dat) >= 256,
"Buffer too small to serve used array indices");
/* C99 */{
uz o, i;
for(o = 0, i = sizeof a_rand->a._dat;;){
sz gr;
# if mx_HAVE_RANDOM == mx_RANDOM_IMPL_GETENTROPY
if((gr = getentropy(&a_rand->a._dat[o], i)) != -1)
gr = i;
# else
gr = mx_RANDOM_GETRANDOM_FUN(&a_rand->a._dat[o], i);
# endif
if(gr == -1 && su_err_no() == su_ERR_NOSYS)
break;
a_rand->a._i = (a_rand->a._dat[a_rand->a._dat[1] ^
a_rand->a._dat[84]]);
a_rand->a._j = (a_rand->a._dat[a_rand->a._dat[65] ^
a_rand->a._dat[42]]);
/* ..but be on the safe side */
if(gr > 0){
i -= S(uz,gr);
if(i == 0)
goto jleave;
o += S(uz,gr);
}
n_err(_("Not enough entropy for the "
"P(seudo)R(andom)N(umber)G(enerator), waiting a bit\n"));
n_msleep(250, FAL0);
}
}
# elif mx_HAVE_RANDOM == mx_RANDOM_IMPL_URANDOM
if((u.fd = open("/dev/urandom", O_RDONLY)) != -1){
boole ok;
ok = (sizeof(a_rand->a._dat) == S(uz,read(u.fd,
a_rand->a._dat, sizeof(a_rand->a._dat))));
close(u.fd);
a_rand->a._i = (a_rand->a._dat[a_rand->a._dat[1] ^ a_rand->a._dat[84]]);
a_rand->a._j = (a_rand->a._dat[a_rand->a._dat[65] ^ a_rand->a._dat[42]]);
if(ok)
goto jleave;
}
# elif mx_HAVE_RANDOM != mx_RANDOM_IMPL_BUILTIN
# error a_rand_init(): the value of mx_HAVE_RANDOM is not supported
# endif
/* As a fallback, a homebrew seed */
if(n_poption & n_PO_D_V)
n_err(_("P(seudo)R(andom)N(umber)G(enerator): "
"creating homebrew seed\n"));
/* C99 */{
# ifdef mx_HAVE_CLOCK_GETTIME
struct timespec ts;
# else
struct timeval ts;
# endif
boole slept;
u32 seed, rnd, t, k;
/* We first do three rounds, and then add onto that a (cramped) random
* number of rounds; in between we give up our timeslice once (from our
* point of view) */
seed = R(up,a_rand) & U32_MAX;
rnd = 3;
slept = FAL0;
for(;;){
/* Stir the entire pool once */
for(u.i = NELEM(a_rand->b32); u.i-- != 0;){
# ifdef mx_HAVE_CLOCK_GETTIME
clock_gettime(CLOCK_REALTIME, &ts);
t = S(u32,ts.tv_nsec);
# else
gettimeofday(&ts, NIL);
t = S(u32,ts.tv_usec);
# endif
if(rnd & 1)
t = (t >> 16) | (t << 16);
a_rand->b32[u.i] ^= a_rand_weak(seed ^ t);
a_rand->b32[t % NELEM(a_rand->b32)] ^= seed;
if(rnd == 7 || rnd == 17)
a_rand->b32[u.i] ^= a_rand_weak(seed ^ S(u32,ts.tv_sec));
k = a_rand->b32[u.i] % NELEM(a_rand->b32);
a_rand->b32[k] ^= a_rand->b32[u.i];
seed ^= a_rand_weak(a_rand->b32[k]);
if((rnd & 3) == 3)
seed ^= su_prime_lookup_next(seed);
}
if(--rnd == 0){
if(slept)
break;
rnd = (a_rand_get8() % 5) + 3;
# ifdef mx_HAVE_SCHED_YIELD
sched_yield();
# elif defined mx_HAVE_NANOSLEEP
ts.tv_sec = 0, ts.tv_nsec = 0;
nanosleep(&ts, NIL);
# else
rnd += 10;
# endif
slept = TRU1;
}
}
for(u.i = sizeof(a_rand->b8) * ((a_rand_get8() % 5) + 1);
u.i != 0; --u.i)
a_rand_get8();
goto jleave; /* (avoid unused warning) */
}
jleave:
NYD2_OU;
}
su_SINLINE u8
a_rand_get8(void){
u8 i, j;
i = a_rand->a._dat[++a_rand->a._i];
j = a_rand->a._dat[a_rand->a._j += i];
a_rand->a._dat[a_rand->a._i] = j;
a_rand->a._dat[a_rand->a._j] = i;
return a_rand->a._dat[S(u8,i + j)];
}
static u32
a_rand_weak(u32 seed){
/* From "Random number generators: good ones are hard to find",
* <NAME>, Communications of the ACM, vol. 31, no. 10,
* October 1988, p. 1195.
* (In fact: FreeBSD 4.7, /usr/src/lib/libc/stdlib/random.c.) */
u32 hi;
if(seed == 0)
seed = 123459876;
hi = seed / 127773;
seed %= 127773;
seed = (seed * 16807) - (hi * 2836);
if(S(s32,seed) < 0)
seed += S32_MAX;
return seed;
}
#endif /* a_RAND_USE_BUILTIN */
char *
mx_random_create_buf(char *dat, uz len, u32 *reprocnt_or_nil){
struct str b64;
char *indat, *cp, *oudat;
uz i, inlen, oulen;
NYD_IN;
if(!(n_psonce & n_PSO_RANDOM_INIT)){
n_psonce |= n_PSO_RANDOM_INIT;
if(n_poption & n_PO_D_V){
char const *prngn;
#if mx_HAVE_RANDOM == mx_RANDOM_IMPL_ARC4
prngn = "arc4random";
#elif mx_HAVE_RANDOM == mx_RANDOM_IMPL_TLS
prngn = "*TLS RAND_*";
#elif mx_HAVE_RANDOM == mx_RANDOM_IMPL_GETENTROPY
prngn = "getentropy(3) + builtin ARC4";
#elif mx_HAVE_RANDOM == mx_RANDOM_IMPL_GETRANDOM
prngn = "getrandom(2/3) + builtin ARC4";
#elif mx_HAVE_RANDOM == mx_RANDOM_IMPL_URANDOM
prngn = "/dev/urandom + builtin ARC4";
#elif mx_HAVE_RANDOM == mx_RANDOM_IMPL_BUILTIN
prngn = "builtin ARC4";
#else
# error mx_random_create_buf(): the value of mx_HAVE_RANDOM is not supported
#endif
n_err(_("P(seudo)R(andom)N(umber)G(enerator): %s\n"), prngn);
}
#ifdef a_RAND_USE_BUILTIN
a_rand_init();
#endif
}
/* We use our base64 encoder with _NOPAD set, so ensure the encoded result
* with PAD stripped is still longer than what the user requests, easy way.
* The relation of base64 is fixed 3 in = 4 out, and we do not want to
* include the base64 PAD characters in our random string: give some pad */
i = len;
if((inlen = i % 3) != 0)
i += 3 - inlen;
jinc1:
inlen = i >> 2;
oulen = inlen << 2;
if(oulen < len){
i += 3;
goto jinc1;
}
inlen = inlen + (inlen << 1);
indat = n_lofi_alloc(inlen +1);
if(!su_state_has(su_STATE_REPRODUCIBLE) || reprocnt_or_nil == NIL){
#if mx_HAVE_RANDOM == mx_RANDOM_IMPL_TLS
mx_tls_rand_bytes(indat, inlen);
#elif mx_HAVE_RANDOM != mx_RANDOM_IMPL_ARC4
for(i = inlen; i-- > 0;)
indat[i] = S(char,a_rand_get8());
#else
for(cp = indat, i = inlen; i > 0;){
union {u32 i4; char c[4];} r;
uz j;
r.i4 = S(u32,arc4random());
switch((j = i & 3)){
case 0: cp[3] = r.c[3]; j = 4; /* FALLTHRU */
case 3: cp[2] = r.c[2]; /* FALLTHRU */
case 2: cp[1] = r.c[1]; /* FALLTHRU */
default: cp[0] = r.c[0]; break;
}
cp += j;
i -= j;
}
#endif
}else{
for(cp = indat, i = inlen; i > 0;){
union {u32 i4; char c[4];} r;
uz j;
r.i4 = ++*reprocnt_or_nil;
if(su_BOM_IS_BIG()){ /* TODO BSWAP */
char x;
x = r.c[0];
r.c[0] = r.c[3];
r.c[3] = x;
x = r.c[1];
r.c[1] = r.c[2];
r.c[2] = x;
}
switch((j = i & 3)){
case 0: cp[3] = r.c[3]; j = 4; /* FALLTHRU */
case 3: cp[2] = r.c[2]; /* FALLTHRU */
case 2: cp[1] = r.c[1]; /* FALLTHRU */
default: cp[0] = r.c[0]; break;
}
cp += j;
i -= j;
}
}
oudat = (len >= oulen) ? dat : n_lofi_alloc(oulen +1);
b64.s = oudat;
b64_encode_buf(&b64, indat, inlen, B64_BUF | B64_RFC4648URL | B64_NOPAD);
ASSERT(b64.l >= len);
su_mem_copy(dat, b64.s, len);
dat[len] = '\0';
if(oudat != dat)
n_lofi_free(oudat);
n_lofi_free(indat);
NYD_OU;
return dat;
}
char *
mx_random_create_cp(uz len, u32 *reprocnt_or_nil){
char *dat;
NYD_IN;
dat = n_autorec_alloc(len +1);
dat = mx_random_create_buf(dat, len, reprocnt_or_nil);
NYD_OU;
return dat;
}
#include "su/code-ou.h"
/* s-it-mode */
|
catroll/mailx
|
src/mx/file-streams.c
|
/*@ S-nail - a mail user agent derived from Berkeley Mail.
*@ Implementation of file-streams.h.
*@ TODO tmp_release() should be removed: tmp_open() should take an optional
*@ TODO vector of NIL terminated {char const *mode;sz fd_result;} structs,
*@ TODO and create all desired copies; drop HOLDSIGS, then, too!
*
* Copyright (c) 2012 - 2020 <NAME>) Nurpmeso <<EMAIL>>.
* SPDX-License-Identifier: ISC
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#undef su_FILE
#define su_FILE file_streams
#define mx_SOURCE
#define mx_SOURCE_FILE_STREAMS
#ifndef mx_HAVE_AMALGAMATION
# include "mx/nail.h"
#endif
#include <fcntl.h>
#include <su/cs.h>
#include <su/mem.h>
#include "mx/child.h"
#include "mx/cmd-filetype.h"
#include "mx/random.h"
#include "mx/sigs.h"
#include "mx/termcap.h"
#include "mx/file-streams.h"
#include "su/code-in.h"
#ifdef O_CLOEXEC
# define a_FS__O_CLOEXEC O_CLOEXEC
#else
# define a_FS__O_CLOEXEC 0
#endif
enum{
a_FS_PIPE_READ = 0,
a_FS_PIPE_WRITE = 1
};
enum a_fs_ent_flags{
a_FS_EF_RAW,
a_FS_EF_IMAP = 1u<<1,
a_FS_EF_MAILDIR = 1u<<2,
a_FS_EF_HOOK = 1u<<3,
a_FS_EF_PIPE = 1u<<4,
a_FS_EF_MASK = (1u<<7) - 1,
/* TODO a_FS_EF_UNLINK: should be in a separate process so that unlinking
* TODO the temporary "garbage" is "safe"(r than it is like that) */
a_FS_EF_UNLINK = 1u<<8,
/* mx_fs_tmp_release() callable? */
a_FS_EF_HOLDSIGS = 1u<<9,
a_FS_EF_FD_PASS_NEEDS_WAIT = 1u<<10
};
/* This struct is what backs struct mx_fs_tmp_ctx! */
struct a_fs_ent{
char *fse_realfile;
struct a_fs_ent *fse_link;
u32 fse_flags;
int fse_omode;
long fse_offset; /* TODO SU I/O 64-bit */
FILE *fse_fp;
char *fse_save_cmd;
struct mx_child_ctx fse_cc;
};
struct a_fs_lpool_ent{
struct a_fs_lpool_ent *fsle_last;
char *fsle_dat;
uz fsle_size;
};
static struct a_fs_ent *a_fs_fp_head;
struct a_fs_lpool_ent *a_fs_lpool_free;
struct a_fs_lpool_ent *a_fs_lpool_used;
/* Scan file open mode, and turn it to flags. If & was prepended, set *mode
* to NIL to indicate O_REGISTER shall not be set */
static boole a_fs_scan_mode(char const **mode, int *omode);
/* */
static struct a_fs_ent *a_fs_register_file(FILE *fp, int omode,
struct mx_child_ctx *ccp,
u32 flags, char const *realfile, long offset, char const *save_cmd);
static boole a_fs_unregister_file(FILE *fp);
/* */
static boole a_fs_file_load(uz flags, int infd, int outfd,
char const *load_cmd);
static boole a_fs_file_save(struct a_fs_ent *fpp);
static boole
a_fs_scan_mode(char const **mode, int *omode){
static struct{
char const mode[4];
int omode;
}const maps[] = {
{"r", O_RDONLY},
{"w", O_WRONLY | O_CREAT | mx_O_NOXY_BITS | O_TRUNC},
{"wx", O_WRONLY | O_CREAT | O_EXCL},
{"a", O_WRONLY | O_APPEND | O_CREAT | mx_O_NOXY_BITS},
{"a+", O_RDWR | O_APPEND | O_CREAT | mx_O_NOXY_BITS},
{"r+", O_RDWR},
{"w+", O_RDWR | O_CREAT | mx_O_NOXY_BITS | O_TRUNC},
{"W+", O_RDWR | O_CREAT | O_EXCL}
};
boole rv;
uz i;
char const *xmode;
NYD2_IN;
if((xmode = *mode)[0] == '&'){
*mode = NIL;
++xmode;
}
for(i = 0; i < NELEM(maps); ++i)
if(!su_cs_cmp(maps[i].mode, xmode)){
*omode = maps[i].omode;
rv = TRU1;
goto jleave;
}
su_DBG( n_alert(_("Internal error: bad stdio open mode %s"), xmode); )
su_NDBG( su_err_set_no(su_ERR_INVAL); )
*omode = 0; /* (silence CC) */
rv = FAL0;
jleave:
NYD2_OU;
return rv;
}
static struct a_fs_ent *
a_fs_register_file(FILE *fp, int omode, struct mx_child_ctx *ccp, u32 flags,
char const *realfile, long offset, char const *save_cmd){
struct a_fs_ent *fsep;
NYD_IN;
ASSERT(!(flags & a_FS_EF_UNLINK) || realfile != NIL);
fsep = su_TCALLOC(struct a_fs_ent, 1);
if(realfile != NIL)
fsep->fse_realfile = su_cs_dup(realfile, 0);
fsep->fse_link = a_fs_fp_head;
fsep->fse_flags = flags;
fsep->fse_omode = omode;
fsep->fse_offset = offset;
fsep->fse_fp = fp;
if(save_cmd != NIL)
fsep->fse_save_cmd = su_cs_dup(save_cmd, 0);
if(ccp != NIL)
fsep->fse_cc = *ccp;
a_fs_fp_head = fsep;
NYD_OU;
return fsep;
}
static boole
a_fs_unregister_file(FILE *fp){
struct a_fs_ent **fsepp, *fsep;
boole rv;
NYD_IN;
rv = TRU1;
for(fsepp = &a_fs_fp_head;; fsepp = &fsep->fse_link){
if(UNLIKELY((fsep = *fsepp) == NIL)){
su_DBGOR(n_panic, n_alert)(_("Invalid file pointer"));
rv = FAL0;
break;
}else if(fsep->fse_fp != fp)
continue;
switch(fsep->fse_flags & a_FS_EF_MASK){
case a_FS_EF_RAW:
case a_FS_EF_PIPE:
break;
default:
rv = a_fs_file_save(fsep);
break;
}
if((fsep->fse_flags & a_FS_EF_UNLINK) && unlink(fsep->fse_realfile))
rv = FAL0;
*fsepp = fsep->fse_link;
if(fsep->fse_realfile != NIL)
su_FREE(fsep->fse_realfile);
if(fsep->fse_save_cmd != NIL)
su_FREE(fsep->fse_save_cmd);
su_FREE(fsep);
break;
}
NYD_OU;
return rv;
}
static boole
a_fs_file_load(uz flags, int infd, int outfd, char const *load_cmd){
struct mx_child_ctx cc;
boole rv;
NYD2_IN;
mx_child_ctx_setup(&cc);
cc.cc_flags = mx_CHILD_RUN_WAIT_LIFE;
cc.cc_fds[mx_CHILD_FD_IN] = infd;
cc.cc_fds[mx_CHILD_FD_OUT] = outfd;
switch(flags & a_FS_EF_MASK){
case a_FS_EF_IMAP:
case a_FS_EF_MAILDIR:
rv = TRU1;
break;
case a_FS_EF_HOOK:
cc.cc_cmd = ok_vlook(SHELL);
cc.cc_args[0] = "-c";
cc.cc_args[1] = load_cmd;
if(0){
/* FALLTHRU */
default:
cc.cc_cmd = mx_FS_FILETYPE_CAT_PROG;
}
rv = (mx_child_run(&cc) && cc.cc_exit_status == 0);
break;
}
NYD2_OU;
return rv;
}
static boole
a_fs_file_save(struct a_fs_ent *fsep){
struct mx_child_ctx cc;
boole rv;
NYD_IN;
if(fsep->fse_omode == O_RDONLY){
rv = TRU1;
goto jleave;
}
rv = FAL0;
fflush(fsep->fse_fp);
clearerr(fsep->fse_fp);
/* Ensure the I/O library does not optimize the fseek(3) away! */
if(!n_real_seek(fsep->fse_fp, fsep->fse_offset, SEEK_SET)){
s32 err;
err = su_err_no();
n_err(_("Fatal: cannot restore file position and save %s: %s\n"),
n_shexp_quote_cp(fsep->fse_realfile, FAL0), su_err_doc(err));
goto jleave;
}
#ifdef mx_HAVE_MAILDIR
if((fsep->fse_flags & a_FS_EF_MASK) == a_FS_EF_MAILDIR){
rv = maildir_append(fsep->fse_realfile, fsep->fse_fp, fsep->fse_offset);
goto jleave;
}
#endif
#ifdef mx_HAVE_IMAP
if((fsep->fse_flags & a_FS_EF_MASK) == a_FS_EF_IMAP){
rv = imap_append(fsep->fse_realfile, fsep->fse_fp, fsep->fse_offset);
goto jleave;
}
#endif
mx_child_ctx_setup(&cc);
cc.cc_flags = mx_CHILD_RUN_WAIT_LIFE;
cc.cc_fds[mx_CHILD_FD_IN] = fileno(fsep->fse_fp);
if((cc.cc_fds[mx_CHILD_FD_OUT] = open(fsep->fse_realfile,
((fsep->fse_omode | O_CREAT |
(fsep->fse_omode & O_APPEND ? 0 : O_TRUNC) | mx_O_NOXY_BITS
) & ~O_EXCL), 0666)) == -1){
s32 err;
err = su_err_no();
n_err(_("Fatal: cannot create %s: %s\n"),
n_shexp_quote_cp(fsep->fse_realfile, FAL0), su_err_doc(err));
goto jleave;
}
switch(fsep->fse_flags & a_FS_EF_MASK){
case a_FS_EF_HOOK:
if(n_poption & n_PO_D_V)
n_err(_("Using `filetype' handler %s to save %s\n"),
n_shexp_quote_cp(fsep->fse_save_cmd, FAL0),
n_shexp_quote_cp(fsep->fse_realfile, FAL0));
cc.cc_cmd = ok_vlook(SHELL);
cc.cc_args[0] = "-c";
cc.cc_args[1] = fsep->fse_save_cmd;
break;
default:
cc.cc_cmd = mx_FS_FILETYPE_CAT_PROG;
break;
}
rv = (mx_child_run(&cc) && cc.cc_exit_status == 0);
close(cc.cc_fds[mx_CHILD_FD_OUT]); /* XXX no error handling */
jleave:
NYD_OU;
return rv;
}
FILE *
mx_fs_open(char const *file, char const *oflags){
int osflags, fd;
char const *moflags;
FILE *fp;
NYD_IN;
fp = NIL;
moflags = oflags;
if(!a_fs_scan_mode(&moflags, &osflags))
goto jleave;
osflags |= a_FS__O_CLOEXEC;
if(moflags == NIL)
++oflags;
if((fd = open(file, osflags, 0666)) == -1)
goto jleave;
if(!mx_FS_FD_CLOEXEC_SET(fd)){
close(fd);
goto jleave;
}
if((fp = fdopen(fd, oflags)) != NIL && moflags != NIL)
a_fs_register_file(fp, osflags, 0, a_FS_EF_RAW, NIL, 0L, NIL);
jleave:
NYD_OU;
return fp;
}
FILE *
mx_fs_open_any(char const *file, char const *oflags, /* TODO take flags */
enum mx_fs_open_state *fs_or_nil){ /* TODO as bits, return state */
/* TODO Support file locking upon open time */
long offset;
enum protocol p;
enum mx_fs_oflags rof;
uz flags;
int osflags, omode, infd;
char const *cload, *csave;
enum mx_fs_open_state fs;
s32 err;
FILE *rv;
NYD_IN;
rv = NIL;
err = su_ERR_NONE;
fs = mx_FS_OPEN_STATE_NONE;
cload = csave = NIL;
/* !O_REGISTER is disallowed */
if(!a_fs_scan_mode(&oflags, &osflags) || oflags == NIL){
err = su_ERR_INVAL;
goto jleave;
}
flags = 0;
rof = mx_FS_O_RDWR | mx_FS_O_UNLINK;
if(osflags & O_APPEND)
rof |= mx_FS_O_APPEND;
omode = (osflags == O_RDONLY) ? R_OK : R_OK | W_OK;
/* We don't want to find mbox.bz2 when doing "copy * mbox", but only for
* "file mbox", so don't try hooks when writing */
p = which_protocol(csave = file, TRU1, ((omode & W_OK) == 0), &file);
fs = S(enum mx_fs_open_state,p);
switch(p){
default:
err = su_ERR_OPNOTSUPP;
goto jleave;
case n_PROTO_IMAP:
#ifdef mx_HAVE_IMAP
file = csave;
flags |= a_FS_EF_IMAP;
osflags = O_RDWR | O_APPEND | O_CREAT | mx_O_NOXY_BITS;
infd = -1;
break;
#else
err = su_ERR_OPNOTSUPP;
goto jleave;
#endif
case n_PROTO_MAILDIR:
#ifdef mx_HAVE_MAILDIR
if(fs_or_nil != NIL && !access(file, F_OK))
fs |= mx_FS_OPEN_STATE_EXISTS;
flags |= a_FS_EF_MAILDIR;
osflags = O_RDWR | O_APPEND | O_CREAT | mx_O_NOXY_BITS;
infd = -1;
break;
#else
err = su_ERR_OPNOTSUPP;
goto jleave;
#endif
case n_PROTO_EML:
if(!(osflags & O_RDONLY)){
err = su_ERR_OPNOTSUPP;
goto jleave;
}
/* FALLTHRU */
case n_PROTO_FILE:{
struct mx_filetype ft;
if(!(osflags & O_EXCL) && fs_or_nil != NIL && !access(file, F_OK))
fs |= mx_FS_OPEN_STATE_EXISTS;
if(mx_filetype_exists(&ft, file)){/* TODO report real name to outside */
flags |= a_FS_EF_HOOK;
cload = ft.ft_load_dat;
csave = ft.ft_save_dat;
/* Cause truncation for compressor/hook output files */
osflags &= ~O_APPEND;
rof &= ~mx_FS_O_APPEND;
if((infd = open(file, (omode & W_OK ? O_RDWR : O_RDONLY))) != -1){
fs |= mx_FS_OPEN_STATE_EXISTS;
if(n_poption & n_PO_D_V)
n_err(_("Using `filetype' handler %s to load %s\n"),
n_shexp_quote_cp(cload, FAL0), n_shexp_quote_cp(file, FAL0));
}else{
err = su_err_no();
if(!(osflags & O_CREAT) || err != su_ERR_NOENT)
goto jleave;
}
}else{
/*flags |= a_FS_EF_RAW;*/
rv = mx_fs_open(file, oflags);
if((osflags & O_EXCL) && rv == NIL)
fs |= mx_FS_OPEN_STATE_EXISTS;
goto jleave;
}
}break;
}
/* Note rv is not yet register_file()d, fclose() it in error path! */
if((rv = mx_fs_tmp_open("fopenany", rof, NIL)) == NIL){
n_perr(_("tmpfile"), err = su_err_no());
goto Jerr;
}
if(flags & (a_FS_EF_IMAP | a_FS_EF_MAILDIR))
;
else if(infd >= 0){
if(!a_fs_file_load(flags, infd, fileno(rv), cload)) Jerr:{
err = su_err_no();
if(rv != NIL)
mx_fs_close(rv);
rv = NIL;
if(infd >= 0)
close(infd);
goto jleave;
}
}else{
if((infd = creat(file, 0666)) == -1){
err = su_err_no();
fclose(rv);
rv = NIL;
goto jleave;
}
}
if(infd >= 0)
close(infd);
fflush(rv);
if(!(osflags & O_APPEND))
rewind(rv);
if((offset = ftell(rv)) == -1){
err = su_err_no();
mx_fs_close(rv);
rv = NIL;
goto jleave;
}
a_fs_register_file(rv, osflags, 0, flags, file, offset, csave);
jleave:
if(fs_or_nil != NIL)
*fs_or_nil = fs;
if(rv == NIL && err != su_ERR_NONE)
su_err_set_no(err);
NYD_OU;
return rv;
}
FILE *
mx_fs_tmp_open(char const *namehint, u32 oflags,
struct mx_fs_tmp_ctx **fstcp_or_nil){
/* The 6 is arbitrary but leaves room for an eight character hint (the
* POSIX minimum path length is 14, though we do not check that XXX).
* 6 should be more than sufficient given that we use base64url encoding
* for our random string */
enum {a_RANDCHARS = 6u, a_HINT_MIN = 8u};
char *cp_base, *cp;
uz maxname, hintlen, i;
char const *tmpdir;
int osoflags, fd, e;
boole relesigs;
FILE *fp;
NYD_IN;
ASSERT(namehint != NIL);
ASSERT((oflags & mx_FS_O_WRONLY) || (oflags & mx_FS_O_RDWR));
ASSERT(!(oflags & mx_FS_O_RDONLY));
ASSERT(!(oflags & mx_FS_O_REGISTER_UNLINK) || (oflags & mx_FS_O_REGISTER));
ASSERT(!(oflags & mx_FS_O_HOLDSIGS) || !(oflags & mx_FS_O_UNLINK));
ASSERT(fstcp_or_nil == NIL || ((oflags & mx_FS_O_REGISTER) ||
(oflags & mx_FS_O_HOLDSIGS) || !(oflags & mx_FS_O_UNLINK)));
if(fstcp_or_nil != NIL)
*fstcp_or_nil = NIL;
fp = NIL;
relesigs = FAL0;
e = 0;
tmpdir = ok_vlook(TMPDIR);
maxname = NAME_MAX;
#ifdef mx_HAVE_PATHCONF
/* C99 */{
long pc;
if((pc = pathconf(tmpdir, _PC_NAME_MAX)) != -1){
maxname = S(uz,pc);
if(maxname < a_RANDCHARS + a_HINT_MIN){
su_err_set_no(su_ERR_NAMETOOLONG);
goto jleave;
}
}
}
#endif
/* We are prepared to ignore the namehint .. unless we may not */
if((oflags & mx_FS_O_SUFFIX) && *namehint != '\0'){
if((hintlen = su_cs_len(namehint)) >= maxname - a_RANDCHARS){
su_err_set_no(su_ERR_NAMETOOLONG);
goto jleave;
}
}else
hintlen = 0;
/* Prepare the template string once, then iterate over the random range.
* But first ensure we can report the name in !O_REGISTER cases ("hack") */
i = su_cs_len(tmpdir) + 1 + maxname +1;
if(!(oflags & mx_FS_O_REGISTER) && fstcp_or_nil != NIL){
union {struct a_fs_ent *fse; void *v; struct mx_fs_tmp_ctx *fstc;} p;
/* Store character data right after the struct */
p.v = n_autorec_alloc(sizeof(*p.fse) + i);
su_mem_set(p.fse, 0, sizeof(*p.fse));
p.fse->fse_realfile = R(char*,&p.fse[1]);
if(oflags & mx_FS_O_HOLDSIGS) /* Enable tmp_release() nonetheless? */
p.fse->fse_flags = a_FS_EF_HOLDSIGS;
*fstcp_or_nil = p.fstc;
}
cp_base = cp = n_lofi_alloc(i);
cp = su_cs_pcopy(cp, tmpdir);
*cp++ = '/';
/* C99 */{
uz j;
char *xp;
/* xxx We silently assume VAL_UAGENT easily fits in NAME_MAX-1 */
xp = su_cs_pcopy(cp, VAL_UAGENT);
*xp++ = '-';
if(!(oflags & mx_FS_O_SUFFIX))
xp = su_cs_pcopy(xp, namehint);
/* Just cut off as many of VAL_UAGENT as necessary */
if((i = P2UZ(xp - cp)) > (j = maxname - hintlen - a_RANDCHARS))
xp -= i - j;
if((oflags & mx_FS_O_SUFFIX) && hintlen > 0)
su_mem_copy(&xp[a_RANDCHARS], namehint, hintlen);
xp[hintlen + a_RANDCHARS] = '\0';
cp = xp;
}
osoflags = O_CREAT | O_EXCL | a_FS__O_CLOEXEC;
osoflags |= (oflags & mx_FS_O_WRONLY) ? O_WRONLY : O_RDWR;
if(oflags & mx_FS_O_APPEND)
osoflags |= O_APPEND;
for(relesigs = TRU1, i = 0;; ++i){
su_mem_copy(cp, mx_random_create_cp(a_RANDCHARS, NIL), a_RANDCHARS);
mx_sigs_all_holdx();
if((fd = open(cp_base, osoflags, 0600)) != -1){
if(mx_FS_FD_CLOEXEC_SET(fd))
break;
close(fd);
}
if(i >= mx_FS_TMP_OPEN_TRIES){
e = su_err_no();
goto jfree;
}
mx_sigs_all_rele();
}
/* C99 */{
char const *osflags;
osflags = (oflags & mx_FS_O_RDWR ? "w+" : "w");
if((fp = fdopen(fd, osflags)) != NIL){
if(oflags & mx_FS_O_REGISTER){
struct a_fs_ent *fsep;
int osflagbits;
a_fs_scan_mode(&osflags, &osflagbits); /* TODO osoflags&xy ?!!? */
fsep = a_fs_register_file(fp, osflagbits | a_FS__O_CLOEXEC, 0,
(a_FS_EF_RAW |
(oflags & mx_FS_O_REGISTER_UNLINK ? a_FS_EF_UNLINK : 0) |
(oflags & mx_FS_O_HOLDSIGS ? a_FS_EF_HOLDSIGS : 0)),
cp_base, 0L, NIL);
/* User arg points to registered data in this case */
if(fstcp_or_nil != NIL){
union {void *v; struct mx_fs_tmp_ctx *fstc;} p;
p.v = fsep;
*fstcp_or_nil = p.fstc;
}
}else if(fstcp_or_nil != NIL){
/* Otherwise copy filename buffer into autorec storage */
cp = UNCONST(char*,(*fstcp_or_nil)->fstc_filename);
su_cs_pcopy(cp, cp_base);
}
}
}
if(fp == NIL || (oflags & mx_FS_O_UNLINK)){
e = su_err_no();
unlink(cp_base);
if(fp == NIL)
close(fd);
goto jfree;
}else if(fp != NIL){
/* We will succeed and keep the file around for further usage, likely
* another stream will be opened for pure reading purposes (this is true
* at the time of this writing. A restrictive umask(2) settings may have
* turned the path inaccessible, so ensure it may be read at least!
* TODO once ok_vlook() can return an integer, look up *umask* first! */
(void)fchmod(fd, S_IWUSR | S_IRUSR);
}
n_lofi_free(cp_base);
jleave:
if(relesigs && (fp == NIL || !(oflags & mx_FS_O_HOLDSIGS)))
mx_sigs_all_rele();
if(fp == NIL){
su_err_set_no(e);
if(fstcp_or_nil != NIL)
*fstcp_or_nil = NIL;
}
NYD_OU;
return fp;
jfree:
if((cp = cp_base) != NIL)
n_lofi_free(cp);
goto jleave;
}
void
mx_fs_tmp_release(struct mx_fs_tmp_ctx *fstcp){
union {void *vp; struct a_fs_ent *fsep;} u;
NYD_IN;
ASSERT(fstcp != NIL);
u.vp = fstcp;
ASSERT(u.fsep->fse_flags & a_FS_EF_HOLDSIGS);
DBG( if(u.fsep->fse_flags & a_FS_EF_UNLINK)
n_alert("tmp_release(): REGISTER_UNLINK set!"); )
unlink(u.fsep->fse_realfile);
u.fsep->fse_flags &= ~(a_FS_EF_HOLDSIGS | a_FS_EF_UNLINK);
mx_sigs_all_rele();
NYD_OU;
}
FILE *
mx_fs_fd_open(sz fd, char const *oflags, boole nocloexec){
FILE *fp;
int osflags;
NYD_IN;
a_fs_scan_mode(&oflags, &osflags);
if(!nocloexec)
osflags |= a_FS__O_CLOEXEC; /* Ensured by caller as documented! */
if((fp = fdopen(S(int,fd), oflags)) != NIL && oflags != NIL)
a_fs_register_file(fp, osflags, 0, a_FS_EF_RAW, NIL, 0L, NIL);
NYD_OU;
return fp;
}
boole
mx_fs_fd_cloexec_set(sz fd){
s32 ifd;
boole rv;
NYD2_IN;
ifd = S(s32,fd);
/*if(!(rv = ((a__fl = fcntl(ifd, F_GETFD)) != -1 && !(ifd & FD_CLOEXEC))))*/
rv = (fcntl(ifd, F_SETFD, FD_CLOEXEC) != -1);
NYD2_OU;
return rv;
}
boole
mx_fs_close(FILE *fp){
boole rv;
NYD_IN;
rv = (a_fs_unregister_file(fp) && fclose(fp) == 0);
NYD_OU;
return rv;
}
boole
mx_fs_pipe_cloexec(sz fd[2]){
int xfd[2];
boole rv;
NYD_IN;
rv = FAL0;
#ifdef mx_HAVE_PIPE2
if(pipe2(xfd, O_CLOEXEC) != -1){
fd[0] = xfd[0];
fd[1] = xfd[1];
rv = TRU1;
}
#else
if(pipe(xfd) != -1){
fd[0] = xfd[0];
fd[1] = xfd[1];
mx_fs_fd_cloexec_set(fd[0]);
mx_fs_fd_cloexec_set(fd[1]);
rv = TRU1;
}
#endif
NYD_OU;
return rv;
}
FILE *
mx_fs_pipe_open(char const *cmd, char const *mode, char const *sh,
char const **env_addon, int newfd1){
struct mx_child_ctx cc;
sz p[2], myside, hisside, fd0, fd1;
sigset_t nset;
char mod[2];
FILE *rv;
NYD_IN;
rv = NIL;
mod[0] = '0', mod[1] = '\0';
if(!mx_fs_pipe_cloexec(p))
goto jleave;
if(*mode == 'r'){
myside = p[a_FS_PIPE_READ];
fd0 = mx_CHILD_FD_PASS;
hisside = fd1 = p[a_FS_PIPE_WRITE];
mod[0] = *mode;
}else if(*mode == 'W'){
myside = p[a_FS_PIPE_WRITE];
hisside = fd0 = p[a_FS_PIPE_READ];
fd1 = newfd1;
mod[0] = 'w';
}else{
myside = p[a_FS_PIPE_WRITE];
hisside = fd0 = p[a_FS_PIPE_READ];
fd1 = mx_CHILD_FD_PASS;
mod[0] = 'w';
}
sigemptyset(&nset);
mx_child_ctx_setup(&cc);
/* Be simple and let's just synchronize completely on that */
cc.cc_flags = ((cc.cc_cmd = cmd) == R(char*,-1)) ? mx_CHILD_SPAWN_CONTROL
: mx_CHILD_SPAWN_CONTROL | mx_CHILD_SPAWN_CONTROL_LINGER;
cc.cc_mask = &nset;
cc.cc_fds[mx_CHILD_FD_IN] = fd0;
cc.cc_fds[mx_CHILD_FD_OUT] = fd1;
cc.cc_env_addon = env_addon;
/* Is this a special in-process fork setup? */
if(cmd == R(char*,-1)){
if(!mx_child_fork(&cc))
n_perr(_("fork"), 0);
else if(cc.cc_pid == 0){
union {char const *ccp; int (*ptf)(void); int es;} u;
mx_child_in_child_setup(&cc);
close(S(int,p[a_FS_PIPE_READ]));
close(S(int,p[a_FS_PIPE_WRITE]));
/* TODO close all other open FDs except stds and reset memory */
/* Standard I/O drives me insane! All we need is a sync operation
* that causes n_stdin to forget about any read buffer it may have.
* We cannot use fflush(3), this works with Musl and Solaris, but not
* with GlibC. (For at least pipes.) We cannot use fdreopen(),
* because this function does not exist! Luckily (!!!) we only use
* n_stdin not stdin in our child, otherwise all bets were off!
* TODO (Unless we would fiddle around with FILE* directly:
* TODO #ifdef __GLIBC__
* TODO n_stdin->_IO_read_ptr = n_stdin->_IO_read_end;
* TODO #elif *BSD*
* TODO n_stdin->_r = 0;
* TODO #elif su_OS_SOLARIS || su_OS_SUNOS
* TODO n_stdin->_cnt = 0;
* TODO #endif
* TODO ) which should have additional config test for sure! */
n_stdin = fdopen(STDIN_FILENO, "r");
/*n_stdout = fdopen(STDOUT_FILENO, "w");*/
/*n_stderr = fdopen(STDERR_FILENO, "w");*/
u.ccp = sh;
u.es = (*u.ptf)();
/*fflush(NULL);*/
for(;;)
_exit(u.es);
}
}else{
if(sh != NIL){
cc.cc_cmd = sh;
cc.cc_args[0] = "-c";
cc.cc_args[1] = cmd;
}
mx_child_run(&cc);
}
if(cc.cc_pid < 0){
close(S(int,p[a_FS_PIPE_READ]));
close(S(int,p[a_FS_PIPE_WRITE]));
goto jleave;
}
close(S(int,hisside));
if((rv = fdopen(myside, mod)) != NIL)
a_fs_register_file(rv, 0, &cc,
((fd0 != mx_CHILD_FD_PASS && fd1 != mx_CHILD_FD_PASS)
? a_FS_EF_PIPE : a_FS_EF_PIPE | a_FS_EF_FD_PASS_NEEDS_WAIT),
NIL, 0L, NIL);
else
close(myside);
jleave:
NYD_OU;
return rv;
}
s32
mx_fs_pipe_signal(FILE *fp, s32 sig){
s32 rv;
struct a_fs_ent *fsep;
NYD_IN;
for(fsep = a_fs_fp_head;; fsep = fsep->fse_link)
if(fsep == NIL){
rv = -1;
break;
}else if(fsep->fse_fp == fp){
rv = mx_child_signal(&fsep->fse_cc, sig);
break;
}
NYD_OU;
return rv;
}
boole
mx_fs_pipe_close(FILE *ptr, boole dowait){
n_sighdl_t opipe;
struct mx_child_ctx cc;
boole rv;
struct a_fs_ent *fsep;
NYD_IN;
for(fsep = a_fs_fp_head;; fsep = fsep->fse_link)
if(UNLIKELY(fsep == NIL)){
DBG( n_alert(_("pipe_close: invalid file pointer")); )
rv = FAL0;
goto jleave;
}else if(fsep->fse_fp == ptr)
break;
cc = fsep->fse_cc;
ASSERT(!(fsep->fse_flags & a_FS_EF_FD_PASS_NEEDS_WAIT) || dowait);
a_fs_unregister_file(ptr);
opipe = safe_signal(SIGPIPE, SIG_IGN); /* TODO only because we jump stuff */
fclose(ptr);
safe_signal(SIGPIPE, opipe);
if(dowait)
rv = (mx_child_wait(&cc) && cc.cc_exit_status == 0);
else{
mx_child_forget(&cc);
rv = TRU1;
}
jleave:
NYD_OU;
return rv;
}
boole
mx_fs_flush(FILE *fp){
boole rv;
NYD_IN;
rv = (fflush(fp) != EOF);
NYD_OU;
return rv;
}
void
mx_fs_close_all(void){
NYD_IN;
while(a_fs_fp_head != NIL)
if((a_fs_fp_head->fse_flags & a_FS_EF_MASK) == a_FS_EF_PIPE)
mx_fs_pipe_close(a_fs_fp_head->fse_fp, TRU1);
else
mx_fs_close(a_fs_fp_head->fse_fp);
NYD_OU;
}
void
mx_fs_linepool_aquire(char **dpp, uz *dsp){
struct a_fs_lpool_ent *lpep;
NYD2_IN;
if((lpep = a_fs_lpool_free) != NIL)
a_fs_lpool_free = lpep->fsle_last;
else
lpep = su_TCALLOC(struct a_fs_lpool_ent, 1);
lpep->fsle_last = a_fs_lpool_used;
a_fs_lpool_used = lpep;
*dpp = lpep->fsle_dat;
lpep->fsle_dat = NIL;
*dsp = lpep->fsle_size;
lpep->fsle_size = 0;
NYD2_OU;
}
void
mx_fs_linepool_release(char *dp, uz ds){
struct a_fs_lpool_ent *lpep;
NYD2_IN;
ASSERT(a_fs_lpool_used != NIL);
lpep = a_fs_lpool_used;
a_fs_lpool_used = lpep->fsle_last;
lpep->fsle_last = a_fs_lpool_free;
a_fs_lpool_free = lpep;
lpep->fsle_dat = dp;
lpep->fsle_size = ds;
NYD2_OU;
}
boole
(mx_fs_linepool_book)(char **dp, uz *dsp, uz len, uz toadd
su_DBG_LOC_ARGS_DECL){
boole rv;
NYD2_IN;
rv = FAL0;
if(UZ_MAX - 192 <= toadd)
goto jeoverflow;
toadd = (toadd + 192) & ~127;
if(!su_mem_get_can_book(1, len, toadd))
goto jeoverflow;
len += toadd;
if(*dsp < len){
char *ndp;
if((ndp = su_MEM_REALLOC_LOCOR(*dp, len, su_DBG_LOC_ARGS_ORUSE)) == NIL)
goto jleave;
*dp = ndp;
*dsp = len;
}
rv = TRU1;
jleave:
NYD2_OU;
return rv;
jeoverflow:
su_state_err(su_STATE_ERR_OVERFLOW, (su_STATE_ERR_PASS |
su_STATE_ERR_NOERRNO), _("fs_linepool_book(): buffer size overflow"));
goto jleave;
}
void
mx_fs_linepool_cleanup(boole completely){
struct a_fs_lpool_ent *lpep, *tmp, *keep;
NYD2_IN;
if(!completely)
completely = 3; /* XXX magic */
else
completely = FAL0;
lpep = a_fs_lpool_free;
a_fs_lpool_free = keep = NIL;
jredo:
while((tmp = lpep) != NIL){
void *vp;
lpep = lpep->fsle_last;
if((vp = tmp->fsle_dat) != NIL && completely &&
tmp->fsle_size <= LINESIZE * 2){
--completely;
tmp->fsle_last = a_fs_lpool_free;
a_fs_lpool_free = tmp;
}else{
if(vp != NIL)
su_FREE(vp);
su_FREE(tmp);
}
}
/* Only called from go_main_loop(), save to throw the hulls away */
if((lpep = a_fs_lpool_used) != NIL){
a_fs_lpool_used = NIL;
goto jredo;
}
NYD2_OU;
}
/* TODO The rest below is old-style v15 */
/* line is a buffer with the result of fgets(). Returns the first newline or
* the last character read */
static uz _length_of_line(char const *line, uz linesize);
/* Read a line, one character at a time */
static char *a_fs_fgetline_byone(char **line, uz *linesize, uz *llen_or_nil,
FILE *fp, int appendnl, uz n su_DBG_LOC_ARGS_DECL);
static uz
_length_of_line(char const *line, uz linesize)
{
uz i;
NYD2_IN;
/* Last character is always '\0' and was added by fgets() */
for (--linesize, i = 0; i < linesize; i++)
if (line[i] == '\n')
break;
i = (i < linesize) ? i + 1 : linesize;
NYD2_OU;
return i;
}
static char *
a_fs_fgetline_byone(char **line, uz *linesize, uz *llen_or_nil, FILE *fp,
int appendnl, uz n su_DBG_LOC_ARGS_DECL)
{
char *rv;
int c;
NYD2_IN;
ASSERT(*linesize == 0 || *line != NULL);
/* Always leave room for NETNL, not only \n */
for (rv = *line;;) {
if (*linesize <= LINESIZE || n >= *linesize - 128) {
*linesize += ((rv == NULL) ? LINESIZE + n + 2 : 256);
*line = rv = su_MEM_REALLOC_LOCOR(rv, *linesize,
su_DBG_LOC_ARGS_ORUSE);
}
c = getc(fp);
if (c != EOF) {
rv[n++] = c;
rv[n] = '\0';
if (c == '\n') {
n_pstate |= n_PS_READLINE_NL;
break;
}
} else {
if (n > 0 && feof(fp)) {
if (appendnl) {
rv[n++] = '\n';
rv[n] = '\0';
}
break;
} else {
rv = NULL;
goto jleave;
}
}
}
if(llen_or_nil != NIL)
*llen_or_nil = n;
jleave:
NYD2_OU;
return rv;
}
char *
(fgetline)(char **line, uz *linesize, uz *cnt, uz *llen_or_nil, FILE *fp,
int appendnl su_DBG_LOC_ARGS_DECL)
{
uz i_llen, size;
char *rv;
NYD2_IN;
n_pstate &= ~n_PS_READLINE_NL;
if(llen_or_nil != NIL)
*llen_or_nil = 0;
if(cnt == NIL){
/* Without we cannot determine where the chars returned by fgets()
* end if there's no newline. We have to read one character by one */
rv = a_fs_fgetline_byone(line, linesize, llen_or_nil, fp, appendnl, 0
su_DBG_LOC_ARGS_USE);
goto jleave;
}
if ((rv = *line) == NULL || *linesize < LINESIZE)
*line = rv = su_MEM_REALLOC_LOCOR(rv, *linesize = LINESIZE,
su_DBG_LOC_ARGS_ORUSE);
size = (*linesize <= *cnt) ? *linesize : *cnt + 1;
if (size <= 1 || fgets(rv, size, fp) == NULL) {
/* Leave llen untouched; it is used to determine whether the last line
* was \n-terminated in some callers */
rv = NULL;
goto jleave;
}
i_llen = _length_of_line(rv, size);
*cnt -= i_llen;
while (rv[i_llen - 1] != '\n') {
*line = rv = su_MEM_REALLOC_LOCOR(rv, *linesize += 256,
su_DBG_LOC_ARGS_ORUSE);
size = *linesize - i_llen;
size = (size <= *cnt) ? size : *cnt + 1;
if (size <= 1) {
if (appendnl) {
rv[i_llen++] = '\n';
rv[i_llen] = '\0';
}
break;
} else if (fgets(rv + i_llen, size, fp) == NULL) {
if (!feof(fp)) {
rv = NULL;
goto jleave;
}
if (appendnl) {
rv[i_llen++] = '\n';
rv[i_llen] = '\0';
}
break;
}
size = _length_of_line(rv + i_llen, size);
i_llen += size;
*cnt -= size;
}
/* Always leave room for NETNL, not only \n */
if(appendnl && *linesize - i_llen < 3)
*line = rv = su_MEM_REALLOC_LOCOR(rv, *linesize += 256,
su_DBG_LOC_ARGS_ORUSE);
if(llen_or_nil != NIL)
*llen_or_nil = i_llen;
jleave:
NYD2_OU;
return rv;
}
int
(readline_restart)(FILE *ibuf, char **linebuf, uz *linesize, uz n
su_DBG_LOC_ARGS_DECL)
{
/* TODO readline_restart(): always *appends* LF just to strip it again;
* TODO should be configurable just as for fgetline(); ..or whatever..
* TODO intwrap */
int rv = -1;
long size;
NYD2_IN;
clearerr(ibuf);
/* Interrupts will cause trouble if we are inside a stdio call. As this is
* only relevant if input is from tty, bypass it by read(), then */
if ((n_psonce & n_PSO_TTYIN) && fileno(ibuf) == 0) {
ASSERT(*linesize == 0 || *linebuf != NULL);
n_pstate &= ~n_PS_READLINE_NL;
for (;;) {
if (*linesize <= LINESIZE || n >= *linesize - 128) {
*linesize += ((*linebuf == NULL) ? LINESIZE + n + 1 : 256);
*linebuf = su_MEM_REALLOC_LOCOR(*linebuf, *linesize,
su_DBG_LOC_ARGS_ORUSE);
}
jagain:
size = read(0, *linebuf + n, *linesize - n - 1);
if (size > 0) {
n += size;
(*linebuf)[n] = '\0';
if ((*linebuf)[n - 1] == '\n') {
n_pstate |= n_PS_READLINE_NL;
break;
}
} else {
if (size == -1 && su_err_no() == su_ERR_INTR)
goto jagain;
/* TODO eh. what is this? that now supposed to be a line?!? */
if (n > 0) {
if ((*linebuf)[n - 1] != '\n') {
(*linebuf)[n++] = '\n';
(*linebuf)[n] = '\0';
} else
n_pstate |= n_PS_READLINE_NL;
break;
} else
goto jleave;
}
}
} else {
/* Not reading from standard input or standard input not a terminal. We
* read one char at a time as it is the only way to get lines with
* embedded NUL characters in standard stdio */
if(a_fs_fgetline_byone(linebuf, linesize, &n, ibuf, 1,
n su_DBG_LOC_ARGS_USE) == NIL)
goto jleave;
}
if (n > 0 && (*linebuf)[n - 1] == '\n')
(*linebuf)[--n] = '\0';
rv = (int)n;
jleave:
NYD2_OU;
return rv;
}
off_t
fsize(FILE *iob)
{
struct stat sbuf;
off_t rv;
NYD_IN;
rv = (fstat(fileno(iob), &sbuf) == -1) ? 0 : sbuf.st_size;
NYD_OU;
return rv;
}
#include "su/code-ou.h"
/* s-it-mode */
|
catroll/mailx
|
src/mx/send.c
|
<gh_stars>1-10
/*@ S-nail - a mail user agent derived from Berkeley Mail.
*@ Message content preparation (sendmp()).
*
* Copyright (c) 2000-2004 <NAME>, Freiburg i. Br., Germany.
* Copyright (c) 2012 - 2020 <NAME>) Nurpmeso <<EMAIL>>.
* SPDX-License-Identifier: BSD-3-Clause
*/
/*
* Copyright (c) 1980, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#undef su_FILE
#define su_FILE send
#define mx_SOURCE
#ifndef mx_HAVE_AMALGAMATION
# include "mx/nail.h"
#endif
#include <su/cs.h>
#include <su/mem.h>
#include "mx/child.h"
#include "mx/colour.h"
#include "mx/file-streams.h"
/* TODO but only for creating chain! */
#include "mx/filter-quote.h"
#include "mx/iconv.h"
#include "mx/mime-type.h"
#include "mx/random.h"
#include "mx/sigs.h"
#include "mx/tty.h"
#include "mx/ui-str.h"
/* TODO fake */
#include "su/code-in.h"
static sigjmp_buf _send_pipejmp;
/* Going for user display, print Part: info string */
static void _print_part_info(FILE *obuf, struct mimepart const *mpp,
struct n_ignore const *doitp, int level,
struct quoteflt *qf, u64 *stats);
/* Create a pipe; if mpp is not NULL, place some n_PIPEENV_* environment
* variables accordingly */
static FILE *a_send_pipefile(enum sendaction action,
struct mx_mimetype_handler *mhp, struct mimepart const *mpp, FILE **qbuf,
char const *tmpname, int term_infd);
/* Call mime_write() as appropriate and adjust statistics */
su_SINLINE sz _out(char const *buf, uz len, FILE *fp,
enum conversion convert, enum sendaction action, struct quoteflt *qf,
u64 *stats, struct str *outrest, struct str *inrest);
/* Simply (!) print out a LF (via qf if not NIL) */
static boole a_send_out_nl(FILE *fp, struct quoteflt *qf, u64 *stats);
/* SIGPIPE handler */
static void _send_onpipe(int signo);
/* Send one part */
static int sendpart(struct message *zmp, struct mimepart *ip,
FILE *obuf, struct n_ignore const *doitp,
struct quoteflt *qf, enum sendaction action,
char **linedat, uz *linesize,
u64 *stats, int level, boole *anyoutput/* XXX fake*/);
/* Dependent on *mime-alternative-favour-rich* (favour_rich) do a tree walk
* and check whether there are any such down mpp, which is a .m_multipart of
* an /alternative container.. */
static boole _send_al7ive_have_better(struct mimepart *mpp,
enum sendaction action, boole want_rich);
/* Get a file for an attachment */
static FILE * newfile(struct mimepart *ip, boole volatile *ispipe);
static boole a_send_pipecpy(FILE *pipebuf, FILE *outbuf, FILE *origobuf,
struct quoteflt *qf, u64 *stats);
/* Output a reasonable looking status field */
static void statusput(const struct message *mp, FILE *obuf,
struct quoteflt *qf, u64 *stats);
static void xstatusput(const struct message *mp, FILE *obuf,
struct quoteflt *qf, u64 *stats);
static void put_from_(FILE *fp, struct mimepart *ip, u64 *stats);
su_SINLINE sz
_out(char const *buf, uz len, FILE *fp, enum conversion convert, enum
sendaction action, struct quoteflt *qf, u64 *stats, struct str *outrest,
struct str *inrest)
{
sz size = 0, n;
int flags;
NYD_IN;
/* TODO We should not need is_head() here, i think in v15 the actual Mailbox
* TODO subclass should detect From_ cases and either re-encode the part
* TODO in question, or perform From_ quoting as necessary!?!?!? How?!? */
/* C99 */{
boole from_;
if((action == SEND_MBOX || action == SEND_DECRYPT) &&
(from_ = is_head(buf, len, TRU1))){
if(from_ != TRUM1 || (mb.mb_active & MB_BAD_FROM_) ||
ok_blook(mbox_rfc4155)){
putc('>', fp);
++size;
}
}
}
flags = ((int)action & _TD_EOF);
action &= ~_TD_EOF;
n = mime_write(buf, len, fp,
action == SEND_MBOX ? CONV_NONE : convert,
flags | ((action == SEND_TODISP || action == SEND_TODISP_ALL ||
action == SEND_TODISP_PARTS ||
action == SEND_QUOTE || action == SEND_QUOTE_ALL)
? TD_ISPR | TD_ICONV
: (action == SEND_TOSRCH || action == SEND_TOPIPE ||
action == SEND_TOFILE)
? TD_ICONV : (action == SEND_SHOW ? TD_ISPR : TD_NONE)),
qf, outrest, inrest);
if (n < 0)
size = n;
else if (n > 0) {
size += n;
if (stats != NULL)
*stats += size;
}
NYD_OU;
return size;
}
static void
_print_part_info(FILE *obuf, struct mimepart const *mpp, /* TODO strtofmt.. */
struct n_ignore const *doitp, int level, struct quoteflt *qf, u64 *stats)
{
char buf[64];
struct str ti, to;
boole want_ct, needsep;
struct str const *cpre, *csuf;
char const *cp;
NYD2_IN;
cpre = csuf = NULL;
#ifdef mx_HAVE_COLOUR
if(mx_COLOUR_IS_ACTIVE()){
struct mx_colour_pen *cpen;
cpen = mx_colour_pen_create(mx_COLOUR_ID_VIEW_PARTINFO, NULL);
if((cpre = mx_colour_pen_to_str(cpen)) != NIL)
csuf = mx_colour_reset_to_str();
}
#endif
/* Take care of "99.99", i.e., 5 */
if ((cp = mpp->m_partstring) == NULL || cp[0] == '\0')
cp = n_qm;
if (level || (cp[0] != '1' && cp[1] == '\0') || (cp[0] == '1' && /* TODO */
cp[1] == '.' && cp[2] != '1')) /* TODO code should not look like so */
_out("\n", 1, obuf, CONV_NONE, SEND_MBOX, qf, stats, NULL, NULL);
/* Part id, content-type, encoding, charset */
if (cpre != NULL)
_out(cpre->s, cpre->l, obuf, CONV_NONE, SEND_MBOX, qf, stats, NULL,NULL);
_out("[-- #", 5, obuf, CONV_NONE, SEND_MBOX, qf, stats, NULL,NULL);
_out(cp, su_cs_len(cp), obuf, CONV_NONE, SEND_MBOX, qf, stats, NULL,NULL);
to.l = snprintf(buf, sizeof buf, " %" PRIuZ "/%" PRIuZ " ",
(uz)mpp->m_lines, (uz)mpp->m_size);
_out(buf, to.l, obuf, CONV_NONE, SEND_MBOX, qf, stats, NULL,NULL);
needsep = FAL0;
if((cp = mpp->m_ct_type_usr_ovwr) != NULL){
_out("+", 1, obuf, CONV_NONE, SEND_MBOX, qf, stats, NULL,NULL);
want_ct = TRU1;
}else if((want_ct = n_ignore_is_ign(doitp,
"content-type", sizeof("content-type") -1)))
cp = mpp->m_ct_type_plain;
if (want_ct && (to.l = su_cs_len(cp)) > 30 &&
su_cs_starts_with_case(cp, "application/")) {
uz const al = sizeof("appl../") -1, fl = sizeof("application/") -1;
uz i = to.l - fl;
char *x = n_autorec_alloc(al + i +1);
su_mem_copy(x, "appl../", al);
su_mem_copy(x + al, cp + fl, i +1);
cp = x;
to.l = al + i;
}
if(cp != NULL){
_out(cp, to.l, obuf, CONV_NONE, SEND_MBOX, qf, stats, NULL,NULL);
needsep = TRU1;
}
if(mpp->m_multipart == NULL/* TODO */ && (cp = mpp->m_ct_enc) != NULL &&
(!su_cs_cmp_case(cp, "7bit") ||
n_ignore_is_ign(doitp, "content-transfer-encoding",
sizeof("content-transfer-encoding") -1))){
if(needsep)
_out(", ", 2, obuf, CONV_NONE, SEND_MBOX, qf, stats, NULL,NULL);
if (to.l > 25 && !su_cs_cmp_case(cp, "quoted-printable"))
cp = "qu.-pr.";
_out(cp, su_cs_len(cp), obuf, CONV_NONE, SEND_MBOX, qf, stats,
NULL,NULL);
needsep = TRU1;
}
if (want_ct && mpp->m_multipart == NULL/* TODO */ &&
(cp = mpp->m_charset) != NULL) {
if(needsep)
_out(", ", 2, obuf, CONV_NONE, SEND_MBOX, qf, stats, NULL,NULL);
_out(cp, su_cs_len(cp), obuf, CONV_NONE, SEND_MBOX, qf, stats,
NULL,NULL);
}
needsep = !needsep;
_out(&" --]"[su_S(su_u8,needsep)], 4 - needsep,
obuf, CONV_NONE, SEND_MBOX, qf, stats, NULL,NULL);
if (csuf != NULL)
_out(csuf->s, csuf->l, obuf, CONV_NONE, SEND_MBOX, qf, stats, NULL,NULL);
_out("\n", 1, obuf, CONV_NONE, SEND_MBOX, qf, stats, NULL,NULL);
/* */
if (mpp->m_content_info & CI_MIME_ERRORS) {
if (cpre != NULL)
_out(cpre->s, cpre->l, obuf, CONV_NONE, SEND_MBOX, qf, stats,
NULL, NULL);
_out("[-- ", 4, obuf, CONV_NONE, SEND_MBOX, qf, stats, NULL, NULL);
ti.l = su_cs_len(ti.s = n_UNCONST(_("Defective MIME structure")));
makeprint(&ti, &to);
to.l = delctrl(to.s, to.l);
_out(to.s, to.l, obuf, CONV_NONE, SEND_MBOX, qf, stats, NULL, NULL);
n_free(to.s);
_out(" --]", 4, obuf, CONV_NONE, SEND_MBOX, qf, stats, NULL, NULL);
if (csuf != NULL)
_out(csuf->s, csuf->l, obuf, CONV_NONE, SEND_MBOX, qf, stats,
NULL, NULL);
_out("\n", 1, obuf, CONV_NONE, SEND_MBOX, qf, stats, NULL, NULL);
}
/* Content-Description */
if (n_ignore_is_ign(doitp, "content-description", 19) &&
(cp = mpp->m_content_description) != NULL && *cp != '\0') {
if (cpre != NULL)
_out(cpre->s, cpre->l, obuf, CONV_NONE, SEND_MBOX, qf, stats,
NULL, NULL);
_out("[-- ", 4, obuf, CONV_NONE, SEND_MBOX, qf, stats, NULL, NULL);
ti.l = su_cs_len(ti.s = n_UNCONST(mpp->m_content_description));
mime_fromhdr(&ti, &to, TD_ISPR | TD_ICONV);
_out(to.s, to.l, obuf, CONV_NONE, SEND_MBOX, qf, stats, NULL, NULL);
n_free(to.s);
_out(" --]", 4, obuf, CONV_NONE, SEND_MBOX, qf, stats, NULL, NULL);
if (csuf != NULL)
_out(csuf->s, csuf->l, obuf, CONV_NONE, SEND_MBOX, qf, stats,
NULL, NULL);
_out("\n", 1, obuf, CONV_NONE, SEND_MBOX, qf, stats, NULL, NULL);
}
/* Filename */
if (n_ignore_is_ign(doitp, "content-disposition", 19) &&
mpp->m_filename != NULL && *mpp->m_filename != '\0') {
if (cpre != NULL)
_out(cpre->s, cpre->l, obuf, CONV_NONE, SEND_MBOX, qf, stats,
NULL, NULL);
_out("[-- ", 4, obuf, CONV_NONE, SEND_MBOX, qf, stats, NULL, NULL);
ti.l = su_cs_len(ti.s = mpp->m_filename);
makeprint(&ti, &to);
to.l = delctrl(to.s, to.l);
_out(to.s, to.l, obuf, CONV_NONE, SEND_MBOX, qf, stats, NULL, NULL);
n_free(to.s);
_out(" --]", 4, obuf, CONV_NONE, SEND_MBOX, qf, stats, NULL, NULL);
if (csuf != NULL)
_out(csuf->s, csuf->l, obuf, CONV_NONE, SEND_MBOX, qf, stats,
NULL, NULL);
_out("\n", 1, obuf, CONV_NONE, SEND_MBOX, qf, stats, NULL, NULL);
}
NYD2_OU;
}
static FILE *
a_send_pipefile(enum sendaction action, struct mx_mimetype_handler *mthp,
struct mimepart const *mpp, FILE **qbuf, char const *tmpname,
int term_infd)
{
static u32 reprocnt;
struct str s;
char const *env_addon[9 +8/*v15*/], *cp, *sh;
uz i;
FILE *rbuf;
NYD_IN;
rbuf = *qbuf;
if(action == SEND_QUOTE || action == SEND_QUOTE_ALL){
if((*qbuf = mx_fs_tmp_open("sendp", (mx_FS_O_RDWR | mx_FS_O_UNLINK |
mx_FS_O_REGISTER), NIL)) == NIL){
n_perr(_("tmpfile"), 0);
*qbuf = rbuf;
}
}
if((mthp->mth_flags & mx_MIMETYPE_HDL_TYPE_MASK) == mx_MIMETYPE_HDL_PTF){
union {int (*ptf)(void); char const *sh;} u;
fflush(*qbuf);
if (*qbuf != n_stdout) /* xxx never? v15: it'll be a filter anyway */
fflush(n_stdout);
u.ptf = mthp->mth_ptf;
if((rbuf = mx_fs_pipe_open(R(char*,-1), "W", u.sh, NIL, fileno(*qbuf))
) == NIL)
goto jerror;
goto jleave;
}
i = 0;
/* MAILX_FILENAME */
if (mpp == NULL || (cp = mpp->m_filename) == NULL)
cp = n_empty;
env_addon[i++] = str_concat_csvl(&s, n_PIPEENV_FILENAME, "=", cp, NULL)->s;
env_addon[i++] = str_concat_csvl(&s, "NAIL_FILENAME", "=", cp, NULL)->s;/*v15*/
/* MAILX_FILENAME_GENERATED *//* TODO pathconf NAME_MAX; but user can create
* TODO a file wherever he wants! *Do* create a zero-size temporary file
* TODO and give *that* path as MAILX_FILENAME_TEMPORARY, clean it up once
* TODO the pipe returns? Like this we *can* verify path/name issues! */
cp = mx_random_create_cp(MIN(NAME_MAX - 3, 16), &reprocnt);
env_addon[i++] = str_concat_csvl(&s, n_PIPEENV_FILENAME_GENERATED, "=", cp,
NULL)->s;
env_addon[i++] = str_concat_csvl(&s, "NAIL_FILENAME_GENERATED", "=", cp,/*v15*/
NULL)->s;
/* MAILX_CONTENT{,_EVIDENCE} */
if (mpp == NULL || (cp = mpp->m_ct_type_plain) == NULL)
cp = n_empty;
env_addon[i++] = str_concat_csvl(&s, n_PIPEENV_CONTENT, "=", cp, NULL)->s;
env_addon[i++] = str_concat_csvl(&s, "NAIL_CONTENT", "=", cp, NULL)->s;/*v15*/
if (mpp != NULL && mpp->m_ct_type_usr_ovwr != NULL)
cp = mpp->m_ct_type_usr_ovwr;
env_addon[i++] = str_concat_csvl(&s, n_PIPEENV_CONTENT_EVIDENCE, "=", cp,
NULL)->s;
env_addon[i++] = str_concat_csvl(&s, "NAIL_CONTENT_EVIDENCE", "=", cp,/* v15 */
NULL)->s;
/* message/external-body, access-type=url */
env_addon[i++] = str_concat_csvl(&s, n_PIPEENV_EXTERNAL_BODY_URL, "=",
((mpp != NULL && (cp = mpp->m_external_body_url) != NULL
) ? cp : n_empty), NULL)->s;
/* MAILX_FILENAME_TEMPORARY? */
if (tmpname != NULL) {
env_addon[i++] = str_concat_csvl(&s,
n_PIPEENV_FILENAME_TEMPORARY, "=", tmpname, NULL)->s;
env_addon[i++] = str_concat_csvl(&s,
"NAIL_FILENAME_TEMPORARY", "=", tmpname, NULL)->s;/* v15 */
}
/* TODO we should include header information, especially From:, so
* TODO that same-origin can be tested for e.g. external-body!!! */
env_addon[i] = NULL;
sh = ok_vlook(SHELL);
if(mthp->mth_flags & mx_MIMETYPE_HDL_NEEDSTERM){
struct mx_child_ctx cc;
sigset_t nset;
sigemptyset(&nset);
mx_child_ctx_setup(&cc);
cc.cc_flags = mx_CHILD_RUN_WAIT_LIFE;
cc.cc_mask = &nset;
cc.cc_fds[mx_CHILD_FD_IN] = term_infd;
cc.cc_cmd = sh;
cc.cc_args[0] = "-c";
cc.cc_args[1] = mthp->mth_shell_cmd;
cc.cc_env_addon = env_addon;
rbuf = !mx_child_run(&cc) ? NIL : R(FILE*,-1);
}else{
rbuf = mx_fs_pipe_open(mthp->mth_shell_cmd, "W", sh, env_addon,
(mthp->mth_flags & mx_MIMETYPE_HDL_ASYNC ? mx_CHILD_FD_NULL
: fileno(*qbuf)));
jerror:
if(rbuf == NIL)
n_err(_("Cannot run MIME type handler: %s: %s\n"),
mthp->mth_msg, su_err_doc(su_err_no()));
else{
fflush(*qbuf);
if(*qbuf != n_stdout)
fflush(n_stdout);
}
}
jleave:
NYD_OU;
return rbuf;
}
static boole
a_send_out_nl(FILE *fp, struct quoteflt *qf, u64 *stats){
boole rv;
NYD2_IN;
if(qf == NIL)
qf = quoteflt_dummy();
quoteflt_reset(qf, fp);
rv = (_out("\n", 1, fp, CONV_NONE, SEND_MBOX, qf, stats, NIL,NIL) > 0);
quoteflt_flush(qf);
NYD2_OU;
return rv;
}
static void
_send_onpipe(int signo)
{
NYD; /* Signal handler */
UNUSED(signo);
siglongjmp(_send_pipejmp, 1);
}
static sigjmp_buf __sendp_actjmp; /* TODO someday.. */
static int __sendp_sig; /* TODO someday.. */
static n_sighdl_t __sendp_opipe;
static void
__sendp_onsig(int sig) /* TODO someday, we won't need it no more */
{
NYD; /* Signal handler */
__sendp_sig = sig;
siglongjmp(__sendp_actjmp, 1);
}
static int
sendpart(struct message *zmp, struct mimepart *ip, FILE * volatile obuf,
struct n_ignore const *doitp, struct quoteflt *qf,
enum sendaction volatile action,
char **linedat, uz *linesize, u64 * volatile stats, int volatile level,
boole *anyoutput)
{
int volatile rv = 0;
struct mx_mimetype_handler mth_stack, * volatile mthp;
struct str outrest, inrest;
boole hany, hign;
enum sendaction oaction;
char *cp;
char const * volatile tmpname = NULL;
uz linelen, cnt;
int volatile dostat, term_infd;
int c;
struct mimepart * volatile np;
FILE * volatile ibuf = NULL, * volatile pbuf = obuf,
* volatile qbuf = obuf, *origobuf = obuf;
enum conversion volatile convert;
n_sighdl_t volatile oldpipe = SIG_DFL;
NYD_IN;
UNINIT(term_infd, 0);
UNINIT(cnt, 0);
oaction = action;
hany = hign = FAL0;
quoteflt_reset(qf, obuf);
if((ibuf = setinput(&mb, R(struct message*,ip), NEED_BODY)) == NIL){
rv = -1;
goto jleave;
}
cnt = ip->m_size;
dostat = 0;
if(action == SEND_TODISP || action == SEND_TODISP_ALL ||
action == SEND_TODISP_PARTS ||
action == SEND_QUOTE || action == SEND_QUOTE_ALL ||
action == SEND_TOSRCH){
dostat |= 4;
if(ip->m_mimetype != mx_MIMETYPE_DISCARD && level != 0 &&
action != SEND_QUOTE && action != SEND_QUOTE_ALL){
_print_part_info(obuf, ip, doitp, level, qf, stats);
hany = TRU1;
}
if(ip->m_parent != NIL && ip->m_parent->m_mimetype == mx_MIMETYPE_822){
ASSERT(ip->m_flag & MNOFROM);
hign = TRU1;
}
}
if(ip->m_mimetype == mx_MIMETYPE_DISCARD)
goto jheaders_skip;
if (ip->m_mimetype == mx_MIMETYPE_PKCS7) {
if (ip->m_multipart &&
action != SEND_MBOX && action != SEND_RFC822 && action != SEND_SHOW)
goto jheaders_skip;
}
if(!(ip->m_flag & MNOFROM))
while(cnt > 0 && (c = getc(ibuf)) != EOF){
--cnt;
if(c == '\n')
break;
}
if(!hign && level == 0 && action != SEND_TODISP_PARTS){
if(doitp != NIL){
if(!n_ignore_is_ign(doitp, "status", 6))
dostat |= 1;
if(!n_ignore_is_ign(doitp, "x-status", 8))
dostat |= 2;
}else
dostat |= 3;
}
jhdr_redo:
convert = (dostat & 4) ? CONV_FROMHDR : CONV_NONE;
/* Work the headers */
/* C99 */{
struct n_string hl, *hlp;
uz lineno;
boole hstop;
hlp = n_string_creat_auto(&hl); /* TODO pool [or, v15: filter!] */
/* Reserve three lines, still not enough for references and DKIM etc. */
hlp = n_string_reserve(hlp, MAX(MIME_LINELEN, MIME_LINELEN_RFC2047) * 3);
lineno = 0;
for(hstop = FAL0; !hstop;){
uz lcnt;
lcnt = cnt;
if(fgetline(linedat, linesize, &cnt, &linelen, ibuf, FAL0) == NIL)
break;
++lineno;
if (linelen == 0 || (cp = *linedat)[0] == '\n')
/* If line is blank, we've reached end of headers */
break;
if(cp[linelen - 1] == '\n'){
cp[--linelen] = '\0';
if(linelen == 0)
break;
}
/* Are we in a header? */
if(hlp->s_len > 0){
if(!su_cs_is_blank(*cp)){
fseek(ibuf, -(off_t)(lcnt - cnt), SEEK_CUR);
cnt = lcnt;
goto jhdrput;
}
goto jhdrpush;
}else{
/* Pick up the header field if we have one */
while((c = *cp) != ':' && !su_cs_is_space(c) && c != '\0')
++cp;
for(;;){
if(!su_cs_is_space(c) || c == '\0')
break;
c = *++cp;
}
if(c != ':'){
/* That won't work with MIME when saving etc., before v15 */
if (lineno != 1)
/* XXX This disturbs, and may happen multiple times, and we
* XXX cannot heal it for multipart except for display <v15 */
n_err(_("Malformed message: headers and body not separated "
"(with empty line)\n"));
if(level != 0)
dostat &= ~(1 | 2);
fseek(ibuf, -(off_t)(lcnt - cnt), SEEK_CUR);
cnt = lcnt;
break;
}
cp = *linedat;
jhdrpush:
if(!(dostat & 4)){
hlp = n_string_push_buf(hlp, cp, (u32)linelen);
hlp = n_string_push_c(hlp, '\n');
}else{
boole lblank, xblank;
for(lblank = FAL0, lcnt = 0; lcnt < linelen; ++cp, ++lcnt){
char c8;
c8 = *cp;
if(!(xblank = su_cs_is_blank(c8)) || !lblank){
if((lblank = xblank))
c8 = ' ';
hlp = n_string_push_c(hlp, c8);
}
}
}
continue;
}
jhdrput:
/* If it is an ignored header, skip it */
*(cp = su_mem_find(hlp->s_dat, ':', hlp->s_len)) = '\0';
/* C99 */{
uz i;
i = P2UZ(cp - hlp->s_dat);
if(hign || (doitp != NULL && n_ignore_is_ign(doitp, hlp->s_dat, i)) ||
!su_cs_cmp_case(hlp->s_dat, "status") ||
!su_cs_cmp_case(hlp->s_dat, "x-status") ||
(action == SEND_MBOX &&
(!su_cs_cmp_case(hlp->s_dat, "content-length") ||
!su_cs_cmp_case(hlp->s_dat, "lines")) &&
!ok_blook(keep_content_length)))
goto jhdrtrunc;
}
/* Dump it */
if(!hany && (dostat & 4) && level > 0)
a_send_out_nl(obuf, NIL, stats);
mx_COLOUR(
if(mx_COLOUR_IS_ACTIVE())
mx_colour_put(mx_COLOUR_ID_VIEW_HEADER, hlp->s_dat);
)
*cp = ':';
_out(hlp->s_dat, hlp->s_len, obuf, convert, action, qf, stats, NIL,NIL);
mx_COLOUR(
if(mx_COLOUR_IS_ACTIVE())
mx_colour_reset();
)
if(dostat & 4)
a_send_out_nl(obuf, qf, stats);
hany = TRU1;
jhdrtrunc:
hlp = n_string_trunc(hlp, 0);
}
hstop = TRU1;
if(hlp->s_len > 0)
goto jhdrput;
if(hign /*|| (!hany && (dostat & (1 | 2)))*/){
a_send_out_nl(obuf, qf, stats);
if(hign)
goto jheaders_skip;
}
/* We have reached end of headers, so eventually force out status: field
* and note that we are no longer in header fields */
if(dostat & 1){
statusput(zmp, obuf, qf, stats);
hany = TRU1;
}
if(dostat & 2){
xstatusput(zmp, obuf, qf, stats);
hany = TRU1;
}
if((hany /*&& doitp != n_IGNORE_ALL*/) ||
(oaction == SEND_DECRYPT && ip->m_parent != NIL &&
ip != ip->m_multipart) ||
((oaction == SEND_QUOTE || oaction == SEND_QUOTE_ALL) &&
level != 0 && *anyoutput &&
(ip->m_mimetype != mx_MIMETYPE_DISCARD &&
ip->m_mimetype != mx_MIMETYPE_PKCS7 &&
ip->m_mimetype != mx_MIMETYPE_PKCS7 &&
ip->m_mimetype != mx_MIMETYPE_ALTERNATIVE &&
ip->m_mimetype != mx_MIMETYPE_RELATED &&
ip->m_mimetype != mx_MIMETYPE_DIGEST &&
ip->m_mimetype != mx_MIMETYPE_MULTI &&
ip->m_mimetype != mx_MIMETYPE_SIGNED &&
ip->m_mimetype != mx_MIMETYPE_ENCRYPTED))){
if(ip->m_mimetype != mx_MIMETYPE_822 || (dostat & 16)){
/*XXX (void)*/a_send_out_nl(obuf, NIL, stats);
hany = TRU1;
}
}
} /* C99 */
quoteflt_flush(qf);
if(ferror(ibuf) || ferror(obuf)){
rv = -1;
goto jleave;
}
*anyoutput = hany;
jheaders_skip:
su_mem_set(mthp = &mth_stack, 0, sizeof mth_stack);
if(oaction == SEND_MBOX){
convert = CONV_NONE;
goto jsend;
}
switch (ip->m_mimetype) {
case mx_MIMETYPE_822:
switch (action) {
case SEND_TODISP_PARTS:
goto jleave;
case SEND_TODISP:
case SEND_TODISP_ALL:
case SEND_QUOTE:
case SEND_QUOTE_ALL:
if(!(dostat & 16)){ /* XXX */
dostat |= 16;
a_send_out_nl(obuf, qf, stats);
if(ok_blook(rfc822_body_from_)){
if(!qf->qf_bypass){
uz i;
i = fwrite(qf->qf_pfix, sizeof *qf->qf_pfix, qf->qf_pfix_len,
obuf);
if(i == qf->qf_pfix_len && stats != NIL)
*stats += i;
}
put_from_(obuf, ip->m_multipart, stats);
hany = TRU1;
}
goto jhdr_redo;
}
goto jmulti;
case SEND_TOSRCH:
goto jmulti;
case SEND_DECRYPT:
goto jmulti;
case SEND_TOFILE:
case SEND_TOPIPE:
put_from_(obuf, ip->m_multipart, stats);
/* FALLTHRU */
default:
break;
}
break;
case mx_MIMETYPE_TEXT_HTML:
case mx_MIMETYPE_TEXT:
case mx_MIMETYPE_TEXT_PLAIN:
switch (action) {
case SEND_TODISP:
case SEND_TODISP_ALL:
case SEND_TODISP_PARTS:
case SEND_QUOTE:
case SEND_QUOTE_ALL:
if((mthp = ip->m_handler) == NIL)
mx_mimetype_handler(mthp =
ip->m_handler = n_autorec_alloc(sizeof(*mthp)), ip, oaction);
switch(mthp->mth_flags & mx_MIMETYPE_HDL_TYPE_MASK){
case mx_MIMETYPE_HDL_NIL:
if(oaction != SEND_TODISP_PARTS)
break;
/* FALLTHRU */
case mx_MIMETYPE_HDL_MSG:/* TODO these should be part of partinfo! */
if(mthp->mth_msg.l > 0)
_out(mthp->mth_msg.s, mthp->mth_msg.l, obuf, CONV_NONE,
SEND_MBOX, qf, stats, NULL, NULL);
/* We would print this as plain text, so better force going home */
goto jleave;
case mx_MIMETYPE_HDL_CMD:
if(oaction == SEND_TODISP_PARTS){
if(mthp->mth_flags & mx_MIMETYPE_HDL_COPIOUSOUTPUT)
goto jleave;
else{
/* Because: interactive OR batch mode, so */
if(!mx_tty_yesorno(_("Run MIME handler for this part?"),
su_state_has(su_STATE_REPRODUCIBLE)))
goto jleave;
}
}
break;
case mx_MIMETYPE_HDL_TEXT:
case mx_MIMETYPE_HDL_PTF:
if(oaction == SEND_TODISP_PARTS)
goto jleave;
break;
default:
break;
}
/* FALLTRHU */
default:
break;
}
break;
case mx_MIMETYPE_DISCARD:
if(oaction != SEND_DECRYPT)
goto jleave;
break;
case mx_MIMETYPE_PKCS7:
if(oaction != SEND_RFC822 && oaction != SEND_SHOW &&
ip->m_multipart != NIL)
goto jmulti;
/* FALLTHRU */
default:
switch (action) {
case SEND_TODISP:
case SEND_TODISP_ALL:
case SEND_TODISP_PARTS:
case SEND_QUOTE:
case SEND_QUOTE_ALL:
if((mthp = ip->m_handler) == NIL)
mx_mimetype_handler(mthp = ip->m_handler =
n_autorec_alloc(sizeof(*mthp)), ip, oaction);
switch(mthp->mth_flags & mx_MIMETYPE_HDL_TYPE_MASK){
default:
case mx_MIMETYPE_HDL_NIL:
if (oaction != SEND_TODISP && oaction != SEND_TODISP_ALL &&
(level != 0 || cnt))
goto jleave;
/* FALLTHRU */
case mx_MIMETYPE_HDL_MSG:/* TODO these should be part of partinfo! */
if(mthp->mth_msg.l > 0)
_out(mthp->mth_msg.s, mthp->mth_msg.l, obuf, CONV_NONE,
SEND_MBOX, qf, stats, NULL, NULL);
/* We would print this as plain text, so better force going home */
goto jleave;
case mx_MIMETYPE_HDL_CMD:
if(oaction == SEND_TODISP_PARTS){
if(mthp->mth_flags & mx_MIMETYPE_HDL_COPIOUSOUTPUT)
goto jleave;
else{
/* Because: interactive OR batch mode, so */
if(!mx_tty_yesorno(_("Run MIME handler for this part?"),
su_state_has(su_STATE_REPRODUCIBLE)))
goto jleave;
}
}
break;
case mx_MIMETYPE_HDL_TEXT:
case mx_MIMETYPE_HDL_PTF:
if(oaction == SEND_TODISP_PARTS)
goto jleave;
break;
}
break;
default:
break;
}
break;
case mx_MIMETYPE_ALTERNATIVE:
if ((oaction == SEND_TODISP || oaction == SEND_QUOTE) &&
!ok_blook(print_alternatives)) {
/* XXX This (a) should not remain (b) should be own fun
* TODO (despite the fact that v15 will do this completely differently
* TODO by having an action-specific "manager" that will traverse the
* TODO parsed MIME tree and decide for each part whether it'll be
* TODO displayed or not *before* we walk the tree for doing action */
struct mpstack {
struct mpstack *outer;
struct mimepart *mp;
} outermost, * volatile curr, * volatile mpsp;
enum {
_NONE,
_DORICH = 1<<0, /* We are looking for rich parts */
_HADPART = 1<<1, /* Did print a part already */
_NEEDNL = 1<<3 /* Need a visual separator */
} flags;
struct n_sigman smalter;
(curr = &outermost)->outer = NULL;
curr->mp = ip;
flags = ok_blook(mime_alternative_favour_rich) ? _DORICH : _NONE;
if(!_send_al7ive_have_better(ip->m_multipart, action,
((flags & _DORICH) != 0)))
flags ^= _DORICH;
n_SIGMAN_ENTER_SWITCH(&smalter, n_SIGMAN_ALL) {
case 0:
break;
default:
rv = -1;
goto jalter_leave;
}
for(np = ip->m_multipart;;){
jalter_redo:
level = -ABS(level);
for(; np != NIL; np = np->m_nextpart){
level = -ABS(level);
flags |= _NEEDNL;
switch(np->m_mimetype){
case mx_MIMETYPE_ALTERNATIVE:
case mx_MIMETYPE_RELATED:
case mx_MIMETYPE_DIGEST:
case mx_MIMETYPE_SIGNED:
case mx_MIMETYPE_ENCRYPTED:
case mx_MIMETYPE_MULTI:
np->m_flag &= ~MDISPLAY;
mpsp = n_autorec_alloc(sizeof *mpsp);
mpsp->outer = curr;
mpsp->mp = np->m_multipart;
curr->mp = np;
curr = mpsp;
np = mpsp->mp;
flags &= ~_NEEDNL;
goto jalter_redo;
default:
if(!(np->m_flag & MDISPLAY)){
if(np->m_mimetype != mx_MIMETYPE_DISCARD &&
(action == SEND_TODISP ||
action == SEND_TODISP_ALL ||
action == SEND_TODISP_PARTS))
_print_part_info(obuf, np, doitp, level, qf, stats);
break;
}
/* This thing we are going to do */
quoteflt_flush(qf);
flags |= _HADPART;
flags &= ~_NEEDNL;
rv = ABS(level) + 1;
if(level < 0){
level = -level;
rv = -rv;
}
rv = sendpart(zmp, np, obuf, doitp, qf, oaction,
linedat, linesize, stats, rv, anyoutput);
quoteflt_reset(qf, origobuf);
if (rv < 0)
curr = &outermost; /* Cause overall loop termination */
break;
}
}
mpsp = curr->outer;
if (mpsp == NULL)
break;
curr = mpsp;
np = curr->mp->m_nextpart;
}
jalter_leave:
n_sigman_leave(&smalter, n_SIGMAN_VIPSIGS_NTTYOUT);
goto jleave;
}
/* FALLTHRU */
case mx_MIMETYPE_RELATED:
case mx_MIMETYPE_DIGEST:
case mx_MIMETYPE_SIGNED:
case mx_MIMETYPE_ENCRYPTED:
case mx_MIMETYPE_MULTI:
switch(action){
case SEND_TODISP:
case SEND_TODISP_ALL:
case SEND_TODISP_PARTS:
case SEND_QUOTE:
case SEND_QUOTE_ALL:
case SEND_TOFILE:
case SEND_TOPIPE:
case SEND_TOSRCH:
case SEND_DECRYPT:
jmulti:
if((oaction == SEND_TODISP || oaction == SEND_TODISP_ALL) &&
ip->m_multipart != NIL &&
ip->m_multipart->m_mimetype == mx_MIMETYPE_DISCARD &&
ip->m_multipart->m_nextpart == NULL) {
char const *x = _("[Missing multipart boundary - use `show' "
"to display the raw message]\n");
_out(x, su_cs_len(x), obuf, CONV_NONE, SEND_MBOX, qf, stats,
NULL,NULL);
}
level = -ABS(level);
for (np = ip->m_multipart; np != NULL; np = np->m_nextpart) {
boole volatile ispipe;
if(np->m_mimetype == mx_MIMETYPE_DISCARD &&
oaction != SEND_DECRYPT)
continue;
ispipe = FAL0;
switch(oaction){
case SEND_TOFILE:
if (np->m_partstring &&
np->m_partstring[0] == '1' && np->m_partstring[1] == '\0')
break;
stats = NULL;
/* TODO Always open multipart on /dev/null, it's a hack to be
* TODO able to dive into that structure, and still better
* TODO than asking the user for something stupid.
* TODO oh, wait, we did ask for a filename for this MIME mail,
* TODO and that outer container is useless anyway ;-P */
if(np->m_multipart != NULL &&
np->m_mimetype != mx_MIMETYPE_822){
if((obuf = mx_fs_open(n_path_devnull, "w")) == NIL)
continue;
}else if((obuf = newfile(np, &ispipe)) == NIL)
continue;
if(ispipe){
oldpipe = safe_signal(SIGPIPE, &_send_onpipe);
if(sigsetjmp(_send_pipejmp, 1)){
rv = -1;
goto jpipe_close;
}
}
break;
default:
break;
}
quoteflt_flush(qf);
{
int nlvl = ABS(level) + 1;
if(level < 0){
level = -level;
nlvl = -nlvl;
}
if(sendpart(zmp, np, obuf, doitp, qf, oaction, linedat,
linesize, stats, nlvl, anyoutput) < 0)
rv = -1;
}
quoteflt_reset(qf, origobuf);
if(oaction == SEND_QUOTE){
if(ip->m_mimetype != mx_MIMETYPE_RELATED)
break;
}
if(oaction == SEND_TOFILE && obuf != origobuf){
if(!ispipe)
mx_fs_close(obuf);
else {
jpipe_close:
mx_fs_pipe_close(obuf, TRU1);
safe_signal(SIGPIPE, oldpipe);
}
}
}
goto jleave;
default:
break;
}
break;
}
/* Copy out message body */
if (doitp == n_IGNORE_ALL && level == 0) /* skip final blank line */
--cnt;
switch (ip->m_mime_enc) {
case MIMEE_BIN:
case MIMEE_7B:
case MIMEE_8B:
convert = CONV_NONE;
break;
case MIMEE_QP:
convert = CONV_FROMQP;
break;
case MIMEE_B64:
switch(ip->m_mimetype){
case mx_MIMETYPE_TEXT:
case mx_MIMETYPE_TEXT_PLAIN:
case mx_MIMETYPE_TEXT_HTML:
convert = CONV_FROMB64_T;
break;
default:
switch (mthp->mth_flags & mx_MIMETYPE_HDL_TYPE_MASK) {
case mx_MIMETYPE_HDL_TEXT:
case mx_MIMETYPE_HDL_PTF:
convert = CONV_FROMB64_T;
break;
default:
convert = CONV_FROMB64;
break;
}
break;
}
break;
default:
convert = CONV_NONE;
}
/* TODO Unless we have filters, ensure iconvd==-1 so that mime.c:fwrite_td()
* TODO cannot mess things up misusing outrest as line buffer */
#ifdef mx_HAVE_ICONV
if (iconvd != (iconv_t)-1) {
n_iconv_close(iconvd);
iconvd = (iconv_t)-1;
}
#endif
if(oaction == SEND_DECRYPT || oaction == SEND_MBOX ||
oaction == SEND_RFC822 || oaction == SEND_SHOW)
convert = CONV_NONE;
#ifdef mx_HAVE_ICONV
else if((oaction == SEND_TODISP || oaction == SEND_TODISP_ALL ||
oaction == SEND_TODISP_PARTS ||
oaction == SEND_QUOTE || oaction == SEND_QUOTE_ALL ||
oaction == SEND_TOSRCH || oaction == SEND_TOFILE) &&
(ip->m_mimetype == mx_MIMETYPE_TEXT_PLAIN ||
ip->m_mimetype == mx_MIMETYPE_TEXT_HTML ||
ip->m_mimetype == mx_MIMETYPE_TEXT ||
(mthp->mth_flags & mx_MIMETYPE_HDL_TYPE_MASK
) == mx_MIMETYPE_HDL_TEXT ||
(mthp->mth_flags & mx_MIMETYPE_HDL_TYPE_MASK
) == mx_MIMETYPE_HDL_PTF)) {
char const *tcs;
tcs = ok_vlook(ttycharset);
if (su_cs_cmp_case(tcs, ip->m_charset) &&
su_cs_cmp_case(ok_vlook(charset_7bit), ip->m_charset)) {
iconvd = n_iconv_open(tcs, ip->m_charset);
if (iconvd == (iconv_t)-1 && su_err_no() == su_ERR_INVAL) {
n_err(_("Cannot convert from %s to %s\n"), ip->m_charset, tcs);
/*rv = 1; goto jleave;*/
}
}
}
#endif
switch (mthp->mth_flags & mx_MIMETYPE_HDL_TYPE_MASK) {
case mx_MIMETYPE_HDL_CMD:
if(!(mthp->mth_flags & mx_MIMETYPE_HDL_COPIOUSOUTPUT)){
if(oaction != SEND_TODISP_PARTS)
goto jmthp_default;
/* FIXME Ach, what a hack! We need filters.. v15! */
if(convert != CONV_FROMB64_T)
action = SEND_TOPIPE;
}
/* FALLTHRU */
case mx_MIMETYPE_HDL_PTF:
tmpname = NULL;
qbuf = obuf;
term_infd = mx_CHILD_FD_PASS;
if(mthp->mth_flags & (mx_MIMETYPE_HDL_TMPF | mx_MIMETYPE_HDL_NEEDSTERM)){
struct mx_fs_tmp_ctx *fstcp;
char const *pref;
BITENUM_IS(u32,mx_fs_oflags) of;
of = mx_FS_O_RDWR | mx_FS_O_REGISTER;
if(!(mthp->mth_flags & mx_MIMETYPE_HDL_TMPF)){
term_infd = 0;
mthp->mth_flags |= mx_MIMETYPE_HDL_TMPF_FILL;
of |= mx_FS_O_UNLINK;
pref = "mtanonfill";
}else{
/* (async and unlink are mutual exclusive) */
if(mthp->mth_flags & mx_MIMETYPE_HDL_TMPF_UNLINK)
of |= mx_FS_O_REGISTER_UNLINK;
if(mthp->mth_flags & mx_MIMETYPE_HDL_TMPF_NAMETMPL){
pref = mthp->mth_tmpf_nametmpl;
if(mthp->mth_flags & mx_MIMETYPE_HDL_TMPF_NAMETMPL_SUFFIX)
of |= mx_FS_O_SUFFIX;
}else if(mthp->mth_flags & mx_MIMETYPE_HDL_TMPF_FILL)
pref = "mimetypefill";
else
pref = "mimetype";
}
if((pbuf = mx_fs_tmp_open(pref, of,
(mthp->mth_flags & mx_MIMETYPE_HDL_TMPF ? &fstcp : NIL))
) == NIL)
goto jesend;
if(mthp->mth_flags & mx_MIMETYPE_HDL_TMPF)
tmpname = fstcp->fstc_filename; /* In autorec storage! */
if(mthp->mth_flags & mx_MIMETYPE_HDL_TMPF_FILL){
action = SEND_TOPIPE;
if(term_infd == 0)
term_infd = fileno(pbuf);
goto jsend;
}
}
jpipe_for_real:
pbuf = a_send_pipefile(oaction, mthp, ip, UNVOLATILE(FILE**,&qbuf),
tmpname, term_infd);
if(pbuf == NIL){
jesend:
pbuf = qbuf = NIL;
rv = -1;
goto jend;
}else if((mthp->mth_flags & mx_MIMETYPE_HDL_NEEDSTERM) &&
pbuf == R(FILE*,-1)){
pbuf = qbuf = NIL;
goto jend;
}
tmpname = NIL;
action = SEND_TOPIPE;
if (pbuf != qbuf) {
oldpipe = safe_signal(SIGPIPE, &_send_onpipe);
if (sigsetjmp(_send_pipejmp, 1))
goto jend;
}
break;
default:
jmthp_default:
mthp->mth_flags = mx_MIMETYPE_HDL_NIL;
pbuf = qbuf = obuf;
break;
}
jsend:
{
boole volatile eof;
boole save_qf_bypass = qf->qf_bypass;
u64 *save_stats = stats;
if (pbuf != origobuf) {
qf->qf_bypass = TRU1;/* XXX legacy (remove filter instead) */
stats = NULL;
}
eof = FAL0;
outrest.s = inrest.s = NULL;
outrest.l = inrest.l = 0;
if (pbuf == qbuf) {
__sendp_sig = 0;
__sendp_opipe = safe_signal(SIGPIPE, &__sendp_onsig);
if (sigsetjmp(__sendp_actjmp, 1)) {
n_pstate &= ~n_PS_BASE64_STRIP_CR;/* (but outer sigman protected) */
if (outrest.s != NULL)
n_free(outrest.s);
if (inrest.s != NULL)
n_free(inrest.s);
#ifdef mx_HAVE_ICONV
if (iconvd != (iconv_t)-1)
n_iconv_close(iconvd);
#endif
safe_signal(SIGPIPE, __sendp_opipe);
n_raise(__sendp_sig);
}
}
quoteflt_reset(qf, pbuf);
if(dostat & 4){
if(pbuf == origobuf) /* TODO */
n_pstate |= n_PS_BASE64_STRIP_CR;
}
while(!eof && fgetline(linedat, linesize, &cnt, &linelen, ibuf, FAL0)){
joutln:
if (_out(*linedat, linelen, pbuf, convert, action, qf, stats, &outrest,
(action & _TD_EOF ? NULL : &inrest)) < 0 || ferror(pbuf)) {
rv = -1; /* XXX Should bail away?! */
break;
}
}
if(ferror(ibuf))
rv = -1;
if(eof <= FAL0 && rv >= 0 && (outrest.l != 0 || inrest.l != 0)){
linelen = 0;
if(eof || inrest.l == 0)
action |= _TD_EOF;
eof = eof ? TRU1 : TRUM1;
goto joutln;
}
n_pstate &= ~n_PS_BASE64_STRIP_CR;
action &= ~_TD_EOF;
/* TODO HACK: when sending to the display we yet get fooled if a message
* TODO doesn't end in a newline, because of our input/output 1:1.
* TODO This should be handled automatically by a display filter, then */
if(rv >= 0 && !qf->qf_nl_last &&
(action == SEND_TODISP || action == SEND_TODISP_ALL ||
action == SEND_QUOTE || action == SEND_QUOTE_ALL))
rv = quoteflt_push(qf, "\n", 1);
quoteflt_flush(qf);
if(!(qf->qf_bypass = save_qf_bypass))
*anyoutput = TRU1;
stats = save_stats;
if (rv >= 0 && (mthp->mth_flags & mx_MIMETYPE_HDL_TMPF_FILL)) {
mthp->mth_flags &= ~mx_MIMETYPE_HDL_TMPF_FILL;
fflush(pbuf);
really_rewind(pbuf);
/* Don't fs_close() a tmp_open() thing due to FS_O_UNREGISTER_UNLINK++ */
goto jpipe_for_real;
}
if (pbuf == qbuf)
safe_signal(SIGPIPE, __sendp_opipe);
if (outrest.s != NULL)
n_free(outrest.s);
if (inrest.s != NULL)
n_free(inrest.s);
}
jend:
if(pbuf != qbuf){
mx_fs_pipe_close(pbuf, !(mthp->mth_flags & mx_MIMETYPE_HDL_ASYNC));
safe_signal(SIGPIPE, oldpipe);
if (rv >= 0 && qbuf != NULL && qbuf != obuf){
*anyoutput = TRU1;
if(!a_send_pipecpy(qbuf, obuf, origobuf, qf, stats))
rv = -1;
}
}
#ifdef mx_HAVE_ICONV
if (iconvd != (iconv_t)-1)
n_iconv_close(iconvd);
#endif
jleave:
NYD_OU;
return rv;
}
static boole
_send_al7ive_have_better(struct mimepart *mpp, enum sendaction action,
boole want_rich){
struct mimepart *plain, *rich;
boole rv;
NYD_IN;
rv = FAL0;
plain = rich = NIL;
for(; mpp != NIL; mpp = mpp->m_nextpart){
switch(mpp->m_mimetype){
case mx_MIMETYPE_TEXT_PLAIN:
plain = mpp;
if(!want_rich)
goto jfound;
continue;
case mx_MIMETYPE_ALTERNATIVE:
case mx_MIMETYPE_RELATED:
case mx_MIMETYPE_DIGEST:
case mx_MIMETYPE_SIGNED:
case mx_MIMETYPE_ENCRYPTED:
case mx_MIMETYPE_MULTI:
/* Be simple and recurse */
if(_send_al7ive_have_better(mpp->m_multipart, action, want_rich))
goto jleave;
continue;
default:
break;
}
if(mpp->m_handler == NIL)
mx_mimetype_handler(mpp->m_handler =
su_AUTO_ALLOC(sizeof(*mpp->m_handler)), mpp, action);
switch(mpp->m_handler->mth_flags & mx_MIMETYPE_HDL_TYPE_MASK){
case mx_MIMETYPE_HDL_TEXT:
if(!want_rich)
goto jfound;
if(plain == NIL)
plain = mpp;
break;
case mx_MIMETYPE_HDL_PTF:
if(want_rich)
goto jfound;
if(rich == NIL ||
(rich->m_handler->mth_flags & mx_MIMETYPE_HDL_TYPE_MASK
) != mx_MIMETYPE_HDL_PTF)
rich = mpp;
break;
case mx_MIMETYPE_HDL_CMD:
if(mpp->m_handler->mth_flags & mx_MIMETYPE_HDL_COPIOUSOUTPUT){
if(want_rich)
goto jfound;
if(rich == NIL)
rich = mpp;
}
/* FALLTHRU */
default:
break;
}
}
/* Without plain part at all, choose an existing rich no matter what */
if((mpp = plain) != NIL || (mpp = rich) != NIL){
jfound:
mpp->m_flag |= MDISPLAY;
ASSERT(mpp->m_parent != NIL);
mpp->m_parent->m_flag |= MDISPLAY;
rv = TRU1;
}
jleave:
NYD_OU;
return rv;
}
static FILE *
newfile(struct mimepart *ip, boole volatile *ispipe)
{
struct str in, out;
char *f;
FILE *fp;
NYD_IN;
f = ip->m_filename;
*ispipe = FAL0;
if (f != NULL && f != (char*)-1) {
in.s = f;
in.l = su_cs_len(f);
makeprint(&in, &out);
out.l = delctrl(out.s, out.l);
f = savestrbuf(out.s, out.l);
n_free(out.s);
}
/* In interactive mode, let user perform all kind of expansions as desired,
* and offer |SHELL-SPEC pipe targets, too */
if (n_psonce & n_PSO_INTERACTIVE) {
struct str prompt;
struct n_string shou, *shoup;
char *f2, *f3;
shoup = n_string_creat_auto(&shou);
/* TODO If the current part is the first textpart the target
* TODO is implicit from outer `write' etc! */
/* I18N: Filename input prompt with file type indication */
str_concat_csvl(&prompt, _("Enter filename for part "),
(ip->m_partstring != NULL ? ip->m_partstring : n_qm),
" (", ip->m_ct_type_plain, "): ", NULL);
jgetname:
while(mx_tty_getfilename(shoup,
(n_GO_INPUT_CTX_DEFAULT | n_GO_INPUT_HIST_ADD), prompt.s,
((f != R(char*,-1) && f != NIL) ? n_shexp_quote_cp(f, FAL0) : NIL
)) < TRU1){
}
f2 = n_string_cp(shoup);
if(*f2 == '\0') {
if(n_poption & n_PO_D_V)
n_err(_("... skipping this\n"));
n_string_gut(shoup);
fp = NIL;
goto jleave;
}
if(*f2 == '|')
/* Pipes are expanded by the shell */
f = f2;
else if((f3 = fexpand(f2, (FEXP_LOCAL_FILE | FEXP_NVAR))) == NIL)
/* (Error message written by fexpand()) */
goto jgetname;
else
f = f3;
n_string_gut(shoup);
}
if (f == NULL || f == (char*)-1 || *f == '\0')
fp = NULL;
else if(n_psonce & n_PSO_INTERACTIVE){
if(*f == '|'){
fp = mx_fs_pipe_open(&f[1], "w", ok_vlook(SHELL), NIL, -1);
if(!(*ispipe = (fp != NIL)))
n_perr(f, 0);
}else if((fp = mx_fs_open(f, "w")) == NIL)
n_err(_("Cannot open %s\n"), n_shexp_quote_cp(f, FAL0));
}else{
/* Be very picky in non-interactive mode: actively disallow pipes,
* prevent directory separators, and any filename member that would
* become expanded by the shell if the name would be echo(1)ed */
if(su_cs_first_of(f, "/" n_SHEXP_MAGIC_PATH_CHARS) != su_UZ_MAX){
char c;
for(out.s = n_autorec_alloc((su_cs_len(f) * 3) +1), out.l = 0;
(c = *f++) != '\0';)
if(su_cs_find_c("/" n_SHEXP_MAGIC_PATH_CHARS, c)){
out.s[out.l++] = '%';
n_c_to_hex_base16(&out.s[out.l], c);
out.l += 2;
}else
out.s[out.l++] = c;
out.s[out.l] = '\0';
f = out.s;
}
/* Avoid overwriting of existing files */
while((fp = mx_fs_open(f, "wx")) == NIL){
int e;
if((e = su_err_no()) != su_ERR_EXIST){
n_err(_("Cannot open %s: %s\n"),
n_shexp_quote_cp(f, FAL0), su_err_doc(e));
break;
}
if(ip->m_partstring != NULL)
f = savecatsep(f, '#', ip->m_partstring);
else
f = savecat(f, "#.");
}
}
jleave:
NYD_OU;
return fp;
}
static boole
a_send_pipecpy(FILE *pipebuf, FILE *outbuf, FILE *origobuf,
struct quoteflt *qf, u64 *stats){
sz all_sz, i;
uz linesize, linelen, cnt;
char *line;
boole rv;
NYD_IN;
rv = TRU1;
mx_fs_linepool_aquire(&line, &linesize);
quoteflt_reset(qf, outbuf);
fflush_rewind(pipebuf);
cnt = S(uz,fsize(pipebuf));
all_sz = 0;
while(fgetline(&line, &linesize, &cnt, &linelen, pipebuf, FAL0) != NIL){
if((i = quoteflt_push(qf, line, linelen)) == -1){
rv = FAL0;
break;
}
all_sz += i;
}
if((i = quoteflt_flush(qf)) != -1){
all_sz += i;
if(all_sz > 0 && outbuf == origobuf && stats != NIL)
*stats += all_sz;
}else
rv = FAL0;
mx_fs_linepool_release(line, linesize);
if(ferror(pipebuf))
rv = FAL0;
if(!mx_fs_close(pipebuf))
rv = FAL0;
NYD_OU;
return rv;
}
static void
statusput(const struct message *mp, FILE *obuf, struct quoteflt *qf,
u64 *stats)
{
char statout[3], *cp = statout;
NYD_IN;
if (mp->m_flag & MREAD)
*cp++ = 'R';
if (!(mp->m_flag & MNEW))
*cp++ = 'O';
*cp = 0;
if (statout[0]) {
int i = fprintf(obuf, "%.*sStatus: %s\n", (int)qf->qf_pfix_len,
(qf->qf_bypass ? NULL : qf->qf_pfix), statout);
if (i > 0 && stats != NULL)
*stats += i;
}
NYD_OU;
}
static void
xstatusput(const struct message *mp, FILE *obuf, struct quoteflt *qf,
u64 *stats)
{
char xstatout[4];
char *xp = xstatout;
NYD_IN;
if (mp->m_flag & MFLAGGED)
*xp++ = 'F';
if (mp->m_flag & MANSWERED)
*xp++ = 'A';
if (mp->m_flag & MDRAFTED)
*xp++ = 'T';
*xp = 0;
if (xstatout[0]) {
int i = fprintf(obuf, "%.*sX-Status: %s\n", (int)qf->qf_pfix_len,
(qf->qf_bypass ? NULL : qf->qf_pfix), xstatout);
if (i > 0 && stats != NULL)
*stats += i;
}
NYD_OU;
}
static void
put_from_(FILE *fp, struct mimepart *ip, u64 *stats)
{
char const *froma, *date, *nl;
int i;
NYD_IN;
if (ip != NULL && ip->m_from != NULL) {
froma = ip->m_from;
date = n_time_ctime(ip->m_time, NULL);
nl = "\n";
} else {
froma = ok_vlook(LOGNAME);
date = time_current.tc_ctime;
nl = n_empty;
}
mx_COLOUR(
if(mx_COLOUR_IS_ACTIVE())
mx_colour_put(mx_COLOUR_ID_VIEW_FROM_, NULL);
)
i = fprintf(fp, "From %s %s%s", froma, date, nl);
mx_COLOUR(
if(mx_COLOUR_IS_ACTIVE())
mx_colour_reset();
)
if (i > 0 && stats != NULL)
*stats += i;
NYD_OU;
}
FL int
sendmp(struct message *mp, FILE *obuf, struct n_ignore const *doitp,
char const *prefix, enum sendaction action, u64 *stats)
{
struct n_sigman linedat_protect;
struct quoteflt qf;
boole anyoutput;
FILE *ibuf;
enum mime_parse_flags mpf;
struct mimepart *ip;
uz linesize, cnt, size, i;
char *linedat;
int rv, c;
NYD_IN;
time_current_update(&time_current, TRU1);
rv = -1;
linedat = NULL;
linesize = 0;
quoteflt_init(&qf, prefix, (prefix == NULL));
n_SIGMAN_ENTER_SWITCH(&linedat_protect, n_SIGMAN_ALL){
case 0:
break;
default:
goto jleave;
}
if (mp == dot && action != SEND_TOSRCH)
n_pstate |= n_PS_DID_PRINT_DOT;
if (stats != NULL)
*stats = 0;
/* First line is the From_ line, so no headers there to worry about */
if ((ibuf = setinput(&mb, mp, NEED_BODY)) == NULL)
goto jleave;
cnt = mp->m_size;
size = 0;
{
boole nozap;
char const *cpre = n_empty, *csuf = n_empty;
#ifdef mx_HAVE_COLOUR
if(mx_COLOUR_IS_ACTIVE()){
struct mx_colour_pen *cpen;
struct str const *s;
cpen = mx_colour_pen_create(mx_COLOUR_ID_VIEW_FROM_,NULL);
if((s = mx_colour_pen_to_str(cpen)) != NIL){
cpre = s->s;
s = mx_colour_reset_to_str();
if(s != NIL)
csuf = s->s;
}
}
#endif
nozap = (doitp != n_IGNORE_ALL && doitp != n_IGNORE_FWD &&
action != SEND_RFC822 &&
!n_ignore_is_ign(doitp, "from_", sizeof("from_") -1));
if (mp->m_flag & (MNOFROM | MBADFROM_)) {
if (nozap)
size = fprintf(obuf, "%s%.*sFrom %s %s%s\n",
cpre, (int)qf.qf_pfix_len,
(qf.qf_bypass ? n_empty : qf.qf_pfix), fakefrom(mp),
n_time_ctime(mp->m_time, NULL), csuf);
} else if (nozap) {
if (!qf.qf_bypass) {
i = fwrite(qf.qf_pfix, sizeof *qf.qf_pfix, qf.qf_pfix_len, obuf);
if (i != qf.qf_pfix_len)
goto jleave;
size += i;
}
#ifdef mx_HAVE_COLOUR
if(*cpre != '\0'){
fputs(cpre, obuf);
cpre = (char const*)0x1;
}
#endif
while (cnt > 0 && (c = getc(ibuf)) != EOF) {
#ifdef mx_HAVE_COLOUR
if(c == '\n' && *csuf != '\0'){
cpre = (char const*)0x1;
fputs(csuf, obuf);
}
#endif
putc(c, obuf);
++size;
--cnt;
if (c == '\n')
break;
}
#ifdef mx_HAVE_COLOUR
if(*csuf != '\0' && cpre != (char const*)0x1 && *cpre != '\0')
fputs(csuf, obuf);
#endif
} else {
while (cnt > 0 && (c = getc(ibuf)) != EOF) {
--cnt;
if (c == '\n')
break;
}
}
}
if (size > 0 && stats != NULL)
*stats += size;
mpf = MIME_PARSE_NONE;
if (action != SEND_MBOX && action != SEND_RFC822 && action != SEND_SHOW)
mpf |= MIME_PARSE_PARTS | MIME_PARSE_DECRYPT;
if(action == SEND_TODISP || action == SEND_TODISP_ALL ||
action == SEND_QUOTE || action == SEND_QUOTE_ALL)
mpf |= MIME_PARSE_FOR_USER_CONTEXT;
if ((ip = mime_parse_msg(mp, mpf)) == NULL)
goto jleave;
anyoutput = FAL0;
rv = sendpart(mp, ip, obuf, doitp, &qf, action, &linedat, &linesize,
stats, 0, &anyoutput);
n_sigman_cleanup_ping(&linedat_protect);
jleave:
n_pstate &= ~n_PS_BASE64_STRIP_CR;
quoteflt_destroy(&qf);
if(linedat != NULL)
n_free(linedat);
NYD_OU;
n_sigman_leave(&linedat_protect, n_SIGMAN_VIPSIGS_NTTYOUT);
return rv;
}
#include "su/code-ou.h"
/* s-it-mode */
|
catroll/mailx
|
src/mx/net-socket.c
|
/*@ S-nail - a mail user agent derived from Berkeley Mail.
*@ Socket operations.
*
* Copyright (c) 2000-2004 <NAME>, Freiburg i. Br., Germany.
* Copyright (c) 2012 - 2020 <NAME>) Nurpmeso <<EMAIL>>.
* SPDX-License-Identifier: BSD-3-Clause
*/
/*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#undef su_FILE
#define su_FILE net_socket
#define mx_SOURCE
#ifndef mx_HAVE_AMALGAMATION
# include "mx/nail.h"
#endif
su_EMPTY_FILE()
#ifdef mx_HAVE_NET
# ifdef mx_HAVE_NONBLOCKSOCK
/*# include <sys/types.h>*/
# include <sys/select.h>
/*# include <sys/time.h>*/
# include <arpa/inet.h>
/*# include <netinet/in.h>*/
/*# include <errno.h>*/
/*# include <fcntl.h>*/
/*# include <stdlib.h>*/
/*# include <unistd.h>*/
# include <su/icodec.h>
# endif
#include <sys/socket.h>
#include <netdb.h>
#ifdef mx_HAVE_ARPA_INET_H
# include <arpa/inet.h>
#endif
#include <netinet/in.h>
#ifdef mx_HAVE_XTLS
# include <openssl/err.h>
# include <openssl/rand.h>
# include <openssl/ssl.h>
# include <openssl/x509v3.h>
# include <openssl/x509.h>
#endif
#include <su/cs.h>
#include <su/mem.h>
#include "mx/sigs.h"
#include "mx/url.h"
#include "mx/net-socket.h"
/* TODO fake */
#include "su/code-in.h"
/* If a_netso_sig was zeroed .. test if anything happened */
static void a_netso_onsig(int sig); /* TODO someday, need no more */
static void a_netso_test_sig(void);
/* */
static boole a_netso_open(struct mx_socket *sop, struct mx_url *urlp);
/* .url_flags&URL_TLS_MASK, do what is to be done; closes socket on error! */
#ifdef mx_HAVE_TLS
static int a_netso_open_tls_maybe(struct mx_socket *sop, struct mx_url *urlp);
#endif
/* */
static int a_netso_connect(int fd, struct sockaddr *soap, uz soapl);
/* Write to socket fd, restarting on EINTR, unless anything is written */
static long a_netso_xwrite(int fd, char const *data, uz size);
static sigjmp_buf a_netso_actjmp; /* TODO someday, we won't need it no more */
static int a_netso_sig; /* TODO someday, we won't need it no more */
static void
a_netso_onsig(int sig) /* TODO someday, we won't need it no more */
{
NYD; /* Signal handler */
if (a_netso_sig == -1) {
fprintf(n_stderr, _("\nInterrupting this operation may turn "
"the DNS resolver unusable\n"));
a_netso_sig = 0;
} else {
a_netso_sig = sig;
siglongjmp(a_netso_actjmp, 1);
}
}
static void
a_netso_test_sig(void){
/* May need to bounce the signal to the go.c trampoline (or wherever) */
if(a_netso_sig != 0){
sigset_t cset;
sigemptyset(&cset);
sigaddset(&cset, a_netso_sig);
sigprocmask(SIG_UNBLOCK, &cset, NIL);
n_raise(a_netso_sig);
}
}
static boole
a_netso_open(struct mx_socket *sop, struct mx_url *urlp) /*TODO sigs;refactor*/
{
#ifdef mx_HAVE_SO_XTIMEO
struct timeval tv;
#endif
#ifdef mx_HAVE_SO_LINGER
struct linger li;
#endif
#ifdef mx_HAVE_GETADDRINFO
# ifndef NI_MAXHOST
# define NI_MAXHOST 1025
# endif
char hbuf[NI_MAXHOST];
struct addrinfo hints, *res0 = NULL, *res;
#else
struct sockaddr_in servaddr;
struct in_addr **pptr;
struct hostent *hp;
struct servent *ep;
#endif
n_sighdl_t volatile ohup, oint;
char const * volatile serv;
int volatile sofd = -1, errval;
NYD2_IN;
su_mem_set(sop, 0, sizeof *sop);
UNINIT(errval, 0);
serv = (urlp->url_port != NULL) ? urlp->url_port : urlp->url_proto;
if (n_poption & n_PO_D_V)
n_err(_("Resolving host %s:%s ... "), urlp->url_host.s, serv);
/* Signal handling (in respect to a_netso_sig dealing) is heavy, but no
* healing until v15.0 and i want to end up with that functionality */
hold_sigs();
a_netso_sig = 0;
ohup = safe_signal(SIGHUP, &a_netso_onsig);
oint = safe_signal(SIGINT, &a_netso_onsig);
if (sigsetjmp(a_netso_actjmp, 0)) {
jpseudo_jump:
n_err("%s\n",
(a_netso_sig == SIGHUP ? _("Hangup") : _("Interrupted")));
if (sofd >= 0) {
close(sofd);
sofd = -1;
}
goto jjumped;
}
rele_sigs();
#ifdef mx_HAVE_GETADDRINFO
for (;;) {
su_mem_set(&hints, 0, sizeof hints);
hints.ai_socktype = SOCK_STREAM;
a_netso_sig = -1;
errval = getaddrinfo(urlp->url_host.s, serv, &hints, &res0);
if (a_netso_sig != -1) {
a_netso_sig = SIGINT;
goto jpseudo_jump;
}
a_netso_sig = 0;
if (errval == 0)
break;
if (n_poption & n_PO_D_V)
n_err(_("failed\n"));
n_err(_("Lookup of %s:%s failed: %s\n"),
urlp->url_host.s, serv, gai_strerror(errval));
/* Error seems to depend on how "smart" the /etc/service code is: is it
* "able" to state whether the service as such is NONAME or does it only
* check for the given ai_socktype.. */
if (errval == EAI_NONAME || errval == EAI_SERVICE) {
if (serv == urlp->url_proto &&
(serv = mx_url_servbyname(urlp->url_proto, NIL, NIL)) != NIL &&
*serv != '\0') {
n_err(_(" Trying standard protocol port %s\n"), serv);
n_err(_(" If that succeeds consider including the "
"port in the URL!\n"));
continue;
}
if (serv != urlp->url_port)
n_err(_(" Including a port number in the URL may "
"circumvent this problem\n"));
}
ASSERT(sofd == -1);
errval = 0;
goto jjumped;
}
if (n_poption & n_PO_D_V)
n_err(_("done\n"));
for (res = res0; res != NULL && sofd < 0; res = res->ai_next) {
if (n_poption & n_PO_D_V) {
if (getnameinfo(res->ai_addr, res->ai_addrlen, hbuf, sizeof hbuf,
NULL, 0, NI_NUMERICHOST))
su_mem_copy(hbuf, "unknown host", sizeof("unknown host"));
n_err(_("%sConnecting to %s:%s ... "),
(res == res0 ? n_empty : "\n"), hbuf, serv);
}
sofd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if(sofd >= 0 &&
(errval = a_netso_connect(sofd, res->ai_addr, res->ai_addrlen)
) != su_ERR_NONE)
sofd = -1;
}
jjumped:
if (res0 != NULL) {
freeaddrinfo(res0);
res0 = NULL;
}
#else /* mx_HAVE_GETADDRINFO */
if (serv == urlp->url_proto) {
if ((ep = getservbyname(n_UNCONST(serv), "tcp")) != NULL)
urlp->url_portno = ntohs(ep->s_port);
else {
if (n_poption & n_PO_D_V)
n_err(_("failed\n"));
if ((serv = mx_url_servbyname(urlp->url_proto, &urlp->url_portno, NIL)
) != NIL && *serv != '\0')
n_err(_(" Unknown service: %s\n"), urlp->url_proto);
n_err(_(" Trying standard protocol port %s\n"), serv);
n_err(_(" If that succeeds consider including the "
"port in the URL!\n"));
else {
n_err(_(" Unknown service: %s\n"), urlp->url_proto);
n_err(_(" Including a port number in the URL may "
"circumvent this problem\n"));
ASSERT(sofd == -1 && errval == 0);
goto jjumped;
}
}
}
a_netso_sig = -1;
hp = gethostbyname(urlp->url_host.s);
if (a_netso_sig != -1) {
a_netso_sig = SIGINT;
goto jpseudo_jump;
}
a_netso_sig = 0;
if (hp == NULL) {
char const *emsg;
if (n_poption & n_PO_D_V)
n_err(_("failed\n"));
switch (h_errno) {
case HOST_NOT_FOUND: emsg = N_("host not found"); break;
default:
case TRY_AGAIN: emsg = N_("(maybe) try again later"); break;
case NO_RECOVERY: emsg = N_("non-recoverable server error"); break;
case NO_DATA: emsg = N_("valid name without IP address"); break;
}
n_err(_("Lookup of %s:%s failed: %s\n"),
urlp->url_host.s, serv, V_(emsg));
goto jjumped;
} else if (n_poption & n_PO_D_V)
n_err(_("done\n"));
pptr = (struct in_addr**)hp->h_addr_list;
if ((sofd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
n_perr(_("could not create socket"), 0);
ASSERT(sofd == -1 && errval == 0);
goto jjumped;
}
su_mem_set(&servaddr, 0, sizeof servaddr);
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(urlp->url_portno);
su_mem_copy(&servaddr.sin_addr, *pptr, sizeof(struct in_addr));
if (n_poption & n_PO_D_V)
n_err(_("%sConnecting to %s:%d ... "),
n_empty, inet_ntoa(**pptr), (int)urlp->url_portno);
if((errval = a_netso_connect(sofd, (struct sockaddr*)&servaddr,
sizeof servaddr)) != su_ERR_NONE)
sofd = -1;
jjumped:
#endif /* !mx_HAVE_GETADDRINFO */
hold_sigs();
safe_signal(SIGINT, oint);
safe_signal(SIGHUP, ohup);
rele_sigs();
if(sofd < 0){
if(errval != 0){
if(!(n_poption & n_PO_D_V))
n_perr(_("Could not connect(2)"), errval);
su_err_set_no(errval);
}
goto jleave;
}
sop->s_fd = sofd;
if (n_poption & n_PO_D_V)
n_err(_("connected.\n"));
/* And the regular timeouts XXX configurable */
#ifdef mx_HAVE_SO_XTIMEO
tv.tv_sec = 42;
tv.tv_usec = 0;
(void)setsockopt(sofd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv);
(void)setsockopt(sofd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
#endif
#ifdef mx_HAVE_SO_LINGER
li.l_onoff = 1;
li.l_linger = 42;
(void)setsockopt(sofd, SOL_SOCKET, SO_LINGER, &li, sizeof li);
#endif
/* SSL/TLS upgrade? */
#ifdef mx_HAVE_TLS
if(urlp->url_flags & mx_URL_TLS_MASK)
sofd = a_netso_open_tls_maybe(sop, urlp);
#endif
jleave:
a_netso_test_sig();
NYD2_OU;
return (sofd >= 0);
}
#ifdef mx_HAVE_TLS
static int
a_netso_open_tls_maybe(struct mx_socket *sop, struct mx_url *urlp){
n_sighdl_t volatile ohup, oint;
NYD2_IN;
hold_sigs();
a_netso_sig = 0;
# if defined mx_HAVE_GETADDRINFO && defined SSL_CTRL_SET_TLSEXT_HOSTNAME
/* TODO the SSL_ def check should NOT be here */
if(urlp->url_flags & mx_URL_TLS_MASK){
struct {struct addrinfo hints; struct addrinfo *res0;} x;
su_mem_set(&x, 0, sizeof x);
x.hints.ai_family = AF_UNSPEC;
x.hints.ai_flags = AI_NUMERICHOST;
if(getaddrinfo(urlp->url_host.s, NIL, &x.hints, &x.res0) == 0)
freeaddrinfo(x.res0);
else
urlp->url_flags |= mx_URL_HOST_IS_NAME;
}
# endif
if(urlp->url_flags & mx_URL_TLS_REQUIRED){
ohup = safe_signal(SIGHUP, &a_netso_onsig);
oint = safe_signal(SIGINT, &a_netso_onsig);
if(sigsetjmp(a_netso_actjmp, 0)){
n_err(_("%s during SSL/TLS handshake\n"),
(a_netso_sig == SIGHUP ? _("Hangup") : _("Interrupted")));
goto jsclose;
}
rele_sigs();
if(!n_tls_open(urlp, sop)){
jsclose:
mx_socket_close(sop);
ASSERT(sop->s_fd == -1);
}
hold_sigs();
safe_signal(SIGINT, oint);
safe_signal(SIGHUP, ohup);
}
rele_sigs();
NYD2_OU;
return sop->s_fd;
}
#endif /* mx_HAVE_TLS */
static int
a_netso_connect(int fd, struct sockaddr *soap, uz soapl){
int rv;
NYD_IN;
#ifdef mx_HAVE_NONBLOCKSOCK
rv = fcntl(fd, F_GETFL, 0);
if(rv != -1 && !fcntl(fd, F_SETFL, rv | O_NONBLOCK)){
fd_set fdset;
struct timeval tv; /* XXX configurable */
socklen_t sol;
boole show_progress;
uz cnt;
int i, soe;
/* Always select(2) even if it succeeds right away, since on at least
* SunOS/Solaris 5.9 SPARC it will cause failures (busy resources) */
if(connect(fd, soap, soapl) && (i = su_err_no()) != su_ERR_INPROGRESS){
rv = i;
goto jerr_noerrno;
}else{
show_progress = ((n_poption & n_PO_D_V) ||
((n_psonce & n_PSO_INTERACTIVE) && !(n_pstate & n_PS_ROBOT)));
FD_ZERO(&fdset);
FD_SET(fd, &fdset);
/* C99 */{
char const *cp;
if((cp = ok_vlook(socket_connect_timeout)) == NIL ||
(su_idec_uz_cp(&cnt, cp, 0, NIL), cnt < 2))
cnt = 42; /* XXX mx-config.h */
if(show_progress){
tv.tv_sec = 2;
cnt >>= 1;
}else{
tv.tv_sec = (long)cnt; /* XXX */
cnt = 1;
}
}
jrewait:
tv.tv_usec = 0;
if((soe = select(fd + 1, NIL, &fdset, NIL, &tv)) == 1){
i = rv;
sol = sizeof rv;
getsockopt(fd, SOL_SOCKET, SO_ERROR, &rv, &sol);
fcntl(fd, F_SETFL, i);
if(show_progress == TRUM1)
n_err(" ");
}else if(soe == 0){
if(show_progress && --cnt > 0){
show_progress = TRUM1;
n_err(".");
tv.tv_sec = 2;
goto jrewait;
}
n_err(_(" timeout\n"));
close(fd);
rv = su_ERR_TIMEDOUT;
}else
goto jerr;
}
}else
#endif /* mx_HAVE_NONBLOCKSOCK */
if(!connect(fd, soap, soapl))
rv = su_ERR_NONE;
else{
#ifdef mx_HAVE_NONBLOCKSOCK
jerr:
#endif
rv = su_err_no();
#ifdef mx_HAVE_NONBLOCKSOCK
jerr_noerrno:
#endif
if(n_poption & n_PO_D_V)
n_perr(_("connect(2) failed:"), rv);
close(fd);
}
NYD_OU;
return rv;
}
static long
a_netso_xwrite(int fd, char const *data, uz size)
{
long rv = -1, wo;
uz wt = 0;
NYD_IN;
do {
if ((wo = write(fd, data + wt, size - wt)) < 0) {
if (su_err_no() == su_ERR_INTR)
continue;
else
goto jleave;
}
wt += wo;
} while (wt < size);
rv = (long)size;
jleave:
NYD_OU;
return rv;
}
boole
mx_socket_open(struct mx_socket *sop, struct mx_url *urlp){
char const *cp;
boole rv;
NYD_IN;
rv = FAL0;
/* We may have a proxy configured */
if((cp = xok_vlook(socks_proxy, urlp, OXM_ALL)) == NULL)
rv = a_netso_open(sop, urlp);
else{
u8 pbuf[4 + 1 + 255 + 2];
uz i;
char const *emsg;
struct mx_url url2;
if(!mx_url_parse(&url2, CPROTO_SOCKS, cp)){
n_err(_("Failed to parse *socks-proxy*: %s\n"), cp);
goto jleave;
}
if(urlp->url_host.l > 255){
n_err(_("*socks-proxy*: hostname too long: %s\n"),
urlp->url_input);
goto jleave;
}
if(n_poption & n_PO_D_V)
n_err(_("Connecting to *socks-proxy*=%s\n"), cp);
if(!a_netso_open(sop, &url2)){
n_err(_("Failed to connect to *socks-proxy*: %s\n"), cp);
goto jleave;
}
/* RFC 1928: version identifier/method selection message */
pbuf[0] = 0x05; /* VER: protocol version: X'05' */
pbuf[1] = 0x01; /* NMETHODS: 1 */
pbuf[2] = 0x00; /* METHOD: X'00' NO AUTHENTICATION REQUIRED */
if(write(sop->s_fd, pbuf, 3) != 3){
jerrsocks:
n_perr("*socks-proxy*", 0);
jesocks:
mx_socket_close(sop);
goto jleave;
}
/* Receive greeting */
if(read(sop->s_fd, pbuf, 2) != 2)
goto jerrsocks;
if(pbuf[0] != 0x05 || pbuf[1] != 0x00){
jesocksreply:
emsg = N_("unexpected reply\n");
jesocksreplymsg:
/* I18N: error message and failing URL */
n_err(_("*socks-proxy*: %s: %s\n"), V_(emsg), cp);
goto jesocks;
}
/* RFC 1928: CONNECT request */
if(n_poption & n_PO_D_V)
n_err(_("Through *socks-proxy*, connecting to %s:%s ...\n"),
urlp->url_host.s,
(urlp->url_port != NULL ? urlp->url_port : urlp->url_proto));
pbuf[0] = 0x05; /* VER: protocol version: X'05' */
pbuf[1] = 0x01; /* CMD: CONNECT X'01' */
pbuf[2] = 0x00; /* RESERVED */
pbuf[3] = 0x03; /* ATYP: domain name */
pbuf[4] = (u8)urlp->url_host.l;
su_mem_copy(&pbuf[i = 5], urlp->url_host.s, urlp->url_host.l);
/* C99 */{
u16 x;
x = htons(urlp->url_portno);
su_mem_copy(&pbuf[i += urlp->url_host.l], (u8*)&x, sizeof x);
i += sizeof x;
}
if(write(sop->s_fd, pbuf, i) != (sz)i)
goto jerrsocks;
/* Connect result */
if((i = read(sop->s_fd, pbuf, 4)) != 4)
goto jerrsocks;
/* Version 5, reserved must be 0 */
if(pbuf[0] != 0x05 || pbuf[2] != 0x00)
goto jesocksreply;
/* Result */
switch(pbuf[1]){
case 0x00: emsg = NULL; break;
case 0x01: emsg = N_("SOCKS server failure"); break;
case 0x02: emsg = N_("connection not allowed by ruleset"); break;
case 0x03: emsg = N_("network unreachable"); break;
case 0x04: emsg = N_("host unreachable"); break;
case 0x05: emsg = N_("connection refused"); break;
case 0x06: emsg = N_("TTL expired"); break;
case 0x07: emsg = N_("command not supported"); break;
case 0x08: emsg = N_("address type not supported"); break;
default: emsg = N_("unknown SOCKS error code"); break;
}
if(emsg != NULL)
goto jesocksreplymsg;
/* Address type variable; read the BND.PORT with it.
* This is actually false since RFC 1928 says that the BND.ADDR reply to
* CONNECT contains the IP address, so only 0x01 and 0x04 are allowed */
switch(pbuf[3]){
case 0x01: i = 4; break;
case 0x03: i = 1; break;
case 0x04: i = 16; break;
default: goto jesocksreply;
}
i += sizeof(u16);
if(read(sop->s_fd, pbuf, i) != (sz)i)
goto jerrsocks;
if(i == 1 + sizeof(u16)){
i = pbuf[0];
if(read(sop->s_fd, pbuf, i) != (sz)i)
goto jerrsocks;
}
/* SSL/TLS upgrade? */
#ifdef mx_HAVE_TLS
if(urlp->url_flags & mx_URL_TLS_MASK)
rv = (a_netso_open_tls_maybe(sop, urlp) >= 0);
else
#endif
rv = TRU1;
}
jleave:
a_netso_test_sig();
NYD_OU;
return rv;
}
int
mx_socket_close(struct mx_socket *sop)
{
int i;
NYD_IN;
i = sop->s_fd;
sop->s_fd = -1;
/* TODO NOTE: we MUST NOT close the descriptor 0 here...
* TODO of course this should be handled in a VMAILFS->open() .s_fd=-1,
* TODO but unfortunately it isn't yet */
if (i <= 0)
i = 0;
else {
if (sop->s_onclose != NULL)
(*sop->s_onclose)();
if (sop->s_wbuf != NULL)
n_free(sop->s_wbuf);
# ifdef mx_HAVE_XTLS
if (sop->s_use_tls) {
void *s_tls = sop->s_tls;
sop->s_tls = NULL;
sop->s_use_tls = 0;
if(SSL_shutdown(s_tls) == 0) /* XXX proper error handling;signals! */
SSL_shutdown(s_tls);
SSL_free(s_tls);
}
# endif
i = close(i);
}
NYD_OU;
return i;
}
enum okay
mx_socket_write(struct mx_socket *sop, char const *data) /* XXX INLINE */
{
enum okay rv;
NYD2_IN;
rv = mx_socket_write1(sop, data, su_cs_len(data), 0);
NYD2_OU;
return rv;
}
enum okay
mx_socket_write1(struct mx_socket *sop, char const *data, int size,
int use_buffer)
{
enum okay rv = STOP;
int x;
NYD2_IN;
if (use_buffer > 0) {
int di;
if (sop->s_wbuf == NULL) {
sop->s_wbufsize = 4096;
sop->s_wbuf = n_alloc(sop->s_wbufsize);
sop->s_wbufpos = 0;
}
while (sop->s_wbufpos + size > sop->s_wbufsize) {
di = sop->s_wbufsize - sop->s_wbufpos;
size -= di;
if (sop->s_wbufpos > 0) {
su_mem_copy(&sop->s_wbuf[sop->s_wbufpos], data, di);
rv = mx_socket_write1(sop, sop->s_wbuf, sop->s_wbufsize, -1);
} else
rv = mx_socket_write1(sop, data, sop->s_wbufsize, -1);
if (rv != OKAY)
goto jleave;
data += di;
sop->s_wbufpos = 0;
}
if (size == sop->s_wbufsize) {
rv = mx_socket_write1(sop, data, sop->s_wbufsize, -1);
if (rv != OKAY)
goto jleave;
} else if (size > 0) {
su_mem_copy(&sop->s_wbuf[sop->s_wbufpos], data, size);
sop->s_wbufpos += size;
}
rv = OKAY;
goto jleave;
} else if (use_buffer == 0 && sop->s_wbuf != NULL && sop->s_wbufpos > 0) {
x = sop->s_wbufpos;
sop->s_wbufpos = 0;
if ((rv = mx_socket_write1(sop, sop->s_wbuf, x, -1)) != OKAY)
goto jleave;
}
if (size == 0) {
rv = OKAY;
goto jleave;
}
# ifdef mx_HAVE_XTLS
if(sop->s_use_tls){
int errcnt, err;
errcnt = 0;
jssl_retry:
x = SSL_write(sop->s_tls, data, size);
if(x < 0){
if((err = su_err_no()) == su_ERR_INTR)
goto jssl_retry;
if(++errcnt < 3 && err != su_ERR_WOULDBLOCK){
switch(SSL_get_error(sop->s_tls, x)){
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
n_err(_("TLS socket write error, retrying: %s\n"),
su_err_doc(err));
goto jssl_retry;
}
}
}
} else
# endif /* mx_HAVE_XTLS */
{
x = a_netso_xwrite(sop->s_fd, data, size);
}
if (x != size) {
char o[512];
snprintf(o, sizeof o, "%s write error",
(sop->s_desc ? sop->s_desc : "socket"));
# ifdef mx_HAVE_XTLS
if (sop->s_use_tls)
ssl_gen_err("%s", o);
else
# endif
n_perr(o, 0);
if (x < 0)
mx_socket_close(sop);
rv = STOP;
goto jleave;
}
rv = OKAY;
jleave:
NYD2_OU;
return rv;
}
int
(mx_socket_getline)(char **line, uz *linesize, uz *linelen,
struct mx_socket *sop su_DBG_LOC_ARGS_DECL)
{
int rv;
uz lsize;
char *lp_base, *lp;
NYD2_IN;
lsize = *linesize;
lp_base = *line;
lp = lp_base;
if (sop->s_rsz < 0) {
mx_socket_close(sop);
rv = sop->s_rsz;
goto jleave;
}
do {
if (lp_base == NULL || PCMP(lp, >, lp_base + lsize - 128)) {
uz diff = P2UZ(lp - lp_base);
*linesize = (lsize += 256); /* XXX magic */
*line = lp_base = su_MEM_REALLOC_LOCOR(lp_base, lsize,
su_DBG_LOC_ARGS_ORUSE);
lp = lp_base + diff;
}
if (sop->s_rbufptr == NULL ||
PCMP(sop->s_rbufptr, >=, sop->s_rbuf + sop->s_rsz)) {
# ifdef mx_HAVE_XTLS
if(sop->s_use_tls){
int errcnt, err;
errcnt = 0;
jssl_retry:
sop->s_rsz = SSL_read(sop->s_tls, sop->s_rbuf, sizeof sop->s_rbuf);
if (sop->s_rsz <= 0) {
if (sop->s_rsz < 0) {
char o[512];
if((err = su_err_no()) == su_ERR_INTR)
goto jssl_retry;
if(++errcnt < 3 && err != su_ERR_WOULDBLOCK){
switch(SSL_get_error(sop->s_tls, sop->s_rsz)){
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
n_err(_("TLS socket read error, retrying: %s\n"),
su_err_doc(err));
goto jssl_retry;
}
}
snprintf(o, sizeof o, "%s",
(sop->s_desc ? sop->s_desc : "socket"));
ssl_gen_err("%s", o);
}
break;
}
} else
# endif /* mx_HAVE_XTLS */
{
jagain:
sop->s_rsz = read(sop->s_fd, sop->s_rbuf, sizeof sop->s_rbuf);
if (sop->s_rsz <= 0) {
if (sop->s_rsz < 0) {
char o[512];
if (su_err_no() == su_ERR_INTR)
goto jagain;
snprintf(o, sizeof o, "%s",
(sop->s_desc ? sop->s_desc : "socket"));
n_perr(o, 0);
}
break;
}
}
sop->s_rbufptr = sop->s_rbuf;
}
} while ((*lp++ = *sop->s_rbufptr++) != '\n');
*lp = '\0';
lsize = P2UZ(lp - lp_base);
if (linelen)
*linelen = lsize;
rv = (int)lsize;
jleave:
NYD2_OU;
return rv;
}
#include "su/code-ou.h"
#endif /* mx_HAVE_NET */
/* s-it-mode */
|
catroll/mailx
|
src/mx/dig-msg.c
|
<reponame>catroll/mailx
/*@ S-nail - a mail user agent derived from Berkeley Mail.
*@ Dig message objects. TODO Very very restricted (especially non-compose)
*@ Protocol change: adjust mx-config.h:mx_DIG_MSG_PLUMBING_VERSION + `~^' man.
*@ TODO - a_dmsg_cmd() should generate string lists, not perform real I/O.
*@ TODO I.e., drop FILE* arg, generate stringlist; up to callers...
*@ TODO - With our own I/O there should then be a StringListDevice as the
*@ TODO owner and I/O overlay provider: NO temporary file (sic)!
*@ XXX - Multiple objects per message could be possible (a_dmsg_find()),
*@ XXX except in compose mode
*
* Copyright (c) 2016 - 2020 <NAME>) Nurpmeso <<EMAIL>>.
* SPDX-License-Identifier: ISC
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#undef su_FILE
#define su_FILE dig_msg
#define mx_SOURCE
#define mx_SOURCE_DIG_MSG
#ifndef mx_HAVE_AMALGAMATION
# include "mx/nail.h"
#endif
#include <su/cs.h>
#include <su/icodec.h>
#include <su/mem.h>
#include "mx/attachments.h"
#include "mx/cmd.h"
#include "mx/file-streams.h"
#include "mx/mime-type.h"
#include "mx/names.h"
#include "mx/dig-msg.h"
#include "su/code-in.h"
#define a_DMSG_QUOTE(S) n_shexp_quote_cp(S, FAL0)
struct mx_dig_msg_ctx *mx_dig_msg_read_overlay; /* XXX HACK */
struct mx_dig_msg_ctx *mx_dig_msg_compose_ctx; /* Or NIL XXX HACK*/
/* Try to convert cp into an unsigned number that corresponds to an existing
* message number (or ERR_INVAL), search for an existing object (ERR_EXIST if
* oexcl and exists; ERR_NOENT if not oexcl and does not exist).
* On oexcl success *dmcp will be n_alloc()ated with .dmc_msgno and .dmc_mp
* etc. set; but not linked into mb.mb_digmsg and .dmc_fp not created etc. */
static s32 a_dmsg_find(char const *cp, struct mx_dig_msg_ctx **dmcpp,
boole oexcl);
/* Subcommand drivers */
static boole a_dmsg_cmd(FILE *fp, struct mx_dig_msg_ctx *dmcp,
struct mx_cmd_arg *cmd, struct mx_cmd_arg *args);
static boole a_dmsg__header(FILE *fp, struct mx_dig_msg_ctx *dmcp,
struct mx_cmd_arg *args);
static boole a_dmsg__attach(FILE *fp, struct mx_dig_msg_ctx *dmcp,
struct mx_cmd_arg *args);
static s32
a_dmsg_find(char const *cp, struct mx_dig_msg_ctx **dmcpp, boole oexcl){
struct mx_dig_msg_ctx *dmcp;
s32 rv;
u32 msgno;
NYD2_IN;
if(cp[0] == '-' && cp[1] == '\0'){
if((dmcp = mx_dig_msg_compose_ctx) != NIL){
*dmcpp = dmcp;
if(dmcp->dmc_flags & mx_DIG_MSG_COMPOSE_DIGGED)
rv = oexcl ? su_ERR_EXIST : su_ERR_NONE;
else
rv = oexcl ? su_ERR_NONE : su_ERR_NOENT;
}else
rv = su_ERR_INVAL;
goto jleave;
}
if((su_idec_u32_cp(&msgno, cp, 0, NIL
) & (su_IDEC_STATE_EMASK | su_IDEC_STATE_CONSUMED)
) != su_IDEC_STATE_CONSUMED ||
msgno == 0 || UCMP(z, msgno, >, msgCount)){
rv = su_ERR_INVAL;
goto jleave;
}
for(dmcp = mb.mb_digmsg; dmcp != NIL; dmcp = dmcp->dmc_next)
if(dmcp->dmc_msgno == msgno){
*dmcpp = dmcp;
rv = oexcl ? su_ERR_EXIST : su_ERR_NONE;
goto jleave;
}
if(!oexcl){
rv = su_ERR_NOENT;
goto jleave;
}
*dmcpp = dmcp = n_calloc(1, Z_ALIGN(sizeof *dmcp) + sizeof(struct header));
dmcp->dmc_mp = &message[msgno - 1];
dmcp->dmc_flags = mx_DIG_MSG_OWN_MEMBAG |
((TRU1/*TODO*/ || !(mb.mb_perm & MB_DELE))
? mx_DIG_MSG_RDONLY : mx_DIG_MSG_NONE);
dmcp->dmc_msgno = msgno;
dmcp->dmc_hp = R(struct header*,P2UZ(&dmcp[1]));
dmcp->dmc_membag = su_mem_bag_create(&dmcp->dmc__membag_buf[0], 0);
/* Rest done by caller */
rv = su_ERR_NONE;
jleave:
NYD2_OU;
return rv;
}
static boole
a_dmsg_cmd(FILE *fp, struct mx_dig_msg_ctx *dmcp, struct mx_cmd_arg *cmd,
struct mx_cmd_arg *args){
union {struct mx_cmd_arg *ca; char *c; struct str const *s; boole rv;} p;
NYD2_IN;
if(cmd == NIL)
goto jecmd;
p.s = &cmd->ca_arg.ca_str;
if(su_cs_starts_with_case_n("header", p.s->s, p.s->l))
p.rv = a_dmsg__header(fp, dmcp, args);
else if(su_cs_starts_with_case_n("attachment", p.s->s, p.s->l)){
if(!(dmcp->dmc_flags & mx_DIG_MSG_COMPOSE)) /* TODO attachment support */
p.rv = (fprintf(fp,
"505 `digmsg attachment' only in compose mode (yet)\n") > 0);
else
p.rv = a_dmsg__attach(fp, dmcp, args);
}else if(su_cs_starts_with_case_n("version", p.s->s, p.s->l)){
if(args != NIL)
goto jecmd;
p.rv = (fputs("210 " mx_DIG_MSG_PLUMBING_VERSION "\n", fp) != EOF);
}else if((p.s->l == 1 && p.s->s[0] == '?') ||
su_cs_starts_with_case_n("help", p.s->s, p.s->l)){
if(args != NIL)
goto jecmd;
p.rv = (fputs(_("211 (Arguments undergo shell-style evaluation)\n"),
fp) != EOF &&
#ifdef mx_HAVE_UISTRINGS
fputs(_(
"attachment:\n"
" attribute name (212; 501)\n"
" attribute-at position\n"
" attribute-set name key value (210; 505/501)\n"
" attribute-set-at position key value\n"
" insert file[=input-charset[#output-charset]] "
"(210; 501/505/506)\n"
" insert #message-number\n"
" list (212; 501)\n"
" remove name (210; 501/506)\n"
" remove-at position (210; 501/505)\n"), fp) != EOF &&
fputs(_(
"header\n"
" insert field content (210; 501/505/506)\n"
" list [field] (210; [501]);\n"
" remove field (210; 501/505)\n"
" remove-at field position (210; 501/505)\n"
" show field (211/212; 501)\n"
"help (211)\n"
"version (210)\n"), fp) != EOF &&
#endif
putc('\n', fp) != EOF);
}else{
jecmd:
fputs("500\n", fp);
p.rv = FAL0;
}
fflush(fp);
NYD2_OU;
return p.rv;
}
static boole
a_dmsg__header(FILE *fp, struct mx_dig_msg_ctx *dmcp,
struct mx_cmd_arg *args){
struct n_header_field *hfp;
struct mx_name *np, **npp;
uz i;
struct mx_cmd_arg *a3p;
char const *cp;
struct header *hp;
NYD2_IN;
hp = dmcp->dmc_hp;
UNINIT(a3p, NIL);
if(args == NIL){
cp = su_empty; /* xxx not NIL anyway */
goto jdefault;
}
cp = args->ca_arg.ca_str.s;
args = args->ca_next;
/* Strip the optional colon from header names */
if((a3p = args) != NIL){
char *xp;
a3p = a3p->ca_next;
for(xp = args->ca_arg.ca_str.s;; ++xp)
if(*xp == '\0')
break;
else if(*xp == ':'){
*xp = '\0';
break;
}
}
/* TODO ERR_2BIG should happen on the cmd_arg parser side */
if(a3p != NIL && a3p->ca_next != NIL)
goto jecmd;
if(su_cs_starts_with_case("insert", cp)){ /* TODO LOGIC BELONGS head.c
* TODO That is: Header::factory(string) -> object (blahblah).
* TODO I.e., as long as we don't have regular RFC compliant parsers
* TODO which differentiate in between structured and unstructured
* TODO header fields etc., a little workaround */
struct mx_name *xnp;
s8 aerr;
char const *mod_suff;
enum expand_addr_check_mode eacm;
enum gfield ntype;
boole mult_ok;
if(args == NIL || a3p == NIL)
goto jecmd;
if(dmcp->dmc_flags & mx_DIG_MSG_RDONLY)
goto j505r;
/* Strip [\r\n] which would render a body invalid XXX all controls? */
/* C99 */{
char c;
for(cp = a3p->ca_arg.ca_str.s; (c = *cp) != '\0'; ++cp)
if(c == '\n' || c == '\r')
*UNCONST(char*,cp) = ' ';
}
if(!su_cs_cmp_case(args->ca_arg.ca_str.s, cp = "Subject")){
if(a3p->ca_arg.ca_str.l == 0)
goto j501cp;
if(hp->h_subject != NIL)
hp->h_subject = savecatsep(hp->h_subject, ' ',
a3p->ca_arg.ca_str.s);
else
hp->h_subject = a3p->ca_arg.ca_str.s;
if(fprintf(fp, "210 %s 1\n", cp) < 0)
cp = NIL;
goto jleave;
}
mult_ok = TRU1;
ntype = GEXTRA | GFULL | GFULLEXTRA;
eacm = EACM_STRICT;
mod_suff = NIL;
if(!su_cs_cmp_case(args->ca_arg.ca_str.s, cp = "From")){
npp = &hp->h_from;
jins:
aerr = 0;
/* todo As said above, this should be table driven etc., but.. */
if(ntype & GBCC_IS_FCC){
np = nalloc_fcc(a3p->ca_arg.ca_str.s);
if(is_addr_invalid(np, eacm))
goto jins_505;
}else{
if((np = (mult_ok > FAL0 ? lextract : n_extract_single
)(a3p->ca_arg.ca_str.s, ntype | GNULL_OK)) == NIL)
goto j501cp;
if((np = checkaddrs(np, eacm, &aerr), aerr != 0)){
jins_505:
if(fprintf(fp, "505 %s\n", cp) < 0)
cp = NIL;
goto jleave;
}
}
/* Go to the end of the list, track whether it contains any
* non-deleted entries */
i = 0;
if((xnp = *npp) != NIL)
for(;; xnp = xnp->n_flink){
if(!(xnp->n_type & GDEL))
++i;
if(xnp->n_flink == NIL)
break;
}
if(!mult_ok && (i != 0 || np->n_flink != NIL)){
if(fprintf(fp, "506 %s\n", cp) < 0)
cp = NIL;
}else{
if(xnp == NIL)
*npp = np;
else
xnp->n_flink = np;
np->n_blink = xnp;
if(fprintf(fp, "210 %s %" PRIuZ "\n", cp, ++i) < 0)
cp = NIL;
}
goto jleave;
}
#undef a_X
#define a_X(F,H,INS) \
if(!su_cs_cmp_case(args->ca_arg.ca_str.s, cp = F)) \
{npp = &hp->H; INS; goto jins;}
if((cp = su_cs_find_c(args->ca_arg.ca_str.s, '?')) != NIL){
mod_suff = cp;
args->ca_arg.ca_str.s[P2UZ(cp - args->ca_arg.ca_str.s)] = '\0';
if(*++cp != '\0' && !su_cs_starts_with_case("single", cp)){
cp = mod_suff;
goto j501cp;
}
mult_ok = TRUM1;
}
/* Just like with ~t,~c,~b, immediately test *expandaddr* compliance */
a_X("To", h_to, ntype = GTO|GFULL su_COMMA eacm = EACM_NORMAL);
a_X("Cc", h_cc, ntype = GCC|GFULL su_COMMA eacm = EACM_NORMAL);
a_X("Bcc", h_bcc, ntype = GBCC|GFULL su_COMMA eacm = EACM_NORMAL);
if((cp = mod_suff) != NIL)
goto j501cp;
/* Not | EAF_FILE, depend on *expandaddr*! */
a_X("Fcc", h_fcc, ntype = GBCC|GBCC_IS_FCC su_COMMA eacm = EACM_NORMAL);
a_X("Sender", h_sender, mult_ok = FAL0);
a_X("Reply-To", h_reply_to, eacm = EACM_NONAME);
a_X("Mail-Followup-To", h_mft, eacm = EACM_NONAME);
a_X("Message-ID", h_message_id,
mult_ok = FAL0 su_COMMA ntype = GREF su_COMMA eacm = EACM_NONAME);
a_X("References", h_ref, ntype = GREF su_COMMA eacm = EACM_NONAME);
a_X("In-Reply-To", h_in_reply_to, ntype = GREF su_COMMA
eacm = EACM_NONAME);
#undef a_X
if((cp = n_header_is_known(args->ca_arg.ca_str.s, UZ_MAX)) != NIL)
goto j505r;
/* Free-form header fields */
/* C99 */{
uz nl, bl;
struct n_header_field **hfpp;
for(cp = args->ca_arg.ca_str.s; *cp != '\0'; ++cp)
if(!fieldnamechar(*cp)){
cp = args->ca_arg.ca_str.s;
goto j501cp;
}
for(i = 0, hfpp = &hp->h_user_headers; *hfpp != NIL; ++i)
hfpp = &(*hfpp)->hf_next;
nl = su_cs_len(cp = args->ca_arg.ca_str.s) +1;
bl = su_cs_len(a3p->ca_arg.ca_str.s) +1;
*hfpp = hfp = n_autorec_alloc(VSTRUCT_SIZEOF(struct n_header_field,
hf_dat) + nl + bl);
hfp->hf_next = NIL;
hfp->hf_nl = nl - 1;
hfp->hf_bl = bl - 1;
su_mem_copy(&hfp->hf_dat[0], cp, nl);
su_mem_copy(&hfp->hf_dat[nl], a3p->ca_arg.ca_str.s, bl);
if(fprintf(fp, "210 %s %" PRIuZ "\n", &hfp->hf_dat[0], ++i) < 0)
cp = NIL;
}
}else if(su_cs_starts_with_case("list", cp)){
jdefault:
if(args == NIL){
if(fputs("210", fp) == EOF){
cp = NIL;
goto jleave;
}
#undef a_X
#define a_X(F,S) \
if(su_CONCAT(hp->h_, F) != NIL && fputs(" " su_STRING(S), fp) == EOF){\
cp = NIL;\
goto jleave;\
}
a_X(subject, Subject);
a_X(from, From);
a_X(sender, Sender);
a_X(to, To);
a_X(cc, Cc);
a_X(bcc, Bcc);
a_X(fcc, Fcc);
a_X(reply_to, Reply-To);
a_X(mft, Mail-Followup-To);
a_X(message_id, Message-ID);
a_X(ref, References);
a_X(in_reply_to, In-Reply-To);
a_X(mailx_command, Mailx-Command);
a_X(mailx_raw_to, Mailx-Raw-To);
a_X(mailx_raw_cc, Mailx-Raw-Cc);
a_X(mailx_raw_bcc, Mailx-Raw-Bcc);
a_X(mailx_orig_sender, Mailx-Orig-Sender);
a_X(mailx_orig_from, Mailx-Orig-From);
a_X(mailx_orig_to, Mailx-Orig-To);
a_X(mailx_orig_cc, Mailx-Orig-Cc);
a_X(mailx_orig_bcc, Mailx-Orig-Bcc);
#undef a_X
/* Print only one instance of each free-form header */
for(hfp = hp->h_user_headers; hfp != NIL; hfp = hfp->hf_next){
struct n_header_field *hfpx;
for(hfpx = hp->h_user_headers;; hfpx = hfpx->hf_next)
if(hfpx == hfp){
putc(' ', fp);
fputs(&hfp->hf_dat[0], fp);
break;
}else if(!su_cs_cmp_case(&hfpx->hf_dat[0], &hfp->hf_dat[0]))
break;
}
if(putc('\n', fp) == EOF)
cp = NIL;
goto jleave;
}
if(a3p != NIL)
goto jecmd;
if(!su_cs_cmp_case(args->ca_arg.ca_str.s, cp = "Subject")){
np = (hp->h_subject != NIL) ? R(struct mx_name*,-1) : NIL;
goto jlist;
}
if(!su_cs_cmp_case(args->ca_arg.ca_str.s, cp = "From")){
np = hp->h_from;
jlist:
fprintf(fp, "%s %s\n", (np == NIL ? "501" : "210"), cp);
goto jleave;
}
#undef a_X
#define a_X(F,H) \
if(!su_cs_cmp_case(args->ca_arg.ca_str.s, cp = su_STRING(F))){\
np = hp->su_CONCAT(h_,H);\
goto jlist;\
}
a_X(Sender, sender);
a_X(To, to);
a_X(Cc, cc);
a_X(Bcc, bcc);
a_X(Fcc, fcc);
a_X(Reply-To, reply_to);
a_X(Mail-Followup-To, mft);
a_X(Message-ID, message_id);
a_X(References, ref);
a_X(In-Reply-To, in_reply_to);
a_X(Mailx-Raw-To, mailx_raw_to);
a_X(Mailx-Raw-Cc, mailx_raw_cc);
a_X(Mailx-Raw-Bcc, mailx_raw_bcc);
a_X(Mailx-Orig-Sender, mailx_orig_sender);
a_X(Mailx-Orig-From, mailx_orig_from);
a_X(Mailx-Orig-To, mailx_orig_to);
a_X(Mailx-Orig-Cc, mailx_orig_cc);
a_X(Mailx-Orig-Bcc, mailx_orig_bcc);
#undef a_X
if(!su_cs_cmp_case(args->ca_arg.ca_str.s, cp = "Mailx-Command")){
np = (hp->h_mailx_command != NIL) ? R(struct mx_name*,-1) : NIL;
goto jlist;
}
/* Free-form header fields */
for(cp = args->ca_arg.ca_str.s; *cp != '\0'; ++cp)
if(!fieldnamechar(*cp)){
cp = args->ca_arg.ca_str.s;
goto j501cp;
}
cp = args->ca_arg.ca_str.s;
for(hfp = hp->h_user_headers;; hfp = hfp->hf_next){
if(hfp == NIL)
goto j501cp;
else if(!su_cs_cmp_case(cp, &hfp->hf_dat[0])){
if(fprintf(fp, "210 %s\n", &hfp->hf_dat[0]) < 0)
cp = NIL;
break;
}
}
}else if(su_cs_starts_with_case("remove", cp)){
if(args == NIL || a3p != NIL)
goto jecmd;
if(dmcp->dmc_flags & mx_DIG_MSG_RDONLY)
goto j505r;
if(!su_cs_cmp_case(args->ca_arg.ca_str.s, cp = "Subject")){
if(hp->h_subject == NIL)
goto j501cp;
hp->h_subject = NIL;
if(fprintf(fp, "210 %s\n", cp) < 0)
cp = NIL;
goto jleave;
}
if(!su_cs_cmp_case(args->ca_arg.ca_str.s, cp = "From")){
npp = &hp->h_from;
jrem:
if(*npp != NIL){
*npp = NIL;
if(fprintf(fp, "210 %s\n", cp) < 0)
cp = NIL;
goto jleave;
}else
goto j501cp;
}
#undef a_X
#define a_X(F,H) \
if(!su_cs_cmp_case(args->ca_arg.ca_str.s, cp = su_STRING(F))){\
npp = &hp->su_CONCAT(h_,H);\
goto jrem;\
}
a_X(Sender, sender);
a_X(To, to);
a_X(Cc, cc);
a_X(Bcc, bcc);
a_X(Fcc, fcc);
a_X(Reply-To, reply_to);
a_X(Mail-Followup-To, mft);
a_X(Message-ID, message_id);
a_X(References, ref);
a_X(In-Reply-To, in_reply_to);
#undef a_X
if((cp = n_header_is_known(args->ca_arg.ca_str.s, UZ_MAX)) != NIL)
goto j505r;
/* Free-form header fields (note j501cp may print non-normalized name) */
/* C99 */{
struct n_header_field **hfpp;
boole any;
for(cp = args->ca_arg.ca_str.s; *cp != '\0'; ++cp)
if(!fieldnamechar(*cp)){
cp = args->ca_arg.ca_str.s;
goto j501cp;
}
cp = args->ca_arg.ca_str.s;
for(any = FAL0, hfpp = &hp->h_user_headers; (hfp = *hfpp) != NIL;){
if(!su_cs_cmp_case(cp, &hfp->hf_dat[0])){
*hfpp = hfp->hf_next;
if(!any){
if(fprintf(fp, "210 %s\n", &hfp->hf_dat[0]) < 0){
cp = NIL;
goto jleave;
}
}
any = TRU1;
}else
hfpp = &hfp->hf_next;
}
if(!any)
goto j501cp;
}
}else if(su_cs_starts_with_case("remove-at", cp)){
if(args == NIL || a3p == NIL)
goto jecmd;
if(dmcp->dmc_flags & mx_DIG_MSG_RDONLY)
goto j505r;
if((su_idec_uz_cp(&i, a3p->ca_arg.ca_str.s, 0, NIL
) & (su_IDEC_STATE_EMASK | su_IDEC_STATE_CONSUMED)
) != su_IDEC_STATE_CONSUMED || i == 0){
if(fprintf(fp, "505 invalid position: %s\n",
a3p->ca_arg.ca_str.s) < 0)
cp = NIL;
goto jleave;
}
if(!su_cs_cmp_case(args->ca_arg.ca_str.s, cp = "Subject")){
if(hp->h_subject != NIL && i == 1){
hp->h_subject = NIL;
if(fprintf(fp, "210 %s 1\n", cp) < 0)
cp = NIL;
goto jleave;
}else
goto j501cp;
}
if(!su_cs_cmp_case(args->ca_arg.ca_str.s, cp = "From")){
npp = &hp->h_from;
jremat:
if((np = *npp) == NIL)
goto j501cp;
while(--i != 0 && np != NIL)
np = np->n_flink;
if(np == NIL)
goto j501cp;
if(np->n_blink != NIL)
np->n_blink->n_flink = np->n_flink;
else
*npp = np->n_flink;
if(np->n_flink != NIL)
np->n_flink->n_blink = np->n_blink;
if(fprintf(fp, "210 %s\n", cp) < 0)
cp = NIL;
goto jleave;
}
#undef a_X
#define a_X(F,H) \
if(!su_cs_cmp_case(args->ca_arg.ca_str.s, cp = su_STRING(F))){\
npp = &hp->su_CONCAT(h_,H);\
goto jremat;\
}
a_X(Sender, sender);
a_X(To, to);
a_X(Cc, cc);
a_X(Bcc, bcc);
a_X(Fcc, fcc);
a_X(Reply-To, reply_to);
a_X(Mail-Followup-To, mft);
a_X(Message-ID, message_id);
a_X(References, ref);
a_X(In-Reply-To, in_reply_to);
#undef a_X
if((cp = n_header_is_known(args->ca_arg.ca_str.s, UZ_MAX)) != NIL)
goto j505r;
/* Free-form header fields */
/* C99 */{
struct n_header_field **hfpp;
for(cp = args->ca_arg.ca_str.s; *cp != '\0'; ++cp)
if(!fieldnamechar(*cp)){
cp = args->ca_arg.ca_str.s;
goto j501cp;
}
cp = args->ca_arg.ca_str.s;
for(hfpp = &hp->h_user_headers; (hfp = *hfpp) != NIL;){
if(--i == 0){
*hfpp = hfp->hf_next;
if(fprintf(fp, "210 %s %" PRIuZ "\n", &hfp->hf_dat[0], i) < 0){
cp = NIL;
goto jleave;
}
break;
}else
hfpp = &hfp->hf_next;
}
if(hfp == NIL)
goto j501cp;
}
}else if(su_cs_starts_with_case("show", cp)){
if(args == NIL || a3p != NIL)
goto jecmd;
if(!su_cs_cmp_case(args->ca_arg.ca_str.s, cp = "Subject")){
if(hp->h_subject == NIL)
goto j501cp;
if(fprintf(fp, "212 %s\n%s\n\n", cp, a_DMSG_QUOTE(hp->h_subject)) < 0)
cp = NIL;
goto jleave;
}
if(!su_cs_cmp_case(args->ca_arg.ca_str.s, cp = "From")){
np = hp->h_from;
jshow:
if(np == NIL)
goto j501cp;
fprintf(fp, "211 %s\n", cp);
do if(!(np->n_type & GDEL)){
switch(np->n_flags & mx_NAME_ADDRSPEC_ISMASK){
case mx_NAME_ADDRSPEC_ISFILE: cp = n_hy; break;
case mx_NAME_ADDRSPEC_ISPIPE: cp = "|"; break;
case mx_NAME_ADDRSPEC_ISNAME: cp = n_ns; break;
default: cp = np->n_name; break;
}
fprintf(fp, "%s %s\n", cp, a_DMSG_QUOTE(np->n_fullname));
}while((np = np->n_flink) != NIL);
if(putc('\n', fp) == EOF)
cp = NIL;
goto jleave;
}
#undef a_X
#define a_X(F,H) \
if(!su_cs_cmp_case(args->ca_arg.ca_str.s, cp = su_STRING(F))){\
np = hp->su_CONCAT(h_,H);\
goto jshow;\
}
a_X(Sender, sender);
a_X(To, to);
a_X(Cc, cc);
a_X(Bcc, bcc);
a_X(Fcc, fcc);
a_X(Reply-To, reply_to);
a_X(Mail-Followup-To, mft);
a_X(Message-ID, message_id);
a_X(References, ref);
a_X(In-Reply-To, in_reply_to);
a_X(Mailx-Raw-To, mailx_raw_to);
a_X(Mailx-Raw-Cc, mailx_raw_cc);
a_X(Mailx-Raw-Bcc, mailx_raw_bcc);
a_X(Mailx-Orig-Sender, mailx_orig_sender);
a_X(Mailx-Orig-From, mailx_orig_from);
a_X(Mailx-Orig-To, mailx_orig_to);
a_X(Mailx-Orig-Cc, mailx_orig_cc);
a_X(Mailx-Orig-Bcc, mailx_orig_bcc);
#undef a_X
if(!su_cs_cmp_case(args->ca_arg.ca_str.s, cp = "Mailx-Command")){
if(hp->h_mailx_command == NIL)
goto j501cp;
if(fprintf(fp, "212 %s\n%s\n\n", cp, hp->h_mailx_command) < 0)
cp = NIL;
goto jleave;
}
/* Free-form header fields */
/* C99 */{
boole any;
for(cp = args->ca_arg.ca_str.s; *cp != '\0'; ++cp)
if(!fieldnamechar(*cp)){
cp = args->ca_arg.ca_str.s;
goto j501cp;
}
cp = args->ca_arg.ca_str.s;
for(any = FAL0, hfp = hp->h_user_headers; hfp != NIL;
hfp = hfp->hf_next){
if(!su_cs_cmp_case(cp, &hfp->hf_dat[0])){
if(!any)
fprintf(fp, "212 %s\n", &hfp->hf_dat[0]);
any = TRU1;
fprintf(fp, "%s\n", a_DMSG_QUOTE(&hfp->hf_dat[hfp->hf_nl +1]));
}
}
if(!any)
goto j501cp;
if(putc('\n', fp) == EOF)
cp = NIL;
}
}else
goto jecmd;
jleave:
NYD2_OU;
return (cp != NIL);
jecmd:
if(fputs("500\n", fp) == EOF)
cp = NIL;
cp = NIL;
goto jleave;
j505r:
if(fprintf(fp, "505 read-only: %s\n", cp) < 0)
cp = NIL;
goto jleave;
j501cp:
if(fprintf(fp, "501 %s\n", cp) < 0)
cp = NIL;
goto jleave;
}
static boole
a_dmsg__attach(FILE *fp, struct mx_dig_msg_ctx *dmcp,
struct mx_cmd_arg *args){
boole status;
struct mx_attachment *ap;
char const *cp;
struct header *hp;
NYD2_IN;
hp = dmcp->dmc_hp;
if(args == NIL){
cp = su_empty; /* xxx not NIL anyway */
goto jdefault;
}
cp = args->ca_arg.ca_str.s;
args = args->ca_next;
if(su_cs_starts_with_case("attribute", cp)){
if(args == NIL || args->ca_next != NIL)
goto jecmd;
cp = args->ca_arg.ca_str.s;
if((ap = mx_attachments_find(hp->h_attach, cp, NIL)) == NIL)
goto j501;
jatt_att:
fprintf(fp, "212 %s\n", a_DMSG_QUOTE(cp));
if(ap->a_msgno > 0){
if(fprintf(fp, "message-number %d\n\n", ap->a_msgno) < 0)
cp = NIL;
}else{
fprintf(fp, "creation-name %s\nopen-path %s\nfilename %s\n",
a_DMSG_QUOTE(ap->a_path_user), a_DMSG_QUOTE(ap->a_path),
a_DMSG_QUOTE(ap->a_name));
if((cp = ap->a_content_description) != NIL)
fprintf(fp, "content-description %s\n", a_DMSG_QUOTE(cp));
if(ap->a_content_id != NIL)
fprintf(fp, "content-id %s\n", ap->a_content_id->n_name);
if((cp = ap->a_content_type) != NIL)
fprintf(fp, "content-type %s\n", a_DMSG_QUOTE(cp));
if((cp = ap->a_content_disposition) != NIL)
fprintf(fp, "content-disposition %s\n", a_DMSG_QUOTE(cp));
cp = (putc('\n', fp) != EOF) ? su_empty : NIL;
}
}else if(su_cs_starts_with_case("attribute-at", cp)){
uz i;
if(args == NIL || args->ca_next != NIL)
goto jecmd;
if((su_idec_uz_cp(&i, cp = args->ca_arg.ca_str.s, 0, NIL
) & (su_IDEC_STATE_EMASK | su_IDEC_STATE_CONSUMED)
) != su_IDEC_STATE_CONSUMED || i == 0)
goto j505invpos;
for(ap = hp->h_attach; ap != NIL && --i != 0; ap = ap->a_flink)
;
if(ap != NIL)
goto jatt_att;
goto j501;
}else if(su_cs_starts_with_case("attribute-set", cp)){
/* ATT-ID KEYWORD VALUE */
if(args == NIL)
goto jecmd;
cp = args->ca_arg.ca_str.s;
args = args->ca_next;
if(args == NIL || args->ca_next == NIL || args->ca_next->ca_next != NIL)
goto jecmd;
if(dmcp->dmc_flags & mx_DIG_MSG_RDONLY)
goto j505r;
if((ap = mx_attachments_find(hp->h_attach, cp, NIL)) == NIL)
goto j501;
jatt_attset:
if(ap->a_msgno > 0){
if(fprintf(fp, "505 RFC822 message attachment: %s\n", cp) < 0)
cp = NIL;
}else{
char c;
char const *keyw, *xcp;
keyw = args->ca_arg.ca_str.s;
cp = args->ca_next->ca_arg.ca_str.s;
for(xcp = cp; (c = *xcp) != '\0'; ++xcp)
if(su_cs_is_cntrl(c))
goto j505;
c = *cp;
if(!su_cs_cmp_case(keyw, "filename"))
ap->a_name = (c == '\0') ? ap->a_path_bname : cp;
else if(!su_cs_cmp_case(keyw, "content-description"))
ap->a_content_description = (c == '\0') ? NIL : cp;
else if(!su_cs_cmp_case(keyw, "content-id")){
ap->a_content_id = NIL;
if(c != '\0'){
struct mx_name *np;
/* XXX lextract->extract_single() */
np = checkaddrs(lextract(cp, GREF),
/*EACM_STRICT | TODO '/' valid!! */ EACM_NOLOG |
EACM_NONAME, NIL);
if(np != NIL && np->n_flink == NIL)
ap->a_content_id = np;
else
cp = NIL;
}
}else if(!su_cs_cmp_case(keyw, "content-type")){
if((ap->a_content_type = (c == '\0') ? NIL : cp) != NIL){
char *cp2;
for(cp2 = UNCONST(char*,cp); (c = *cp++) != '\0';)
*cp2++ = su_cs_to_lower(c);
if(!mx_mimetype_is_valid(ap->a_content_type, TRU1, FAL0)){
ap->a_content_type = NIL;
goto j505;
}
}
}else if(!su_cs_cmp_case(keyw, "content-disposition"))
ap->a_content_disposition = (c == '\0') ? NIL : cp;
else
cp = NIL;
if(cp != NIL){
uz i;
for(i = 0; ap != NIL; ++i, ap = ap->a_blink)
;
if(fprintf(fp, "210 %" PRIuZ "\n", i) < 0)
cp = NIL;
}else{
cp = xcp;
goto j505; /* xxx jecmd; */
}
}
}else if(su_cs_starts_with_case("attribute-set-at", cp)){
uz i;
cp = args->ca_arg.ca_str.s;
args = args->ca_next;
if(args == NIL || args->ca_next == NIL || args->ca_next->ca_next != NIL)
goto jecmd;
if(dmcp->dmc_flags & mx_DIG_MSG_RDONLY)
goto j505r;
if((su_idec_uz_cp(&i, cp, 0, NIL
) & (su_IDEC_STATE_EMASK | su_IDEC_STATE_CONSUMED)
) != su_IDEC_STATE_CONSUMED || i == 0)
goto j505invpos;
for(ap = hp->h_attach; ap != NIL && --i != 0; ap = ap->a_flink)
;
if(ap != NIL)
goto jatt_attset;
goto j501;
}else if(su_cs_starts_with_case("insert", cp)){
BITENUM_IS(u32,mx_attach_error) aerr;
if(args == NIL || args->ca_next != NIL)
goto jecmd;
if(dmcp->dmc_flags & mx_DIG_MSG_RDONLY)
goto j505r;
hp->h_attach = mx_attachments_append(hp->h_attach, args->ca_arg.ca_str.s,
&aerr, &ap);
switch(aerr){
case mx_ATTACHMENTS_ERR_FILE_OPEN: cp = "505"; goto jatt__ins;
case mx_ATTACHMENTS_ERR_ICONV_FAILED: cp = "506"; goto jatt__ins;
case mx_ATTACHMENTS_ERR_ICONV_NAVAIL: /* FALLTHRU */
case mx_ATTACHMENTS_ERR_OTHER: /* FALLTHRU */
default:
cp = "501";
jatt__ins:
if(fprintf(fp, "%s %s\n", cp, a_DMSG_QUOTE(args->ca_arg.ca_str.s)
) < 0)
cp = NIL;
break;
case mx_ATTACHMENTS_ERR_NONE:{
uz i;
for(i = 0; ap != NIL; ++i, ap = ap->a_blink)
;
if(fprintf(fp, "210 %" PRIuZ "\n", i) < 0)
cp = NIL;
}break;
}
}else if(su_cs_starts_with_case("list", cp)){
jdefault:
if(args != NIL)
goto jecmd;
if((ap = hp->h_attach) == NIL)
goto j501;
fputs("212\n", fp);
do
fprintf(fp, "%s\n", a_DMSG_QUOTE(ap->a_path_user));
while((ap = ap->a_flink) != NIL);
if(putc('\n', fp) == EOF)
cp = NIL;
}else if(su_cs_starts_with_case("remove", cp)){
if(args == NIL || args->ca_next != NIL)
goto jecmd;
if(dmcp->dmc_flags & mx_DIG_MSG_RDONLY)
goto j505r;
cp = args->ca_arg.ca_str.s;
if((ap = mx_attachments_find(hp->h_attach, cp, &status)) == NIL)
goto j501;
if(status == TRUM1)
goto j506;
hp->h_attach = mx_attachments_remove(hp->h_attach, ap);
if(fprintf(fp, "210 %s\n", a_DMSG_QUOTE(cp)) < 0)
cp = NIL;
}else if(su_cs_starts_with_case("remove-at", cp)){
uz i;
if(args == NIL || args->ca_next != NIL)
goto jecmd;
if(dmcp->dmc_flags & mx_DIG_MSG_RDONLY)
goto j505r;
if((su_idec_uz_cp(&i, cp = args->ca_arg.ca_str.s, 0, NIL
) & (su_IDEC_STATE_EMASK | su_IDEC_STATE_CONSUMED)
) != su_IDEC_STATE_CONSUMED || i == 0)
goto j505invpos;
for(ap = hp->h_attach; ap != NIL && --i != 0; ap = ap->a_flink)
;
if(ap != NIL){
hp->h_attach = mx_attachments_remove(hp->h_attach, ap);
if(fprintf(fp, "210 %s\n", cp) < 0)
cp = NIL;
}else
goto j501;
}else
goto jecmd;
jleave:
NYD2_OU;
return (cp != NIL);
jecmd:
if(fputs("500\n", fp) == EOF)
cp = NIL;
cp = NIL;
goto jleave;
j501:
if(fputs("501\n", fp) == EOF)
cp = NIL;
goto jleave;
j505:
if(fputs("505\n", fp) == EOF)
cp = NIL;
goto jleave;
j505r:
if(fprintf(fp, "505 read-only: %s\n", cp) < 0)
cp = NIL;
goto jleave;
j505invpos:
if(fprintf(fp, "505 invalid position: %s\n", cp) < 0)
cp = NIL;
goto jleave;
j506:
if(fputs("506\n", fp) == EOF)
cp = NIL;
goto jleave;
}
void
mx_dig_msg_on_mailbox_close(struct mailbox *mbp){ /* XXX HACK <- event! */
struct mx_dig_msg_ctx *dmcp;
NYD_IN;
while((dmcp = mbp->mb_digmsg) != NIL){
mbp->mb_digmsg = dmcp->dmc_next;
if(dmcp->dmc_flags & mx_DIG_MSG_FCLOSE)
fclose(dmcp->dmc_fp);
if(dmcp->dmc_flags & mx_DIG_MSG_OWN_MEMBAG)
su_mem_bag_gut(dmcp->dmc_membag);
n_free(dmcp);
}
NYD_OU;
}
int
c_digmsg(void *vp){
char const *cp, *emsg;
struct mx_dig_msg_ctx *dmcp;
struct mx_cmd_arg *cap;
struct mx_cmd_arg_ctx *cacp;
NYD_IN;
n_pstate_err_no = su_ERR_NONE;
cacp = vp;
cap = cacp->cac_arg;
if(su_cs_starts_with_case("create", cp = cap->ca_arg.ca_str.s)){
if(cacp->cac_no < 2 || cacp->cac_no > 3) /* XXX argparse is stupid */
goto jesynopsis;
cap = cap->ca_next;
/* Request to use STDOUT? */
if(cacp->cac_no == 3){
cp = cap->ca_next->ca_arg.ca_str.s;
if(*cp != '-' || cp[1] != '\0'){
emsg = N_("digmsg: create: invalid I/O channel: %s\n");
goto jeinval_quote;
}
}
/* First of all, our context object */
switch(a_dmsg_find(cp = cap->ca_arg.ca_str.s, &dmcp, TRU1)){
case su_ERR_INVAL:
emsg = N_("digmsg: create: message number invalid: %s\n");
goto jeinval_quote;
case su_ERR_EXIST:
emsg = N_("digmsg: create: message object already exists: %s\n");
goto jeinval_quote;
default:
break;
}
if(dmcp->dmc_flags & mx_DIG_MSG_COMPOSE)
dmcp->dmc_flags = mx_DIG_MSG_COMPOSE | mx_DIG_MSG_COMPOSE_DIGGED;
else{
FILE *fp;
if((fp = setinput(&mb, dmcp->dmc_mp, NEED_HEADER)) == NIL){
/* XXX Should have panicked before.. */
n_free(dmcp);
emsg = N_("digmsg: create: mailbox I/O error for message: %s\n");
goto jeinval_quote;
}
su_mem_bag_push(n_go_data->gdc_membag, dmcp->dmc_membag);
/* XXX n_header_extract error!! */
n_header_extract((n_HEADER_EXTRACT_FULL |
n_HEADER_EXTRACT_PREFILL_RECEIVERS |
n_HEADER_EXTRACT_IGNORE_FROM_), fp, dmcp->dmc_hp, NIL);
su_mem_bag_pop(n_go_data->gdc_membag, dmcp->dmc_membag);
}
if(cacp->cac_no == 3)
dmcp->dmc_fp = n_stdout;
/* For compose mode simply use FS_O_REGISTER, the number of dangling
* deleted files with open descriptors until next fs_close_all()
* should be very small; if this paradigm is changed
* DIG_MSG_COMPOSE_GUT() needs to be adjusted */
else if((dmcp->dmc_fp = mx_fs_tmp_open("digmsg", (mx_FS_O_RDWR |
mx_FS_O_UNLINK | (dmcp->dmc_flags & mx_DIG_MSG_COMPOSE
? mx_FS_O_REGISTER : 0)),
NIL)) != NIL)
dmcp->dmc_flags |= mx_DIG_MSG_HAVE_FP |
(dmcp->dmc_flags & mx_DIG_MSG_COMPOSE ? 0 : mx_DIG_MSG_FCLOSE);
else{
n_err(_("digmsg: create: cannot create temporary file: %s\n"),
su_err_doc(n_pstate_err_no = su_err_no()));
vp = NIL;
goto jeremove;
}
if(!(dmcp->dmc_flags & mx_DIG_MSG_COMPOSE)){
dmcp->dmc_last = NIL;
if((dmcp->dmc_next = mb.mb_digmsg) != NIL)
dmcp->dmc_next->dmc_last = dmcp;
mb.mb_digmsg = dmcp;
}
}else if(su_cs_starts_with_case("remove", cp)){
if(cacp->cac_no != 2)
goto jesynopsis;
cap = cap->ca_next;
switch(a_dmsg_find(cp = cap->ca_arg.ca_str.s, &dmcp, FAL0)){
case su_ERR_INVAL:
emsg = N_("digmsg: remove: message number invalid: %s\n");
goto jeinval_quote;
default:
if(!(dmcp->dmc_flags & mx_DIG_MSG_COMPOSE) ||
(dmcp->dmc_flags & mx_DIG_MSG_COMPOSE_DIGGED))
break;
/* FALLTHRU */
case su_ERR_NOENT:
emsg = N_("digmsg: remove: no such message object: %s\n");
goto jeinval_quote;
}
if(!(dmcp->dmc_flags & mx_DIG_MSG_COMPOSE)){
if(dmcp->dmc_last != NIL)
dmcp->dmc_last->dmc_next = dmcp->dmc_next;
else{
ASSERT(dmcp == mb.mb_digmsg);
mb.mb_digmsg = dmcp->dmc_next;
}
if(dmcp->dmc_next != NIL)
dmcp->dmc_next->dmc_last = dmcp->dmc_last;
}
if((dmcp->dmc_flags & mx_DIG_MSG_HAVE_FP) &&
mx_dig_msg_read_overlay == dmcp)
mx_dig_msg_read_overlay = NIL;
if(dmcp->dmc_flags & mx_DIG_MSG_FCLOSE)
fclose(dmcp->dmc_fp);
jeremove:
if(dmcp->dmc_flags & mx_DIG_MSG_OWN_MEMBAG)
su_mem_bag_gut(dmcp->dmc_membag);
if(dmcp->dmc_flags & mx_DIG_MSG_COMPOSE)
dmcp->dmc_flags = mx_DIG_MSG_COMPOSE;
else
n_free(dmcp);
}else{
switch(a_dmsg_find(cp, &dmcp, FAL0)){
case su_ERR_INVAL:
emsg = N_("digmsg: message number invalid: %s\n");
goto jeinval_quote;
case su_ERR_NOENT:
emsg = N_("digmsg: no such message object: %s\n");
goto jeinval_quote;
default:
break;
}
cap = cap->ca_next;
if(dmcp->dmc_flags & mx_DIG_MSG_HAVE_FP){
rewind(dmcp->dmc_fp);
ftruncate(fileno(dmcp->dmc_fp), 0);
}
su_mem_bag_push(n_go_data->gdc_membag, dmcp->dmc_membag);
if(!a_dmsg_cmd(dmcp->dmc_fp, dmcp, cap,
((cap != NIL) ? cap->ca_next : NIL)))
vp = NIL;
su_mem_bag_pop(n_go_data->gdc_membag, dmcp->dmc_membag);
if(dmcp->dmc_flags & mx_DIG_MSG_HAVE_FP){
rewind(dmcp->dmc_fp);
/* This will be reset by go_input() _if_ we read to EOF */
mx_dig_msg_read_overlay = dmcp;
}
}
jleave:
NYD_OU;
return (vp == NIL);
jesynopsis:
mx_cmd_print_synopsis(mx_cmd_firstfit("digmsg"), NIL);
goto jeinval;
jeinval_quote:
emsg = V_(emsg);
n_err(emsg, n_shexp_quote_cp(cp, FAL0));
jeinval:
n_pstate_err_no = su_ERR_INVAL;
vp = NIL;
goto jleave;
}
boole
mx_dig_msg_circumflex(struct mx_dig_msg_ctx *dmcp, FILE *fp, char const *cmd){
/* Identical to (subset of) c_digmsg() cmd-tab */
mx_CMD_ARG_DESC_SUBCLASS_DEF_NAME(dm, "digmsg", 5, pseudo_cad){
{mx_CMD_ARG_DESC_SHEXP | mx_CMD_ARG_DESC_HONOUR_STOP,
n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_TRIM_IFSSPACE},
{mx_CMD_ARG_DESC_SHEXP | mx_CMD_ARG_DESC_OPTION |
mx_CMD_ARG_DESC_HONOUR_STOP,
n_SHEXP_PARSE_TRIM_IFSSPACE}, /* arg1 */
{mx_CMD_ARG_DESC_SHEXP | mx_CMD_ARG_DESC_OPTION |
mx_CMD_ARG_DESC_HONOUR_STOP,
n_SHEXP_PARSE_TRIM_IFSSPACE}, /* arg2 */
{mx_CMD_ARG_DESC_SHEXP | mx_CMD_ARG_DESC_OPTION |
mx_CMD_ARG_DESC_HONOUR_STOP,
n_SHEXP_PARSE_TRIM_IFSSPACE}, /* arg3 */
{mx_CMD_ARG_DESC_SHEXP | mx_CMD_ARG_DESC_OPTION |
mx_CMD_ARG_DESC_HONOUR_STOP |
mx_CMD_ARG_DESC_GREEDY | mx_CMD_ARG_DESC_GREEDY_JOIN,
n_SHEXP_PARSE_TRIM_IFSSPACE} /* arg4 */
}mx_CMD_ARG_DESC_SUBCLASS_DEF_END;
struct mx_cmd_arg_ctx cac;
boole rv;
NYD_IN;
cac.cac_desc = mx_CMD_ARG_DESC_SUBCLASS_CAST(&pseudo_cad);
cac.cac_indat = cmd;
cac.cac_inlen = UZ_MAX;
cac.cac_msgflag = cac.cac_msgmask = 0;
if((rv = mx_cmd_arg_parse(&cac)))
rv = a_dmsg_cmd(fp, dmcp, cac.cac_arg, cac.cac_arg->ca_next);
NYD_OU;
return rv;
}
#include "su/code-ou.h"
/* s-it-mode */
|
catroll/mailx
|
src/mx/sendout.c
|
<gh_stars>1-10
/*@ S-nail - a mail user agent derived from Berkeley Mail.
*@ Message sending lifecycle, header composing, etc.
*
* Copyright (c) 2000-2004 <NAME>, Freiburg i. Br., Germany.
* Copyright (c) 2012 - 2020 <NAME>) Nurpmeso <<EMAIL>>.
* SPDX-License-Identifier: BSD-3-Clause
*/
/*
* Copyright (c) 1980, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#undef su_FILE
#define su_FILE sendout
#define mx_SOURCE
#ifndef mx_HAVE_AMALGAMATION
# include "mx/nail.h"
#endif
#include <su/cs.h>
#include <su/mem.h>
#include "mx/attachments.h"
#include "mx/child.h"
#include "mx/cmd.h"
#include "mx/cmd-mlist.h"
#include "mx/cred-auth.h"
#include "mx/file-locks.h"
#include "mx/file-streams.h"
#include "mx/iconv.h"
#include "mx/mime-type.h"
#include "mx/names.h"
#include "mx/net-smtp.h"
#include "mx/privacy.h"
#include "mx/random.h"
#include "mx/sigs.h"
#include "mx/tty.h"
#include "mx/url.h"
/* TODO fake */
#include "su/code-in.h"
#undef SEND_LINESIZE
#define SEND_LINESIZE \
((1024 / B64_ENCODE_INPUT_PER_LINE) * B64_ENCODE_INPUT_PER_LINE)
enum a_sendout_addrline_flags{
a_SENDOUT_AL_INC_INVADDR = 1<<0, /* _Do_ include invalid addresses */
a_SENDOUT_AL_DOMIME = 1<<1, /* Perform MIME conversion */
a_SENDOUT_AL_COMMA = GCOMMA,
a_SENDOUT_AL_FILES = GFILES,
_a_SENDOUT_AL_GMASK = a_SENDOUT_AL_COMMA | a_SENDOUT_AL_FILES
};
CTA(!(_a_SENDOUT_AL_GMASK & (a_SENDOUT_AL_INC_INVADDR|a_SENDOUT_AL_DOMIME)),
"Code-required condition not satisfied but actual bit carrier value");
enum a_sendout_sendwait_flags{
a_SENDOUT_SWF_NONE,
a_SENDOUT_SWF_MTA = 1u<<0,
a_SENDOUT_SWF_PCC = 1u<<1,
a_SENDOUT_SWF_MASK = a_SENDOUT_SWF_MTA | a_SENDOUT_SWF_PCC
};
static char const *__sendout_ident; /* TODO temporary; rewrite n_puthead() */
static char * _sendout_boundary;
static s8 _sendout_error;
/* */
static u32 a_sendout_sendwait_to_swf(void);
/* *fullnames* appears after command line arguments have been parsed */
static struct mx_name *a_sendout_fullnames_cleanup(struct mx_name *np);
/* */
static boole a_sendout_put_name(char const *line, enum gfield w,
enum sendaction action, char const *prefix, FILE *fo,
struct mx_name **xp);
/* Place Content-Type:, Content-Transfer-Encoding:, Content-Disposition:
* headers, respectively */
static int a_sendout_put_ct(FILE *fo, char const *contenttype,
char const *charset);
su_SINLINE int a_sendout_put_cte(FILE *fo, enum conversion conv);
static int a_sendout_put_cd(FILE *fo, char const *cd, char const *filename);
/* Put all entries of the given header list */
static boole _sendout_header_list(FILE *fo, struct n_header_field *hfp,
boole nodisp);
/* */
static s32 a_sendout_body(FILE *fo, FILE *fi, enum conversion convert);
/* Write an attachment to the file buffer, converting to MIME */
static s32 a_sendout_attach_file(struct header *hp, struct mx_attachment *ap,
FILE *fo, boole force);
static s32 a_sendout__attach_file(struct header *hp, struct mx_attachment *ap,
FILE *f, boole force);
/* There are non-local receivers, collect credentials etc. */
static boole _sendbundle_setup_creds(struct sendbundle *sbpm,
boole signing_caps);
/* Attach a message to the file buffer */
static s32 a_sendout_attach_msg(struct header *hp, struct mx_attachment *ap,
FILE *fo);
/* Generate the body of a MIME multipart message */
static s32 make_multipart(struct header *hp, int convert, FILE *fi,
FILE *fo, char const *contenttype, char const *charset, boole force);
/* Prepend a header in front of the collected stuff and return the new file */
static FILE *a_sendout_infix(struct header *hp, FILE *fi, boole dosign,
boole force);
/* Check whether Disposition-Notification-To: is desired */
static boole _check_dispo_notif(struct mx_name *mdn, struct header *hp,
FILE *fo);
/* Send mail to a bunch of user names. The interface is through mail() */
static int a_sendout_sendmail(void *v, enum n_mailsend_flags msf);
/* Deal with file and pipe addressees */
static struct mx_name *a_sendout_file_a_pipe(struct mx_name *names, FILE *fo,
boole *senderror);
/* Record outgoing mail if instructed to do so; in *record* unless to is set */
static boole a_sendout_mightrecord(FILE *fp, struct mx_name *to, boole resend);
static boole a_sendout__savemail(char const *name, FILE *fp, boole resend);
/* Move a message over to non-local recipients (via MTA) */
static boole a_sendout_transfer(struct sendbundle *sbp, boole resent,
boole *senderror);
/* Actual MTA interaction */
static boole a_sendout_mta_start(struct sendbundle *sbp);
static char const **a_sendout_mta_file_args(struct mx_name *to,
struct header *hp);
static void a_sendout_mta_file_debug(struct sendbundle *sbp, char const *mta,
char const **args);
static boole a_sendout_mta_test(struct sendbundle *sbp, char const *mta);
/* Create a Message-ID: header field. Use either host name or from address */
static char const *a_sendout_random_id(struct header *hp, boole msgid);
/* Format the given header line to not exceed 72 characters */
static boole a_sendout_put_addrline(char const *hname, struct mx_name *np,
FILE *fo, enum a_sendout_addrline_flags saf);
/* Rewrite a message for resending, adding the Resent-Headers */
static boole a_sendout_infix_resend(FILE *fi, FILE *fo, struct message *mp,
struct mx_name *to, int add_resent);
static u32
a_sendout_sendwait_to_swf(void){ /* TODO should happen at var assign time */
char *buf;
u32 rv;
char const *cp;
NYD2_IN;
if((cp = ok_vlook(sendwait)) == NIL)
rv = a_SENDOUT_SWF_NONE;
else if(*cp == '\0')
rv = a_SENDOUT_SWF_MASK;
else{
rv = a_SENDOUT_SWF_NONE;
for(buf = savestr(cp); (cp = su_cs_sep_c(&buf, ',', TRU1)) != NIL;){
if(!su_cs_cmp_case(cp, "mta"))
rv |= a_SENDOUT_SWF_MTA;
else if(!su_cs_cmp_case(cp, "pcc"))
rv |= a_SENDOUT_SWF_PCC;
else if(n_poption & n_PO_D_V)
n_err(_("Unknown *sendwait* content: %s\n"),
n_shexp_quote_cp(cp, FAL0));
}
}
NYD2_OU;
return rv;
}
static struct mx_name *
a_sendout_fullnames_cleanup(struct mx_name *np){
struct mx_name *xp;
NYD2_IN;
for(xp = np; xp != NULL; xp = xp->n_flink){
xp->n_type &= ~(GFULL | GFULLEXTRA);
xp->n_fullname = xp->n_name;
xp->n_fullextra = NULL;
}
NYD2_OU;
return np;
}
static boole
a_sendout_put_name(char const *line, enum gfield w, enum sendaction action,
char const *prefix, FILE *fo, struct mx_name **xp){
boole rv;
struct mx_name *np;
NYD_IN;
np = (w & GNOT_A_LIST ? n_extract_single : lextract)(line, GEXTRA | GFULL);
if(xp != NULL)
*xp = np;
if(np == NULL)
rv = FAL0;
else
rv = a_sendout_put_addrline(prefix, np, fo, ((w & GCOMMA) |
((action != SEND_TODISP) ? a_SENDOUT_AL_DOMIME : 0)));
NYD_OU;
return rv;
}
static int
a_sendout_put_ct(FILE *fo, char const *contenttype, char const *charset){
int rv;
NYD2_IN;
if((rv = fprintf(fo, "Content-Type: %s", contenttype)) < 0)
goto jerr;
if(charset == NULL)
goto jend;
if(putc(';', fo) == EOF)
goto jerr;
++rv;
if(su_cs_len(contenttype) + sizeof("Content-Type: ;")-1 > 50){
if(putc('\n', fo) == EOF)
goto jerr;
++rv;
}
/* C99 */{
int i;
i = fprintf(fo, " charset=%s", charset);
if(i < 0)
goto jerr;
rv += i;
}
jend:
if(putc('\n', fo) == EOF)
goto jerr;
++rv;
jleave:
NYD2_OU;
return rv;
jerr:
rv = -1;
goto jleave;
}
su_SINLINE int
a_sendout_put_cte(FILE *fo, enum conversion conv){
int rv;
NYD2_IN;
/* RFC 2045, 6.1.:
* This is the default value -- that is,
* "Content-Transfer-Encoding: 7BIT" is assumed if the
* Content-Transfer-Encoding header field is not present.
*/
rv = (conv == CONV_7BIT) ? 0
: fprintf(fo, "Content-Transfer-Encoding: %s\n",
mime_enc_from_conversion(conv));
NYD2_OU;
return rv;
}
static int
a_sendout_put_cd(FILE *fo, char const *cd, char const *filename){
struct str f;
s8 mpc;
int rv;
NYD2_IN;
f.s = NULL;
/* xxx Ugly with the trailing space in case of wrap! */
if((rv = fprintf(fo, "Content-Disposition: %s; ", cd)) < 0)
goto jerr;
if(!(mpc = mime_param_create(&f, "filename", filename)))
goto jerr;
/* Always fold if result contains newlines */
if(mpc < 0 || f.l + rv > MIME_LINELEN) { /* FIXME MIME_LINELEN_MAX */
if(putc('\n', fo) == EOF || putc(' ', fo) == EOF)
goto jerr;
rv += 2;
}
if(fputs(f.s, fo) == EOF || putc('\n', fo) == EOF)
goto jerr;
rv += (int)++f.l;
jleave:
NYD2_OU;
return rv;
jerr:
rv = -1;
goto jleave;
}
static boole
_sendout_header_list(FILE *fo, struct n_header_field *hfp, boole nodisp){
boole rv;
NYD2_IN;
for(rv = TRU1; hfp != NULL; hfp = hfp->hf_next)
if(fwrite(hfp->hf_dat, sizeof(char), hfp->hf_nl, fo) != hfp->hf_nl ||
putc(':', fo) == EOF || putc(' ', fo) == EOF ||
xmime_write(hfp->hf_dat + hfp->hf_nl +1, hfp->hf_bl, fo,
(!nodisp ? CONV_NONE : CONV_TOHDR),
(!nodisp ? TD_ISPR | TD_ICONV : TD_ICONV), NULL, NULL) < 0 ||
putc('\n', fo) == EOF){
rv = FAL0;
break;
}
NYD2_OU;
return rv;
}
static s32
a_sendout_body(FILE *fo, FILE *fi, enum conversion convert){
struct str outrest, inrest;
boole iseof, seenempty;
char *buf;
uz size, bufsize, cnt;
s32 rv;
NYD2_IN;
rv = su_ERR_INVAL;
mx_fs_linepool_aquire(&buf, &bufsize);
outrest.s = inrest.s = NIL;
outrest.l = inrest.l = 0;
if(convert == CONV_TOQP || convert == CONV_8BIT || convert == CONV_7BIT
#ifdef mx_HAVE_ICONV
|| iconvd != (iconv_t)-1
#endif
){
fflush(fi);
cnt = fsize(fi);
}
seenempty = iseof = FAL0;
while(!iseof){
if(convert == CONV_TOQP || convert == CONV_8BIT || convert == CONV_7BIT
#ifdef mx_HAVE_ICONV
|| iconvd != (iconv_t)-1
#endif
){
if(fgetline(&buf, &bufsize, &cnt, &size, fi, FAL0) == NIL)
break;
if(convert != CONV_TOQP && seenempty && is_head(buf, size, FAL0)){
if(bufsize - 1 >= size + 1){
bufsize += 32;
buf = su_MEM_REALLOC(buf, bufsize);
}
su_mem_move(&buf[1], &buf[0], ++size);
buf[0] = '>';
seenempty = FAL0;
}else
seenempty = (size == 1 /*&& buf[0] == '\n'*/);
}else if((size = fread(buf, sizeof *buf, bufsize, fi)) == 0)
break;
joutln:
if(xmime_write(buf, size, fo, convert, TD_ICONV, &outrest,
(iseof > FAL0 ? NULL : &inrest)) < 0)
goto jleave;
}
if(iseof <= FAL0 && (outrest.l != 0 || inrest.l != 0)){
size = 0;
iseof = (iseof || inrest.l == 0) ? TRU1 : TRUM1;
goto joutln;
}
rv = ferror(fi) ? su_ERR_IO : su_ERR_NONE;
jleave:
if(outrest.s != NIL)
su_FREE(outrest.s);
if(inrest.s != NIL)
su_FREE(inrest.s);
mx_fs_linepool_release(buf, bufsize);
NYD2_OU;
return rv;
}
static s32
a_sendout_attach_file(struct header *hp, struct mx_attachment *ap, FILE *fo,
boole force)
{
/* TODO of course, the MIME classification needs to performed once
* TODO only, not for each and every charset anew ... ;-// */
char *charset_iter_orig[2];
boole any;
long offs;
s32 err;
NYD_IN;
err = su_ERR_NONE;
/* Is this already in target charset? Simply copy over */
if(ap->a_conv == mx_ATTACHMENTS_CONV_TMPFILE){
err = a_sendout__attach_file(hp, ap, fo, force);
mx_fs_close(ap->a_tmpf);
su_DBG( ap->a_tmpf = NIL; )
goto jleave;
}
/* If we don't apply charset conversion at all (fixed input=output charset)
* we also simply copy over, since it's the users desire */
if (ap->a_conv == mx_ATTACHMENTS_CONV_FIX_INCS) {
ap->a_charset = ap->a_input_charset;
err = a_sendout__attach_file(hp, ap, fo, force);
goto jleave;
} else
ASSERT(ap->a_input_charset != NULL);
/* Otherwise we need to iterate over all possible output charsets */
if ((offs = ftell(fo)) == -1) {
err = su_ERR_IO;
goto jleave;
}
charset_iter_recurse(charset_iter_orig);
for(any = FAL0, charset_iter_reset(NULL);; any = TRU1, charset_iter_next()){
boole myforce;
myforce = FAL0;
if (!charset_iter_is_valid()) {
if(!any || !(myforce = force)){
err = su_ERR_NOENT;
break;
}
}
err = a_sendout__attach_file(hp, ap, fo, myforce);
if (err == su_ERR_NONE || (err != su_ERR_ILSEQ && err != su_ERR_INVAL))
break;
clearerr(fo);
if (fseek(fo, offs, SEEK_SET) == -1) {
err = su_ERR_IO;
break;
}
if (ap->a_conv != mx_ATTACHMENTS_CONV_DEFAULT) {
err = su_ERR_ILSEQ;
break;
}
ap->a_charset = NULL;
}
charset_iter_restore(charset_iter_orig);
jleave:
NYD_OU;
return err;
}
static s32
a_sendout__attach_file(struct header *hp, struct mx_attachment *ap, FILE *fo,
boole force)
{
FILE *fi;
char const *charset;
enum conversion convert;
boole do_iconv;
s32 err;
NYD_IN;
err = su_ERR_NONE;
/* Either charset-converted temporary file, or plain path */
if(ap->a_conv == mx_ATTACHMENTS_CONV_TMPFILE){
fi = ap->a_tmpf;
ASSERT(ftell(fi) == 0);
}else if((fi = mx_fs_open(ap->a_path, "r")) == NIL){
err = su_err_no();
n_err(_("%s: %s\n"), n_shexp_quote_cp(ap->a_path, FAL0),
su_err_doc(err));
goto jleave;
}
/* MIME part header for attachment */
{ char const *ct, *cp;
/* No MBOXO quoting here, never!! */
ct = ap->a_content_type;
charset = ap->a_charset;
convert = mx_mimetype_classify_file(fi, (char const**)&ct,
&charset, &do_iconv, TRU1);
if(charset == NIL || ap->a_conv == mx_ATTACHMENTS_CONV_FIX_INCS ||
ap->a_conv == mx_ATTACHMENTS_CONV_TMPFILE)
do_iconv = FAL0;
if(force && do_iconv){
convert = CONV_TOB64;
ap->a_content_type = ct = "application/octet-stream";
ap->a_charset = charset = NULL;
do_iconv = FAL0;
}
if (fprintf(fo, "\n--%s\n", _sendout_boundary) < 0 ||
a_sendout_put_ct(fo, ct, charset) < 0 ||
a_sendout_put_cte(fo, convert) < 0 ||
a_sendout_put_cd(fo, ap->a_content_disposition, ap->a_name) < 0)
goto jerr_header;
if((cp = ok_vlook(stealthmua)) == NULL || !su_cs_cmp(cp, "noagent")){
struct mx_name *np;
/* TODO RFC 2046 specifies that the same Content-ID should be used
* TODO for identical data; this is too hard for use right now,
* TODO because if done right it should be checksum based!?! */
if((np = ap->a_content_id) != NULL)
cp = np->n_name;
else
cp = a_sendout_random_id(hp, FAL0);
if(cp != NULL && fprintf(fo, "Content-ID: <%s>\n", cp) < 0)
goto jerr_header;
}
if ((cp = ap->a_content_description) != NULL &&
(fputs("Content-Description: ", fo) == EOF ||
xmime_write(cp, su_cs_len(cp), fo, CONV_TOHDR,
(TD_ISPR | TD_ICONV), NULL, NULL) < 0 || putc('\n', fo) == EOF))
goto jerr_header;
if (putc('\n', fo) == EOF) {
jerr_header:
err = su_err_no();
goto jerr_fclose;
}
}
#ifdef mx_HAVE_ICONV
if (iconvd != (iconv_t)-1)
n_iconv_close(iconvd);
if (do_iconv) {
/* Do not avoid things like utf-8 -> utf-8 to be able to detect encoding
* errors XXX also this should be !iconv_is_same_charset(), and THAT.. */
if (/*su_cs_cmp_case(charset, ap->a_input_charset) &&*/
(iconvd = n_iconv_open(charset, ap->a_input_charset)
) == (iconv_t)-1 && (err = su_err_no()) != 0) {
if (err == su_ERR_INVAL)
n_err(_("Cannot convert from %s to %s\n"), ap->a_input_charset,
charset);
else
n_err(_("iconv_open: %s\n"), su_err_doc(err));
goto jerr_fclose;
}
}
#endif
err = a_sendout_body(fo, fi, convert);
jerr_fclose:
if(ap->a_conv != mx_ATTACHMENTS_CONV_TMPFILE)
mx_fs_close(fi);
jleave:
NYD_OU;
return err;
}
static boole
_sendbundle_setup_creds(struct sendbundle *sbp, boole signing_caps)
{
boole v15, rv = FAL0;
char *shost, *from;
NYD_IN;
v15 = (ok_vlook(v15_compat) != su_NIL);
shost = (v15 ? ok_vlook(smtp_hostname) : NULL);
from = ((signing_caps || !v15 || shost == NULL)
? skin(myorigin(sbp->sb_hp)) : NULL);
if (signing_caps) {
if (from == NULL) {
#ifdef mx_HAVE_SMIME
n_err(_("No *from* address for signing specified\n"));
goto jleave;
#endif
} else
sbp->sb_signer.l = su_cs_len(sbp->sb_signer.s = from);
}
/* file:// and test:// MTAs do not need credentials */
if(sbp->sb_urlp->url_cproto == CPROTO_NONE){
rv = TRU1;
goto jleave;
}
#ifdef mx_HAVE_SMTP
if (v15) {
if (shost == NULL) {
if (from == NULL)
goto jenofrom;
sbp->sb_urlp->url_u_h.l = su_cs_len(sbp->sb_urlp->url_u_h.s = from);
} else
__sendout_ident = sbp->sb_urlp->url_u_h.s;
if(!mx_cred_auth_lookup(sbp->sb_credp, sbp->sb_urlp))
goto jleave;
}else{
if((sbp->sb_urlp->url_flags & mx_URL_HAD_USER) ||
sbp->sb_urlp->url_pass.s != NULL){
n_err(_("New-style URL used without *v15-compat* being set\n"));
goto jleave;
}
/* TODO part of the entire myorigin() disaster, get rid of this! */
if (from == NULL) {
jenofrom:
n_err(_("Your configuration requires a *from* address, "
"but none was given\n"));
goto jleave;
}
if(!mx_cred_auth_lookup_old(sbp->sb_credp, CPROTO_SMTP, from))
goto jleave;
sbp->sb_urlp->url_u_h.l = su_cs_len(sbp->sb_urlp->url_u_h.s = from);
}
rv = TRU1;
#endif /* mx_HAVE_SMTP */
jleave:
NYD_OU;
return rv;
}
static s32
a_sendout_attach_msg(struct header *hp, struct mx_attachment *ap, FILE *fo)
{
struct message *mp;
char const *ccp;
s32 err;
NYD_IN;
UNUSED(hp);
err = su_ERR_NONE;
if(fprintf(fo, "\n--%s\nContent-Type: message/rfc822\n"
"Content-Disposition: inline\n", _sendout_boundary) < 0)
goto jerr;
if((ccp = ok_vlook(stealthmua)) == NULL || !su_cs_cmp(ccp, "noagent")){
struct mx_name *np;
/* TODO RFC 2046 specifies that the same Content-ID should be used
* TODO for identical data; this is too hard for use right now,
* TODO because if done right it should be checksum based!?! */
if((np = ap->a_content_id) != NULL)
ccp = np->n_name;
else
ccp = a_sendout_random_id(hp, FAL0);
if(ccp != NULL && fprintf(fo, "Content-ID: <%s>\n", ccp) < 0)
goto jerr;
}
if((ccp = ap->a_content_description) != NULL &&
(fputs("Content-Description: ", fo) == EOF ||
xmime_write(ccp, su_cs_len(ccp), fo, CONV_TOHDR,
(TD_ISPR | TD_ICONV), NULL, NULL) < 0 || putc('\n', fo) == EOF))
goto jerr;
if(putc('\n', fo) == EOF)
goto jerr;
mp = message + ap->a_msgno - 1;
touch(mp);
if(sendmp(mp, fo, 0, NULL, SEND_RFC822, NULL) < 0)
jerr:
if((err = su_err_no()) == su_ERR_NONE)
err = su_ERR_IO;
NYD_OU;
return err;
}
static s32
make_multipart(struct header *hp, int convert, FILE *fi, FILE *fo,
char const *contenttype, char const *charset, boole force)
{
struct mx_attachment *att;
s32 err;
NYD_IN;
err = su_ERR_NONE;
if(fputs("This is a multi-part message in MIME format.\n", fo) == EOF)
goto jerr;
if(fsize(fi) != 0){
char const *cp;
if(fprintf(fo, "\n--%s\n", _sendout_boundary) < 0 ||
a_sendout_put_ct(fo, contenttype, charset) < 0 ||
a_sendout_put_cte(fo, convert) < 0 ||
fprintf(fo, "Content-Disposition: inline\n") < 0)
goto jerr;
if (((cp = ok_vlook(stealthmua)) == NULL || !su_cs_cmp(cp, "noagent")) &&
(cp = a_sendout_random_id(hp, FAL0)) != NULL &&
fprintf(fo, "Content-ID: <%s>\n", cp) < 0)
goto jerr;
if(putc('\n', fo) == EOF)
goto jerr;
if((err = a_sendout_body(fo, fi, convert)) != su_ERR_NONE)
goto jleave;
if(ferror(fi))
goto jerr;
}
for (att = hp->h_attach; att != NULL; att = att->a_flink) {
if (att->a_msgno) {
if ((err = a_sendout_attach_msg(hp, att, fo)) != su_ERR_NONE)
goto jleave;
}else if((err = a_sendout_attach_file(hp, att, fo, force)
) != su_ERR_NONE)
goto jleave;
}
/* the final boundary with two attached dashes */
if(fprintf(fo, "\n--%s--\n", _sendout_boundary) < 0)
jerr:
if((err = su_err_no()) == su_ERR_NONE)
err = su_ERR_IO;
jleave:
NYD_OU;
return err;
}
static FILE *
a_sendout_infix(struct header *hp, FILE *fi, boole dosign, boole force)
{
struct mx_fs_tmp_ctx *fstcp;
enum conversion convert;
int err;
boole do_iconv;
char const *contenttype, *charset;
FILE *nfo, *nfi;
#ifdef mx_HAVE_ICONV
char const *tcs, *convhdr = NULL;
#endif
NYD_IN;
nfi = NULL;
charset = NULL;
do_iconv = FAL0;
err = su_ERR_NONE;
if((nfo = mx_fs_tmp_open("infix", (mx_FS_O_WRONLY | mx_FS_O_HOLDSIGS |
mx_FS_O_REGISTER), &fstcp)) == NIL){
n_perr(_("infix: temporary mail file"), err = su_err_no());
goto jleave;
}
if((nfi = mx_fs_open(fstcp->fstc_filename, "r")) == NIL){
n_perr(fstcp->fstc_filename, err = su_err_no());
mx_fs_close(nfo);
}
mx_fs_tmp_release(fstcp);
if(nfi == NIL)
goto jleave;
n_pstate &= ~n_PS_HEADER_NEEDED_MIME; /* TODO hack -> be carrier tracked */
/* C99 */{
boole no_mboxo;
no_mboxo = dosign;
/* Will be NULL for text/plain */
if((n_poption & n_PO_Mm_FLAG) && n_poption_arg_Mm != NULL){
contenttype = n_poption_arg_Mm;
no_mboxo = TRU1;
}else
contenttype = "text/plain";
convert = mx_mimetype_classify_file(fi, &contenttype, &charset,
&do_iconv, no_mboxo);
}
#ifdef mx_HAVE_ICONV
/* This is the logic behind *charset-force-transport*. XXX very weird
* XXX as said a thousand times, Part==object, has dump_to_{wire,user}, and
* XXX does it (including _force_) for _itself_ only; the global header
* XXX has then to become spliced in (for multipart messages) */
if(force && do_iconv){
convert = CONV_TOB64;
contenttype = "application/octet-stream";
charset = NULL;
do_iconv = FAL0;
}
tcs = ok_vlook(ttycharset);
if((convhdr = need_hdrconv(hp))){
if(iconvd != (iconv_t)-1) /* XXX */
n_iconv_close(iconvd);
/* Do not avoid things like utf-8 -> utf-8 to be able to detect encoding
* errors XXX also this should be !iconv_is_same_charset(), and THAT.. */
if(/*su_cs_cmp_case(convhdr, tcs) != 0 &&*/
(iconvd = n_iconv_open(convhdr, tcs)) == (iconv_t)-1 &&
(err = su_err_no()) != su_ERR_NONE)
goto jiconv_err;
}
#endif
if(!n_puthead(FAL0, hp, nfo,
(GTO | GSUBJECT | GCC | GBCC | GNL | GCOMMA | GUA | GMIME | GMSGID |
GIDENT | GREF | GDATE), SEND_MBOX, convert, contenttype, charset)){
if((err = su_err_no()) == su_ERR_NONE)
err = su_ERR_IO;
goto jerr;
}
#ifdef mx_HAVE_ICONV
if (iconvd != (iconv_t)-1)
n_iconv_close(iconvd);
#endif
#ifdef mx_HAVE_ICONV
if(do_iconv && charset != NIL){ /*TODO charset->mimetype_classify_file*/
/* Do not avoid things like utf-8 -> utf-8 to be able to detect encoding
* errors XXX also this should be !iconv_is_same_charset(), and THAT.. */
if(/*su_cs_cmp_case(charset, tcs) != 0 &&*/
(iconvd = n_iconv_open(charset, tcs)) == (iconv_t)-1 &&
(err = su_err_no()) != su_ERR_NONE){
jiconv_err:
if (err == su_ERR_INVAL)
n_err(_("Cannot convert from %s to %s\n"), tcs, charset);
else
n_perr("iconv_open", err);
goto jerr;
}
}
#endif
if(hp->h_attach != NULL){
if((err = make_multipart(hp, convert, fi, nfo, contenttype, charset,
force)) != su_ERR_NONE)
goto jerr;
}else if((err = a_sendout_body(nfo, fi, convert)) != su_ERR_NONE)
goto jerr;
if(fflush(nfo) == EOF)
err = su_err_no();
jerr:
mx_fs_close(nfo);
if(err == su_ERR_NONE){
fflush_rewind(nfi);
mx_fs_close(fi);
}else{
mx_fs_close(nfi);
nfi = NIL;
}
jleave:
#ifdef mx_HAVE_ICONV
if(iconvd != (iconv_t)-1)
n_iconv_close(iconvd);
#endif
if(nfi == NULL)
su_err_set_no(err);
NYD_OU;
return nfi;
}
static boole
_check_dispo_notif(struct mx_name *mdn, struct header *hp, FILE *fo)
{
char const *from;
boole rv = TRU1;
NYD_IN;
/* TODO smtp_disposition_notification (RFC 3798): relation to return-path
* TODO not yet checked */
if (!ok_blook(disposition_notification_send))
goto jleave;
if (mdn != NULL && mdn != (struct mx_name*)0x1)
from = mdn->n_name;
else if ((from = myorigin(hp)) == NULL) {
if (n_poption & n_PO_D_V)
n_err(_("*disposition-notification-send*: *from* not set\n"));
goto jleave;
}
if (!a_sendout_put_addrline("Disposition-Notification-To:",
nalloc(n_UNCONST(from), 0), fo, 0))
rv = FAL0;
jleave:
NYD_OU;
return rv;
}
static int
a_sendout_sendmail(void *v, enum n_mailsend_flags msf)
{
struct header head;
char *str = v;
int rv;
NYD_IN;
su_mem_set(&head, 0, sizeof head);
head.h_mailx_command = "mail";
if((head.h_to = lextract(str, GTO |
(ok_blook(fullnames) ? GFULL | GSKIN : GSKIN))) != NULL)
head.h_mailx_raw_to = n_namelist_dup(head.h_to, head.h_to->n_type);
rv = n_mail1(msf, &head, NULL, NULL);
NYD_OU;
return (rv != OKAY); /* reverse! */
}
static struct mx_name *
a_sendout_file_a_pipe(struct mx_name *names, FILE *fo, boole *senderror){
boole mfap;
char const *sh;
u32 pipecnt, xcnt, i, swf;
struct mx_name *np;
FILE *fp, **fppa;
NYD_IN;
fp = NIL;
fppa = NIL;
/* Look through all recipients and do a quick return if no file or pipe
* addressee is found */
for(pipecnt = xcnt = 0, np = names; np != NIL; np = np->n_flink){
if(np->n_type & GDEL)
continue;
switch(np->n_flags & mx_NAME_ADDRSPEC_ISFILEORPIPE){
case mx_NAME_ADDRSPEC_ISFILE: ++xcnt; break;
case mx_NAME_ADDRSPEC_ISPIPE: ++pipecnt; break;
}
}
if((pipecnt | xcnt) == 0)
goto jleave;
/* Otherwise create an array of file descriptors for each found pipe
* addressee to get around the dup(2)-shared-file-offset problem, i.e.,
* each pipe subprocess needs its very own file descriptor, and we need
* to deal with that.
* This is true even if *sendwait* requires fully synchronous mode, since
* the shell handlers can fork away and pass the descriptor around, so we
* cannot simply use a single one and rewind that after the top children
* shell has returned.
* To make our life a bit easier let's just use the auto-reclaimed
* string storage */
if(pipecnt == 0 || (n_poption & n_PO_D)){
pipecnt = 0;
sh = NIL;
}else{
i = sizeof(FILE*) * pipecnt;
fppa = n_lofi_alloc(i);
su_mem_set(fppa, 0, i);
sh = ok_vlook(SHELL);
}
mfap = ok_blook(mbox_fcc_and_pcc);
swf = a_sendout_sendwait_to_swf();
for(np = names; np != NIL; np = np->n_flink){
if(!(np->n_flags & mx_NAME_ADDRSPEC_ISFILEORPIPE) || (np->n_type & GDEL))
continue;
/* In days of old we removed the entry from the the list; now for sake of
* header expansion we leave it in and mark it as deleted */
np->n_type |= GDEL;
if(n_poption & n_PO_D_VV)
n_err(_(">>> Writing message via %s\n"),
n_shexp_quote_cp(np->n_name, FAL0));
/* We _do_ write to STDOUT, anyway! */
if((n_poption & n_PO_D) &&
((np->n_flags & mx_NAME_ADDRSPEC_ISPIPE) ||
np->n_name[0] != '-' || np->n_name[1] != '\0'))
continue;
/* See if we have copied the complete message out yet. If not, do so */
if(fp == NIL){
int c;
struct mx_fs_tmp_ctx *fstcp;
if((fp = mx_fs_tmp_open("outof", (mx_FS_O_RDWR | mx_FS_O_HOLDSIGS |
mx_FS_O_REGISTER), &fstcp)) == NIL){
n_perr(_("Creation of temporary image"), 0);
pipecnt = 0;
goto jerror;
}
for(i = 0; i < pipecnt; ++i)
if((fppa[i] = mx_fs_open(fstcp->fstc_filename, "r")) == NIL){
n_perr(_("Creation of pipe image descriptor"), 0);
break;
}
mx_fs_tmp_release(fstcp);
if(i != pipecnt){
pipecnt = i;
goto jerror;
}
if(mfap)
fprintf(fp, "From %s %s",
ok_vlook(LOGNAME), time_current.tc_ctime);
c = EOF;
while(i = c, (c = getc(fo)) != EOF)
putc(c, fp);
rewind(fo);
if((int)i != '\n')
putc('\n', fp);
if(mfap)
putc('\n', fp);
fflush(fp);
if(ferror(fp)){
n_perr(_("Finalizing write of temporary image"), 0);
goto jerror;
}
/* From now on use xcnt as a counter for pipecnt */
xcnt = 0;
}
/* Now either copy "image" to the desired file or give it as the
* standard input to the desired program as appropriate */
if(np->n_flags & mx_NAME_ADDRSPEC_ISPIPE){
struct mx_child_ctx cc;
sigset_t nset;
sigemptyset(&nset);
sigaddset(&nset, SIGHUP);
sigaddset(&nset, SIGINT);
sigaddset(&nset, SIGQUIT);
mx_child_ctx_setup(&cc);
cc.cc_flags = mx_CHILD_SPAWN_CONTROL |
(swf & a_SENDOUT_SWF_PCC ? mx_CHILD_RUN_WAIT_LIFE : 0);
cc.cc_mask = &nset;
cc.cc_fds[mx_CHILD_FD_IN] = fileno(fppa[xcnt]);
cc.cc_fds[mx_CHILD_FD_OUT] = mx_CHILD_FD_NULL;
cc.cc_cmd = sh;
cc.cc_args[0] = "-c";
cc.cc_args[1] = &np->n_name[1];
if(!mx_child_run(&cc)){
n_err(_("Piping message to %s failed\n"),
n_shexp_quote_cp(np->n_name, FAL0));
goto jerror;
}
/* C99 */{
FILE *tmp;
tmp = fppa[xcnt];
fppa[xcnt++] = NIL;
mx_fs_close(tmp);
}
if(!(swf & a_SENDOUT_SWF_PCC))
mx_child_forget(&cc);
}else{
int c;
FILE *fout;
char const *fname, *fnameq;
if((fname = fexpand(np->n_name, FEXP_NSHELL)) == NIL) /* TODO */
goto jerror;
fnameq = n_shexp_quote_cp(fname, FAL0);
if(fname[0] == '-' && fname[1] == '\0')
fout = n_stdout;
else{
int xerr;
enum mx_fs_open_state fs;
if((fout = mx_fs_open_any(fname, (mfap ? "a+" : "w"), &fs)
) == NIL){
xerr = su_err_no();
jefile:
n_err(_("Writing message to %s failed: %s\n"),
fnameq, su_err_doc(xerr));
goto jerror;
}
if((fs & (n_PROTO_MASK | mx_FS_OPEN_STATE_EXISTS)) ==
(n_PROTO_FILE | mx_FS_OPEN_STATE_EXISTS)){
mx_file_lock(fileno(fout), mx_FILE_LOCK_TYPE_WRITE, 0,0,
UZ_MAX);
if(mfap && (xerr = n_folder_mbox_prepare_append(fout, NIL)
) != su_ERR_NONE)
goto jefile;
}
}
rewind(fp);
while((c = getc(fp)) != EOF)
putc(c, fout);
if(ferror(fout)){
n_err(_("Writing message to %s failed: %s\n"),
fnameq, _("write error"));
*senderror = TRU1;
}
if(fout != n_stdout)
mx_fs_close(fout);
else
clearerr(fout);
}
}
jleave:
if(fp != NIL)
mx_fs_close(fp);
if(fppa != NIL){
for(i = 0; i < pipecnt; ++i)
if((fp = fppa[i]) != NIL)
mx_fs_close(fp);
n_lofi_free(fppa);
}
NYD_OU;
return names;
jerror:
*senderror = TRU1;
while(np != NIL){
if(np->n_flags & mx_NAME_ADDRSPEC_ISFILEORPIPE)
np->n_type |= GDEL;
np = np->n_flink;
}
goto jleave;
}
static boole
a_sendout_mightrecord(FILE *fp, struct mx_name *to, boole resend){
char const *ccp;
char *cp;
boole rv;
NYD2_IN;
rv = TRU1;
if(to != NIL){
ccp = cp = savestr(to->n_name);
while(*cp != '\0' && *cp != '@')
++cp;
*cp = '\0';
}else
ccp = ok_vlook(record);
if(ccp == NIL)
goto jleave;
if((cp = fexpand(ccp, FEXP_NSHELL)) == NIL) /* TODO */
goto jbail;
switch(which_protocol(ccp, FAL0, FAL0, NIL)){
case n_PROTO_EML:
case n_PROTO_POP3:
case n_PROTO_UNKNOWN:
goto jbail;
default:
break;
}
switch(*(ccp = cp)){
case '.':
if(cp[1] != '/'){ /* DIRSEP */
default:
if(ok_blook(outfolder)){
struct str s;
char const *nccp, *folder;
switch(which_protocol(ccp, TRU1, FAL0, &nccp)){
case PROTO_FILE:
ccp = "file://";
if(0){
/* FALLTHRU */
case PROTO_MAILDIR:
#ifdef mx_HAVE_MAILDIR
ccp = "maildir://";
#else
n_err(_("*record*: *outfolder*: no Maildir directory "
"support compiled in\n"));
goto jbail;
#endif
}
folder = n_folder_query();
#ifdef mx_HAVE_IMAP
if(which_protocol(folder, FAL0, FAL0, NIL) == PROTO_IMAP){
n_err(_("*record*: *outfolder* set, *folder* is IMAP "
"based: only one protocol per file is possible\n"));
goto jbail;
}
#endif
ccp = str_concat_csvl(&s, ccp, folder, nccp, NIL)->s;
/* FALLTHRU */
case n_PROTO_IMAP:
break;
default:
goto jbail;
}
}
}
/* FALLTHRU */
case '/':
break;
}
if(n_poption & n_PO_D_VV)
n_err(_(">>> Writing message via %s\n"), n_shexp_quote_cp(ccp, FAL0));
if(!(n_poption & n_PO_D) && !a_sendout__savemail(ccp, fp, resend)){
jbail:
n_err(_("Failed to save message in %s - message not sent\n"),
n_shexp_quote_cp(ccp, FAL0));
n_exit_status |= n_EXIT_ERR;
savedeadletter(fp, 1);
rv = FAL0;
}
jleave:
NYD2_OU;
return rv;
}
static boole
a_sendout__savemail(char const *name, FILE *fp, boole resend){
FILE *fo;
uz bufsize, buflen, cnt;
enum mx_fs_open_state fs;
char *buf;
boole rv, emptyline;
NYD_IN;
UNUSED(resend);
rv = FAL0;
mx_fs_linepool_aquire(&buf, &bufsize);
if((fo = mx_fs_open_any(name, "a+", &fs)) == NIL){
n_perr(name, 0);
goto j_leave;
}
if((fs & (n_PROTO_MASK | mx_FS_OPEN_STATE_EXISTS)) ==
(n_PROTO_FILE | mx_FS_OPEN_STATE_EXISTS)){
int xerr;
/* TODO RETURN check, but be aware of protocols: v15: Mailbox->lock()!
* TODO BETTER yet: should be returned in lock state already! */
mx_file_lock(fileno(fo), mx_FILE_LOCK_TYPE_WRITE, 0,0, UZ_MAX);
if((xerr = n_folder_mbox_prepare_append(fo, NULL)) != su_ERR_NONE){
n_perr(name, xerr);
goto jleave;
}
}
if(fprintf(fo, "From %s %s", ok_vlook(LOGNAME), time_current.tc_ctime) < 0)
goto jleave;
rv = TRU1;
fflush_rewind(fp);
for(emptyline = FAL0, buflen = 0, cnt = fsize(fp);
fgetline(&buf, &bufsize, &cnt, &buflen, fp, FAL0) != NIL;){
/* Only if we are resending it can happen that we have to quote From_
* lines here; we don't generate messages which are ambiguous ourselves.
* xxx No longer true after (Reintroduce ^From_ MBOXO with
* xxx *mime-encoding*=8b (too many!)[..]) */
/*if(resend){*/
if(emptyline && is_head(buf, buflen, FAL0)){
if(putc('>', fo) == EOF){
rv = FAL0;
break;
}
}
/*}su_DBG(else ASSERT(!is_head(buf, buflen, FAL0)); )*/
emptyline = (buflen > 0 && *buf == '\n');
if(fwrite(buf, sizeof *buf, buflen, fo) != buflen){
rv = FAL0;
break;
}
}
if(rv){
if(buflen > 0 && buf[buflen - 1] != '\n'){
if(putc('\n', fo) == EOF)
rv = FAL0;
}
if(rv && (putc('\n', fo) == EOF || fflush(fo)))
rv = FAL0;
}
if(!rv){
n_perr(name, su_ERR_IO);
rv = FAL0;
}
jleave:
really_rewind(fp);
if(!mx_fs_close(fo))
rv = FAL0;
j_leave:
mx_fs_linepool_release(buf, bufsize);
NYD_OU;
return rv;
}
static boole
a_sendout_transfer(struct sendbundle *sbp, boole resent, boole *senderror){
u32 cnt;
struct mx_name *np;
FILE *input_save;
boole rv;
NYD_IN;
rv = FAL0;
/* Do we need to create a Bcc: free overlay?
* TODO In v15 we would have an object tree with dump-to-wire, we have our
* TODO file stream which acts upon an I/O device that stores so-and-so-much
* TODO memory, excess in a temporary file; either each object knows its
* TODO offset where it placed its dump-to-wire, or we create a list overlay
* TODO which records these offsets. Then, in our non-blocking eventloop
* TODO which writes data to the MTA child as it goes we simply not write
* TODO the Bcc: as necessary; how about that? */
input_save = sbp->sb_input;
if((resent || (sbp->sb_hp != NIL && sbp->sb_hp->h_bcc != NIL)) &&
!ok_blook(mta_bcc_ok)){
boole inhdr, inskip;
uz bufsize, bcnt, llen;
char *buf;
FILE *fp;
if((fp = mx_fs_tmp_open("mtabccok", (mx_FS_O_RDWR | mx_FS_O_REGISTER |
mx_FS_O_UNLINK), NIL)) == NIL){
jewritebcc:
n_perr(_("Creation of *mta-write-bcc* message"), 0);
*senderror = TRU1;
goto jleave;
}
sbp->sb_input = fp;
mx_fs_linepool_aquire(&buf, &bufsize);
bcnt = fsize(input_save);
inhdr = TRU1;
inskip = FAL0;
while(fgetline(&buf, &bufsize, &bcnt, &llen, input_save, TRU1) != NIL){
if(inhdr){
if(llen == 1 && *buf == '\n')
inhdr = FAL0;
else{
if(inskip && *buf == ' ')
continue;
inskip = FAL0;
/* (We need _case for resent only);
* xxx We do not resent that yet , but place the logic today */
if(su_cs_starts_with_case(buf, "bcc:") ||
(resent && su_cs_starts_with_case(buf, "resent-bcc:"))){
inskip = TRU1;
continue;
}
}
}
if(fwrite(buf, 1, llen, fp) != llen)
goto jewritebcc;
}
mx_fs_linepool_release(buf, bufsize);
if(ferror(input_save)){
*senderror = TRU1;
goto jleave;
}
fflush_rewind(fp);
}
rv = TRU1;
for(cnt = 0, np = sbp->sb_to; np != NIL;){
FILE *ef;
if((ef = mx_privacy_encrypt_try(sbp->sb_input, np->n_name)
) != R(FILE*,-1)){
if(ef != NIL){
struct mx_name *nsave;
FILE *fisave;
fisave = sbp->sb_input;
nsave = sbp->sb_to;
sbp->sb_to = ndup(np, np->n_type & ~(GFULL | GFULLEXTRA | GSKIN));
sbp->sb_input = ef;
if(!a_sendout_mta_start(sbp))
rv = FAL0;
sbp->sb_to = nsave;
sbp->sb_input = fisave;
mx_fs_close(ef);
}else{
n_err(_("Message not sent to: %s\n"), np->n_name);
_sendout_error = TRU1;
}
rewind(sbp->sb_input);
if(np->n_flink != NIL)
np->n_flink->n_blink = np->n_blink;
if(np->n_blink != NIL)
np->n_blink->n_flink = np->n_flink;
if(np == sbp->sb_to)
sbp->sb_to = np->n_flink;
np = np->n_flink;
}else{
++cnt;
np = np->n_flink;
}
}
if(cnt > 0 && (mx_privacy_encrypt_is_forced() || !a_sendout_mta_start(sbp)))
rv = FAL0;
jleave:
if(input_save != sbp->sb_input){
mx_fs_close(sbp->sb_input);
rewind(sbp->sb_input = input_save);
}
NYD_OU;
return rv;
}
static boole
a_sendout_mta_start(struct sendbundle *sbp)
{
struct mx_child_ctx cc;
sigset_t nset;
char const **args, *mta;
boole rv, dowait;
NYD_IN;
/* Let rv be: TRU1=SMTP, FAL0=file, TRUM1=test */
mta = sbp->sb_urlp->url_input;
if(sbp->sb_urlp->url_cproto == CPROTO_NONE){
if(sbp->sb_urlp->url_portno == 0)
rv = FAL0;
else{
ASSERT(sbp->sb_urlp->url_portno == U16_MAX);
rv = TRUM1;
}
}else
rv = TRU1;
sigemptyset(&nset);
sigaddset(&nset, SIGHUP);
sigaddset(&nset, SIGINT);
sigaddset(&nset, SIGQUIT);
sigaddset(&nset, SIGTSTP);
sigaddset(&nset, SIGTTIN);
sigaddset(&nset, SIGTTOU);
mx_child_ctx_setup(&cc);
dowait = ((n_poption & n_PO_D_V) ||
(a_sendout_sendwait_to_swf() & a_SENDOUT_SWF_MTA));
if(rv != TRU1 || dowait)
cc.cc_flags |= mx_CHILD_SPAWN_CONTROL;
cc.cc_mask = &nset;
if(rv != TRU1){
char const *mta_base;
if((mta = fexpand(mta_base = mta, (FEXP_NOPROTO | FEXP_LOCAL_FILE |
FEXP_NSHELL))) == NIL){
n_err(_("*mta* variable file expansion failure: %s\n"),
n_shexp_quote_cp(mta_base, FAL0));
goto jstop;
}
if(rv == TRUM1){
rv = a_sendout_mta_test(sbp, mta);
goto jleave;
}
args = a_sendout_mta_file_args(sbp->sb_to, sbp->sb_hp);
if(n_poption & n_PO_D){
a_sendout_mta_file_debug(sbp, mta, args);
rv = TRU1;
goto jleave;
}
/* Wait with control pipe close until after exec */
ASSERT(cc.cc_flags & mx_CHILD_SPAWN_CONTROL);
cc.cc_flags |= mx_CHILD_SPAWN_CONTROL_LINGER;
cc.cc_fds[mx_CHILD_FD_IN] = fileno(sbp->sb_input);
}else/* if(rv == TRU1)*/{
UNINIT(args, NULL);
#ifndef mx_HAVE_SMTP
n_err(_("No SMTP support compiled in\n"));
goto jstop;
#else
if(n_poption & n_PO_D){
(void)mx_smtp_mta(sbp);
rv = TRU1;
goto jleave;
}
cc.cc_fds[mx_CHILD_FD_IN] = mx_CHILD_FD_NULL;
cc.cc_fds[mx_CHILD_FD_OUT] = mx_CHILD_FD_NULL;
#endif
}
/* Fork, set up the temporary mail file as standard input for "mail", and
* exec with the user list we generated far above */
if(!mx_child_fork(&cc)){
if(cc.cc_flags & mx_CHILD_SPAWN_CONTROL_LINGER){
char const *ecp;
ecp = (cc.cc_error != su_ERR_NOENT) ? su_err_doc(cc.cc_error)
: _("executable not found (adjust *mta* variable)");
n_err(_("Cannot start %s: %s\n"), n_shexp_quote_cp(mta, FAL0), ecp);
}
jstop:
savedeadletter(sbp->sb_input, TRU1);
n_err(_("... message not sent\n"));
_sendout_error = TRU1;
}else if(cc.cc_pid == 0)
goto jkid;
else if(dowait){
/* TODO Now with SPAWN_CONTROL we could actually (1) handle $DEAD only
* TODO in the parent, and (2) report the REAL child error status!! */
rv = (mx_child_wait(&cc) && cc.cc_exit_status == 0);
if(!rv)
goto jstop;
}else{
mx_child_forget(&cc);
rv = TRU1;
}
jleave:
NYD_OU;
return rv;
jkid:
mx_child_in_child_setup(&cc);
#ifdef mx_HAVE_SMTP
if(rv == TRU1){
if(mx_smtp_mta(sbp))
_exit(n_EXIT_OK);
savedeadletter(sbp->sb_input, TRU1);
if(!dowait)
n_err(_("... message not sent\n"));
}else
#endif
{
execv(mta, n_UNCONST(args));
mx_child_in_child_exec_failed(&cc, su_err_no());
}
for(;;)
_exit(n_EXIT_ERR);
}
static char const **
a_sendout_mta_file_args(struct mx_name *to, struct header *hp)
{
uz vas_cnt, i, j;
char **vas;
char const **args, *cp, *cp_v15compat;
boole snda;
NYD_IN;
if((cp_v15compat = ok_vlook(sendmail_arguments)) != NULL)
n_OBSOLETE(_("please use *mta-arguments*, not *sendmail-arguments*"));
if((cp = ok_vlook(mta_arguments)) == NULL)
cp = cp_v15compat;
if ((cp /* TODO v15: = ok_vlook(mta_arguments)*/) == NULL) {
vas_cnt = 0;
vas = NULL;
} else {
/* Don't assume anything on the content but do allocate exactly j slots;
* like this getrawlist will never overflow (and return -1) */
j = su_cs_len(cp);
vas = n_lofi_alloc(sizeof(*vas) * j);
vas_cnt = (uz)getrawlist(TRU1, vas, j, cp, j);
}
i = 4 + n_smopts_cnt + vas_cnt + 4 + 1 + count(to) + 1;
args = n_autorec_alloc(i * sizeof(char*));
if((cp_v15compat = ok_vlook(sendmail_progname)) != NULL)
n_OBSOLETE(_("please use *mta-argv0*, not *sendmail-progname*"));
cp = ok_vlook(mta_argv0);
if(cp_v15compat != NULL && !su_cs_cmp(cp, VAL_MTA_ARGV0))
cp = cp_v15compat;
args[0] = cp/* TODO v15 only : = ok_vlook(mta_argv0) */;
if ((snda = ok_blook(sendmail_no_default_arguments)))
n_OBSOLETE(_("please use *mta-no-default-arguments*, "
"not *sendmail-no-default-arguments*"));
snda |= ok_blook(mta_no_default_arguments);
if ((snda /* TODO v15: = ok_blook(mta_no_default_arguments)*/))
i = 1;
else {
args[1] = "-i";
i = 2;
if (ok_blook(metoo))
args[i++] = "-m";
if (n_poption & n_PO_V)
args[i++] = "-v";
}
for (j = 0; j < n_smopts_cnt; ++j, ++i)
args[i] = n_smopts[j];
for (j = 0; j < vas_cnt; ++j, ++i)
args[i] = vas[j];
/* -r option? In conjunction with -t we act compatible to postfix(1) and
* ignore it (it is -f / -F there) if the message specified From:/Sender:.
* The interdependency with -t has been resolved in n_puthead() */
if (!snda && ((n_poption & n_PO_r_FLAG) || ok_blook(r_option_implicit))) {
struct mx_name const *np;
if (hp != NULL && (np = hp->h_from) != NULL) {
/* However, what wasn't resolved there was the case that the message
* specified multiple From: addresses and a Sender: */
if((n_poption & n_PO_t_FLAG) && hp->h_sender != NULL)
np = hp->h_sender;
if (np->n_fullextra != NULL) {
args[i++] = "-F";
args[i++] = np->n_fullextra;
}
cp = np->n_name;
} else {
ASSERT(n_poption_arg_r == NULL);
cp = skin(myorigin(NULL));
}
if (cp != NULL) {
args[i++] = "-f";
args[i++] = cp;
}
}
/* Terminate option list to avoid false interpretation of system-wide
* aliases that start with hyphen */
if (!snda)
args[i++] = "--";
/* Receivers follow */
if(!ok_blook(mta_no_receiver_arguments))
for (; to != NULL; to = to->n_flink)
if (!(to->n_type & GDEL))
args[i++] = to->n_name;
args[i] = NULL;
if(vas != NULL)
n_lofi_free(vas);
NYD_OU;
return args;
}
static void
a_sendout_mta_file_debug(struct sendbundle *sbp, char const *mta,
char const **args)
{
uz cnt, bufsize, llen;
char *buf;
NYD_IN;
n_err(_(">>> MTA: %s, arguments:"), n_shexp_quote_cp(mta, FAL0));
for (; *args != NULL; ++args)
n_err(" %s", n_shexp_quote_cp(*args, FAL0));
n_err("\n");
fflush_rewind(sbp->sb_input);
cnt = fsize(sbp->sb_input);
buf = NULL;
bufsize = 0;
while (fgetline(&buf, &bufsize, &cnt, &llen, sbp->sb_input, TRU1) != NULL) {
buf[--llen] = '\0';
n_err(">>> %s\n", buf);
}
if (buf != NULL)
n_free(buf);
NYD_OU;
}
static boole
a_sendout_mta_test(struct sendbundle *sbp, char const *mta)
{
enum{
a_OK = 0,
a_ERR = 1u<<0,
a_MAFC = 1u<<1,
a_ANY = 1u<<2,
a_LASTNL = 1u<<3
};
FILE *fp;
s32 f;
uz bufsize, cnt, llen;
char *buf;
NYD_IN;
mx_fs_linepool_aquire(&buf, &bufsize);
if(*mta == '\0')
fp = n_stdout;
else{
if((fp = mx_fs_open(mta, "W+")) != NIL)
;
else if((fp = mx_fs_open(mta, "r+")) == NIL)
goto jeno;
else if(!mx_file_lock(fileno(fp), (mx_FILE_LOCK_TYPE_READ |
mx_FILE_LOCK_TYPE_WRITE), 0,0, UZ_MAX)){
f = su_ERR_NOLCK;
goto jefo;
}else if((f = n_folder_mbox_prepare_append(fp, NIL)) != su_ERR_NONE)
goto jefo;
}
fflush_rewind(sbp->sb_input);
cnt = fsize(sbp->sb_input);
f = ok_blook(mbox_fcc_and_pcc) ? a_MAFC : a_OK;
if((f & a_MAFC) &&
fprintf(fp, "From %s %s", ok_vlook(LOGNAME), time_current.tc_ctime
) < 0)
goto jeno;
while(fgetline(&buf, &bufsize, &cnt, &llen, sbp->sb_input, TRU1) != NIL){
if(fwrite(buf, 1, llen, fp) != llen)
goto jeno;
if(f & a_MAFC){
f |= a_ANY;
if(llen > 0 && buf[llen - 1] == '\0')
f |= a_LASTNL;
else
f &= ~a_LASTNL;
}
}
if(ferror(sbp->sb_input))
goto jefo;
if((f & (a_ANY | a_LASTNL)) == a_ANY && putc('\n', fp) == EOF)
goto jeno;
jdone:
if(fp != n_stdout)
mx_fs_close(fp);
else
clearerr(fp);
jleave:
mx_fs_linepool_release(buf, bufsize);
NYD_OU;
return ((f & a_ERR) == 0);
jeno:
f = su_err_no();
jefo:
n_err(_("test MTA: cannot open/prepare/write: %s: %s\n"),
n_shexp_quote_cp(mta, FAL0), su_err_doc(f));
f = a_ERR;
if(fp != NIL)
goto jdone;
goto jleave;
}
static char const *
a_sendout_random_id(struct header *hp, boole msgid)
{
static u32 reprocnt;
struct tm *tmp;
char const *h;
uz rl, i;
char *rv, sep;
NYD_IN;
rv = NULL;
if(msgid && hp != NULL && hp->h_message_id != NULL){
rv = hp->h_message_id->n_name;
goto jleave;
}
if(ok_blook(message_id_disable))
goto jleave;
sep = '%';
rl = 5;
if((h = __sendout_ident) != NULL)
goto jgen;
if(ok_vlook(hostname) != NULL){
h = n_nodename(TRU1);
sep = '@';
rl = 8;
goto jgen;
}
if(hp != NULL && (h = skin(myorigin(hp))) != NULL &&
su_cs_find_c(h, '@') != NULL)
goto jgen;
goto jleave;
jgen:
tmp = &time_current.tc_gm;
i = sizeof("%04d%02d%02d%02d%02d%02d.%s%c%s") -1 + rl + su_cs_len(h);
rv = n_autorec_alloc(i +1);
snprintf(rv, i, "%04d%02d%02d%02d%02d%02d.%s%c%s",
tmp->tm_year + 1900, tmp->tm_mon + 1, tmp->tm_mday,
tmp->tm_hour, tmp->tm_min, tmp->tm_sec,
mx_random_create_cp(rl, &reprocnt), sep, h);
rv[i] = '\0'; /* Because we don't test snprintf(3) return */
jleave:
NYD_OU;
return rv;
}
static boole
a_sendout_put_addrline(char const *hname, struct mx_name *np, FILE *fo,
enum a_sendout_addrline_flags saf)
{
sz hnlen, col, len;
enum{
m_ERROR = 1u<<0,
m_INIT = 1u<<1,
m_COMMA = 1u<<2,
m_NOPF = 1u<<3,
m_NONAME = 1u<<4,
m_CSEEN = 1u<<5
} m;
NYD_IN;
m = (saf & GCOMMA) ? m_ERROR | m_COMMA : m_ERROR;
if((col = hnlen = su_cs_len(hname)) > 0){
#undef _X
#define _X(S) (col == sizeof(S) -1 && !su_cs_cmp_case(hname, S))
if (saf & GFILES) {
;
} else if (_X("reply-to:") || _X("mail-followup-to:") ||
_X("references:") || _X("in-reply-to:") ||
_X("disposition-notification-to:"))
m |= m_NOPF | m_NONAME;
else if (ok_blook(add_file_recipients)) {
;
} else if (_X("to:") || _X("cc:") || _X("bcc:") || _X("resent-to:"))
m |= m_NOPF;
#undef _X
}
for (; np != NULL; np = np->n_flink) {
if(np->n_type & GDEL)
continue;
if(is_addr_invalid(np,
((saf & a_SENDOUT_AL_INC_INVADDR ? 0 : EACM_NOLOG) |
(m & m_NONAME ? EACM_NONAME : EACM_NONE))) &&
!(saf & a_SENDOUT_AL_INC_INVADDR))
continue;
/* File and pipe addresses only printed with set *add-file-recipients* */
if ((m & m_NOPF) && is_fileorpipe_addr(np))
continue;
if ((m & (m_INIT | m_COMMA)) == (m_INIT | m_COMMA)) {
if (putc(',', fo) == EOF)
goto jleave;
m |= m_CSEEN;
++col;
}
len = su_cs_len(np->n_fullname);
if (np->n_type & GREF)
len += 2;
++col; /* The separating space */
if ((m & m_INIT) && /*col > 1 &&*/
UCMP(z, col + len, >,
(np->n_type & GREF ? MIME_LINELEN : 72))) {
if (fputs("\n ", fo) == EOF)
goto jleave;
col = 1;
m &= ~m_CSEEN;
} else {
if(!(m & m_INIT) && fwrite(hname, sizeof *hname, hnlen, fo
) != sizeof *hname * hnlen)
goto jleave;
if(putc(' ', fo) == EOF)
goto jleave;
}
m = (m & ~m_CSEEN) | m_INIT;
/* C99 */{
char *hb;
/* GREF needs to be placed in angle brackets, but which are missing */
hb = np->n_fullname;
if(np->n_type & GREF){
ASSERT(UCMP(z, len, ==, su_cs_len(np->n_fullname) + 2));
hb = n_lofi_alloc(len +1);
len -= 2;
hb[0] = '<';
hb[len + 1] = '>';
hb[len + 2] = '\0';
su_mem_copy(&hb[1], np->n_fullname, len);
len += 2;
}
len = xmime_write(hb, len, fo,
((saf & a_SENDOUT_AL_DOMIME) ? CONV_TOHDR_A : CONV_NONE),
TD_ICONV, NULL, NULL);
if(np->n_type & GREF)
n_lofi_free(hb);
}
if (len < 0)
goto jleave;
col += len;
}
if(!(m & m_INIT) || putc('\n', fo) != EOF)
m ^= m_ERROR;
jleave:
NYD_OU;
return ((m & m_ERROR) == 0);
}
static boole
a_sendout_infix_resend(FILE *fi, FILE *fo, struct message *mp,
struct mx_name *to, int add_resent)
{
uz cnt, c, bufsize;
char *buf;
char const *cp;
struct mx_name *fromfield = NULL, *senderfield = NULL, *mdn;
boole rv;
NYD_IN;
rv = FAL0;
mx_fs_linepool_aquire(&buf, &bufsize);
cnt = mp->m_size;
/* Write the Resent-Fields */
if (add_resent) {
if(fputs("Resent-", fo) == EOF)
goto jleave;
if(mkdate(fo, "Date") == -1)
goto jleave;
if ((cp = myaddrs(NULL)) != NULL) {
if (!a_sendout_put_name(cp, GCOMMA, SEND_MBOX, "Resent-From:", fo,
&fromfield))
goto jleave;
}
/* TODO RFC 5322: Resent-Sender SHOULD NOT be used if it's EQ -From: */
if ((cp = ok_vlook(sender)) != NULL) {
if (!a_sendout_put_name(cp, GCOMMA | GNOT_A_LIST, SEND_MBOX,
"Resent-Sender:", fo, &senderfield))
goto jleave;
}
if (!a_sendout_put_addrline("Resent-To:", to, fo, a_SENDOUT_AL_COMMA))
goto jleave;
if (((cp = ok_vlook(stealthmua)) == NULL || !su_cs_cmp(cp, "noagent")) &&
(cp = a_sendout_random_id(NULL, TRU1)) != NULL &&
fprintf(fo, "Resent-Message-ID: <%s>\n", cp) < 0)
goto jleave;
}
if((mdn = n_UNCONST(check_from_and_sender(fromfield, senderfield))) == NIL)
goto jleave;
if (!_check_dispo_notif(mdn, NULL, fo))
goto jleave;
/* Write the original headers */
while (cnt > 0) {
if(fgetline(&buf, &bufsize, &cnt, &c, fi, FAL0) == NIL){
if(ferror(fi))
goto jleave;
break;
}
if (su_cs_cmp_case_n("status:", buf, 7) &&
su_cs_cmp_case_n("disposition-notification-to:", buf, 28) &&
!is_head(buf, c, FAL0)){
if(fwrite(buf, sizeof *buf, c, fo) != c)
goto jleave;
}
if (cnt > 0 && *buf == '\n')
break;
}
/* Write the message body */
while(cnt > 0){
if(fgetline(&buf, &bufsize, &cnt, &c, fi, FAL0) == NIL){
if(ferror(fi))
goto jleave;
break;
}
if(cnt == 0 && *buf == '\n')
break;
if(fwrite(buf, sizeof *buf, c, fo) != c)
goto jleave;
}
rv = TRU1;
jleave:
mx_fs_linepool_release(buf, bufsize);
if(!rv)
n_err(_("infix_resend: creation of temporary mail file failed\n"));
NYD_OU;
return rv;
}
FL boole
mx_sendout_mta_url(struct mx_url *urlp){
/* TODO In v15 this should simply be url_creat(,ok_vlook(mta).
* TODO Register a "test" protocol handler, and if the protocol ends up
* TODO as file and the path is "test", then this is also test.
* TODO I.e., CPROTO_FILE and CPROTO_TEST. Until then this is messy */
char const *mta;
boole rv;
NYD_IN;
rv = FAL0;
if((mta = ok_vlook(smtp)) == NIL){
boole issnd;
u16 pno;
char const *proto;
mta = ok_vlook(mta);
if((proto = ok_vlook(sendmail)) != NIL){ /* v15-compat */
n_OBSOLETE(_("please use *mta* instead of *sendmail*"));
/* But use it in favour of default value, then */
if(!su_cs_cmp(mta, VAL_MTA))
mta = proto;
}
if(su_cs_find_c(mta, ':') == NIL){
if(su_cs_cmp(mta, "test")){
pno = 0;
goto jisfile;
}
pno = U16_MAX;
goto jistest;
}else if((proto = mx_url_servbyname(mta, &pno, &issnd)) == NIL){
goto jemta;
}else if(*proto == '\0'){
if(pno == 0)
mta += sizeof("file://") -1;
else{
/* test -> stdout, test://X -> X */
ASSERT(pno == U16_MAX);
jistest:
mta += sizeof("test") -1;
if(mta[0] == ':' && mta[1] == '/' && mta[2] == '/')
mta += 3;
}
jisfile:
su_mem_set(urlp, 0, sizeof *urlp);
urlp->url_input = mta;
urlp->url_portno = pno;
urlp->url_cproto = CPROTO_NONE;
rv = TRUM1;
goto jleave;
}else if(!issnd)
goto jemta;
}else{
n_OBSOLETE(_("please do not use *smtp*, instead "
"assign a smtp:// URL to *mta*!"));
/* For *smtp* the smtp:// protocol was optional; be simple: do not check
* that *smtp* is misused with file:// or so */
if(mx_url_servbyname(mta, NIL, NIL) == NIL)
mta = savecat("smtp://", mta);
}
#ifdef mx_HAVE_NET
rv = mx_url_parse(urlp, CPROTO_SMTP, mta);
#endif
if(!rv)
jemta:
n_err(_("*mta*: invalid or unsupported value: %s\n"),
n_shexp_quote_cp(mta, FAL0));
jleave:
NYD_OU;
return rv;
}
FL int
n_mail(enum n_mailsend_flags msf, struct mx_name *to, struct mx_name *cc,
struct mx_name *bcc, char const *subject, struct mx_attachment *attach,
char const *quotefile)
{
struct header head;
struct str in, out;
boole fullnames;
NYD_IN;
su_mem_set(&head, 0, sizeof head);
/* The given subject may be in RFC1522 format. */
if (subject != NULL) {
in.s = n_UNCONST(subject);
in.l = su_cs_len(subject);
mime_fromhdr(&in, &out, /* TODO ??? TD_ISPR |*/ TD_ICONV);
head.h_subject = out.s;
}
fullnames = ok_blook(fullnames);
head.h_mailx_command = "mail";
if((head.h_to = to) != NULL){
if(!fullnames)
head.h_to = to = a_sendout_fullnames_cleanup(to);
head.h_mailx_raw_to = n_namelist_dup(to, to->n_type);
}
if((head.h_cc = cc) != NULL){
if(!fullnames)
head.h_cc = cc = a_sendout_fullnames_cleanup(cc);
head.h_mailx_raw_cc = n_namelist_dup(cc, cc->n_type);
}
if((head.h_bcc = bcc) != NULL){
if(!fullnames)
head.h_bcc = bcc = a_sendout_fullnames_cleanup(bcc);
head.h_mailx_raw_bcc = n_namelist_dup(bcc, bcc->n_type);
}
head.h_attach = attach;
/* TODO n_exit_status only!!?? */n_mail1(msf, &head, NULL, quotefile);
if (subject != NULL)
n_free(out.s);
NYD_OU;
return 0;
}
FL int
c_sendmail(void *v)
{
int rv;
NYD_IN;
rv = a_sendout_sendmail(v, n_MAILSEND_NONE);
NYD_OU;
return rv;
}
FL int
c_Sendmail(void *v)
{
int rv;
NYD_IN;
rv = a_sendout_sendmail(v, n_MAILSEND_RECORD_RECIPIENT);
NYD_OU;
return rv;
}
FL enum okay
n_mail1(enum n_mailsend_flags msf, struct header *hp, struct message *quote,
char const *quotefile)
{
#ifdef mx_HAVE_NET
struct mx_cred_ctx cc;
#endif
struct mx_url url, *urlp = &url;
struct n_sigman sm;
struct sendbundle sb;
struct mx_name *to;
boole dosign, mta_isexe;
FILE * volatile mtf, *nmtf;
enum okay volatile rv;
NYD_IN;
_sendout_error = FAL0;
__sendout_ident = NULL;
n_pstate_err_no = su_ERR_INVAL;
rv = STOP;
mtf = NULL;
n_SIGMAN_ENTER_SWITCH(&sm, n_SIGMAN_ALL) {
case 0:
break;
default:
goto jleave;
}
/* Update some globals we likely need first */
time_current_update(&time_current, TRU1);
/* Collect user's mail from standard input. Get the result as mtf */
mtf = n_collect(msf, hp, quote, quotefile, &_sendout_error);
if (mtf == NULL)
goto jleave;
/* TODO All custom headers should be joined here at latest
* TODO In fact that should happen before we enter compose mode, so that the
* TODO -C headers can be managed (removed etc.) via ~^, too, but the
* TODO *customhdr* ones are fixated at this very place here, no sooner! */
/* */
#ifdef mx_HAVE_PRIVACY
dosign = TRUM1;
#else
dosign = FAL0;
#endif
if(n_psonce & n_PSO_INTERACTIVE){
#ifdef mx_HAVE_PRIVACY
if(ok_blook(asksign))
dosign = mx_tty_yesorno(_("Sign this message"), TRU1);
#endif
}
if(fsize(mtf) == 0){
if(n_poption & n_PO_E_FLAG){
n_pstate_err_no = su_ERR_NONE;
rv = OKAY;
goto jleave;
}
if(hp->h_subject == NULL)
n_err(_("No message, no subject; hope that's ok\n"));
else if(ok_blook(bsdcompat) || ok_blook(bsdmsgs))
n_err(_("Null message body; hope that's ok\n"));
}
#ifdef mx_HAVE_PRIVACY
if(dosign == TRUM1)
dosign = mx_privacy_sign_is_desired(); /* TODO USER@HOST, *from*++!!! */
#endif
/* XXX Update time_current again; once n_collect() offers editing of more
* XXX headers, including Date:, this must only happen if Date: is the
* XXX same that it was before n_collect() (e.g., postponing etc.).
* XXX But *do* update otherwise because the mail seems to be backdated
* XXX if the user edited some time, which looks odd and it happened
* XXX to me that i got mis-dated response mails due to that... */
time_current_update(&time_current, TRU1);
/* TODO hrmpf; the MIME/send layer rewrite MUST address the init crap:
* TODO setup the header ONCE; note this affects edit.c, collect.c ...,
* TODO but: offer a hook that rebuilds/expands/checks/fixates all
* TODO header fields ONCE, call that ONCE after user editing etc. has
* TODO completed (one edit cycle) */
if(!(mta_isexe = mx_sendout_mta_url(urlp)))
goto jfail_dead;
mta_isexe = (mta_isexe != TRU1);
/* Take the user names from the combined to and cc lists and do all the
* alias processing. The POSIX standard says:
* The names shall be substituted when alias is used as a recipient
* address specified by the user in an outgoing message (that is,
* other recipients addressed indirectly through the reply command
* shall not be substituted in this manner).
* XXX S-nail thus violates POSIX, as has been pointed out correctly by
* XXX Martin Neitzel, but logic and usability of POSIX standards is
* XXX sometimes disputable: go for user friendliness */
to = n_namelist_vaporise_head(hp, TRU1, ((quote != NULL &&
(msf & n_MAILSEND_IS_FWD) == 0) || !ok_blook(posix)),
(EACM_NORMAL | EACM_DOMAINCHECK |
(mta_isexe ? EACM_NONE : EACM_NONAME | EACM_NONAME_OR_FAIL)),
&_sendout_error);
if(_sendout_error < 0){
n_err(_("Some addressees were classified as \"hard error\"\n"));
n_pstate_err_no = su_ERR_PERM;
goto jfail_dead;
}
if(to == NULL){
n_err(_("No recipients specified\n"));
n_pstate_err_no = su_ERR_DESTADDRREQ;
goto jfail_dead;
}
/* */
su_mem_set(&sb, 0, sizeof sb);
sb.sb_hp = hp;
sb.sb_to = to;
sb.sb_input = mtf;
sb.sb_urlp = urlp;
#ifdef mx_HAVE_NET
sb.sb_credp = &cc;
#endif
if((dosign || count_nonlocal(to) > 0) &&
!_sendbundle_setup_creds(&sb, (dosign > 0))){
/* TODO saving $DEAD and recovering etc is not yet well defined */
n_pstate_err_no = su_ERR_INVAL;
goto jfail_dead;
}
/* 'Bit ugly kind of control flow until we find a charset that does it */
/* C99 */{
boole any;
for(any = FAL0, charset_iter_reset(hp->h_charset);;
any = TRU1, charset_iter_next()){
int err;
boole volatile force;
force = FAL0;
if(!charset_iter_is_valid() &&
(!any || !(force = ok_blook(mime_force_sendout))))
err = su_ERR_NOENT;
else if((nmtf = a_sendout_infix(hp, mtf, dosign, force)) != NULL)
break;
#ifdef mx_HAVE_ICONV
else if((err = n_iconv_err_no) == su_ERR_ILSEQ ||
err == su_ERR_INVAL || err == su_ERR_NOENT){
rewind(mtf);
continue;
}
#endif
n_perr(_("Cannot find a usable character set to encode message"),
err);
n_pstate_err_no = su_ERR_NOTSUP;
goto jfail_dead;
}
}
mtf = nmtf;
/* */
#ifdef mx_HAVE_PRIVACY
if(dosign){
if((nmtf = mx_privacy_sign(mtf, sb.sb_signer.s)) == NIL)
goto jfail_dead;
mx_fs_close(mtf);
mtf = nmtf;
}
#endif
/* TODO truly - i still don't get what follows: (1) we deliver file
* TODO and pipe addressees, (2) we mightrecord() and (3) we transfer
* TODO even if (1) savedeadletter() etc. To me this doesn't make sense? */
/* C99 */{
u32 cnt;
boole b;
/* Deliver pipe and file addressees */
b = (ok_blook(record_files) && count(to) > 0);
to = a_sendout_file_a_pipe(to, mtf, &_sendout_error);
if (_sendout_error)
savedeadletter(mtf, FAL0);
to = elide(to); /* XXX only to drop GDELs due a_sendout_file_a_pipe()! */
cnt = count(to);
if(((msf & n_MAILSEND_RECORD_RECIPIENT) || b || cnt > 0) &&
!a_sendout_mightrecord(mtf,
(msf & n_MAILSEND_RECORD_RECIPIENT ? to : NIL), FAL0))
goto jleave;
if (cnt > 0) {
sb.sb_hp = hp;
sb.sb_to = to;
sb.sb_input = mtf;
b = FAL0;
if(a_sendout_transfer(&sb, FAL0, &b))
rv = OKAY;
else if(b && _sendout_error == 0){
_sendout_error = b;
savedeadletter(mtf, FAL0);
}
} else if (!_sendout_error)
rv = OKAY;
}
n_sigman_cleanup_ping(&sm);
jleave:
if(mtf != NIL){
char const *cp;
mx_fs_close(mtf);
if((cp = ok_vlook(on_compose_cleanup)) != NULL)
temporary_compose_mode_hook_call(cp, NULL, NULL);
}
temporary_compose_mode_hook_unroll();
if(_sendout_error){
n_psonce |= n_PSO_SEND_ERROR;
n_exit_status |= n_EXIT_SEND_ERROR;
}
if(rv == OKAY)
n_pstate_err_no = su_ERR_NONE;
NYD_OU;
n_sigman_leave(&sm, n_SIGMAN_VIPSIGS_NTTYOUT);
return rv;
jfail_dead:
_sendout_error = TRU1;
savedeadletter(mtf, TRU1);
n_err(_("... message not sent\n"));
goto jleave;
}
FL int
mkdate(FILE *fo, char const *field)
{
struct tm tmpgm, *tmptr;
int tzdiff_hour, tzdiff_min, rv;
NYD_IN;
su_mem_copy(&tmpgm, &time_current.tc_gm, sizeof tmpgm);
tmptr = &time_current.tc_local;
tzdiff_min = S(int,n_time_tzdiff(time_current.tc_time, NIL, tmptr));
tzdiff_min /= 60; /* TODO su_TIME_MIN_SECS */
tzdiff_hour = tzdiff_min / 60;
tzdiff_min %= 60; /* TODO su_TIME_HOUR_MINS */
rv = fprintf(fo, "%s: %s, %02d %s %04d %02d:%02d:%02d %+05d\n",
field,
n_weekday_names[tmptr->tm_wday],
tmptr->tm_mday, n_month_names[tmptr->tm_mon],
tmptr->tm_year + 1900, tmptr->tm_hour,
tmptr->tm_min, tmptr->tm_sec,
tzdiff_hour * 100 + tzdiff_min);
if(rv < 0)
rv = -1;
NYD_OU;
return rv;
}
FL boole
n_puthead(boole nosend_msg, struct header *hp, FILE *fo, enum gfield w,
enum sendaction action, enum conversion convert, char const *contenttype,
char const *charset)
{
#define a_PUT_CC_BCC_FCC() \
do {\
if ((w & GCC) && (hp->h_cc != NULL || nosend_msg == TRUM1)) {\
if (!a_sendout_put_addrline("Cc:", hp->h_cc, fo, saf))\
goto jleave;\
++gotcha;\
}\
if ((w & GBCC) && (hp->h_bcc != NULL || nosend_msg == TRUM1)) {\
if (!a_sendout_put_addrline("Bcc:", hp->h_bcc, fo, saf))\
goto jleave;\
++gotcha;\
}\
if((w & GBCC_IS_FCC) && nosend_msg){\
for(np = hp->h_fcc; np != NULL; np = np->n_flink){\
if(fprintf(fo, "Fcc: %s\n", np->n_name) < 0)\
goto jleave;\
++gotcha;\
}\
}\
} while (0)
char const *addr;
uz gotcha;
int stealthmua;
boole nodisp;
enum a_sendout_addrline_flags saf;
struct mx_name *np, *fromasender, *mft, **mftp;
boole rv;
NYD_IN;
mftp = NIL;
fromasender = mft = NIL;
rv = FAL0;
if(nosend_msg == TRUM1 && !(hp->h_flags & HF_USER_EDITED)){
if(fputs(_("# Message will be discarded unless file is saved\n"),
fo) == EOF)
goto jleave;
}
if ((addr = ok_vlook(stealthmua)) != NULL)
stealthmua = !su_cs_cmp(addr, "noagent") ? -1 : 1;
else
stealthmua = 0;
gotcha = 0;
nodisp = (action != SEND_TODISP);
saf = (w & (GCOMMA | GFILES)) | (nodisp ? a_SENDOUT_AL_DOMIME : 0);
if(nosend_msg)
saf |= a_SENDOUT_AL_INC_INVADDR;
if (w & GDATE)
mkdate(fo, "Date"), ++gotcha;
if (w & GIDENT) {
if (hp->h_from == NULL || hp->h_sender == NULL)
setup_from_and_sender(hp);
if (hp->h_from != NULL) {
if (!a_sendout_put_addrline("From:", hp->h_from, fo, saf))
goto jleave;
++gotcha;
}
if (hp->h_sender != NULL) {
if (!a_sendout_put_addrline("Sender:", hp->h_sender, fo, saf))
goto jleave;
++gotcha;
}
fromasender = n_UNCONST(check_from_and_sender(hp->h_from, hp->h_sender));
if (fromasender == NULL)
goto jleave;
/* Note that fromasender is (NULL,) 0x1 or real sender here */
}
/* M-F-T: check this now, and possibly place us in Cc: */
if((w & GIDENT) && !nosend_msg){
/* Mail-Followup-To: TODO factor out this huge block of code.
* TODO Also, this performs multiple expensive list operations, which
* TODO hopefully can be heavily optimized later on! */
/* Place ourselves in there if any non-subscribed list is an addressee */
if((hp->h_flags & HF_LIST_REPLY) || hp->h_mft != NIL ||
ok_blook(followup_to)){
enum{
a_HADMFT = 1u<<(HF__NEXT_SHIFT + 0),
a_WASINMFT = 1u<<(HF__NEXT_SHIFT + 1),
a_ANYLIST = 1u<<(HF__NEXT_SHIFT + 2),
a_OTHER = 1u<<(HF__NEXT_SHIFT + 3)
};
struct mx_name *x;
u32 f;
f = hp->h_flags | (hp->h_mft != NIL ? a_HADMFT : 0);
if(f & a_HADMFT){
/* Detect whether we were part of the former MFT:.
* Throw away MFT: if we were the sole member (kidding) */
hp->h_mft = mft = elide(hp->h_mft);
mft = mx_alternates_remove(n_namelist_dup(mft, GNONE), FAL0);
if(mft == NIL)
f ^= a_HADMFT;
else for(x = hp->h_mft; x != NIL;
x = x->n_flink, mft = mft->n_flink){
if(mft == NIL){
f |= a_WASINMFT;
break;
}
}
}
/* But for that, remove all incarnations of ourselves first.
* TODO It is total crap that we have alternates_remove(), is_myname()
* TODO or whatever; these work only with variables, not with data
* TODO that is _currently_ in some header fields!!! v15.0: complete
* TODO rewrite, object based, lazy evaluated, on-the-fly marked.
* TODO then this should be a really cheap thing in here... */
np = elide(mx_alternates_remove(cat(
n_namelist_dup(hp->h_to, GEXTRA | GFULL),
n_namelist_dup(hp->h_cc, GEXTRA | GFULL)), FAL0));
addr = hp->h_list_post;
mft = NIL;
mftp = &mft;
while((x = np) != NIL){
s8 ml;
np = np->n_flink;
/* Automatically make MLIST_KNOWN List-Post: address */
/* XXX mx_mlist_query_mp()?? */
if(((ml = mx_mlist_query(x->n_name, FAL0)) == mx_MLIST_OTHER ||
ml == mx_MLIST_POSSIBLY) &&
addr != NIL && !su_cs_cmp_case(addr, x->n_name))
ml = mx_MLIST_KNOWN;
/* Any non-subscribed list? Add ourselves */
switch(ml){
case mx_MLIST_KNOWN:
f |= HF_MFT_SENDER;
/* FALLTHRU */
case mx_MLIST_SUBSCRIBED:
f |= a_ANYLIST;
goto j_mft_add;
case mx_MLIST_OTHER:
case mx_MLIST_POSSIBLY:
f |= a_OTHER;
if(!(f & HF_LIST_REPLY)){
j_mft_add:
if(!is_addr_invalid(x,
EACM_STRICT | EACM_NOLOG | EACM_NONAME)){
x->n_blink = *mftp;
x->n_flink = NIL;
*mftp = x;
mftp = &x->n_flink;
} /* XXX write some warning? if verbose?? */
continue;
}
/* And if this is a reply that honoured a M-F-T: header then
* we'll also add all members of the original M-F-T: that are
* still addressed by us, regardless of other circumstances */
/* TODO If the user edited this list, then we should include
* TODO whatever she did therewith, even if _LIST_REPLY! */
else if(f & a_HADMFT){
struct mx_name *ox;
for(ox = hp->h_mft; ox != NIL; ox = ox->n_flink)
if(!su_cs_cmp_case(ox->n_name, x->n_name))
goto j_mft_add;
}
break;
}
}
if((f & (a_ANYLIST | a_HADMFT)) && mft != NIL){
if(((f & HF_MFT_SENDER) ||
((f & (a_ANYLIST | a_HADMFT)) == a_HADMFT)) &&
(np = fromasender) != NIL && np != R(struct mx_name*,0x1)){
*mftp = ndup(np, (np->n_type & ~GMASK) | GEXTRA | GFULL);
/* Place ourselves in the Cc: if we will be a member of M-F-T:,
* and we are not subscribed (and are no addressee yet)? */
/* TODO This entire block is much to expensive and should
* TODO be somewhere else (like name_unite(), or so) */
if(ok_blook(followup_to_add_cc)){
struct mx_name **npp;
np = ndup(np, (np->n_type & ~GMASK) | GCC | GFULL);
np = cat(cat(hp->h_to, hp->h_cc), np);
np = mx_alternates_remove(np, TRU1);
np = elide(np);
hp->h_to = hp->h_cc = NIL;
for(; np != NIL; np = np->n_flink){
switch(np->n_type & (GDEL | GMASK)){
case GTO: npp = &hp->h_to; break;
case GCC: npp = &hp->h_cc; break;
default: continue;
}
*npp = cat(*npp, ndup(np, np->n_type | GFULL));
}
}
}
}else
mft = NIL;
}
}
if(nosend_msg == TRUM1 && !(hp->h_flags & HF_USER_EDITED)){
if(fputs(_("# To:, Cc: and Bcc: support a ?single modifier: "
"To?: exa, <m@ple>\n"), fo) == EOF)
goto jleave;
}
#if 1
if ((w & GTO) && (hp->h_to != NULL || nosend_msg == TRUM1)) {
if (!a_sendout_put_addrline("To:", hp->h_to, fo, saf))
goto jleave;
++gotcha;
}
#else
/* TODO Thought about undisclosed recipients:;, but would be such a fake
* TODO given that we cannot handle group addresses. Ridiculous */
if (w & GTO) {
struct mx_name *xto;
if ((xto = hp->h_to) != NULL) {
char const ud[] = "To: Undisclosed recipients:;\n" /* TODO groups */;
if (count_nonlocal(xto) != 0 || ok_blook(add_file_recipients) ||
(hp->h_cc != NULL && count_nonlocal(hp->h_cc) > 0))
goto jto_fmt;
if (fwrite(ud, 1, sizeof(ud) -1, fo) != sizeof(ud) -1)
goto jleave;
++gotcha;
} else if (nosend_msg == TRUM1) {
jto_fmt:
if (!a_sendout_put_addrline("To:", hp->h_to, fo, saf))
goto jleave;
++gotcha;
}
}
#endif
if(!ok_blook(bsdcompat) && !ok_blook(bsdorder))
a_PUT_CC_BCC_FCC();
if ((w & GSUBJECT) && (hp->h_subject != NULL || nosend_msg == TRUM1)) {
if (fwrite("Subject: ", sizeof(char), 9, fo) != 9)
goto jleave;
if (hp->h_subject != NULL) {
uz sublen;
char const *sub;
sublen = su_cs_len(sub = subject_re_trim(hp->h_subject));
/* Trimmed something, (re-)add Re: */
if (sub != hp->h_subject) {
if (fwrite("Re: ", 1, 4, fo) != 4) /* RFC mandates eng. "Re: " */
goto jleave;
if (sublen > 0 &&
xmime_write(sub, sublen, fo,
(!nodisp ? CONV_NONE : CONV_TOHDR),
(!nodisp ? TD_ISPR | TD_ICONV : TD_ICONV), NIL,NIL) < 0)
goto jleave;
}
/* This may be, e.g., a Fwd: XXX yes, unfortunately we do like that */
else if (*sub != '\0') {
if(xmime_write(sub, sublen, fo, (!nodisp ? CONV_NONE : CONV_TOHDR),
(!nodisp ? TD_ISPR | TD_ICONV : TD_ICONV), NIL,NIL) < 0)
goto jleave;
}
}
++gotcha;
putc('\n', fo);
}
if (ok_blook(bsdcompat) || ok_blook(bsdorder))
a_PUT_CC_BCC_FCC();
if ((w & GMSGID) && stealthmua <= 0 &&
(addr = a_sendout_random_id(hp, TRU1)) != NULL) {
if (fprintf(fo, "Message-ID: <%s>\n", addr) < 0)
goto jleave;
++gotcha;
}
if(w & (GREF | GREF_IRT)){
if((np = hp->h_in_reply_to) == NULL)
hp->h_in_reply_to = np = n_header_setup_in_reply_to(hp);
if(np != NULL){
if(nosend_msg == TRUM1 && !(hp->h_flags & HF_USER_EDITED)){
if(fputs(_("# Removing or modifying In-Reply-To: "
"breaks the old, and starts a new thread.\n"
"# Assigning hyphen-minus - creates a thread of only the "
"replied-to message\n"), fo) == EOF)
goto jleave;
}
if(!a_sendout_put_addrline("In-Reply-To:", np, fo, 0))
goto jleave;
++gotcha;
}
if((w & GREF) && (np = hp->h_ref) != NULL){
if(!a_sendout_put_addrline("References:", np, fo, 0))
goto jleave;
++gotcha;
}
}
if (w & GIDENT) {
/* Reply-To:. Be careful not to destroy a possible user input, duplicate
* the list first.. TODO it is a terrible codebase.. */
if((np = hp->h_reply_to) != NULL)
np = n_namelist_dup(np, np->n_type);
else{
char const *v15compat;
if((v15compat = ok_vlook(replyto)) != NULL)
n_OBSOLETE(_("please use *reply-to*, not *replyto*"));
if((addr = ok_vlook(reply_to)) == NULL)
addr = v15compat;
np = lextract(addr, GEXTRA |
(ok_blook(fullnames) ? GFULL | GSKIN : GSKIN));
}
if (np != NULL &&
(np = elide(
checkaddrs(usermap(np, TRU1), EACM_STRICT | EACM_NOLOG,
NULL))) != NULL) {
if (!a_sendout_put_addrline("Reply-To:", np, fo, saf))
goto jleave;
++gotcha;
}
}
if((w & GIDENT) && !nosend_msg){
if(mft != NIL){
if(!a_sendout_put_addrline("Mail-Followup-To:", mft, fo, saf))
goto jleave;
++gotcha;
}
if(!_check_dispo_notif(fromasender, hp, fo))
goto jleave;
}
if ((w & GUA) && stealthmua == 0) {
if (fprintf(fo, "User-Agent: %s %s\n", n_uagent,
(su_state_has(su_STATE_REPRODUCIBLE)
? su_reproducible_build : ok_vlook(version))) < 0)
goto jleave;
++gotcha;
}
/* Custom headers, as via -C and *customhdr* TODO JOINED AFTER COMPOSE! */
if(!nosend_msg){
struct n_header_field *chlp[2], *hfp;
u32 i;
chlp[0] = n_poption_arg_C;
chlp[1] = n_customhdr_list;
for(i = 0; i < NELEM(chlp); ++i)
if((hfp = chlp[i]) != NULL){
if(!_sendout_header_list(fo, hfp, nodisp))
goto jleave;
++gotcha;
}
}
/* The user may have placed headers when editing */
if(1){
struct n_header_field *hfp;
if((hfp = hp->h_user_headers) != NULL){
if(!_sendout_header_list(fo, hfp, nodisp))
goto jleave;
++gotcha;
}
}
/* We don't need MIME unless.. we need MIME?! */
if ((w & GMIME) && ((n_pstate & n_PS_HEADER_NEEDED_MIME) ||
hp->h_attach != NULL ||
((n_poption & n_PO_Mm_FLAG) && n_poption_arg_Mm != NULL) ||
convert != CONV_7BIT || !n_iconv_name_is_ascii(charset))) {
++gotcha;
if (fputs("MIME-Version: 1.0\n", fo) == EOF)
goto jleave;
if (hp->h_attach != NULL) {
_sendout_boundary = mime_param_boundary_create();/*TODO carrier*/
if (fprintf(fo,
"Content-Type: multipart/mixed;\n boundary=\"%s\"\n",
_sendout_boundary) < 0)
goto jleave;
} else {
if(a_sendout_put_ct(fo, contenttype, charset) < 0 ||
a_sendout_put_cte(fo, convert) < 0)
goto jleave;
}
}
if (gotcha && (w & GNL))
if (putc('\n', fo) == EOF)
goto jleave;
rv = TRU1;
jleave:
if(nosend_msg == TRUM1)
hp->h_flags |= HF_USER_EDITED;
NYD_OU;
return rv;
#undef a_PUT_CC_BCC_FCC
}
FL enum okay
n_resend_msg(struct message *mp, struct mx_url *urlp, struct header *hp,
boole add_resent)
{
#ifdef mx_HAVE_NET
struct mx_cred_ctx cc;
#endif
struct n_sigman sm;
struct sendbundle sb;
FILE * volatile ibuf, *nfo, * volatile nfi;
struct mx_fs_tmp_ctx *fstcp;
struct mx_name *to;
enum okay volatile rv;
NYD_IN;
_sendout_error = FAL0;
__sendout_ident = NULL;
n_pstate_err_no = su_ERR_INVAL;
rv = STOP;
to = hp->h_to;
ASSERT(hp->h_cc == NIL);
ASSERT(hp->h_bcc == NIL);
nfi = ibuf = NULL;
n_SIGMAN_ENTER_SWITCH(&sm, n_SIGMAN_ALL) {
case 0:
break;
default:
goto jleave;
}
/* Update some globals we likely need first */
time_current_update(&time_current, TRU1);
if((nfo = mx_fs_tmp_open("resend", (mx_FS_O_WRONLY | mx_FS_O_HOLDSIGS |
mx_FS_O_REGISTER), &fstcp)) == NIL){
_sendout_error = TRU1;
n_perr(_("resend_msg: temporary mail file"), 0);
n_pstate_err_no = su_ERR_IO;
goto jleave;
}
if((nfi = mx_fs_open(fstcp->fstc_filename, "r")) == NIL){
n_perr(fstcp->fstc_filename, 0);
n_pstate_err_no = su_ERR_IO;
}
mx_fs_tmp_release(fstcp);
if(nfi == NIL)
goto jerr_o;
if((ibuf = setinput(&mb, mp, NEED_BODY)) == NULL){
n_pstate_err_no = su_ERR_IO;
goto jerr_io;
}
/* C99 */{
char const *cp;
if((cp = ok_vlook(on_resend_enter)) != NULL){
/*setup_from_and_sender(hp);*/
temporary_compose_mode_hook_call(cp, &n_temporary_compose_hook_varset,
hp);
}
}
su_mem_set(&sb, 0, sizeof sb);
sb.sb_to = to;
sb.sb_input = nfi;
sb.sb_urlp = urlp;
#ifdef mx_HAVE_NET
sb.sb_credp = &cc;
#endif
/* All the complicated address massage things happened in the callee(s) */
if(!_sendout_error &&
count_nonlocal(to) > 0 && !_sendbundle_setup_creds(&sb, FAL0)){
/* ..wait until we can write DEAD */
n_pstate_err_no = su_ERR_INVAL;
_sendout_error = -1;
}
if(!a_sendout_infix_resend(ibuf, nfo, mp, to, add_resent)){
jfail_dead:
savedeadletter(nfi, TRU1);
n_err(_("... message not sent\n"));
jerr_io:
mx_fs_close(nfi);
nfi = NIL;
jerr_o:
mx_fs_close(nfo);
_sendout_error = TRU1;
goto jleave;
}
if(_sendout_error < 0)
goto jfail_dead;
mx_fs_close(nfo);
rewind(nfi);
/* C99 */{
boole b, c;
/* Deliver pipe and file addressees */
b = (ok_blook(record_files) && count(to) > 0);
to = a_sendout_file_a_pipe(to, nfi, &_sendout_error);
if(_sendout_error)
savedeadletter(nfi, FAL0);
to = elide(to); /* XXX only to drop GDELs due a_sendout_file_a_pipe()! */
c = (count(to) > 0);
if(b || c){
if(!ok_blook(record_resent) || a_sendout_mightrecord(nfi, NIL, TRU1)){
sb.sb_to = to;
/*sb.sb_input = nfi;*/
b = FAL0;
if(!c || a_sendout_transfer(&sb, TRU1, &b))
rv = OKAY;
else if(b && _sendout_error == 0){
_sendout_error = b;
savedeadletter(nfi, FAL0);
}
}
}else if(!_sendout_error)
rv = OKAY;
}
n_sigman_cleanup_ping(&sm);
jleave:
if(nfi != NIL){
char const *cp;
mx_fs_close(nfi);
if(ibuf != NULL){
if((cp = ok_vlook(on_resend_cleanup)) != NULL)
temporary_compose_mode_hook_call(cp, NULL, NULL);
temporary_compose_mode_hook_unroll();
}
}
if(_sendout_error){
n_psonce |= n_PSO_SEND_ERROR;
n_exit_status |= n_EXIT_SEND_ERROR;
}
if(rv == OKAY)
n_pstate_err_no = su_ERR_NONE;
NYD_OU;
n_sigman_leave(&sm, n_SIGMAN_VIPSIGS_NTTYOUT);
return rv;
}
FL void
savedeadletter(FILE *fp, boole fflush_rewind_first){
struct n_string line;
int c;
enum {a_NONE, a_INIT = 1<<0, a_BODY = 1<<1, a_NL = 1<<2} flags;
ul bytes, lines;
FILE *dbuf;
char const *cp, *cpq;
NYD_IN;
if(!ok_blook(save))
goto jleave;
if(fflush_rewind_first){
fflush(fp);
rewind(fp);
}
if(fsize(fp) == 0)
goto jleave;
cp = n_getdeadletter();
cpq = n_shexp_quote_cp(cp, FAL0);
if(n_poption & n_PO_D){
n_err(_(">>> Would (try to) write $DEAD %s\n"), cpq);
goto jleave;
}
if((dbuf = mx_fs_open(cp, "w")) == NIL){
n_perr(_("Cannot save to $DEAD"), 0);
goto jleave;
}
/* XXX Natomic */
mx_file_lock(fileno(dbuf), mx_FILE_LOCK_TYPE_WRITE, 0,0, UZ_MAX);
fprintf(n_stdout, "%s ", cpq);
fflush(n_stdout);
/* TODO savedeadletter() non-conforming: should check whether we have any
* TODO headers, if not we need to place "something", anything will do.
* TODO MIME is completely missing, we use MBOXO quoting!! Yuck.
* TODO I/O error handling missing. Yuck! */
n_string_reserve(n_string_creat_auto(&line), 2 * SEND_LINESIZE);
bytes = (ul)fprintf(dbuf, "From %s %s",
ok_vlook(LOGNAME), time_current.tc_ctime);
lines = 1;
for(flags = a_NONE, c = '\0'; c != EOF; bytes += line.s_len, ++lines){
n_string_trunc(&line, 0);
while((c = getc(fp)) != EOF && c != '\n')
n_string_push_c(&line, c);
/* TODO It may be that we have only some plain text. It may be that we
* TODO have a complete MIME encoded message. We don't know, and we
* TODO have no usable mechanism to dig it!! We need v15! */
if(!(flags & a_INIT)){
uz i;
/* Throw away leading empty lines! */
if(line.s_len == 0)
continue;
for(i = 0; i < line.s_len; ++i){
if(fieldnamechar(line.s_dat[i]))
continue;
if(line.s_dat[i] == ':'){
flags |= a_INIT;
break;
}else{
/* We have no headers, this is already a body line! */
flags |= a_INIT | a_BODY;
break;
}
}
/* Well, i had to check whether the RFC allows this. Assume we've
* passed the headers, too, then! */
if(i == line.s_len)
flags |= a_INIT | a_BODY;
}
if(flags & a_BODY){
if(line.s_len >= 5 && !su_mem_cmp(line.s_dat, "From ", 5))
n_string_unshift_c(&line, '>');
}
if(line.s_len == 0)
flags |= a_BODY | a_NL;
else
flags &= ~a_NL;
n_string_push_c(&line, '\n');
fwrite(line.s_dat, sizeof *line.s_dat, line.s_len, dbuf);
}
if(!(flags & a_NL)){
putc('\n', dbuf);
++bytes;
++lines;
}
n_string_gut(&line);
mx_fs_close(dbuf);
fprintf(n_stdout, "%lu/%lu\n", lines, bytes);
fflush(n_stdout);
rewind(fp);
jleave:
NYD_OU;
}
#undef SEND_LINESIZE
#include "su/code-ou.h"
/* s-it-mode */
|
Jack957/BigNumber
|
src/bignumber.h
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
* OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef BIGNUMBER_H
#define BIGNUMBER_H
#include <vector>
#include <string>
#include <iostream>
/**
* BigNumber class
*/
class BigNumber {
public:
//@{
/**
* BigNumber constructor
* @param number - The initial value of the BigNumber
*/
BigNumber(std::string number);
BigNumber(long long number);
//@}
/**
* Add another BigNumber to the current instance
* @param other - The other BigNumber
* @return The sum of the two BigNumbers
*/
BigNumber add(BigNumber other);
/**
* Subtract another BigNumber from the current instance
* @param other - The other BigNumber
* @return The difference of the two BigNumbers
*/
BigNumber subtract(BigNumber other);
/**
* Multiply the current instance by another BigNumber
* @param other - The other BigNumber
* @return The product of the two BigNumbers
*/
BigNumber multiply(BigNumber other);
/**
* Divide the current instance by another BigNumber
* @param other - The other BigNumber
* @return The quotient of the two BigNumbers
*/
BigNumber divide(BigNumber other);
/**
* Raise the current instance to the power of an exponent
* @param exponent - The power to be raised by
* @return - The resulting BigNumber after exponentiation
*/
BigNumber pow(int exponent);
/**
* Get the string value of the current instance
* @return The BigNumber as a string
*/
std::string getString();
/**
* Set the value of the current instance with a string
* @param newStr - The new value for the BigNumber
* @return The BigNumber with the new value
*/
BigNumber setString(const std::string &newStr);
/**
* Negates the current instance
* @return The BigNumber after negation
*/
BigNumber negate();
BigNumber trimLeadingZeros();
//@{
/**
* Check if another BigNumber is equal to the current instance
* @param other - The other BigNumber
* @return True if equal, otherwise false
*/
bool equals(const BigNumber &other);
bool equals(const long long &other);
bool equals(const std::string &other);
//@}
/**
* Get the number of digits in the current instance
* @return The number of digits
*/
unsigned int digits();
/**
* Get whether or not the current instance is a negative number
* @return True if negative, otherwise false
*/
bool isNegative() const;
/**
* Get whether or not the current instance is a positive number
* @return True if positive, otherwise false
*/
bool isPositive();
/**
* Get whether or not the current instance is an even number
* @return True if even, otherwise false
*/
bool isEven();
/**
* Get whether or not the current instance is an odd number
* @return True if odd, otherwise false
*/
bool isOdd();
/**
* Get the absolute value of the current instance
* @return The absolute value of the BigNumber
*/
BigNumber abs() const;
/**
* Output stream operator
* @param os The output stream
* @param num The current instance
* @return The output stream with the current instance
*/
friend std::ostream &operator<<(std::ostream &os, const BigNumber &num);
//@{
/**
* Addition operator
* @param b1 - The current instance
* @param b2 - The number being added
* @return The sum of the two numbers
*/
friend BigNumber operator+(BigNumber b1, const BigNumber &b2);
friend BigNumber operator+(BigNumber b1, const long long &b2);
friend BigNumber operator+(BigNumber b1, const std::string &b2);
//@}
//@{
/**
* Subtraction operator
* @param b1 - The current instance
* @param b2 - The number being subtracted
* @return The difference of the two numbers
*/
friend BigNumber operator-(BigNumber b1, const BigNumber &b2);
friend BigNumber operator-(BigNumber b1, const long long &b2);
friend BigNumber operator-(BigNumber b1, const std::string &b2);
//@}
//@{
/**
* Multiplication operator
* @param b1 - The current instance
* @param b2 - The number being multiplied by
* @return The product of the two numbers
*/
friend BigNumber operator*(BigNumber b1, const BigNumber &b2);
friend BigNumber operator*(BigNumber b1, const long long &b2);
friend BigNumber operator*(BigNumber b1, const std::string &b2);
//@}
//@{
/**
* Division operator
* @param b1 - The current instance
* @param b2 - The number being divided by
* @return The quotient of the two numbers
*/
friend BigNumber operator/(BigNumber b1, const BigNumber &b2);
friend BigNumber operator/(BigNumber b1, const long long &b2);
friend BigNumber operator/(BigNumber b1, const std::string &b2);
//@}
/**
* Exponent operator
* @param b1 - The current instance
* @param b2 - The exponent
* @return The value after exponentiation
*/
friend BigNumber operator^(BigNumber b1, const int &b2);
//@{
/**
* Equality operator
* @param b1 - The current instance
* @param b2 - Another value
* @return True if equal, otherwise false
*/
friend bool operator==(BigNumber b1, const BigNumber &b2);
friend bool operator==(BigNumber b1, const long long &b2);
friend bool operator==(BigNumber b1, const std::string &b2);
//@}
/**
* Greater-than operator
* @param b1 - The current instance
* @param b2 - Another BigNumber
* @return True if current instance is greater, otherwise false
*/
friend bool operator>(BigNumber b1, const BigNumber &b2);
/**
* Less-than operator
* @param b1 - The current instance
* @param b2 - Another BigNumber
* @return True if current instance is less, otherwise false
*/
friend bool operator<(BigNumber b1, const BigNumber &b2);
/**
* Greater-than or equal-to operator
* @param b1 - The current instance
* @param b2 - Another BigNumber
* @return True if current instance is greater or equal, otherwise false
*/
friend bool operator>=(BigNumber b1, const BigNumber &b2);
/**
* Less-than or equal-to operator
* @param b1 - The current instance
* @param b2 - Another BigNumber
* @return True if current instance is less or equal, otherwise false
*/
friend bool operator<=(BigNumber b1, const BigNumber &b2);
//@{
/**
* Assignment operator
* @param other - The new value for the BigNumber
* @return A BigNumber containing the new value
*/
BigNumber& operator=(const BigNumber &other);
BigNumber& operator=(const long long &other);
BigNumber& operator=(const std::string &other);
//@}
//@{
/**
* Addition assignment operator\n
* Adds and assigns a value to the current instance
* @param other - The value being added
* @return The new value after addition and assignment
*/
BigNumber& operator+=(const BigNumber &other);
BigNumber& operator+=(const long long &other);
BigNumber& operator+=(const std::string &other);
//@}
//@{
/**
* Subtraction assignment operator\n
* Subtracts and assigns a value to the current instance
* @param other - The value being subtracted
* @return The new value after subtraction and assignment
*/
BigNumber& operator-=(const BigNumber &other);
BigNumber& operator-=(const long long &other);
BigNumber& operator-=(const std::string &other);
//@}
//@{
/**
* Multiplication assignment operator\n
* Multiplies and assigns a value to the current instance
* @param other - The value being multiplied
* @return The new value after multiplication and assignment
*/
BigNumber& operator*=(const BigNumber &other);
BigNumber& operator*=(const long long &other);
BigNumber& operator*=(const std::string &other);
//@}
//@{
/**
* Division assignment operator\n
* Divides and assigns a value to the current instance
* @param other - The value being divided
* @return The new value after division and assignment
*/
BigNumber& operator/=(const BigNumber &other);
BigNumber& operator/=(const long long &other);
BigNumber& operator/=(const std::string &other);
//@}
/**
* Pre-increment operator
* @return The incremented BigNumber
*/
BigNumber& operator++();
/**
* Pre-decrement operator
* @return The decremented BigNumber
*/
BigNumber& operator--();
/**
* Post-increment operator
* @return The incremented BigNumber
*/
BigNumber operator++(int);
/**
* Post-decrement operator
* @return The decremented BigNumber
*/
BigNumber operator--(int);
/**
* The index operator
* @param index The position being looked at
* @return The number at the specified position in the BigNumber string
*/
unsigned int operator[](int index);
private:
std::string _numberString; //The big number represented as a string
//Methods
BigNumber addll(const long long &other);
BigNumber addstr(const std::string &other);
BigNumber subtractll(const long long &other);
BigNumber subtractstr(const std::string &other);
BigNumber multiplyll(const long long &other);
BigNumber multiplystr(const std::string &other);
BigNumber dividell(const long long &other);
BigNumber dividestr(const std::string &other);
};
#endif
|
shadow-of-arman/UIButtonExtension
|
UIButtonExtension/UIButtonExtension.h
|
//
// UIButtonExtension.h
// UIButtonExtension
//
// Created by <NAME> on 9/28/20.
//
#import <Foundation/Foundation.h>
//! Project version number for UIButtonExtension.
FOUNDATION_EXPORT double UIButtonExtensionVersionNumber;
//! Project version string for UIButtonExtension.
FOUNDATION_EXPORT const unsigned char UIButtonExtensionVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <UIButtonExtension/PublicHeader.h>
|
wodely/ASAlterView
|
ASAlterView/Classes/ASAlertControllerTool.h
|
<reponame>wodely/ASAlterView<gh_stars>0
//
// ASAlertControllerTool.h
// hxxdj
//
// Created by 刘 on 2019/5/17.
// Copyright © 2019 aisino. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
typedef void (^ActionBlock)(NSInteger buttonIndex);
typedef void (^CancelBlock)();
NS_ASSUME_NONNULL_BEGIN
@interface ASAlertControllerTool : NSObject
+(void)showAlertViewWithTitle:(nullable NSString *) title
message:(nullable NSString *) message alterStytel:(UIAlertControllerStyle)style
cancelButtonTitle:(nullable NSString *) cancelButtonTitle
otherButtonTitles:(nullable NSArray *) otherButtons
onAction:(nullable ActionBlock) actionBlock
onCancel:(nullable CancelBlock) cancelBlock; ;
@end
NS_ASSUME_NONNULL_END
|
carlosmouracorreia/AlbumFolksFetcher
|
AlbumFolks/Classes/external/UIScrollView+InfiniteScroll.h
|
//Library to easy enable infinite scroll. Easier integration than through CocoaPods
//Taken from https://github.com/pronebird/UIScrollView-InfiniteScroll
// UIScrollView+InfiniteScroll.h
//
// UIScrollView infinite scroll category
//
// Created by <NAME> on 9/4/13.
// Copyright (c) 2013-2015 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
UIScrollView infinite scroll category
*/
@interface UIScrollView (InfiniteScroll)
/**
* Flag that indicates whether infinite scroll is animating
*/
@property (nonatomic, readonly, getter=isAnimatingInfiniteScroll) BOOL animatingInfiniteScroll;
/**
* Infinite scroll activity indicator style (default: UIActivityIndicatorViewStyleGray on iOS, UIActivityIndicatorViewStyleWhite on tvOS)
*/
@property (nonatomic) UIActivityIndicatorViewStyle infiniteScrollIndicatorStyle;
/**
* Infinite indicator view
*
* You can set your own custom view instead of default activity indicator,
* make sure it implements methods below:
*
* * `- (void)startAnimating`
* * `- (void)stopAnimating`
*
* Infinite scroll will call implemented methods during user interaction.
*/
@property (nonatomic, nullable) UIView *infiniteScrollIndicatorView;
/**
* Vertical margin around indicator view (Default: 11)
*/
@property (nonatomic) CGFloat infiniteScrollIndicatorMargin;
/**
* Set vertical adjustment for scroll coordinate used to determine when to call handler block.
* Non-zero value advances the point when handler block is being called
* making it fire by N points earlier before scroll view reaches the bottom.
* This value is measured in points and must be positive number.
* Default: 0.0
*/
@property (nonatomic) CGFloat infiniteScrollTriggerOffset;
/**
* Setup infinite scroll handler
*
* @param handler a handler block
*/
- (void)addInfiniteScrollWithHandler:(void(^)(UIScrollView *scrollView))handler;
/**
* Set a handler to be called to check if the infinite scroll should be shown
*
* @param handler a handler block
*/
- (void)setShouldShowInfiniteScrollHandler:(nullable BOOL(^)(UIScrollView *scrollView))handler;
/**
* Unregister infinite scroll
*/
- (void)removeInfiniteScroll;
/**
* Manually begin infinite scroll animations
*
* This method provides identical behavior to user initiated scrolling.
*
* @param forceScroll pass YES to scroll to indicator view
*/
- (void)beginInfiniteScroll:(BOOL)forceScroll;
/**
* Finish infinite scroll animations
*
* You must call this method from your infinite scroll handler to finish all
* animations properly and reset infinite scroll state
*
* @param handler a completion block handler called when animation finished
*/
- (void)finishInfiniteScrollWithCompletion:(nullable void(^)(UIScrollView *scrollView))handler;
/**
* Finish infinite scroll animations
*
* You must call this method from your infinite scroll handler to finish all
* animations properly and reset infinite scroll state
*/
- (void)finishInfiniteScroll;
@end
/**
Convenience interface for UIScrollView+InfiniteScroll category.
*/
@interface UITableView (InfiniteScrollConvenienceInterface)
/**
* Setup infinite scroll handler
*
* @param handler a handler block
*/
- (void)addInfiniteScrollWithHandler:(void(^)(UITableView *tableView))handler;
/**
* Set a handler to be called to check if the infinite scroll should be shown
*
* @param handler a handler block
*/
- (void)setShouldShowInfiniteScrollHandler:(BOOL(^)(UITableView *tableView))handler;
/**
* Finish infinite scroll animations
*
* You must call this method from your infinite scroll handler to finish all
* animations properly and reset infinite scroll state
*
* @param handler a completion block handler called when animation finished
*/
- (void)finishInfiniteScrollWithCompletion:(nullable void(^)(UITableView *tableView))handler;
@end
/**
Convenience interface for UIScrollView+InfiniteScroll category.
*/
@interface UICollectionView (InfiniteScrollConvenienceInterface)
/**
* Setup infinite scroll handler
*
* @param handler a handler block
*/
- (void)addInfiniteScrollWithHandler:(void(^)(UICollectionView *collectionView))handler;
/**
* Set a handler to be called to check if the infinite scroll should be shown
*
* @param handler a handler block
*/
- (void)setShouldShowInfiniteScrollHandler:(BOOL(^)(UICollectionView *collectionView))handler;
/**
* Finish infinite scroll animations
*
* You must call this method from your infinite scroll handler to finish all
* animations properly and reset infinite scroll state
*
* @param handler a completion block handler called when animation finished
*/
- (void)finishInfiniteScrollWithCompletion:(nullable void(^)(UICollectionView *collectionView))handler;
@end
NS_ASSUME_NONNULL_END
|
carlosmouracorreia/AlbumFolksFetcher
|
AlbumFolks/Classes/external/AlbumFolks-Bridging-Header.h
|
//Library to easy enable infinite scroll. Easier integration than through CocoaPods
//Taken from https://github.com/pronebird/UIScrollView-InfiniteScroll
#import "UIScrollView+InfiniteScroll.h"
|
jcspencer/lobsters-ios
|
vendor/InfiniteScroll/UIScrollView+InfiniteScroll.h
|
//
// UIScrollView+InfiniteScroll.h
//
// UIScrollView infinite scroll category
//
// Created by <NAME> on 9/4/13.
// Copyright (c) 2013 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef void(^pb_infinite_scroll_handler_t)(void);
typedef void(^pb_infinite_scroll_completion_t)(void);
@interface UIScrollView (PBInfiniteScroll)
// Setup infinite scroll handler
- (void)addInfiniteScrollWithHandler:(pb_infinite_scroll_handler_t)handler;
// Unregister infinite scroll
- (void)removeInfiniteScroll;
// You must call this method from your handler to finish
// all animations properly and reset infinite scroll state
- (void)finishInfiniteScrollWithCompletion:(pb_infinite_scroll_completion_t)handler;
- (void)finishInfiniteScroll;
@end
|
jcspencer/lobsters-ios
|
vendor/InfiniteScroll/UIBarButtonItem+ETBlockActions.h
|
<reponame>jcspencer/lobsters-ios
#import <UIKit/UIKit.h>
@interface UIBarButtonItem (ETBlockActions)
- (id) initWithTitle:(NSString *)title style:(UIBarButtonItemStyle)style eventHandler:(void(^)(void))handler;
@end
|
pedrocardoso5/Grall
|
include/graal.h
|
<reponame>pedrocardoso5/Grall<filename>include/graal.h
#ifndef GRAAL_H
#define GRAAL_H
#include<iostream>
#include<vector>
#include<cstring>
#include <iterator>
#include <functional>
#include <algorithm>
//Faltou serem feitas as funções uniq() e qsort()
using Compare = bool(*)(const void*, const void*);
using Predicate = bool(*)(const void*);
using Equal = bool(*)(const void*, const void*);
namespace graal{
const void* min(const void* first, const void* last, std::size_t size, Compare cmp);
void reverse(void* first, void* last, std::size_t size);
void* copy(const void* first, const void* last, const void* d_first, std::size_t size);
void* clone(const void* first, const void* last, std::size_t size);
const void* find_if(const void* first, const void* last, std::size_t size, Predicate p);
const void* find(const void* first, const void* last, std::size_t size, const void* value, Equal eq);
bool all_of(const void* first, const void* last, std::size_t size, Predicate p);
bool any_of(const void* first, const void* last, std::size_t size, Predicate p);
bool none_of(const void* first, const void* last, std::size_t size, Predicate p);
bool equal(const void* first1, const void* last1, const void* first2, std::size_t size, Equal eq);
bool equal(const void* first1, const void* last1, const void* first2, const void* last2, Equal eq);
bool equal(const void* first1, const void* last1, const void* first2, const void* last2, std::size_t size, Equal eq);
bool equal(const void* first1, const void* last1, const void* first2);
void* partition(void* first, void* last, std::size_t size, Predicate p);
}
#endif
|
tarachandverma/ngx-openidc
|
src/common-utils/common_utils.c
|
/*
* Created by <NAME> on 01/04/14.
*
*/
#include <common_utils.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#include <apr_time.h>
#include <errno.h>
#include <openssl/err.h>
#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/rsa.h>
#include <openssl/bio.h>
#include <openssl/crypto.h>
#include <openssl/aes.h>
#include <apr_file_io.h>
#include <apr_uuid.h>
char* cu_getElement(apr_array_header_t* data, int element){
if(data!=NULL&&data->nelts>element&&element>=0){
return ((char**)data->elts)[element];
}
return NULL;
}
void** cu_getElementRef(apr_array_header_t* data, int element){
if(data!=NULL&&data->nelts>element&&element>=0){
return ((void**)data->elts)+element;
}
return NULL;
}
char* cu_getNodeDetails(apr_pool_t* p,unsigned int defaultHttpPort){
int i;
//for second ip get test
struct ifaddrs *ifa = NULL, *ifp = NULL;
socklen_t salen;
char ip[512];
char* ret=NULL;
if (getifaddrs (&ifp) >= 0){
i=0;
for (ifa = ifp; ifa&&ifa->ifa_addr; ifa = ifa->ifa_next){
if (ifa->ifa_addr->sa_family == AF_INET)
salen = sizeof (struct sockaddr_in);
else if (ifa->ifa_addr->sa_family == AF_INET6)
salen = sizeof (struct sockaddr_in6);
else
continue;
if (getnameinfo (ifa->ifa_addr, salen,ip, sizeof (ip), NULL, 0, NI_NUMERICHOST) < 0){
continue;
}
if(strcmp(ip,"127.0.0.1")!=0&&strcmp(ip,"::1")!=0){ //don't need to know localhost ip4 or ip6
if(ifa->ifa_addr->sa_family == AF_INET){
if(i==0)
ret=apr_psprintf(p,"%s:%u",ip,defaultHttpPort);
else
ret=apr_psprintf(p,"%s,%s:%u",ret,ip,defaultHttpPort);
}
else{
if(i==0)
ret=apr_pstrdup(p,ip);
else
ret=apr_pstrcat(p,ret,",",ip,NULL);
}
i++;
}
}
freeifaddrs (ifp);
}
return ret;
}
#define CTEM_PRE "{"
#define CTEP_POST "}"
char* cu_templateString(apr_pool_t* p, char* src, apr_hash_t* vals){
char* cpy=NULL;
char* ret=NULL,*begin=NULL, *end=NULL, *token=NULL, *tval=NULL;
if(src==NULL){ return NULL; }
cpy=apr_pstrdup(p,src);
begin=strstr(cpy,"{");
while(begin!=NULL){
//find end
end=strstr(begin,"}");
//do append
if(end!=NULL){
*begin='\0';
*end='\0';
token=begin+1;
tval=vals!=NULL?SAFESTRBLANK(apr_hash_get(vals,token,APR_HASH_KEY_STRING)):"";
if(ret==NULL){
ret=apr_pstrcat(p,cpy,tval,NULL);
}else{
ret=apr_pstrcat(p,ret,cpy,tval,NULL);
}
begin=cpy=end+1;
}else{
begin++;
}
//continue
begin=strstr(begin,"{");
}
if(cpy!=NULL&&*cpy!='\0'){
ret=apr_pstrcat(p,ret,cpy,NULL);
}
return ret;
}
time_t cu_dateStringToSeconds(const char* dateString){
struct tm tm;
if(dateString==NULL||strptime(dateString, "%a %b %d %H:%M:%S %Y", &tm)==0) return -1;
tm.tm_isdst=-1;//daylight saving
return mktime(&tm);
}
// format is same asa apr_strftime
/*
%a Abbreviated weekday name * Thu
%A Full weekday name * Thursday
%b Abbreviated month name * Aug
%B Full month name * August
%c Date and time representation * Thu Aug 23 14:55:02 2001
%d Day of the month (01-31) 23
%H Hour in 24h format (00-23) 14
%I Hour in 12h format (01-12) 02
%j Day of the year (001-366) 235
%m Month as a decimal number (01-12) 08
%M Minute (00-59) 55
%p AM or PM designation PM
%S Second (00-61) 02
%U Week number with the first Sunday as the first day of week one (00-53) 33
%w Weekday as a decimal number with Sunday as 0 (0-6) 4
%W Week number with the first Monday as the first day of week one (00-53) 34
%x Date representation * 08/23/01
%X Time representation * 14:55:02
%y Year, last two digits (00-99) 01
%Y Year 2001
%Z Timezone name or abbreviation CDT
%% A % sign %
*/
char* cu_getCurrentDateByFormat2(apr_pool_t* p, const char* format){
#define STR_SIZE 80
apr_status_t status;
apr_time_exp_t t;
apr_size_t sz;
char buf[STR_SIZE];
if ( format==NULL ) return NULL;
memset(buf, '\0', STR_SIZE);
apr_time_exp_lt(&t, apr_time_now());
status = apr_strftime(buf, &sz, STR_SIZE, format, &t);
//assert (status == APR_SUCCESS );
return apr_pstrdup(p, buf);
}
int cu_getElementCount(apr_array_header_t* data){
return (data!=NULL) ? data->nelts : 0;
}
typedef struct html_char{
const char c;
const char* str;
}html_char;
static const html_char html_table[] = {
{'<',"<"},
{'>',">"},
{'\'',"'"}
};
static const char* cu_getHtmlString(const char c) {
int i;
for(i=0; i < sizeof(html_table)/sizeof(html_char); i++ ){
if(html_table[i].c==c) return html_table[i].str;
}
return NULL;
}
char* cu_nonHtmlToHtmlChar(apr_pool_t*p, char*src){
if(src==NULL) return NULL;
int size=8*strlen(src);
char*ret=apr_palloc(p, size+1);
char*q=ret;
const char* str = NULL;
while(*src!='\0'){
if(str = cu_getHtmlString(*src)){
strcpy(q, str);
q += strlen(str);
src++;
}else{
*q++=*src++;
}
}
*q='\0';
return ret;
}
char* cu_getFormattedUrl(apr_pool_t *p, char* cur, char* namespaceid) {
int x,queryStrState=0;
int curlen=0;
if(cur==NULL|namespaceid==NULL) return cur;
curlen=strlen(cur);
for(x=curlen-1;x>=0;x--){
if(cur[x]=='?'){
if(x==curlen-1){
queryStrState=2;
}else{
queryStrState=1;
}
}
}
if(queryStrState==0){
return apr_pstrcat(p,cur,"?ns=",namespaceid,NULL);
}else if(queryStrState==1){
return apr_pstrcat(p,cur,"&ns=",namespaceid,NULL);
}else if(queryStrState==2){
return apr_pstrcat(p,cur,"ns=",namespaceid,NULL);
}
}
char* cu_getTrimmedStr(apr_pool_t* p, char* str){
char* start=NULL,*end=NULL;
int len=0,size=0;
if(str==NULL){
return NULL;
}
start=str;
while(*start!='\0'&&(*start==' '||*start=='\t'||*start=='\n'||*start=='\r')){
start++;
}
len=strlen(str);
end=&(str[len-1]);
while(*end!='\0'&&(*end==' '||*end=='\t'||*end=='\n'||*end=='\r')){
end--;
}
size=end-start+1;
if(size<=0){return NULL;}
return apr_pstrndup(p,start,size);
}
apr_array_header_t* cu_parseStringArrayFromCsv(apr_pool_t* p, int arraySz, const char* delim, char* src){
char *srccpy=NULL, *prodStr=NULL, *p1=NULL;
char **val=NULL;
apr_array_header_t* arr=(apr_array_header_t*)apr_array_make(p,arraySz,sizeof(char*));
if(src==NULL){return arr;}
srccpy=apr_pstrdup(p,src);
if(arr==NULL){
return NULL;
}
prodStr=apr_strtok(srccpy,delim,&p1);
while(prodStr!=NULL){
val= (char**) apr_array_push(arr);
*val = (char*) apr_pstrdup(p,prodStr);
prodStr =strtok_r(NULL,delim,&p1);
}
return arr;
}
char* cu_serializeCsvFromStringArray(apr_pool_t* p, apr_array_header_t* arr){
char* ret=NULL;
int i=0;
if(arr!=NULL){
for(i=0;i<arr->nelts;i++){
if(i==0){
ret=apr_pstrdup(p,cu_getElement(arr,i));
}else{
ret=apr_pstrcat(p,ret,",",cu_getElement(arr,i),NULL);
}
}
}
return ret;
}
apr_table_t* cu_parseNvpTableFromCsv(apr_pool_t* p,const char* itemDelim,const char* nvpDelim, char* src){
apr_array_header_t* list=NULL;
apr_table_t* ret=NULL;
char* item=NULL, *name=NULL,*val=NULL;
int i=0;
if(src==NULL){return NULL;}
list=cu_parseStringArrayFromCsv(p,4,itemDelim,src);
if(list!=NULL&&list->nelts>0){
ret=apr_table_make(p,list->nelts);
for(i=0;i<list->nelts;i++){
item=cu_getElement(list,i);
name=item;
val=strstr(item,nvpDelim);
if(val!=NULL&&(*(val+1))!='\0'){
*val='\0';
val++;
apr_table_set(ret,name,val);
}
}
}
if(apr_is_empty_table(ret)){
return NULL;
}else{
return ret;
}
}
// RSA implementation
int padding = RSA_PKCS1_PADDING;
#define OAUTH_ERROR_STRING_MAX_LENGTH 256
static void comu_printHex(const char *title, const unsigned char *s, int len) {
int n;
printf("%s:", title);
for (n = 0; n < len; ++n) {
if ((n % 16) == 0) {
printf("\n%04x", n);
}
printf(" %02x", s[n]);
}
printf("\n");
}
static RSA* comu_createRSA(apr_pool_t* p, unsigned char* key, int public, char** error) {
BIO* mem = NULL;
RSA* rsa = NULL;
char errorBuffer[OAUTH_ERROR_STRING_MAX_LENGTH];
ERR_load_crypto_strings();
mem = BIO_new_mem_buf(key, -1);
if (mem == NULL) {
ERR_error_string(ERR_get_error(), errorBuffer);
if(error!=NULL) { *error = apr_pstrdup(p, errorBuffer); }
return NULL;
}
if(public) {
rsa = PEM_read_bio_RSA_PUBKEY(mem, NULL, NULL, NULL);
}else{
rsa = PEM_read_bio_RSAPrivateKey(mem, NULL, NULL, NULL);
}
BIO_free (mem);
if (rsa == NULL) {
ERR_error_string(ERR_get_error(), errorBuffer);
if(error!=NULL) { *error = apr_pstrdup(p, errorBuffer); }
}
return rsa;
}
static RSA* comu_createRSAFromFile(apr_pool_t* p, unsigned char* keyFile, int public, char** error) {
RSA* rsa = NULL;
char errorBuffer[OAUTH_ERROR_STRING_MAX_LENGTH];
FILE * fp = fopen(keyFile, "rb");
if (fp == NULL) {
if(error!=NULL) { *error = apr_pstrdup(p, "unable to open file"); }
return NULL;
}
ERR_load_crypto_strings();
rsa= RSA_new() ;
if(public) {
rsa = PEM_read_RSA_PUBKEY(fp, &rsa,NULL, NULL);
}else{
rsa = PEM_read_RSAPrivateKey(fp, &rsa,NULL, NULL);
}
fclose(fp);
if (rsa == NULL) {
ERR_error_string(ERR_get_error(), errorBuffer);
if(error!=NULL) { *error = apr_pstrdup(p, errorBuffer); }
}
return rsa;
}
char* comu_rsa256Sign(apr_pool_t*p, unsigned char * data,int dataLen, unsigned char * privateKey, char** error) {
int retEr;
unsigned char sign[256]={0};
unsigned int signLen = 0;
unsigned char encodeSign[1024];
RSA* rsa = comu_createRSA(p, privateKey, FALSE, error);
if(rsa==NULL) return NULL;
// sha256
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256(data, dataLen, hash);
// signing
retEr = RSA_sign(NID_sha256, hash, SHA256_DIGEST_LENGTH, sign, &signLen, rsa);
RSA_free(rsa);
if(retEr != 1) {
char errorBuffer[OAUTH_ERROR_STRING_MAX_LENGTH];
ERR_error_string(ERR_get_error(), errorBuffer);
if(error!=NULL) { *error = apr_pstrdup(p, errorBuffer); }
return NULL;
}
memset(encodeSign,'\0',1024);
base64Url_encode(encodeSign, sign, signLen);
return apr_pstrdup(p, encodeSign);
}
int comu_rsa256Verify(apr_pool_t*p, unsigned char * data,int dataLen, unsigned char * publicKey, char* encodedSign, char** error) {
int retEr;
unsigned char sign[1024];
RSA* rsa = comu_createRSA(p, publicKey, TRUE, error);
if(rsa==NULL) return FALSE;
// sha256
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256(data, dataLen, hash);
// verification
memset(sign,'\0',1024);
int signLen = base64Url_decode(sign, (char*)encodedSign, strlen(encodedSign));
retEr = RSA_verify(NID_sha256, hash, SHA256_DIGEST_LENGTH, sign, signLen, rsa);
RSA_free(rsa);
if(retEr != 1) {
char errorBuffer[OAUTH_ERROR_STRING_MAX_LENGTH];
ERR_error_string(ERR_get_error(), errorBuffer);
if(error!=NULL) { *error = apr_pstrdup(p, errorBuffer); }
}
return (retEr == 1) ? TRUE : FALSE;
}
static RSA* comu_createRSAByModulus(apr_pool_t* p, const char* modulus, const char* exponent, char** error) {
RSA* rsa = NULL;
char errorBuffer[OAUTH_ERROR_STRING_MAX_LENGTH];
unsigned char decoded[1024];
BIGNUM* bn = NULL;
int len;
if(modulus==NULL||exponent==NULL) return NULL;
memset(decoded,'\0',1024);
len = base64Url_decode(decoded, modulus, strlen(modulus));
if(len==0) return NULL;
BIGNUM *n = BN_bin2bn(decoded, len, NULL);
if (n == NULL) {
if(error!=NULL) { *error = apr_pstrdup(p, "Invalid encoding for modulus\n"); }
return NULL;
}
memset(decoded,'\0',1024);
len = base64Url_decode(decoded, exponent, strlen(exponent));
if(len==0) return NULL;
BIGNUM *e = BN_bin2bn(decoded, len, NULL);
if (e == NULL) {
if(error!=NULL) { *error = apr_pstrdup(p, "Invalid encoding for public exponent\n"); }
return NULL;
}
ERR_load_crypto_strings();
rsa = RSA_new();
rsa->e = e;
rsa->n = n;
if (rsa == NULL) {
ERR_error_string(ERR_get_error(), errorBuffer);
if(error!=NULL) { *error = apr_pstrdup(p, errorBuffer); }
}
return rsa;
}
int comu_rsaVerifyByModulus(apr_pool_t*p, const char* algorithm, unsigned char * data,int dataLen, const char* modulus, const char* exponent, char* encodedSign, char** error) {
int retEr;
RSA* rsa = comu_createRSAByModulus(p, modulus, exponent, error);
if(rsa==NULL) return FALSE;
// RSA sha256
if(algorithm!=NULL&&(strcasecmp(algorithm,"RS256")==0)) {
unsigned char sign[1024];
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256(data, dataLen, hash);
// verification
memset(sign,'\0',1024);
int signLen = base64Url_decode(sign, (char*)encodedSign, strlen(encodedSign));
retEr = RSA_verify(NID_sha256, hash, SHA256_DIGEST_LENGTH, sign, signLen, rsa);
if(retEr != 1) {
char errorBuffer[OAUTH_ERROR_STRING_MAX_LENGTH];
ERR_error_string(ERR_get_error(), errorBuffer);
if(error!=NULL) { *error = apr_pstrdup(p, errorBuffer); }
}
}else{
if(error!=NULL) { *error = apr_pstrdup(p, "algorithm not supported\n"); }
retEr = 0;
}
RSA_free(rsa);
return (retEr == 1) ? TRUE : FALSE;
}
char* comu_rsaEncrypt(apr_pool_t*p, unsigned char * data,int dataLen,unsigned char * publicKey, char** error) {
unsigned char encoded[4098];
unsigned char encrypted[4098]={};
RSA* rsa = comu_createRSA(p, publicKey, TRUE, error);
if(rsa==NULL) return NULL;
int retEr = RSA_public_encrypt(dataLen,data,encrypted,rsa,padding);
RSA_free(rsa);
if(retEr == -1) {
char errorBuffer[OAUTH_ERROR_STRING_MAX_LENGTH];
ERR_error_string(ERR_get_error(), errorBuffer);
if(error!=NULL) { *error = apr_pstrdup(p, errorBuffer); }
return NULL;
}
memset(encoded,'\0',4098);
base64Url_encode(encoded, encrypted, retEr);
return apr_pstrdup(p, encoded);
}
char* comu_rsaDecrypt(apr_pool_t*p, unsigned char * encrypted, unsigned char * privateKey, char** error){
unsigned char decrypted[4098]={};
unsigned char decoded[4098];
RSA* rsa = comu_createRSA(p, privateKey, FALSE, error);
if(rsa==NULL) return NULL;
int decodedLen = base64Url_decode(decoded, (char*)encrypted, strlen(encrypted));
int retEr = RSA_private_decrypt(decodedLen,decoded,decrypted,rsa,padding);
RSA_free(rsa);
if(retEr == -1) {
char errorBuffer[OAUTH_ERROR_STRING_MAX_LENGTH];
ERR_error_string(ERR_get_error(), errorBuffer);
if(error!=NULL) { *error = apr_pstrdup(p, errorBuffer); }
return NULL;
}
return apr_pstrdup(p, decrypted);
}
char* comu_rsa256SignFromFile(apr_pool_t*p, unsigned char * data,int dataLen, unsigned char * privateKeyFile, char** error) {
int retEr;
unsigned char sign[256]={0};
unsigned int signLen = 0;
unsigned char encodeSign[1024];
RSA* rsa = comu_createRSAFromFile(p, privateKeyFile, FALSE, error);
if(rsa==NULL) return NULL;
// sha256
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256(data, dataLen, hash);
// signing
retEr = RSA_sign(NID_sha256, hash, SHA256_DIGEST_LENGTH, sign, &signLen, rsa);
RSA_free(rsa);
if(retEr != 1) {
char errorBuffer[OAUTH_ERROR_STRING_MAX_LENGTH];
ERR_error_string(ERR_get_error(), errorBuffer);
if(error!=NULL) { *error = apr_pstrdup(p, errorBuffer); }
return NULL;
}
memset(encodeSign,'\0',1024);
base64Url_encode(encodeSign, sign, signLen);
return apr_pstrdup(p, encodeSign);
}
int comu_rsa256VerifyFromFile(apr_pool_t*p, unsigned char * data,int dataLen, unsigned char * publicKeyFile, char* encodedSign, char** error) {
int retEr;
unsigned char sign[1024];
RSA* rsa = comu_createRSAFromFile(p, publicKeyFile, TRUE, error);
if(rsa==NULL) return FALSE;
// sha256
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256(data, dataLen, hash);
// verification
memset(sign,'\0',1024);
int signLen = base64Url_decode(sign, (char*)encodedSign, strlen(encodedSign));
retEr = RSA_verify(NID_sha256, hash, SHA256_DIGEST_LENGTH, sign, signLen, rsa);
RSA_free(rsa);
if(retEr != 1) {
char errorBuffer[OAUTH_ERROR_STRING_MAX_LENGTH];
ERR_error_string(ERR_get_error(), errorBuffer);
if(error!=NULL) { *error = apr_pstrdup(p, errorBuffer); }
}
return (retEr == 1) ? TRUE : FALSE;
}
char* comu_rsaEncryptFromFile(apr_pool_t*p, unsigned char * data,int dataLen,unsigned char * publicKeyFile, char** error) {
unsigned char encoded[4098];
unsigned char encrypted[4098]={};
RSA* rsa = comu_createRSAFromFile(p, publicKeyFile, TRUE, error);
if(rsa==NULL) return NULL;
int retEr = RSA_public_encrypt(dataLen,data,encrypted,rsa,padding);
RSA_free(rsa);
if(retEr == -1) {
char errorBuffer[OAUTH_ERROR_STRING_MAX_LENGTH];
ERR_error_string(ERR_get_error(), errorBuffer);
if(error!=NULL) { *error = apr_pstrdup(p, errorBuffer); }
return NULL;
}
memset(encoded,'\0',4098);
base64Url_encode(encoded, encrypted, retEr);
return apr_pstrdup(p, encoded);
}
char* comu_rsaDecryptFromFile(apr_pool_t*p, unsigned char * encrypted, unsigned char * privateKeyFile, char** error){
unsigned char decrypted[4098]={};
unsigned char decoded[4098];
RSA* rsa = comu_createRSAFromFile(p, privateKeyFile, FALSE, error);
if(rsa==NULL) return NULL;
int decodedLen = base64Url_decode(decoded, (char*)encrypted, strlen(encrypted));
int retEr = RSA_private_decrypt(decodedLen,decoded,decrypted,rsa,padding);
RSA_free(rsa);
if(retEr == -1) {
char errorBuffer[OAUTH_ERROR_STRING_MAX_LENGTH];
ERR_error_string(ERR_get_error(), errorBuffer);
if(error!=NULL) { *error = apr_pstrdup(p, errorBuffer); }
return NULL;
}
return apr_pstrdup(p, decrypted);
}
char* comu_rsaPrintModulusFromFile(apr_pool_t*p, unsigned char * publicKeyFile, int isPublic) {
int retEr;
unsigned char encoded[1024];
unsigned char buf[1024];
int len;
char* error = NULL;
RSA* rsa = comu_createRSAFromFile(p, publicKeyFile, isPublic, &error);
if(rsa==NULL) {
RSA_free(rsa);
return (error!=NULL) ? error : apr_pstrdup(p, "unable to create rsa");
}
memset(buf,'\0',1024);
len = BN_bn2bin(rsa->n, buf);
if(len<0) {
RSA_free(rsa);
return apr_pstrdup(p, "unable to retrieve modulus");
}
memset(encoded,'\0',1024);
len = base64Url_encode(encoded, buf, len);
if(len<0) {
RSA_free(rsa);
return apr_pstrdup(p, "unable to encode modulus");
}
printf("modulus : %s\r\n", encoded);
memset(buf,'\0',1024);
len = BN_bn2bin(rsa->e, buf);
if(len<0) {
RSA_free(rsa);
return apr_pstrdup(p, "unable to retrieve modulus");
}
memset(encoded,'\0',1024);
len = base64Url_encode(encoded, buf, len);
if(len<0) {
RSA_free(rsa);
return apr_pstrdup(p, "unable to encode exponent");
}
printf("exponent : %s\r\n", encoded);
RSA_free(rsa);
return NULL;
}
// generate base64Url encoded signature ( used in JWT)
const char* comu_generateHS256Signature(apr_pool_t*p, char* payload, unsigned char* secretKey, char** error) {
unsigned char out[EVP_MAX_MD_SIZE];
unsigned int outlen;
char* tmp;
unsigned char encode[64];
unsigned char* result = NULL;
if(secretKey==NULL||payload==NULL) return NULL;
ERR_clear_error();
//Generate signature
result = HMAC(EVP_sha256(), secretKey, strlen(secretKey), (const unsigned char*)payload, strlen(payload), out, &outlen);
if(result==NULL) {
return NULL;
}
memset(encode,'\0',64);
base64Url_encode(encode, out, outlen);
return apr_pstrdup(p, encode);
}
// verifies base64Url encoded signature ( used in JWT)
int comu_verifyHS256Signature(apr_pool_t*p, char* payload, char* encodedSignature, unsigned char* secretKey, char** error) {
unsigned char out[EVP_MAX_MD_SIZE];
unsigned int outlen;
char* tmp;
unsigned char signature[64];
unsigned char* result = NULL;
if(secretKey==NULL||payload==NULL) return FALSE;
ERR_clear_error();
//Generate signature
result = HMAC(EVP_sha256(), secretKey, strlen(secretKey), (const unsigned char*)payload, strlen(payload), out, &outlen);
if(result==0) {
return FALSE;
}
memset(signature,'\0',64);
base64Url_decode(signature, (char*)encodedSignature, 64);
return (memcmp(out, signature, outlen)==0);
}
// generate HMAC-Sha1 signature
char* comu_generateHS1Signature(apr_pool_t* p, char* payload, unsigned char* secretKey, char** error) {
unsigned char out[EVP_MAX_MD_SIZE];
unsigned int outlen;
char* tmp;
unsigned char* result = NULL;
int i; char *signature = NULL;
if(secretKey==NULL||payload==NULL) return NULL;
ERR_clear_error();
//Generate signature
result = HMAC(EVP_sha1(), secretKey, strlen(secretKey), (const unsigned char*)payload, strlen(payload), out, &outlen);
if(result==NULL) {
return NULL;
}
for(i=0;i<outlen;i++){
tmp=apr_psprintf(p,"%02x", out[i]);
if(i!=0) signature=apr_pstrcat(p,signature,tmp,NULL);
else signature=apr_pstrdup(p,tmp);
}
return signature;
}
/*
* initialize the crypto context in the server configuration record; the passphrase is set already
*/
apr_byte_t comu_aesCryptoInit(apr_pool_t*p, oidc_cipher_cfg *cfg,
char** error) {
if (cfg->encrypt_ctx != NULL)
return TRUE;
unsigned char *key_data = (unsigned char *) cfg->crypto_passphrase;
int key_data_len = strlen(cfg->crypto_passphrase);
unsigned int s_salt[] = { 41892, 72930 };
unsigned char *salt = (unsigned char *) &s_salt;
int i, nrounds = 5;
unsigned char key[32], iv[32];
/*
* Gen key & IV for AES 256 CBC mode. A SHA1 digest is used to hash the supplied key material.
* nrounds is the number of times the we hash the material. More rounds are more secure but
* slower.
*/
i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), salt, key_data,
key_data_len, nrounds, key, iv);
if (i != 32) {
if(error!=NULL) *error=apr_psprintf(cfg->p, "key size must be 256 bits!");
return FALSE;
}
cfg->encrypt_ctx = apr_palloc(cfg->p, sizeof(EVP_CIPHER_CTX));
cfg->decrypt_ctx = apr_palloc(cfg->p, sizeof(EVP_CIPHER_CTX));
/* initialize the encoding context */
EVP_CIPHER_CTX_init(cfg->encrypt_ctx);
if (!EVP_EncryptInit_ex(cfg->encrypt_ctx, EVP_aes_256_cbc(), NULL, key,
iv)) {
if(error!=NULL) *error=apr_psprintf(p, "EVP_EncryptInit_ex on the encrypt context failed: %s",
ERR_error_string(ERR_get_error(), NULL));
return FALSE;
}
/* initialize the decoding context */
EVP_CIPHER_CTX_init(cfg->decrypt_ctx);
if (!EVP_DecryptInit_ex(cfg->decrypt_ctx, EVP_aes_256_cbc(), NULL, key,
iv)) {
if(error!=NULL) *error=apr_psprintf(p, "EVP_DecryptInit_ex on the decrypt context failed: %s",
ERR_error_string(ERR_get_error(), NULL));
return FALSE;
}
return TRUE;
}
/*
* AES encrypt plaintext
*/
unsigned char *comu_aesEncrypt(apr_pool_t*p, oidc_cipher_cfg *cfg,
unsigned char *plaintext, int *len, char** error) {
if (comu_aesCryptoInit(p, cfg, error) == FALSE)
return NULL;
/* max ciphertext len for a n bytes of plaintext is n + AES_BLOCK_SIZE -1 bytes */
int c_len = *len + AES_BLOCK_SIZE, f_len = 0;
unsigned char *ciphertext = apr_palloc(p, c_len);
/* allows reusing of 'e' for multiple encryption cycles */
if (!EVP_EncryptInit_ex(cfg->encrypt_ctx, NULL, NULL, NULL, NULL)) {
if(error!=NULL) *error=apr_psprintf(p, "EVP_EncryptInit_ex failed: %s",
ERR_error_string(ERR_get_error(), NULL));
return NULL;
}
/* update ciphertext, c_len is filled with the length of ciphertext generated, len is the size of plaintext in bytes */
if (!EVP_EncryptUpdate(cfg->encrypt_ctx, ciphertext, &c_len, plaintext,
*len)) {
if(error!=NULL) *error=apr_psprintf(p, "EVP_EncryptUpdate failed: %s",
ERR_error_string(ERR_get_error(), NULL));
return NULL;
}
/* update ciphertext with the final remaining bytes */
if (!EVP_EncryptFinal_ex(cfg->encrypt_ctx, ciphertext + c_len, &f_len)) {
if(error!=NULL) *error=apr_psprintf(p, "EVP_EncryptFinal_ex failed: %s",
ERR_error_string(ERR_get_error(), NULL));
return NULL;
}
*len = c_len + f_len;
return ciphertext;
}
/*
* AES decrypt ciphertext
*/
unsigned char *comu_aesDecrypt(apr_pool_t*p, oidc_cipher_cfg *cfg,
unsigned char *ciphertext, int *len, char** error) {
if (comu_aesCryptoInit(p, cfg, error) == FALSE)
return NULL;
/* because we have padding ON, we must allocate an extra cipher block size of memory */
int p_len = *len, f_len = 0;
unsigned char *plaintext = apr_palloc(p, p_len + AES_BLOCK_SIZE);
/* allows reusing of 'e' for multiple encryption cycles */
if (!EVP_DecryptInit_ex(cfg->decrypt_ctx, NULL, NULL, NULL, NULL)) {
if(error!=NULL) *error=apr_psprintf(p, "EVP_DecryptInit_ex failed: %s",
ERR_error_string(ERR_get_error(), NULL));
return NULL;
}
/* update plaintext, p_len is filled with the length of plaintext generated, len is the size of ciphertext in bytes */
if (!EVP_DecryptUpdate(cfg->decrypt_ctx, plaintext, &p_len, ciphertext,
*len)) {
if(error!=NULL) *error=apr_psprintf(p, "EVP_DecryptUpdate failed: %s",
ERR_error_string(ERR_get_error(), NULL));
return NULL;
}
/* update plaintext with the final remaining bytes */
if (!EVP_DecryptFinal_ex(cfg->decrypt_ctx, plaintext + p_len, &f_len)) {
if(error!=NULL) *error=apr_psprintf(p, "EVP_DecryptFinal_ex failed: %s",
ERR_error_string(ERR_get_error(), NULL));
return NULL;
}
*len = p_len + f_len;
return plaintext;
}
/*
* cleanup the crypto context in the server configuration record
*/
apr_byte_t comu_aesCryptoDestroy(oidc_cipher_cfg *cfg) {
if (cfg->encrypt_ctx == NULL)
return TRUE;
EVP_CIPHER_CTX_cleanup(cfg->encrypt_ctx);
EVP_CIPHER_CTX_cleanup(cfg->decrypt_ctx);
cfg->encrypt_ctx = NULL;
cfg->decrypt_ctx = NULL;
return TRUE;
}
char* cu_generateGuid(apr_pool_t* p){
apr_uuid_t uuid;
char buf[APR_UUID_FORMATTED_LENGTH + 1];
apr_uuid_get(&uuid);
apr_uuid_format(buf, &uuid);
return apr_pstrdup(p,buf);
}
/*
* base64url encode a string
*/
int cu_base64urlEncode(apr_pool_t*p, char **dst, const char *src,
int src_len, int remove_padding) {
if ((src == NULL) || (src_len <= 0)) {
// printf("not encoding anything; src=NULL and/or src_len<1");
return -1;
}
int enc_len = apr_base64_encode_len(src_len);
char *enc = apr_palloc(p, enc_len);
apr_base64_encode(enc, (const char *) src, src_len);
int i = 0;
while (enc[i] != '\0') {
if (enc[i] == '+')
enc[i] = '-';
if (enc[i] == '/')
enc[i] = '_';
if (enc[i] == '=')
enc[i] = ',';
i++;
}
if (remove_padding) {
/* remove /0 and padding */
enc_len--;
if (enc[enc_len - 1] == ',')
enc_len--;
if (enc[enc_len - 1] == ',')
enc_len--;
enc[enc_len] = '\0';
}
*dst = enc;
return enc_len;
}
/*
* base64url decode a string
*/
int cu_base64urlDecode(apr_pool_t*p, char **dst, const char *src) {
if (src == NULL) {
// printf("not decoding anything; src=NULL");
return -1;
}
char *dec = apr_pstrdup(p, src);
int i = 0;
while (dec[i] != '\0') {
if (dec[i] == '-')
dec[i] = '+';
if (dec[i] == '_')
dec[i] = '/';
if (dec[i] == ',')
dec[i] = '=';
i++;
}
switch (strlen(dec) % 4) {
case 0:
break;
case 2:
dec = apr_pstrcat(p, dec, "==", NULL);
break;
case 3:
dec = apr_pstrcat(p, dec, "=", NULL);
break;
default:
return 0;
}
int dlen = apr_base64_decode_len(dec);
*dst = apr_palloc(p, dlen);
return apr_base64_decode(*dst, dec);
}
/*
* encrypt and base64url encode a string
*/
int cu_encryptAndBase64urlEncode(apr_pool_t*p, oidc_cipher_cfg*cfg, char **dst,
const char *src, char** error) {
int crypted_len = strlen(src) + 1;
unsigned char *crypted = comu_aesEncrypt(p, cfg, (unsigned char *) src, &crypted_len, error);
if (crypted == NULL) {
// printf("cu_crypto_aes_encrypt failed");
return -1;
}
return cu_base64urlEncode(p, dst, (const char *) crypted, crypted_len, 1);
}
/*
* decrypt and base64url decode a string
*/
int cu_base64urlDecodeAndDecrypt(apr_pool_t*p, oidc_cipher_cfg*cfg, char **dst,
const char *src, char** error) {
char *decbuf = NULL;
int dec_len = cu_base64urlDecode(p, &decbuf, src);
if (dec_len <= 0) {
if(error!=NULL) *error = apr_pstrdup(p, "cu_base64urlDecode failed");
return -1;
}
*dst = (char *) comu_aesDecrypt(p, cfg, (unsigned char *) decbuf,
&dec_len, error);
if (*dst == NULL) {
if(error!=NULL) *error = apr_pstrdup(p, "comu_aesDecrypt failed");
return -1;
}
return dec_len;
}
|
tarachandverma/ngx-openidc
|
src/shm_core/shm_apr.h
|
<reponame>tarachandverma/ngx-openidc<gh_stars>10-100
#ifndef __TCREWRITE_SHM_APR__H_
#define __TCREWRITE_SHM_APR__H_
#include <sys/types.h>
#include <shm_data.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Abstract type for hash tables.
*/
typedef struct shapr_hash_t shapr_hash_t;
/**
* Abstract type for scanning hash tables.
*/
typedef struct shapr_hash_index_t shapr_hash_index_t;
array_header* shapr_array_make(shared_heap* sheap, int nelts, int elt_size);
void * shapr_array_push(shared_heap* sheap, array_header *arr);
array_header* shapr_parseStringArrayFromCsv(shared_heap* sheap, int arraySz, const char* delim, char* src);
array_header* shapr_parseLongArrayFromCsv(shared_heap* sheap, int arraySz, const char* delim, char* src);
array_header* shapr_copyStringArrayToSheap(shared_heap* sheap, array_header* sarray);
shapr_hash_t* shapr_hash_make(shared_heap* sheap);
void* shapr_hash_get(shapr_hash_t *ht,const void *key,apr_ssize_t klen);
void shapr_hash_set(shared_heap* sheap,shapr_hash_t *ht,const void *key,apr_ssize_t klen,const void *val);
shapr_hash_index_t * shapr_hash_first(apr_pool_t* pool, shapr_hash_t *ht);
shapr_hash_index_t* shapr_hash_next(shapr_hash_index_t *hi);
void shapr_hash_this(shapr_hash_index_t *hi,const void **key,apr_ssize_t *klen,void **val);
unsigned int shapr_hash_count(shapr_hash_t *ht);
#ifdef __cplusplus
}
#endif
#endif
|
tarachandverma/ngx-openidc
|
src/oidc-core/oidc_core_constants.h
|
#ifndef ACTION_MAPPINGS_CONSTANTS_H_
#define ACTION_MAPPINGS_CONSTANTS_H_
typedef enum {
header_add = 'a', /* add header (could mean multiple hdrs) */
header_set = 's', /* set (replace old value) */
header_append = 'm', /* append (merge into any old value) */
header_merge = 'g', /* merge (merge, but avoid duplicates) */
header_unset = 'u', /* unset header */
header_echo = 'e', /* echo headers from request to response */
header_edit = 'r' /* change value by regexp */
} header_actions;
typedef enum {
action_login = 'l', /* login action */
action_denial = 'd', /* denial action*/
action_authorize = 'a', /* authorize action */
action_callback = 'c' /* callback action */
} action_types;
// token encryption/decryption buffer size
#define OAUTH_CRYPTO_BUFSIZE 1024
#define OAUTH_BASE64_BUFSIZE 4096
// delimiters and wildcard
#define OAUTH_TOKEN_DELIM ":"
#define OAUTH_TOKEN_WILDCARD "*"
// versions
#define OAUTH_AUTHORIZED_CODE_VERSION1 "V1"
#define OAUTH_ACCESS_TOKEN_VERSION1 "V1"
#define OAUTH_REFRESH_TOKEN_VERSION1 "V1"
#define OAUTH_USER_TOKEN_VERSION1 "V1"
#define OAUTH_PAGE_TOKEN_VERSION1 "V1"
// response types
#define OAUTH_TYPE_UNKNOWN 0
#define OAUTH_TYPE_AUTHORIZE_CODE 1
#define OAUTH_TYPE_ACCESS_TOKEN 2
#define OAUTH_TYPE_AUTHENTICATE_CODE 3
#define OAUTH_TYPE_ID_TOKEN 4
#define OAUTH_TYPE_CODE_AND_ID_TOKEN 5
// subject types
#define OAUTH_SUBJECT_TYPE_UNKNOWN 0
#define OAUTH_SUBJECT_TYPE_UUID 1
#define OAUTH_SUBJECT_TYPE_APP 2
// response types
#define OAUTH_GRANT_TYPE_UNKNOWN 0
#define OAUTH_GRANT_TYPE_AUTHORIZE_CODE 1
#define OAUTH_GRANT_TYPE_PASSWORD 2
#define OAUTH_GRANT_TYPE_JWT 3
#define OAUTH_GRANT_TYPE_REFRESH_TOKEN 4
#define OAUTH_GRANT_TYPE_CLIENT_CREDENTIALS 5
#define OAUTH_GRANT_TYPE_PWD_WITH_CLIENT_CREDENTIALS 6
#define OAUTH_GRANT_TYPE_UUID_WITH_CLIENT_CREDENTIALS 7
// versions
#define OAUTH_TCS_RESPONSE_SUCCESS 0
#define OAUTH_TCS_RESPONSE_FAILURE 1
#define OAUTH_LIS_RESPONSE_SUCCESS 0
#define OAUTH_LIS_RESPONSE_FAILURE 1
#define OAUTH_LIS_RESPONSE_UNAVILABLE 2
#define OAUTH_AUTHID_SUCCESS 0
#define OAUTH_AUTHID_FAILURE 1
// OIDC headers
#define OIDC_STATUS_HEADER "VALIDATE-STATUS"
#define OIDC_DESC_HEADER "VALIDATE-DESCRIPTION"
#define OIDC_ISSUER_HEADER "ISSUER"
#define OIDC_AUDIENCE_HEADER "AUDIENCE"
#define OIDC_SUBJECT_HEADER "SUBJECT"
#define OIDC_ROLES_HEADER "ROLES"
#define OIDC_RP_SESSIONID "X-RP-SESSION"
#endif /*ACTION_MAPPINGS_CONSTANTS_H_*/
|
tarachandverma/ngx-openidc
|
src/template-core/template_handler_url.h
|
<reponame>tarachandverma/ngx-openidc<filename>src/template-core/template_handler_url.h
#ifndef TOKEN_TEMPLATE_URL_H_
#define TOKEN_TEMPLATE_URL_H_
#include "apache_typedefs.h"
char* temphand_url_encodeToken(pool* p,void* config,char* src);
char* temphand_url_decodeToken(pool* p,void* config,char* src);
// base64 encode decode
char* temphand_base64_encodeToken(pool* p,void* config,char* src);
char* temphand_base64_decodeToken(pool* p,void* config,char* src);
#endif /*TOKEN_TEMPLATE_ENCRYPTION_H_*/
|
tarachandverma/ngx-openidc
|
src/common-utils/cookie.c
|
#ifndef _COOKIE_C_
#define _COOKIE_C_
#include "cookie.h"
#include "url_utils.h"
//Creater methods
Cookie* cookie_newObj(pool*p){
Cookie* ret=(Cookie*)apr_pcalloc(p,sizeof(Cookie));
ret->name=NULL;
ret->nameLen=0;
ret->age=-1;
ret->httpOnly=FALSE;
ret->secure=FALSE;
return ret;
}
Cookie* cookie_createCookieByName(pool*p, char*name) {
Cookie* cookie = NULL;
if(name){
cookie = cookie_newObj(p);
cookie->name= apr_pstrdup(p, name);
cookie->nameLen=strlen(cookie->name);
}
return cookie;
}
Cookie* cookie_cookieDup(pool*p, Cookie*src){
Cookie* ret=NULL;
if(src){
ret = cookie_newObj(p);
ret->name=apr_pstrdup(p, src->name);
ret->nameLen=src->nameLen;
ret->age=src->age;
ret->httpOnly=src->httpOnly;
ret->secure=src->secure;
}
return ret;
}
//Accessor Methods
void cookie_setCookieName(pool*p, Cookie*cookie, char*name) {
if(cookie && name){
cookie->name= apr_pstrdup(p, name);
cookie->nameLen=strlen(cookie->name);
}
}
char* cookie_getCookieName(Cookie*cookie) {
return cookie->name;
}
void cookie_setCookieLifeTime(Cookie* cookie, int lifeTime){
cookie->age = lifeTime;
}
int cookie_getCookieLifeTime(Cookie* cookie){
return cookie->age;
}
void cookie_setCookieHttpOnlyflag(Cookie* cookie, unsigned int httpOnly){
cookie->httpOnly = httpOnly;
}
void cookie_setCookieSecureHttpOnlyflag(Cookie* cookie, int secure){
cookie->secure = secure;
}
unsigned int cookie_getCookieHttpOnlyflag(Cookie* cookie){
return cookie->httpOnly;
}
//Cookie sheap methods
Cookie* cookie_newShmObj(shared_heap*sheap){
Cookie* ret=(Cookie*)shdata_shpalloc(sheap,sizeof(Cookie));
ret->name=NULL;
ret->nameLen=0;
ret->age=-1;
ret->httpOnly=FALSE;
ret->secure=FALSE;
return ret;
}
Cookie* cookie_cookieShmDup(shared_heap*sheap, Cookie*src){
Cookie* ret=NULL;
if(src) {
ret = cookie_newShmObj(sheap);
ret->name=shdata_32BitString_copy(sheap,src->name);
ret->nameLen=src->nameLen;
ret->age=src->age;
ret->httpOnly=src->httpOnly;
ret->secure=src->secure;
}
return ret;
}
//Cookie utility methods
char* cookie_cookieTemplateByName(pool* p,char* icookiename, char *ivalue,
char *idomain, long maxAge, unsigned int httpOnly) {
char* ret=NULL;
char* value=SAFESTRBLANK(ivalue),*domain=SAFESTRBLANK(idomain),*cookiename=SAFESTRBLANK(icookiename);
int sz=0,ulen=0;
char* encoded_url=NULL;
sz=strlen(domain)+strlen(cookiename)+64;
ulen=strlen(value)*3+1;
encoded_url=apr_pcalloc(p,ulen);
url_encode(value, encoded_url, ulen);
sz+=strlen(encoded_url);
ret=apr_pcalloc(p,sz);
if (maxAge < 0) {
sprintf(ret,
"%s=%s; domain=%s; path=/",
cookiename == NULL ? "" : cookiename,
value == NULL ? "" : encoded_url,
domain == NULL ? "" : domain);
} else {
sprintf(ret,
"%s=%s; domain=%s; path=/; Expires=%s; max-age=%d%s",
cookiename == NULL ? "" : cookiename,
value == NULL ? "" : encoded_url,
domain == NULL ? "" : domain,
cookie_getGMTDate(p,maxAge),
maxAge,
httpOnly == TRUE ? "; httpOnly" : "");
}
return ret;
}
//Assuming the cookie age in and needs to convert in seconds.
char* cookie_cookieTemplate(pool* p, Cookie* cookie, char *ivalue, char *idomain) {
char* ret=NULL;
char* value=SAFESTRBLANK(ivalue),*domain=SAFESTRBLANK(idomain);
int sz=0,ulen=0;
char* encoded_url=NULL;
long maxAge=0;
if(cookie==NULL) return NULL;
maxAge = cookie_convertDaysToSeconds(cookie->age);
sz=strlen(domain)+strlen(cookie->name)+96;
ulen=strlen(value)*3+1;
encoded_url=apr_pcalloc(p,ulen);
url_encode(value, encoded_url, ulen);
sz+=strlen(encoded_url);
ret=apr_pcalloc(p,sz);
if (maxAge < 0) {
if(cookie->secure == TRUE) {
sprintf(ret, "%s=%s; domain=%s; path=/%s",
cookie->name == NULL ? "" : cookie->name,
value == NULL ? "" : encoded_url,
domain == NULL ? "" : domain, "; httpOnly; Secure");
} else {
sprintf(ret, "%s=%s; domain=%s; path=/%s",
cookie->name == NULL ? "" : cookie->name,
value == NULL ? "" : encoded_url,
domain == NULL ? "" : domain,
cookie->httpOnly == TRUE ? "; httpOnly" : "");
}
} else {
if(cookie->secure == TRUE) {
sprintf(ret, "%s=%s; domain=%s; path=/; Expires=%s; max-age=%d%s",
cookie->name == NULL ? "" : cookie->name,
value == NULL ? "" : encoded_url,
domain == NULL ? "" : domain,
cookie_getGMTDate(p,maxAge),
maxAge, "; httpOnly; Secure");
} else {
sprintf(ret, "%s=%s; domain=%s; path=/; Expires=%s; max-age=%d%s",
cookie->name == NULL ? "" : cookie->name,
value == NULL ? "" : encoded_url,
domain == NULL ? "" : domain,
cookie_getGMTDate(p,maxAge),
maxAge,
cookie->httpOnly == TRUE ? "; httpOnly" : "");
}
}
return ret;
}
char* cookie_cookieUntemplate(pool* p,char* name){
char* ret=NULL;
int rlen=0;
if(name==NULL)return NULL;
rlen=strlen(name)+1;
ret=apr_pcalloc(p,rlen);
url_decode(name,ret,rlen);
return ret;
}
int cookie_convertDaysToSeconds(int days){
if(days<0) return days;
return days*86400;
}
char* cookie_getGMTDate(pool* p, int secondsInFuture){
char buf[64];
apr_time_t date=apr_time_now();
date=date+(APR_USEC_PER_SEC*secondsInFuture);
memset(buf,'\0',64);
apr_ctime(buf,date);
return apr_pstrdup(p,buf);
}
char* cookie_parseCookie(pool* p, char* name, char* cookies){
char *cursor, *strCookie, *cookiereturn,*cend, *cnamestart;
int len,x,found=0;
int cookieLen=0;
if(cookies==NULL||name==NULL) return NULL;
cend=cnamestart=cookiereturn=strCookie=NULL;
cookieLen=strlen(name);
strCookie=cookies;
while(1){
cnamestart=strstr(strCookie, name);
//printf("\n\nCycle:%s\n\n\n",cnamestart);
if(cnamestart){
cursor=cnamestart+cookieLen;
//printf("cursorFOUND:%s\n",cursor);
if(*cursor&&(*cursor=='='||*cursor==' ')){
while(*cursor&&*cursor!='='){
cursor++;
}
cursor++;
//printf("\n\nCURSOR:%s\n\n",cursor);
cend=strchr(cursor,';');
if(cend){
//printf("cend:%s\n",cend);
}else{
cend=strchr(cursor,'\0');
}
len=cend-cursor;
cookiereturn=(char*)apr_palloc(p,len+1);
strncpy(cookiereturn,cursor,len);
cookiereturn[len]='\0';
//printf("COOKIERETURN: [%s]\n",cookiereturn);
break;
}else{
strCookie=cursor;
//printf("cursor:%s\n",cursor);
}
}else{
break;
}
}
return cookiereturn;
}
char *cookie_getCookie(pool* p, apr_table_t* headers_in, Cookie* cookie)
{
char *cursor, *strCookie, *cookiereturn,*cend, *cnamestart;
int len,x,found=0;
cend=cnamestart=cookiereturn=strCookie=NULL;
if (cookie==NULL||cookie->name == NULL||cookie->nameLen<0)
return NULL;
if ((strCookie = (char*)apr_table_get(headers_in, "Cookie")) != NULL)
{
while(1){
cnamestart=strstr(strCookie, cookie->name);
//printf("\n\nCycle:%s\n\n\n",cnamestart);
if(cnamestart){
cursor=cnamestart+cookie->nameLen;
//printf("cursorFOUND:%s\n",cursor);
if(*cursor&&(*cursor=='='||*cursor==' ')){
while(*cursor&&*cursor!='='){
cursor++;
}
cursor++;
//printf("\n\nCURSOR:%s\n\n",cursor);
cend=strchr(cursor,';');
if(cend){
//printf("cend:%s\n",cend);
}else{
cend=strchr(cursor,'\0');
}
len=cend-cursor;
cookiereturn=(char*)apr_palloc(p,len+1);
strncpy(cookiereturn,cursor,len);
cookiereturn[len]='\0';
//printf("COOKIERETURN: [%s]\n",cookiereturn);
break;
}else{
strCookie=cursor;
//printf("cursor:%s\n",cursor);
}
}else{
break;
}
}
}
return cookiereturn;
}
char *cookie_getCookieByName(pool* p, apr_table_t* headers_in, char *cookie_name, int cookie_name_len)
{
char *cursor, *strCookie, *cookiereturn,*cend, *cnamestart;
int len,x,found=0;
cend=cnamestart=cookiereturn=strCookie=NULL;
if (cookie_name == NULL||cookie_name_len<0)
return NULL;
if ((strCookie = (char*)apr_table_get(headers_in, "Cookie")) != NULL)
{
while(1){
cnamestart=strstr(strCookie, cookie_name);
//printf("\n\nCycle:%s\n\n\n",cnamestart);
if(cnamestart){
cursor=cnamestart+cookie_name_len;
//printf("cursorFOUND:%s\n",cursor);
if(*cursor&&(*cursor=='='||*cursor==' ')){
while(*cursor&&*cursor!='='){
cursor++;
}
cursor++;
//printf("\n\nCURSOR:%s\n\n",cursor);
cend=strchr(cursor,';');
if(cend){
//printf("cend:%s\n",cend);
}else{
cend=strchr(cursor,'\0');
}
len=cend-cursor;
cookiereturn=(char*)apr_palloc(p,len+1);
strncpy(cookiereturn,cursor,len);
cookiereturn[len]='\0';
//printf("COOKIERETURN: [%s]\n",cookiereturn);
break;
}else{
strCookie=cursor;
//printf("cursor:%s\n",cursor);
}
}else{
break;
}
}
}
return cookiereturn;
}
void cookie_deleteCookie(pool* p, apr_table_t* err_headers_out, Cookie* cookie, char* domain){
char delstr[768];
if(cookie!=NULL&&cookie->name!=NULL){
sprintf(delstr,"%s=remove;domain=%s;path=/;Expires=Thu, 01-Jan-1970 00:00:10 GMT;max-age=0",
cookie->name== NULL ? "" : cookie->name,
domain == NULL ? "" : domain
);
apr_table_add(err_headers_out,"Set-Cookie",delstr);
}
}
void cookie_deleteCookieByName(pool* p, apr_table_t* err_headers_out, char* cookie_name, char* domain){
char delstr[768];
if(cookie_name!=NULL){
sprintf(delstr,"%s=remove;domain=%s;path=/;Expires=Thu, 01-Jan-1970 00:00:10 GMT;max-age=0",
cookie_name== NULL ? "" : cookie_name,
domain == NULL ? "" : domain
);
apr_table_add(err_headers_out,"Set-Cookie",delstr);
}
}
#endif //_COOKIE_C_
|
tarachandverma/ngx-openidc
|
src/xml-core/xml_core.h
|
<reponame>tarachandverma/ngx-openidc
/*
* Created by <NAME> on 01/04/14.
*
*/
#ifndef __TCREWRITE_XML_CORE__H_
#define __TCREWRITE_XML_CORE__H_
#ifdef __cplusplus
extern "C" {
#endif
#include "apache_typedefs.h"
typedef struct llnode {
void* data;
struct llnode *next;
struct llnode *prev;
}llnode;
typedef struct DLinkedList{
llnode *head;
llnode *tail;
int elts;
}DLinkedList;
typedef struct xc_rec{
DLinkedList* xpath_nodes;
DLinkedList* xpath_handlers;
pool* p;
}XmlCore;
typedef int (*xfunc) (pool*,char*,int,const char **,void*);
typedef int (*bfunc) (pool*,char*,int,const char *,void*);
typedef int (*efunc) (pool*,char*,int,void*);
typedef struct x_rec{
char* path;
DLinkedList* xpath_nodes;
void* userdata;
xfunc start_function;
bfunc body_function;
efunc end_function;
char* body;
}x_rec;
typedef struct node_info_rec{
char* name;
}node_info;
DLinkedList* xc_getLinkedList(pool *p);
int xc_AddToTail(pool* p, DLinkedList* xCore, void* elt);
void* xc_peekTail(pool* p, DLinkedList* ll);
XmlCore* xc_getXmlCore(pool *p);
int xc_addXPathHandler(XmlCore* xCore, char* path, int options, const xfunc sfunction, const bfunc bfunction, const efunc efunction, void* udata);
int xc_beginParsing(XmlCore* xCore,const char* file);
int xc_parseFromStringSource(XmlCore* xCore,const char* source);
char* xc_beginParsingTextResponse(XmlCore* xCore, char* file);
char* xc_parseFromStringSourceTextResponse(XmlCore* xCore, char* source);
#ifdef __cplusplus
}
#endif
#endif //__TCREWRITE_XML_CORE__H_
|
tarachandverma/ngx-openidc
|
src/config-core/config_messaging_parsing.c
|
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include "xml_core.h"
#include "config_messaging_parsing.h"
#include "common_utils.h"
#include "oidc_version.h"
typedef struct cfgm_parse_bundle{
char* tmp;
cfgm_wire_message* msg;
}cfgm_parse_bundle;
/**
* Begin Wire Message Code
*/
static cfgm_wire_header* cfgm_newWireHeaderBlank(pool* p){
cfgm_wire_header* ret=(cfgm_wire_header*)apr_palloc(p,sizeof(cfgm_wire_header));
ret->nodeName=NULL;
ret->componentId=NULL;
ret->version=NULL;
return ret;
}
cfgm_wire_header* cfgm_newWireHeader(pool* p){
int i;
char buf[128];
//for second ip get test
cfgm_wire_header* ret=cfgm_newWireHeaderBlank(p);
if(gethostname(buf,128)==0){
ret->nodeName=apr_pstrdup(p,buf);
}
ret->componentId=apr_pstrdup(p,MODULE_COMPONENT_ID);
ret->version=apr_pstrdup(p,MODULE_VERSION_ID);
return ret;
}
cfgm_wire_message* cfgm_newWireMessage(pool* p,cfgm_wire_header* header){
char buf[64];
cfgm_wire_message* ret=(cfgm_wire_message*)apr_palloc(p,sizeof(cfgm_wire_message));
ret->type=NULL;
ret->header=header;
ret->params=apr_hash_make(p);
sprintf(buf,"%d",getpid());
apr_hash_set(ret->params,"pid",APR_HASH_KEY_STRING,apr_pstrdup(p,buf));
return ret;
}
cfgm_wire_message* cfgm_newWireMessageType(pool* p,const char* type,cfgm_wire_header* header){
cfgm_wire_message* ret=cfgm_newWireMessage(p,header);
ret->type=apr_pstrdup(p,type);
return ret;
}
char* cfgm_serializeMessage(apr_pool_t* p, cfgm_wire_message* msg){
apr_hash_index_t *hi;
char* name=NULL,*value=NULL;
char* ret=NULL;
apr_pool_t* subp=NULL;
if(msg==NULL) return NULL;
if(apr_pool_create(&subp,p)!=APR_SUCCESS){
return NULL;
}
ret=apr_pstrcat(subp,"<message type=\"",msg->type,"\"",NULL);
if(msg->header!=NULL){
if(msg->header->nodeName!=NULL){
ret=apr_pstrcat(subp,ret," node=\"",msg->header->nodeName,"\"",NULL);
}
if(msg->header->componentId!=NULL){
ret=apr_pstrcat(subp,ret," com=\"",msg->header->componentId,"\"",NULL);
}
if(msg->header->version!=NULL){
ret=apr_pstrcat(subp,ret," ver=\"",msg->header->version,"\"",NULL);
}
}
ret=apr_pstrcat(subp,ret,">\n",NULL);
for (hi = apr_hash_first(subp, msg->params); hi; hi = apr_hash_next(hi)) {
apr_hash_this(hi,(const void**)&name, NULL, (void**)&value);
ret=apr_pstrcat(subp,ret,"\t<param name=\"",name,"\"><![CDATA[",value,"]]></param>\n",NULL);
}
//make last concat to non temporary memory pool
ret=apr_pstrcat(p,ret,"</message>",NULL);
//destroy temporary memeory pool
apr_pool_destroy(subp);
return ret;
}
|
tarachandverma/ngx-openidc
|
src/shm_core/shm_dup.h
|
#ifndef __TCREWRITE_SHM_DUP__H_
#define __TCREWRITE_SHM_DUP__H_
#include <sys/types.h>
#include "apache_typedefs.h"
#ifdef __cplusplus
extern "C" {
#endif
int shdup_32BitString_size(char* str);
char* shdup_32BitString_copy(char** icharbuf, char* str);
int shdup_arrayheader_size(array_header* arr);
#ifdef __cplusplus
}
#endif
#endif
|
tarachandverma/ngx-openidc
|
src/config-core/config_messaging_parsing.h
|
<filename>src/config-core/config_messaging_parsing.h
#ifndef __TCREWRITE_CONFIG_MESSAGING_PARSING__H_
#define __TCREWRITE_CONFIG_MESSAGING_PARSING__H_
#include <sys/types.h>
#include "apache_typedefs.h"
typedef struct cfgm_wire_header{
char* nodeName;
char* componentId;
char* version;
}cfgm_wire_header;
typedef struct cfgm_wire_message{
char* type;
cfgm_wire_header* header;
apr_hash_t* params;
}cfgm_wire_message;
cfgm_wire_header* cfgm_newWireHeader(pool* p);
cfgm_wire_message* cfgm_newWireMessage(pool* p,cfgm_wire_header* header);
cfgm_wire_message* cfgm_newWireMessageType(pool* p,const char* type,cfgm_wire_header* header);
char* cfgm_serializeMessage(apr_pool_t* p, cfgm_wire_message* msg);
#endif
|
tarachandverma/ngx-openidc
|
src/config-core/config_bindings_shm.c
|
#include <shm_data.h>
#include <shm_apr.h>
#include <common_utils.h>
#include <http-utils/http_client.h>
#include <config-core/config_bindings.h>
#include <config-core/config_bindings_shm.h>
#define SHEAP_ITEM_ID_CONFIG_CORE_GLOBALS "CONFIG_CORE_GLOBALS"
shapr_hash_t* cbs_copyParamsOnSheap(pool*p, shared_heap*sheap, apr_hash_t*params){
apr_hash_index_t* hi=NULL;
char* val, *key;
char* shmVal, *shmKey;
shapr_hash_t* ret= shapr_hash_make(sheap);
for (hi = apr_hash_first(p, params); hi; hi = apr_hash_next(hi)) {
apr_hash_this(hi,(const void**)(&key),NULL,(void**)(&val));
shmKey=shdata_32BitString_copy(sheap,key);
shmVal=shdata_32BitString_copy(sheap,val);
shapr_hash_set(sheap,ret,shmKey,APR_HASH_KEY_STRING,shmVal);
}
return ret;
}
cbs_service_descriptor* cbs_copyServiceDescripterOnSheap(pool*p, shared_heap* sheap,cfg_service_descriptor* sd){
if(sd==NULL) return NULL;
cbs_service_descriptor* ret=(cbs_service_descriptor*)shdata_shpcalloc(sheap,sizeof(cbs_service_descriptor));
ret->id=shdata_32BitString_copy(sheap,sd->id);
ret->name=shdata_32BitString_copy(sheap,sd->name);
ret->uri=shdata_32BitString_copy(sheap,sd->uri);
ret->userColonPass=shdata_32BitString_copy(sheap,sd->userColonPass);
ret->timeoutSeconds=sd->timeoutSeconds;
ret->params=cbs_copyParamsOnSheap(p, sheap,sd->params);
return ret;
}
cbs_globals* cbs_copyGlobalsOnSheap(pool*p, shared_heap* sheap, cfg_globals* globals, int isRefresh){
shdata_OpenItemTag(sheap,SHEAP_ITEM_ID_CONFIG_CORE_GLOBALS);
cbs_globals* ret=(cbs_globals*)shdata_shpcalloc(sheap,sizeof(cbs_globals));
ret->homeDir=shdata_32BitString_copy(sheap,globals->homeDir);
ret->logsDir=shdata_32BitString_copy(sheap,globals->logsDir);
ret->resourceService=cbs_copyServiceDescripterOnSheap(p,sheap,globals->resourceService);
ret->isRefresh = isRefresh;
shdata_CloseItemTagWithInfo(sheap,"Config Core Globals");
return ret;
}
char* cbs_getRemoteResourcePath(pool* p, cbs_globals* globals,char* resource,char**details){
char* ret=NULL,*reqUri;
cbs_service_descriptor* rs=NULL;
int responseCode=-1;
pool* tp;
apr_finfo_t finfo;
apr_status_t rv;
char* localPath=NULL;
if(resource==NULL) return NULL;
if(globals->resourceService!=NULL){
rs=globals->resourceService;
//setup filepool
if(apr_pool_create(&tp,p)!=APR_SUCCESS){
if(details!=NULL){
*details=apr_pstrdup(p,"Failure to create subpool");
}
return NULL;
}
//try to load from local name space.
reqUri=apr_pstrcat(p,rs->uri,"/",resource,NULL);
ret=cb_writeRemoteResourceToDisk(p,globals->homeDir,reqUri,resource,rs->timeoutSeconds,rs->userColonPass,tp,details,&responseCode);
apr_pool_destroy(tp);
}
return ret;
}
char* cbs_getLocalResourcePath(pool* p, cbs_globals* globals,char* resource,char**details){
if(resource==NULL){return NULL;}
return apr_pstrcat(p,globals->homeDir,"/",resource,NULL);
}
|
tarachandverma/ngx-openidc
|
src/oidc-globals/oidc_globals.c
|
<reponame>tarachandverma/ngx-openidc<filename>src/oidc-globals/oidc_globals.c
/*
* Created by <NAME> on 04/27/15.
*
*/
#include <oidc_globals.h>
#include <common_utils.h>
static int DJRE_EnableUnnamedSHM = FALSE;
static int DJRE_ConfigCheckPhaseDelaySec = 0;
void djrglobals_setEnableUnnamedSHM(const char * arg) {
DJRE_EnableUnnamedSHM = STRTOBOOL(arg);
}
int djrglobals_isUnnamedSHMEnabled() {
return DJRE_EnableUnnamedSHM;
}
void djrglobals_setConfigCheckPhaseDelaySec(const char * arg) {
if(arg != NULL) {
DJRE_ConfigCheckPhaseDelaySec = atoi(arg);
}
}
int djrglobals_getConfigCheckPhaseDelaySec() {
return DJRE_ConfigCheckPhaseDelaySec;
}
|
tarachandverma/ngx-openidc
|
src/xml-core/xml_core.c
|
<reponame>tarachandverma/ngx-openidc
/*
* Created by <NAME> on 01/04/14.
*
*/
#include <xml_core.h>
#include <expat.h>
#include <stdio.h>
#include <string.h>
#include <token_utils.h>
#include "apr_strings.h"
#define BUFFSIZE 8192
#ifdef XML_LARGE_SIZE
#if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400
#define XML_FMT_INT_MOD "I64"
#else
#define XML_FMT_INT_MOD "ll"
#endif
#else
#define XML_FMT_INT_MOD "l"
#endif
#define CONST_FAILURE_FILE_OPEN -1
#define CONST_FAILURE_CREATE -2
#define CONST_FAILURE_READ -4
#define CONST_FAILURE_XMLERROR -8
#define CONST_SUCCESS 1
DLinkedList* xc_getLinkedList(pool *p){
DLinkedList* dlist;
dlist=apr_palloc(p,sizeof(DLinkedList));
dlist->head=NULL;
dlist->tail=NULL;
dlist->elts=0;
return dlist;
}
int xc_AddToTail(pool* p, DLinkedList* ll, void* elt){
llnode* node;
node=apr_palloc(p,sizeof(llnode));
node->data=elt;
node->prev=NULL;
node->next=NULL;
if(ll->head==NULL||ll->tail==NULL){
ll->head=ll->tail=node;
}else{
ll->tail->next=node;
node->prev=ll->tail;
ll->tail=ll->tail->next;
}
ll->elts++;
return ll->elts;
}
void* xc_peekTail(pool* p, DLinkedList* ll){
if(ll->tail!=NULL){
return ll->tail->data;
}
return NULL;
}
void* xc_RemoveFromTail(pool* p, DLinkedList* ll){
void* elt=NULL;
if(ll->head==ll->tail){
elt=ll->head->data;
ll->head=ll->tail=NULL;
}else if(ll->head!=NULL&&ll->tail!=NULL){
elt=ll->tail->data;
ll->tail=ll->tail->prev;
ll->tail->next=NULL;
}
return elt;
}
static void xc_printxrec_list(pool* p, DLinkedList* ll){
llnode* node;
x_rec* xrec;
node=ll->head;
while(node!=NULL){
xrec=(x_rec*)(node->data);
printf("xrec: %s\n",xrec->path);
node=node->next;
}
}
static void xc_printNodeInfo_list(pool* p, DLinkedList* ll){
llnode* node;
node_info *ninfo;
node=ll->head;
while(node!=NULL){
ninfo=(node_info*)(node->data);
printf("node: %s\n",ninfo->name);
node=node->next;
}
}
static DLinkedList* xc_parseXpathNodes(pool* p, char* str){
node_info *ninfo;
DLinkedList* ll;
Tokener* tk;
char* tok;
ll=xc_getLinkedList(p);
tk=tu_getTokenizer(p,str,"/");
//printf("str:%s\n",str);
while((tok=tu_next_token(tk))!=NULL){
ninfo=apr_palloc(p,sizeof(node_info));
ninfo->name=tok;
//printf("tok:%s\n",ninfo->name);
xc_AddToTail(p,ll,ninfo);
}
return ll;
}
XmlCore* xc_getXmlCore(pool *p){
XmlCore *c=apr_palloc(p,sizeof(XmlCore));
c->p=p;
c->xpath_nodes=xc_getLinkedList(p);
c->xpath_handlers=xc_getLinkedList(p);
return c;
}
int xc_addXPathHandler(XmlCore* xCore, char* path, int options, const xfunc sfunction, const bfunc bfunction, const efunc efunction, void* udata){
int ret;
x_rec* xrec;
xrec=apr_palloc(xCore->p,sizeof(x_rec));
//printf("Add Handler:%s\n",path);
xrec->path=apr_pstrdup(xCore->p,path);
xrec->userdata=udata;
xrec->start_function=sfunction;
xrec->body_function=bfunction;
xrec->end_function=efunction;
xrec->xpath_nodes=xc_parseXpathNodes(xCore->p,path);
xrec->body=NULL;
ret=xc_AddToTail(xCore->p,xCore->xpath_handlers,xrec);
//xc_printxrec_list(xCore->p,xCore->xpath_handlers);
return ret;
}
static int xc_matchNodeDLists(DLinkedList* l1, DLinkedList* l2){
llnode *node1, *node2;
node_info* ninfo1, *ninfo2;
node1=l1->head;
node2=l2->head;
while(node1!=NULL&&node2!=NULL){
ninfo1=(node_info*)node1->data;
ninfo2=(node_info*)node2->data;
//printf("1:%s, 2:%s\r\n",ninfo1->name,ninfo2->name);
if(strcmp(ninfo1->name,"*")!=0&&strcmp(ninfo2->name,ninfo1->name)!=0){ //allows for wildcard all
//printf("no match: %s,%s\n",ninfo2->name,ninfo1->name);
return 0;
}
node1=node1->next;
node2=node2->next;
if((node1==NULL && node2==NULL)){
//printf("MATC\r\n");
return 1;
}
}
//printf("no match3: %s,%s\n",ninfo2->name,ninfo1->name);
return 0;
}
static void XMLCALL elementStart(void *data, const char *el, const char **attr){
XmlCore* xCore=(XmlCore*)data;
node_info* ninfo;
//start handler data
llnode* node;
x_rec* xrec;
//begin process element
ninfo=(node_info*)apr_palloc(xCore->p,sizeof(node_info));
ninfo->name=apr_pstrdup(xCore->p,el);
//printf("add node:%s\n",el);
xc_AddToTail(xCore->p,xCore->xpath_nodes,ninfo);
//xc_printNodeInfo_list(xCore->p,xCore->xpath_nodes);
//fire start handlers
node=xCore->xpath_handlers->head;
while(node!=NULL){
xrec=(x_rec*)(node->data);
//xc_printNodeInfo_list(xCore->p,xrec->xpath_nodes);
if(xc_matchNodeDLists(xrec->xpath_nodes,xCore->xpath_nodes)){
//printf("node match!\n");
if(xrec->start_function!=NULL){
(*xrec->start_function)(xCore->p,(char*)el,0,attr,xrec->userdata);
}
}
node=node->next;
}
}
static void XMLCALL elementEnd(void *data, const char *el){
XmlCore* xCore=(XmlCore*)data;
//start handler data
llnode* node;
x_rec* xrec;
node_info* ninfo;
//printf("END ELEMENT BEGIN\r\n");
// fire end element handlers
node=xCore->xpath_handlers->head;
while(node!=NULL){
xrec=(x_rec*)(node->data);
//printf("ELEMENT END\r\n");
if(xc_matchNodeDLists(xrec->xpath_nodes,xCore->xpath_nodes)){
//printf("endnode match!\n");
//fire end body handler
if(xrec->body_function!=NULL){
(*xrec->body_function)(xCore->p,(char*)el,0,xrec->body,xrec->userdata);
}
//fire end element handler
if(xrec->end_function!=NULL){
(*xrec->end_function)(xCore->p,(char*)el,0,xrec->userdata);
}
xrec->body=NULL;
}
node=node->next;
}
//clean up nodes
ninfo=xc_RemoveFromTail(xCore->p,xCore->xpath_nodes);
//printf("rem node:%s\n",ninfo->name);
//xc_printNodeInfo_list(xCore->p,xCore->xpath_nodes);
}
static void XMLCALL cdataHandler(void *data, const XML_Char *s, int len){
XmlCore* xCore=(XmlCore*)data;
llnode* node;
x_rec* xrec;
node_info* ninfo;
char* str=NULL;
node=xCore->xpath_handlers->head;
while(node!=NULL){
xrec=(x_rec*)(node->data);
if(xc_matchNodeDLists(xrec->xpath_nodes,xCore->xpath_nodes)){
//printf("cdata!! match:!\n");
if(str==NULL){
str=apr_palloc(xCore->p,(len+1)*sizeof(char));
memset(str,'\0',len+1);
strncpy(str,s,len);
}
if(xrec->body==NULL){
xrec->body=str;
}else{
xrec->body=apr_pstrcat(xCore->p,xrec->body,str,NULL);
}
//printf("val: [%s]\n",xrec->body);
}
node=node->next;
}
//printf("len: %d: %s\n",len,s);
}
static void XMLCALL cdataSectionHandlerStart(void *userData){
//printf("!!!!!!!!!!!!!!!: \n");
}
static void XMLCALL cdataSectionHandlerEnd(void *userData){
//printf("lenSecE\n");
}
int xc_beginParsing(XmlCore* xCore,const char* file){
XML_Parser parser=NULL;
FILE* xFile=NULL;
char xBuffer[BUFFSIZE];
memset (xBuffer,'\0',BUFFSIZE);
if(file!=NULL){xFile=fopen(file,"r");}
if(xFile!=NULL){
parser=XML_ParserCreate(NULL);
if (! parser) {
fclose(xFile);
return CONST_FAILURE_CREATE;
}
XML_SetUserData(parser,xCore);
XML_SetElementHandler(parser, elementStart, elementEnd);
XML_SetCdataSectionHandler(parser,cdataSectionHandlerStart,cdataSectionHandlerEnd);
XML_SetCharacterDataHandler(parser,cdataHandler);
//begin actual parsing
for (;;) {
int done;
int len;
len = fread(xBuffer, 1, BUFFSIZE, xFile);
if (ferror(stdin)) {
fclose(xFile);
XML_ParserFree(parser);
return CONST_FAILURE_READ;
}
done = feof(xFile);
//printf("done: %d\n",done);
if (XML_Parse(parser, xBuffer, len, done) == XML_STATUS_ERROR) {
//fprintf(stderr, "Parse error at line %" XML_FMT_INT_MOD "u:\n%s\n",
//XML_GetCurrentLineNumber(parser),
//XML_ErrorString(XML_GetErrorCode(parser)));
//printf("code: %d\n",XML_GetErrorCode(parser));
fclose(xFile);
XML_ParserFree(parser);
return CONST_FAILURE_XMLERROR;
}
if (done){
break;
}
}
fclose(xFile);
XML_ParserFree(parser);
return 1;
}
return CONST_FAILURE_FILE_OPEN;
}
int xc_parseFromStringSource(XmlCore* xCore,const char* source){
XML_Parser parser=NULL;
char xBuffer[BUFFSIZE];
if(source!=NULL){
parser=XML_ParserCreate(NULL);
if (! parser) {
return CONST_FAILURE_CREATE;
}
XML_SetUserData(parser,xCore);
XML_SetElementHandler(parser, elementStart, elementEnd);
XML_SetCdataSectionHandler(parser,cdataSectionHandlerStart,cdataSectionHandlerEnd);
XML_SetCharacterDataHandler(parser,cdataHandler);
//begin actual parsing
if (XML_Parse(parser, source, strlen(source), 1) == XML_STATUS_ERROR) {
XML_ParserFree(parser);
return CONST_FAILURE_XMLERROR;
}
XML_ParserFree(parser);
return 1;
}
return CONST_FAILURE_READ;
}
static char* xc_parseTextResponse(apr_pool_t* p, int code, char* file){
if(code==CONST_FAILURE_FILE_OPEN){
return apr_pstrcat(p,"Failure to open file:",file!=NULL?file:"NULL",NULL);
}else if(code==CONST_FAILURE_XMLERROR){
return apr_pstrcat(p,"Failure parsing xml:",file!=NULL?file:"NULL",NULL);
}else if(code==CONST_FAILURE_READ){
return apr_pstrcat(p,"Failure reading file:",file!=NULL?file:"NULL",NULL);
}else if(code==CONST_FAILURE_CREATE){
return apr_pstrcat(p,"Failure creating parser:",file!=NULL?file:"NULL",NULL);
}
return NULL;
}
char* xc_parseFromStringSourceTextResponse(XmlCore* xCore, char* source){
int ret;
ret=xc_parseFromStringSource(xCore,source);
return xc_parseTextResponse(xCore->p,ret,source);
}
char* xc_beginParsingTextResponse(XmlCore* xCore, char* file){
int ret;
ret=xc_beginParsing(xCore,file);
return xc_parseTextResponse(xCore->p,ret,file);
}
|
tarachandverma/ngx-openidc
|
src/url-utils/url_utils.h
|
#ifndef __TCREWRITE_URL_UTILS__H_
#define __TCREWRITE_URL_UTILS__H_
#include <apr_general.h>
#include <apr_pools.h>
#include <apr_tables.h>
#include <apr_strings.h>
#include <apr_lib.h>
#include "apache_typedefs.h"
#ifdef __cplusplus
extern "C" {
#endif
int url_get_param(const char *queryString, const char *paramName, char *dest, int dlen);
char* url_getParam(pool* p, char* queryString,const char* name);
int url_decode(const char *src, char *dst, int dlen);
int url_encode(const char *src, char *dst, int dlen);
long base64_encode (char *to, char *from, unsigned int len);
long base64_decode (char *to, char *from, unsigned int len);
char* url_addParam(pool* p, char* url, char* pName, char* pVal);
char* url_encode2(pool* p, char* src);
char* url_decode2(pool* p, char* src);
char* url_appendParamToQuery(pool*p, char*query, char*pName,char*pVal);
long base64Url_encode (char *to, char *from, unsigned int len);
long base64Url_decode (char *to, char *from, unsigned int len);
#ifdef __cplusplus
}
#endif
#endif
|
tarachandverma/ngx-openidc
|
src/ngx_http_openidc_module.c
|
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
#include <nginx.h>
#include <apr_pools.h>
#include <apr_tables.h>
#include <apr_strings.h>
#include "oidc_config.h"
#include "config_core.h"
#include "common_utils.h"
#include "http-utils/http_client.h"
#include "logging.h"
#include "url_utils.h"
#include "rewrite_core.h"
#include "oidc_version.h"
#include "oidc_globals.h"
#define MODULE_NAME_ACTION_MAPPINGS "oidcConfig"
#define HOST_BUFSIZE 256
#define RBUF_SIZE 64000
#define OAUTH_IDTOKEN_MAX_SIZE 8192
// subrequest types
#define SUB_REQUEST_TYPE_UNKNOWN 0
#define SUB_REQUEST_TYPE_OAUTH_TOKEN 1
#define SUB_REQUEST_TYPE_AUTHENTICATE 2
#define SUB_REQUEST_TYPE_AUTHORIZE 3
typedef struct oidc_authz_sub_request_type{
ngx_uint_t type; // request type authenticate or token
ngx_str_t uri; // subrequest uri
ngx_str_t content_type; // requestBody content type
}oidc_authz_sub_request_type;
oidc_authz_sub_request_type oidc_authz_subrequest_type_oauth_token =
{ SUB_REQUEST_TYPE_OAUTH_TOKEN, ngx_string("/internal/oauth2/token"), ngx_string("application/x-www-form-urlencoded")};
#define ALLOC_IF_NULL(r) \
{if(r->data==NULL) { r->data = (char*)apr_palloc(r->pool,RBUF_SIZE); memset(r->data,'\0', RBUF_SIZE);}}
#define ngx_http_openidc_rprintf(r,arg1) \
{char temp[6144]; sprintf(temp,arg1); int cnt = strlen(temp); if(r->cur+cnt<RBUF_SIZE) { ALLOC_IF_NULL(r) memcpy(r->data+r->cur,temp, cnt); r->cur+=cnt;}}
#define ngx_http_openidc_rprintf1(r,tem,arg1) \
{char temp[6144]; sprintf(temp,tem,arg1); int cnt = strlen(temp); if(r->cur+cnt<RBUF_SIZE) {ALLOC_IF_NULL(r) memcpy(r->data+r->cur,temp, cnt); r->cur+=cnt;}}
#define ngx_http_openidc_rprintf2(r,tem,arg1,arg2) \
{char temp[6144]; sprintf(temp,tem,arg1,arg2); int cnt = strlen(temp); if(r->cur+cnt<RBUF_SIZE) {ALLOC_IF_NULL(r) memcpy(r->data+r->cur,temp, cnt); r->cur+=cnt;}}
#define ngx_http_openidc_rprintf3(r,tem,arg1,arg2,arg3) \
{char temp[6144]; sprintf(temp,tem,arg1,arg2,arg3); int cnt = strlen(temp); if(r->cur+cnt<RBUF_SIZE) {ALLOC_IF_NULL(r) memcpy(r->data+r->cur,temp, cnt); r->cur+=cnt;}}
#define ngx_http_openidc_rprintf4(r,tem,arg1,arg2,arg3,arg4) \
{char temp[6144]; sprintf(temp,tem,arg1,arg2,arg3,arg4); int cnt = strlen(temp); if(r->cur+cnt<RBUF_SIZE) {ALLOC_IF_NULL(r) memcpy(r->data+r->cur,temp, cnt); r->cur+=cnt;}}
#define ngx_http_openidc_rprintf5(r,tem,arg1,arg2,arg3,arg4,arg5) \
{char temp[6144]; sprintf(temp,tem,arg1,arg2,arg3,arg4,arg5); int cnt = strlen(temp); if(r->cur+cnt<RBUF_SIZE) {ALLOC_IF_NULL(r) memcpy(r->data+r->cur,temp, cnt); r->cur+=cnt;}}
#define ngx_http_openidc_rputs(str,r) \
{ if(str) { int cnt = strlen(str); if(r->cur<RBUF_SIZE) { ALLOC_IF_NULL(r) memcpy(r->data+r->cur,str, cnt); r->cur+=cnt;} } }
apr_pool_t* mainPool = NULL;
int initializedAPR = 0;
typedef struct {
char* homeDir;
char* logFile;
char* sheapMapFile;
int sheapPageSize;
char* remotePath;
char* remoteAuth;
int remotePathTimeout;
char* passPhrase;
char* oidcHeaderPrefix;
int refreshWaitSeconds;
char* oidcConfigFile;
oidc_config* oidcConfig;
config_core* configCore;
} Config;
typedef struct {
ngx_str_t homeDir;
ngx_str_t logFile;
ngx_str_t sheapMapFile;
ngx_int_t sheapPageSize;
ngx_str_t remotePath;
ngx_str_t remoteAuth;
ngx_int_t remotePathTimeout;
ngx_str_t passPhrase;
ngx_str_t oidcHeaderPrefix;
ngx_str_t oidcConfigFile;
ngx_int_t refreshWaitSeconds;
Config* config;
} ngx_http_openidc_srv_conf_t;
/** A structure that represents the current rewrite request */
typedef struct {
apr_pool_t *pool;
char *connection_remote_ip;
const char *hostname;
apr_table_t *headers_in;
apr_table_t *headers_out;
apr_hash_t* variableHash;
const char *handler; /* What we *really* dispatch on */
char *unparsed_uri;
char *uri;
apr_uri_t parsed_uri;
ngx_http_request_t* httpRequest;
char* data;
long cur;
}ngx_http_openidc_request_t;
typedef struct {
ngx_uint_t done;
ngx_uint_t status;
ngx_http_request_t *subrequest;
ngx_str_t responseBody;
ngx_str_t responseType;
} ngx_http_openidc_subrequest_ctx_t;
static void *ngx_http_openidc_create_srv_conf(ngx_conf_t *cf);
static char *ngx_http_openidc_merge_srv_conf(ngx_conf_t *cf,
void *parent, void *child);
static ngx_int_t ngx_http_openidc_post_config(ngx_conf_t *cf);
static ngx_int_t ngx_http_openidc_checkForAccess(ngx_http_request_t * httpRequest);
static ngx_int_t ngx_http_openidc_handler(ngx_http_request_t *r);
static void ngx_http_openidc_setActionHeaders(ngx_http_openidc_request_t*r, apr_table_t* headers, array_header* actionHeaders, template_engine* tengine, char* originUri, int addHeaderToHttpRequest);
static int ngx_http_openidc_execUri(ngx_http_openidc_request_t* r, char* uri,int isForward, int isPermanent, char* originUri);
static char* ngx_http_openidc_getPostEntity(ngx_http_openidc_request_t* r, long* sz);
static void ngx_http_openidc_deleteHeader(ngx_http_request_t *r, u_char *key);
static ngx_int_t ngx_http_openidc_setHeader(ngx_http_request_t *r, const char *key, const char *val);
static ngx_int_t ngx_http_openidc_deleteHeaderPart(ngx_list_t *l, ngx_list_part_t *cur, ngx_uint_t i);
static int oidc_index(ngx_http_openidc_request_t *r, Config* config);
static int oidc_version(ngx_http_openidc_request_t *r, Config* config);
static int oidc_rewrite_actionmappings(ngx_http_openidc_request_t *r, Config *config);
static int oidc_rewrite_match(ngx_http_openidc_request_t *r, Config *config);
static int oidc_rewrite_pageactions(ngx_http_openidc_request_t *r, Config *config);
static int oidc_config_core_status(ngx_http_openidc_request_t *r, Config *config);
static int oidc_headers(ngx_http_openidc_request_t *r, Config *config);
static char* ngx_http_openidc_getFullRequestUrl(ngx_http_openidc_request_t* r);
static ngx_int_t ngx_http_openidc_subrequest_post_handler(ngx_http_request_t *r, void *data, ngx_int_t rc);
static ngx_int_t ngx_http_openidc_set_subrequest_post_body(ngx_http_request_t * r, ngx_http_request_t * sr, const char* requestBody, ngx_str_t contentType);
static ngx_int_t ngx_http_openidc_preAuthorize(ngx_http_openidc_request_t* r, Config* config);
static ngx_int_t ngx_http_openidc_create_post_subrequest(ngx_http_request_t * r, oidc_authz_sub_request_type sub_request_type, const char* requestBody);
ngx_str_t ngx_http_openidc_content_length_header_key =
ngx_string("Content-Length");
ngx_str_t ngx_http_openidc_content_type_header_key =
ngx_string("Content-Type");
ngx_str_t ngx_http_openidc_content_type_formurlencoded =
ngx_string("application/x-www-form-urlencoded");
ngx_str_t ngx_http_openidc_content_type_json =
ngx_string("application/json");
static void ngx_http_openidc_terminate() {
if(mainPool) apr_pool_destroy(mainPool);
apr_terminate();
}
static int ngx_http_openidc_die(int exitCode, const char *message, apr_status_t reason) {
char msgbuf[80];
apr_strerror(reason, msgbuf, sizeof(msgbuf));
fprintf(stderr, "%s: %s (%d)\n", message, msgbuf, reason);
exit(exitCode);
return reason;
}
static void ngx_http_openidc_initializeAPR() {
apr_status_t status;
// Initialize library
status = apr_initialize();
if(status!=APR_SUCCESS) { ngx_http_openidc_die(-2, "Could not initialize", status); }
atexit(ngx_http_openidc_terminate);
// create mainPool
status = apr_pool_create(&mainPool, NULL);
if(status!=APR_SUCCESS) { ngx_http_openidc_die(-2, "Could not initialize main pool", status); }
initializedAPR = 1;
}
static char *
ngx_http_openidc_set_home_dir(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_http_openidc_srv_conf_t *sscf = conf;
ngx_str_t *value;
value = cf->args->elts;
sscf->homeDir = value[1];
// printf("ngx_http_openidc_set_home_dir:%d", getpid());
return NGX_CONF_OK;
}
static char *
ngx_http_openidc_set_log_file(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_http_openidc_srv_conf_t *sscf = conf;
ngx_str_t *value, *url;
value = cf->args->elts;
url = &value[1];
sscf->logFile = value[1];
// printf("ngx_http_openidc_set_log_file:%d", getpid());
return NGX_CONF_OK;
}
static char *
ngx_http_openidc_set_shm(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_http_openidc_srv_conf_t *sscf = conf;
ngx_str_t* value;
int i;
value = cf->args->elts;
for (i = 1; i < cf->args->nelts; i++) {
if (ngx_strncmp(value[i].data, "file=", 5) == 0) {
sscf->sheapMapFile.len = value[i].len - 5;
sscf->sheapMapFile.data = value[i].data + 5;
continue;
}
if (ngx_strncmp(value[i].data, "size=", 5) == 0) {
sscf->sheapPageSize= ngx_atoi(value[i].data + 5, value[i].len - 5);
continue;
}
}
// printf("ngx_http_openidc_set_shm:%d", getpid());
return NGX_CONF_OK;
}
static char *
ngx_http_openidc_set_remote_path(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_http_openidc_srv_conf_t *sscf = conf;
ngx_str_t* value;
int i;
value = cf->args->elts;
for (i = 1; i < cf->args->nelts; i++) {
if (ngx_strncmp(value[i].data, "uri=", 4) == 0) {
sscf->remotePath.len = value[i].len - 4;
sscf->remotePath.data = value[i].data + 4;
continue;
}
if (ngx_strncmp(value[i].data, "timeout=", 8) == 0) {
sscf->remotePathTimeout= ngx_atoi(value[i].data + 8, value[i].len - 8);
continue;
}
if (ngx_strncmp(value[i].data, "user:pass=", 10) == 0) {
sscf->remoteAuth.len = value[i].len - 10;
sscf->remoteAuth.data = value[i].data + 10;
continue;
}
}
// printf("ngx_http_openidc_set_remote_path:%d", getpid());
return NGX_CONF_OK;
}
static char *
ngx_http_openidc_set_pass_phrase(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_http_openidc_srv_conf_t *sscf = conf;
ngx_str_t *value, *url;
value = cf->args->elts;
url = &value[1];
sscf->passPhrase = value[1];
// printf("ngx_http_openidc_set_pass_phrase:%d", getpid());
return NGX_CONF_OK;
}
static char *
ngx_http_openidc_set_header_prefix(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_http_openidc_srv_conf_t *sscf = conf;
ngx_str_t *value, *url;
value = cf->args->elts;
url = &value[1];
sscf->oidcHeaderPrefix = value[1];
// printf("ngx_http_openidc_set_header_prefix:%d", getpid());
return NGX_CONF_OK;
}
static char *
ngx_http_openidc_set_refresh_wait(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_http_openidc_srv_conf_t *sscf = conf;
ngx_str_t *value, *url;
value = cf->args->elts;
url = &value[1];
sscf->refreshWaitSeconds= ngx_atoi(value[1].data, value[1].len);
// printf("ngx_http_openidc_set_header_prefix:%d", getpid());
return NGX_CONF_OK;
}
typedef struct ce_error_list{
apr_array_header_t* data;
}ce_error_list;
static ce_error_list* ce_newErrorListObj(pool* p){
ce_error_list* ret=(ce_error_list*)apr_pcalloc(p,sizeof(ce_error_list));
ret->data=apr_array_make(p,4,sizeof(char*));\
return ret;
}
static void ce_addErrorWithType(pool* p, ce_error_list* elist, char* mtype, char* msg){
char** place=NULL;
char* item=NULL;
if(elist==NULL||msg==NULL) return;
if(mtype!=NULL){
item=apr_pstrcat(p,"[",mtype,"] ",msg,NULL);
}else{
item=apr_pstrdup(p,msg);
}
place=(char**)apr_array_push(elist->data);
*place=item;
}
static void ce_printList(pool* p,ce_error_list* elist){
int i=0;
char* item=NULL;
apr_array_header_t* arry=NULL;
if(elist==NULL) return;
arry=elist->data;
for(i=0;i<arry->nelts;i++){
item=cu_getElement(arry,i);
printf("• %s\n",item);
}
}
static int ce_hasErrors(ce_error_list* elist){
return elist!=NULL&&elist->data->nelts>0;
}
static char* ngx_http_openidc_postRefreshBind(apr_pool_t* p,Config* config){
if(config->configCore==NULL){
return apr_pstrdup(p,"Config Core is NULL");
}
config->oidcConfig=(oidc_config*)configcore_getModuleConfigByName(config->configCore,MODULE_NAME_ACTION_MAPPINGS);
if(config->oidcConfig==NULL){
return apr_pstrcat(p,"! Missing Required Service Name:",MODULE_NAME_ACTION_MAPPINGS,NULL);
}
return NULL;
}
static void ngx_http_openidc_postConfigStarting(apr_pool_t* p, const char* defn_name, int is_virtual, Config* config){
printf("\n»»» Initializing(%s)%s \n",defn_name!=NULL?defn_name:"-",is_virtual?"**VIRTUAL**":"");
printf("* Note: If initialization seems slow. Check your DNS. It may have become slow or unresponsive.\r\n");
if(config->oidcConfigFile!=NULL){
config_core* ccore=NULL;
ce_error_list* errorList=NULL;
char* error=NULL;
char cbuf[APR_CTIME_LEN + 1];
config->logFile = apr_pstrcat(p,config->homeDir,"/",config->logFile,NULL);
lc_openLogFile(p,config->logFile);
lc_truncateLogFile();
apr_time_t t1 = apr_time_now();
apr_ctime(cbuf, t1);
lc_printLog("\n°\t Initializing %s [%s]\n",VERSION_ID,cbuf);
fflush(stdout);
hc_init();
//init Error Obj
errorList=ce_newErrorListObj(p);
//load crypto core
lc_printLog("\r\n\r\n");
ccore=configcore_newConfigCoreObj(p);
ccore->globals->homeDir=apr_pstrdup(p,config->homeDir);
ccore->globals->logsDir=apr_pstrcat(p,config->homeDir,"/logs",NULL);
ccore->refreshLogFile=apr_pstrdup(p,config->logFile);
// shared memory
ccore->sheapMapFile=apr_pstrdup(p,config->sheapMapFile);
ccore->sheapPageSize=config->sheapPageSize;
// remote path
if(config->remotePath!=NULL) {
ccore->globals->resourceService = cb_newServiceDescriptorObj(p);
ccore->globals->resourceService->uri=apr_pstrdup(p,config->remotePath);
ccore->globals->resourceService->userColonPass=apr_pstrdup(p,config->remoteAuth);
ccore->globals->resourceService->timeoutSeconds=config->remotePathTimeout;
}
// oidc stuff
ccore->passPhrase=apr_pstrdup(p,config->passPhrase);
ccore->cipherConfig->crypto_passphrase=ccore->passPhrase;
ccore->oidcHeaderPrefix=apr_pstrdup(p,config->oidcHeaderPrefix);
ccore->refreshWaitSeconds=config->refreshWaitSeconds;
ccore->oidcConfigFile=apr_pstrdup(p,config->oidcConfigFile);
ce_addErrorWithType(p,errorList,"Config Core Load File",error);
if(error==NULL){
configcore_printConfigCoreDetails(p,ccore);
error=configcore_initializeConfigCore(p,ccore);
ce_addErrorWithType(p,errorList,"Config Core Init",error);
config->configCore=ccore;
lc_printLog("‚àö Config Core Initialized\n");
lc_printLog("° Binding Config Core Services\n");
error=ngx_http_openidc_postRefreshBind(p,config);
ce_addErrorWithType(p,errorList,"Config Core Bind",error);
}
if(!ce_hasErrors(errorList)){
long timeTakenMillis = ((apr_time_now() - t1) / 1000);
lc_printLog("\r\n>> %s - SUCCESS - Configuration loaded successfully [time taken : %d milliseconds]<<\r\n",VERSION_ID,timeTakenMillis);
}else{
lc_printLog("\r\n>> %s - ERRORS - Please check with development support if its ok to continue deployment..<<\r\n\n\n",VERSION_ID);
ce_printList(p,errorList);
}
lc_closeLogFile();
}else{
printf("!\n!\n!\t%sModule Config un-initializable!\n",is_virtual?"**VIRTUAL** ":"");
printf("!\tThis is usually because you are missing settings for the default host.\n!\n!\n\n");
}
}
static char *
ngx_http_openidc_set_configcore_file(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_http_openidc_srv_conf_t *sscf = conf;
ngx_str_t *value;
value = cf->args->elts;
sscf->oidcConfigFile = value[1];
// printf("ngx_http_openidc_set_configcore_file:%d", getpid());
if(!initializedAPR) {
ngx_http_openidc_initializeAPR();
}
if(sscf->homeDir.data==NULL) {
// ngx_log_error(NGX_LOG_ERR, cmd->log, 0, "rewrite home directory missing");
// return NGX_ERROR;
}
sscf->config=ngx_pcalloc(cf->pool, sizeof(Config));
sscf->config->homeDir=apr_pstrndup(mainPool, (char*)sscf->homeDir.data, sscf->homeDir.len);
sscf->config->logFile=apr_pstrndup(mainPool, (char*)sscf->logFile.data, sscf->logFile.len);
// shared memory
sscf->config->sheapMapFile = (sscf->sheapMapFile.len>0)
? apr_pstrndup(mainPool, (char*)sscf->sheapMapFile.data, sscf->sheapMapFile.len)
: apr_pstrdup(mainPool, "/config.shm");
sscf->config->sheapPageSize=(sscf->sheapPageSize>0) ? sscf->sheapPageSize : 64000;
// remote path
if(sscf->remotePath.len>0) {
sscf->config->remotePath=apr_pstrndup(mainPool, (char*)sscf->remotePath.data, sscf->remotePath.len);
sscf->config->remoteAuth = (sscf->remoteAuth.len>0)
? apr_pstrndup(mainPool, (char*)sscf->remoteAuth.data, sscf->remoteAuth.len)
: NULL;
sscf->config->remotePathTimeout=(sscf->remotePathTimeout>0) ? sscf->remotePathTimeout : 10;
}
sscf->config->passPhrase = (sscf->passPhrase.len>0)
? apr_pstrndup(mainPool, (char*)sscf->passPhrase.data, sscf->passPhrase.len)
: NULL;
sscf->config->oidcHeaderPrefix = (sscf->oidcHeaderPrefix.len>0)
? apr_pstrndup(mainPool, (char*)sscf->oidcHeaderPrefix.data, sscf->oidcHeaderPrefix.len)
: apr_pstrdup(mainPool, "X-OIDC-");
sscf->config->refreshWaitSeconds=(sscf->refreshWaitSeconds>0) ? sscf->refreshWaitSeconds : 0;
sscf->config->oidcConfigFile = (sscf->oidcConfigFile.len>0)
? apr_pstrndup(mainPool, (char*)sscf->oidcConfigFile.data, sscf->oidcConfigFile.len)
: apr_pstrdup(mainPool, "oidc-config.xml");
djrglobals_setEnableUnnamedSHM("true");
ngx_http_openidc_postConfigStarting(mainPool,"authz_oidc",FALSE,sscf->config);
return NGX_CONF_OK;
}
static ngx_command_t ngx_http_openidc_commands[] = {
{ ngx_string("OPENIDC_HomeDir"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_CONF_TAKE12,
ngx_http_openidc_set_home_dir,
NGX_HTTP_SRV_CONF_OFFSET,
0,
NULL },
{ ngx_string("OPENIDC_LogFile"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_CONF_TAKE12,
ngx_http_openidc_set_log_file,
NGX_HTTP_SRV_CONF_OFFSET,
0,
NULL },
{ ngx_string("OPENIDC_SharedMemory"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_CONF_TAKE12,
ngx_http_openidc_set_shm,
NGX_HTTP_SRV_CONF_OFFSET,
0,
NULL },
{ ngx_string("OPENIDC_RemotePath"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_CONF_TAKE123,
ngx_http_openidc_set_remote_path,
NGX_HTTP_SRV_CONF_OFFSET,
0,
NULL },
{ ngx_string("OPENIDC_PassPhrase"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_CONF_TAKE12,
ngx_http_openidc_set_pass_phrase,
NGX_HTTP_SRV_CONF_OFFSET,
0,
NULL },
{ ngx_string("OPENIDC_HeaderPrefix"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_CONF_TAKE12,
ngx_http_openidc_set_header_prefix,
NGX_HTTP_SRV_CONF_OFFSET,
0,
NULL },
{ ngx_string("OPENIDC_RefreshWaitSeconds"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_CONF_TAKE12,
ngx_http_openidc_set_refresh_wait,
NGX_HTTP_SRV_CONF_OFFSET,
0,
NULL },
{ ngx_string("OPENIDC_ConfigFile"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_CONF_TAKE12,
ngx_http_openidc_set_configcore_file,
NGX_HTTP_SRV_CONF_OFFSET,
0,
NULL },
ngx_null_command
};
static ngx_http_module_t ngx_http_openidc_module_ctx = {
NULL, /* preconfiguration */
ngx_http_openidc_post_config, /* postconfiguration */
NULL, /* create main configuration */
NULL, /* init main configuration */
ngx_http_openidc_create_srv_conf, /* create server configuration */
ngx_http_openidc_merge_srv_conf, /* merge server configuration */
NULL, /* create location configuration */
NULL /* merge location configuration */
};
ngx_int_t ainit_master(ngx_log_t *log) {
// printf("ainit_master:%d", getpid());
return NGX_OK;
}
ngx_int_t ainit_module(ngx_cycle_t *cycle) {
// printf("ainit_module:%d", getpid());
return NGX_OK;
}
ngx_int_t ainit_process(ngx_cycle_t *cycle) {
// printf("ainit_process:%d", getpid());
return NGX_OK;
}
void aexit_process(ngx_cycle_t *cycle) {
ngx_http_openidc_terminate();
// printf("aexit_process:%d", getpid());
}
void aexit_master(ngx_cycle_t *cycle) {
ngx_http_openidc_terminate();
// printf("aexit_master:%d", getpid());
}
ngx_module_t ngx_http_openidc_module = {
NGX_MODULE_V1,
&ngx_http_openidc_module_ctx, /* module context */
ngx_http_openidc_commands, /* module directives */
NGX_HTTP_MODULE, /* module type */
ainit_master, /* init master */
ainit_module, /* init module */
ainit_process, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
aexit_process, /* exit process */
aexit_master, /* exit master */
NGX_MODULE_V1_PADDING
};
static void *
ngx_http_openidc_create_srv_conf(ngx_conf_t *cf)
{
ngx_http_openidc_srv_conf_t *sscf;
sscf = ngx_pcalloc(cf->pool, sizeof(ngx_http_openidc_srv_conf_t));
if (sscf == NULL) {
return NULL;
}
// printf("ngx_http_openidc_create_srv_conf:%p %d\r\n", sscf, getpid());
return sscf;
}
static char *
ngx_http_openidc_merge_srv_conf(ngx_conf_t *cf, void *parent, void *child)
{
ngx_http_openidc_srv_conf_t *prev = parent;
ngx_http_openidc_srv_conf_t *conf = child;
if(conf->homeDir.data==NULL) {
conf->homeDir = prev->homeDir;
}
if(conf->logFile.data==NULL) {
conf->logFile = prev->logFile;
}
if(conf->sheapMapFile.data==NULL) {
conf->sheapMapFile = prev->sheapMapFile;
}
if(conf->sheapPageSize==0) {
conf->sheapPageSize = prev->sheapPageSize;
}
if(conf->remotePath.data==NULL) {
conf->remotePath = prev->remotePath;
}
if(conf->remoteAuth.data==NULL) {
conf->remoteAuth = prev->remoteAuth;
}
if(conf->remotePathTimeout==0) {
conf->remotePathTimeout = prev->remotePathTimeout;
}
if(conf->passPhrase.data==NULL) {
conf->passPhrase = prev->passPhrase;
}
if(conf->oidcHeaderPrefix.data==NULL) {
conf->oidcHeaderPrefix = prev->oidcHeaderPrefix;
}
if(conf->refreshWaitSeconds==0) {
conf->refreshWaitSeconds = prev->refreshWaitSeconds;
}
if(conf->oidcConfigFile.data==NULL) {
conf->oidcConfigFile = prev->oidcConfigFile;
}
if(conf->config==NULL) {
conf->config = prev->config;
}
// printf("ngx_http_openidc_merge_srv_conf:%p %p %d\r\n", prev,conf,getpid());
return NGX_CONF_OK;
}
static ngx_http_openidc_request_t* ngx_http_openidc_createRequest(apr_pool_t* p) {
ngx_http_openidc_request_t* r = (ngx_http_openidc_request_t *) apr_pcalloc(p, sizeof(ngx_http_openidc_request_t));
r->pool = p;
r->connection_remote_ip=NULL;
r->headers_in = apr_table_make(r->pool, 12);
r->headers_out = apr_table_make(r->pool, 12);
r->variableHash = apr_hash_make(r->pool);
//memset(r_buf,'\0', RBUF_SIZE);
r->data=NULL;
r->cur=0;
return r;
}
static void ngx_http_openidc_setHeadersIn(ngx_http_request_t *httpRequest, ngx_http_openidc_request_t* r, char* headerPrefix) {
ngx_list_part_t *part;
ngx_table_elt_t *h;
ngx_uint_t i;
apr_pool_t* p = r->pool;
apr_table_t* headersIn = r->headers_in;
size_t prefixLen = (headerPrefix!=NULL) ? strlen(headerPrefix) : 0;
/*
Get the first part of the list. There is usual only one part.
*/
part = &httpRequest->headers_in.headers.part;
h = part->elts;
/*
Headers list array may consist of more than one part,
so loop through all of it
*/
for (i = 0; /* void */ ; i++) {
if (i >= part->nelts) {
if (part->next == NULL) {
/* The last part, search is done. */
break;
}
part = part->next;
h = part->elts;
i = 0;
}
if ( prefixLen>0 && prefixLen < h[i].key.len && (ngx_strcasestrn(h[i].key.data, headerPrefix, prefixLen-1)==h[i].key.data) ) {
/* This is incompletion. */
/*
h[i].hash = 0;
h[i].key.len = 0;
h[i].key.data = NULL;
h[i].value.len = 0;
h[i].value.data = NULL;
*/
ngx_http_openidc_deleteHeaderPart(&httpRequest->headers_in.headers, part, i);
}else{
char* key = apr_pstrndup(p, (char*)h[i].key.data, h[i].key.len);
char* value = apr_pstrndup(p, (char*)h[i].value.data, h[i].value.len);
apr_table_set(headersIn,key,value);
}
}
/*
No headers was found
*/
return ;
}
ngx_int_t ngx_http_openidc_setHeaderInHeadersOut(ngx_http_request_t *r, const char *key, const char *val) {
ngx_table_elt_t *h;
h = ngx_list_push(&r->headers_out.headers);
if (h == NULL) {
return NGX_ERROR;
}
h->key.len = strlen(key);
h->value.len = strlen(val);;
h->key.data = ngx_pnalloc(r->pool,
h->key.len + 1 + h->value.len + 1 + h->key.len);
if (h->key.data == NULL) {
return NGX_ERROR;
}
h->value.data = h->key.data + h->key.len + 1;
h->lowcase_key = h->key.data + h->key.len + 1 + h->value.len + 1;
ngx_memcpy(h->key.data, key, h->key.len);
h->key.data[h->key.len] = '\0';
ngx_memcpy(h->value.data, val, h->value.len);
h->value.data[h->value.len] = '\0';
ngx_strlow(h->lowcase_key, h->key.data, h->key.len);
h->hash = r->header_hash;
return NGX_OK;
}
ngx_int_t ngx_http_openidc_setHeaderInHeadersIn(ngx_http_request_t *r, const char *keyStr, const char *valueStr) {
ngx_table_elt_t *h;
h = ngx_list_push(&r->headers_in.headers);
if (h == NULL) {
return NGX_ERROR;
}
h->key.len = strlen(keyStr);
h->value.len = strlen(valueStr);;
h->key.data = ngx_pnalloc(r->pool,
h->key.len + 1 + h->value.len + 1 + h->key.len);
if (h->key.data == NULL) {
return NGX_ERROR;
}
h->value.data = h->key.data + h->key.len + 1;
h->lowcase_key = h->key.data + h->key.len + 1 + h->value.len + 1;
ngx_memcpy(h->key.data, keyStr, h->key.len);
h->key.data[h->key.len] = '\0';
ngx_memcpy(h->value.data, valueStr, h->value.len);
h->value.data[h->value.len] = '\0';
ngx_strlow(h->lowcase_key, h->key.data, h->key.len);
h->hash = r->header_hash;
return NGX_OK;
}
static ngx_int_t ngx_http_openidc_post_config(ngx_conf_t *cf) {
ngx_http_handler_pt *h;
ngx_http_core_main_conf_t *cmcf;
cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);
// check access phase
h = ngx_array_push(&cmcf->phases[NGX_HTTP_ACCESS_PHASE].handlers);
if (h == NULL) {
return NGX_ERROR;
}
*h = ngx_http_openidc_checkForAccess;
// custom content generator handler
// h = ngx_array_push(&cmcf->phases[NGX_HTTP_CONTENT_PHASE].handlers);
// if (h == NULL) {
// return NGX_ERROR;
// }
// *h = ngx_http_openidc_handler;
// printf("ngx_http_openidc_post_config:%d\r\n", getpid());
return NGX_OK;
}
static int ngx_http_openidc_addResponseHeaderCallback(void *rec, const char *keyStr, const char *valueStr){
ngx_http_request_t *httpRequest = (ngx_http_request_t*)rec;
if(keyStr&&valueStr&&httpRequest) {
ngx_http_openidc_setHeaderInHeadersOut(httpRequest, keyStr, valueStr);
}
return 1;
}
static ngx_int_t ngx_http_openidc_sendResponse(ngx_http_openidc_request_t* r) {
ngx_int_t rc;
ngx_buf_t *b;
ngx_chain_t out;
int dataLen=0;
// return if contentType or body not found
if(r->data==NULL) return NGX_HTTP_INTERNAL_SERVER_ERROR;
/* set the 'Content-type' header */
r->httpRequest->headers_out.content_type_len = sizeof("text/html") - 1;
r->httpRequest->headers_out.content_type.len = sizeof("text/html") - 1;
r->httpRequest->headers_out.content_type.data = (u_char *) "text/html";
/* allocate a buffer for your response body */
b = ngx_pcalloc(r->httpRequest->pool, sizeof(ngx_buf_t));
if (b == NULL) {
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
/* attach this buffer to the buffer chain */
out.buf = b;
out.next = NULL;
//r->data = apr_psprintf(workerPool, "r->handler=%s retCode=%d", r->handler, retCode);
/* adjust the pointers of the buffer */
dataLen = strlen(r->data);
b->pos = (u_char*)r->data;
b->last = (u_char*)r->data + dataLen;
b->memory = 1; /* this buffer is in memory */
b->last_buf = 1; /* this is the last buffer in the buffer chain */
/* set the status line */
r->httpRequest->headers_out.status = NGX_HTTP_OK;
r->httpRequest->headers_out.content_length_n = dataLen;
/* send the headers of your response */
rc = ngx_http_send_header(r->httpRequest);
if (rc == NGX_ERROR || rc > NGX_OK || r->httpRequest->header_only) {
return rc;
}
/* send the buffer chain of your response */
return ngx_http_output_filter(r->httpRequest, &out);
}
ngx_table_elt_t* ngx_http_openidc_lookupHeader(ngx_http_request_t *r, u_char *key) {
ngx_list_part_t *part;
ngx_table_elt_t *h;
ngx_uint_t i;
size_t len = strlen((char *)key);
part = &r->headers_in.headers.part;
h = part->elts;
for (i = 0; ; i++) {
if (i >= part->nelts) {
if (part->next == NULL) {
break;
}
part = part->next;
h = part->elts;
i = 0;
}
if (len != h[i].key.len || ngx_strcasecmp(key, h[i].key.data) != 0) {
continue;
}
return &h[i];
}
return NULL;
}
ngx_int_t ngx_http_openidc_setHeader(ngx_http_request_t *r, const char *key, const char *val) {
ngx_table_elt_t *h;
h = ngx_list_push(&r->headers_in.headers);
if (h == NULL) {
return NGX_ERROR;
}
h->key.len = strlen(key);
h->value.len = strlen(val);;
h->key.data = ngx_pnalloc(r->pool,
h->key.len + 1 + h->value.len + 1 + h->key.len);
if (h->key.data == NULL) {
return NGX_ERROR;
}
h->value.data = h->key.data + h->key.len + 1;
h->lowcase_key = h->key.data + h->key.len + 1 + h->value.len + 1;
ngx_memcpy(h->key.data, key, h->key.len);
h->key.data[h->key.len] = '\0';
ngx_memcpy(h->value.data, val, h->value.len);
h->value.data[h->value.len] = '\0';
ngx_strlow(h->lowcase_key, h->key.data, h->key.len);
h->hash = r->header_hash;
return NGX_OK;
}
/*
* delete header part
*/
static ngx_int_t ngx_http_openidc_deleteHeaderPart(ngx_list_t *l,
ngx_list_part_t *cur,
ngx_uint_t i) {
ngx_table_elt_t *elts = cur->elts;
ngx_list_part_t *new, *part;
if (i == 0) {
cur->elts = (char *) cur->elts + l->size;
cur->nelts--;
if (cur == l->last) {
if (l->nalloc > 1) {
l->nalloc--;
return NGX_OK;
}
part = &l->part;
while (part->next != cur) {
if (part->next == NULL) {
return NGX_ERROR;
}
part = part->next;
}
part->next = NULL;
l->last = part;
return NGX_OK;
}
if (cur->nelts == 0) {
part = &l->part;
while (part->next != cur) {
if (part->next == NULL) {
return NGX_ERROR;
}
part = part->next;
}
part->next = cur->next;
return NGX_OK;
}
return NGX_OK;
}
if (i == cur->nelts - 1) {
cur->nelts--;
if (cur == l->last) {
l->nalloc--;
}
return NGX_OK;
}
new = ngx_palloc(l->pool, sizeof(ngx_list_part_t));
if (new == NULL) {
return NGX_ERROR;
}
new->elts = &elts[i + 1];
new->nelts = cur->nelts - i - 1;
new->next = cur->next;
l->nalloc = new->nelts;
cur->nelts = i;
cur->next = new;
if (cur == l->last) {
l->last = new;
}
cur = new;
return NGX_OK;
}
/*
* delete header if exists
*/
void ngx_http_openidc_deleteHeader(ngx_http_request_t *r, u_char *key) {
ngx_list_part_t *part;
ngx_table_elt_t *h;
ngx_uint_t i;
size_t len = strlen((char *)key);
part = &r->headers_in.headers.part;
h = part->elts;
for (i = 0; ; i++) {
if (i >= part->nelts) {
if (part->next == NULL) {
break;
}
part = part->next;
h = part->elts;
i = 0;
}
if (len == h[i].key.len && ngx_strcasecmp(key, h[i].key.data) == 0) {
/* This is incompletion. */
/*
h[i].hash = 0;
h[i].key.len = 0;
h[i].key.data = NULL;
h[i].value.len = 0;
h[i].value.data = NULL;
*/
ngx_http_openidc_deleteHeaderPart(&r->headers_in.headers, part, i);
}
}
}
static const char *ngx_http_openidc_requestVar(ngx_http_openidc_request_t *r, const char* arg)
{
char* start = NULL;
if(arg==NULL) return NULL;
if((start = strstr(arg, "HTTP_"))) {
return apr_table_get(r->headers_in, start+5);
} else if(strcmp(arg,"REQ_URI")==0) {
return r->uri;
} else if(strcmp(arg,"REQ_UNPARSED_URI")==0) {
return r->unparsed_uri;
}else if(strcmp(arg,"REQ_URI_ENCODED")==0) {
return url_encode2(r->pool, r->uri);
} else if(strcmp(arg,"REQ_UNPARSED_URI_ENCODED")==0) {
return url_encode2(r->pool, r->unparsed_uri);
} else if(strcmp(arg,"REQ_QUERY")==0) {
uri_components *url = &r->parsed_uri;
return url_getParam(r->pool, url->query, arg);
}
return NULL;
}
static const char *ngx_http_openidc_serverVars(ngx_http_openidc_request_t *r, const char* arg)
{
return (arg!=NULL) ? apr_hash_get(r->variableHash, arg, APR_HASH_KEY_STRING) : NULL;
}
static const char *ngx_http_openidc_requestCookie(ngx_http_openidc_request_t *r, const char *arg)
{
if(arg==NULL) return "(null)";
const char *s = cookie_getCookieByName(r->pool, r->headers_in, arg, strlen(arg));
if (s)
return s;
else
return "(null)";
}
static const char *ngx_http_openidc_urlDecodeToken(ngx_http_openidc_request_t *r, const char *arg){
return url_decode2(r->pool,(char*)arg);
}
static const char *ngx_http_openidc_urlEncodeToken(ngx_http_openidc_request_t *r, const char *arg){
return url_encode2(r->pool,(char*)arg);
}
static const char *ngx_http_openidc_requestQuery(ngx_http_openidc_request_t *r, const char *arg)
{
uri_components *url = &r->parsed_uri;
if(arg==NULL) return "(null)";
const char *s = url_getParam(r->pool, url->query, arg);
if (s)
return s;
else
return "(null)";
}
typedef struct tag_handler{
const char c;
const char* (*func)(ngx_http_openidc_request_t*,const char* arg);
}tag_handler;
static const tag_handler tagHandlers[] = {
{'r', ngx_http_openidc_requestVar},
{'s', ngx_http_openidc_serverVars},
{'c', ngx_http_openidc_requestCookie},
{'u', ngx_http_openidc_urlDecodeToken},
{'U', ngx_http_openidc_urlEncodeToken},
{'q', ngx_http_openidc_requestQuery},
};
static const char* ngx_http_openidc_getTagValue(char* s, ngx_http_openidc_request_t*r, char**next) {
unsigned int i;
char* arg = NULL, *end=NULL;
s++;
if (*s == '{') {
if((end = strchr(s, '}'))!=NULL) {
arg = apr_pstrndup(r->pool, s+1, end-s-1);
s=end+1; // pass by '}'
}
}
for(i=0; i < sizeof(tagHandlers)/sizeof(tag_handler); i++ ){
if(tagHandlers[i].c==*s) {
*next = s+1; // pass by the current character.
return (*tagHandlers[i].func)(r, arg);
}
}
return NULL;
}
static char* ngx_http_openidc_parseString(pool*p, char*src, ngx_http_openidc_request_t *r){
#define HDR_BUF_SIZE 4096
if(src==NULL) return NULL;
char*ret=(char*)apr_palloc(p, HDR_BUF_SIZE);
char*q=ret;
const char* str = NULL;
while(*src!='\0'){
if(*src=='%'&&(str = ngx_http_openidc_getTagValue(src, r, &src))){
strcpy(q, str);
q += strlen(str);
}else{
*q++=*src++;
}
}
*q='\0';
return ret;
}
static char* ngx_http_openidc_processTags(action_header *hdr, ngx_http_openidc_request_t *r, template_engine* tengine, char* originUri)
{
char* hdrValue = ngx_http_openidc_parseString(r->pool, apr_pstrdup(r->pool, hdr->value), r);
if(hdr->regex!=NULL&&hdrValue!=NULL){
array_header* matches=NULL;
rc_matchByStringsPattern(r->pool, hdr->regex, originUri, &matches);
hdrValue=te_templateString(r->pool,tengine,hdrValue,matches);
}
return (hdrValue!=NULL) ? apr_pstrdup(r->pool, hdrValue) : "";
}
static void ngx_http_openidc_setActionHeaders(ngx_http_openidc_request_t*r, apr_table_t* headers, array_header* actionHeaders, template_engine* tengine, char* originUri, int addHeaderToHttpRequest){
int i;
char* headerValue=NULL;
if(actionHeaders==NULL||actionHeaders->nelts<0 || headers==NULL) return;
for(i=0; i<actionHeaders->nelts; i++){
action_header* hdr = (action_header*)cu_getElement(actionHeaders, i);
if(hdr!=NULL){
switch (hdr->action) {
case header_add:
headerValue = ngx_http_openidc_processTags(hdr, r, tengine, originUri);
apr_table_add(headers, hdr->name, headerValue);
if(addHeaderToHttpRequest){
ngx_http_openidc_setHeader(r->httpRequest, hdr->name, headerValue);
}
break;
case header_append:
headerValue = ngx_http_openidc_processTags(hdr, r, tengine, originUri);
apr_table_merge(headers, hdr->name, headerValue);
if(addHeaderToHttpRequest){
ngx_http_openidc_setHeader(r->httpRequest, hdr->name, headerValue);
}
break;
// case header_merge:
// val = apr_table_get(headers, hdr->name);
// if (val == NULL) {
// headerValue = ngx_http_openidc_processTags(hdr, r, tengine, originUri);
// apr_table_add(headers, hdr->name, headerValue);
// if(addHeaderToHttpRequest){
// ngx_http_openidc_setHeader(r->httpRequest, hdr->name, headerValue);
// }
// } else {
// char *new_val = ngx_http_openidc_processTags(hdr, r, tengine, originUri);
// apr_size_t new_val_len = strlen(new_val);
// int tok_found = 0;
//
// /* modified version of logic in ap_get_token() */
// while (*val) {
// const char *tok_start;
//
// while (*val && apr_isspace(*val))
// ++val;
//
// tok_start = val;
//
// while (*val && *val != ',') {
// if (*val++ == '"')
// while (*val)
// if (*val++ == '"')
// break;
// }
//
// if (new_val_len == (apr_size_t)(val - tok_start)
// && !strncmp(tok_start, new_val, new_val_len)) {
// tok_found = 1;
// break;
// }
//
// if (*val)
// ++val;
// }
//
// if (!tok_found) {
// apr_table_merge(headers, hdr->name, new_val);
// }
// }
// break;
case header_set:
if (!strcasecmp(hdr->name, "Content-Type")) {
char* content_type = ngx_http_openidc_processTags(hdr, r, tengine, originUri);
if(content_type!=NULL){
r->httpRequest->headers_out.content_type.len = strlen(content_type);
r->httpRequest->headers_out.content_type.data = (u_char *)content_type;
}
}
headerValue = ngx_http_openidc_processTags(hdr, r, tengine, originUri);
apr_table_set(headers, hdr->name, headerValue);
if(addHeaderToHttpRequest){
ngx_http_openidc_setHeader(r->httpRequest, hdr->name, headerValue);
}
break;
case header_unset:
apr_table_unset(headers, hdr->name);
if(addHeaderToHttpRequest){
ngx_http_openidc_deleteHeader(r->httpRequest,hdr->name);
}
break;
case header_merge:
case header_echo:
case header_edit:
apr_table_add(r->headers_out,"X-HEADER-OPERATION","not supported");
break;
}
}
}
}
static int ngx_http_openidc_execCustomResponse(ngx_http_openidc_request_t *r, int responseCode, char* contentType, const char* responseBodyTemplate, template_engine* tengine) {
if(responseBodyTemplate!=NULL){
// process template
char* responseBody = ngx_http_openidc_parseString(r->pool, apr_pstrdup(r->pool, responseBodyTemplate), r);
/**
* Set the headers in response stream.
*/
apr_table_do(ngx_http_openidc_addResponseHeaderCallback, r->httpRequest, r->headers_out, NULL);
if(responseBody!=NULL){ // have response data from proxy
ngx_int_t rc;
ngx_buf_t *b;
ngx_chain_t out;
// return if contentType or body not found
if(contentType==NULL||responseBody==NULL) return NGX_HTTP_INTERNAL_SERVER_ERROR;
rc = ngx_http_discard_request_body(r->httpRequest);
if (rc != NGX_OK) {
return rc;
}
/* set the 'Content-type' header */
r->httpRequest->headers_out.content_type_len = strlen(contentType);
r->httpRequest->headers_out.content_type.len = strlen(contentType);
r->httpRequest->headers_out.content_type.data = (u_char *)contentType;
/* allocate a buffer for your response body */
b = ngx_pcalloc(r->httpRequest->pool, sizeof(ngx_buf_t));
if (b == NULL) {
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
/* attach this buffer to the buffer chain */
out.buf = b;
out.next = NULL;
//r->data = apr_psprintf(workerPool, "r->handler=%s retCode=%d", r->handler, retCode);
/* adjust the pointers of the buffer */
b->pos = (u_char*)responseBody;
b->last = (u_char*)responseBody + strlen(responseBody);
b->memory = 1; /* this buffer is in memory */
b->last_buf = 1; /* this is the last buffer in the buffer chain */
/* set the status line */
r->httpRequest->headers_out.status = ( responseCode > 0 ) ? responseCode : NGX_HTTP_OK;
r->httpRequest->headers_out.content_length_n = strlen(responseBody);
/* send the headers of your response */
rc = ngx_http_send_header(r->httpRequest);
if (rc == NGX_ERROR || rc > NGX_OK || r->httpRequest->header_only) {
return rc;
}
/* send the buffer chain of your response */
return ngx_http_output_filter(r->httpRequest, &out);
}
return NGX_HTTP_OK;
}
return NGX_DECLINED;
}
static int ngx_http_openidc_execPageAction(ngx_http_openidc_request_t *r, page_action* paction, char* originUri){
char* destUri=NULL;
array_header* matches=NULL;
int ret=0;
// AP_LOG_ERROR(r,"ngx_http_openidc_execPageAction");
if(paction!=NULL){
if(paction->isDebug==1){
char buf[256];
if(gethostname(buf,256)==0){
apr_table_add(r->headers_out,"X-DEBUG-BOX-IDENT",apr_pstrdup(r->pool,buf));
}
}
if (paction->requestHeaders!=NULL) {
ngx_http_openidc_setActionHeaders(r, r->headers_in, paction->requestHeaders, paction->templateEngineRef, originUri, TRUE);
}
if(paction->handler_internal!=NULL){
// AP_LOG_ERROR1(r,"paction->handler_internal=%s",paction->handler_internal);
r->handler=paction->handler_internal;
}
if(paction->type==action_callback) {
// send to target url if found in state
uri_components *url = &r->parsed_uri;
char* state = url_getParam(r->pool, url->query, "state");
if(state!=NULL&&strstr(state, "http")==0) {
unsigned char base64UrlDecoded[4096];
memset(base64UrlDecoded,'\0',4096);
base64Url_decode(base64UrlDecoded, state, strlen(state));
state = base64UrlDecoded;
}
if(state==NULL || (state!=NULL&&strstr(state, "http")==0)) {
char* scheme=(char*)apr_table_get(r->headers_in, "X-Forwarded-Proto");
if(scheme==NULL) { scheme=(char*)apr_table_get(r->headers_in, "X-REQUEST-SCHEME"); }
state=apr_pstrcat(r->pool, scheme,"://", r->hostname, NULL);
}
return ngx_http_openidc_execUri(r, state, FALSE, FALSE, NULL);
}
if(paction->uri!=NULL){
char* paction_uri = paction->uri;
//do url Templating
//destUri
if(paction->regex!=NULL){
rc_matchByStringsPattern(r->pool, paction->regex, originUri, &matches);
destUri=te_templateString(r->pool,paction->templateEngineRef,paction_uri,matches);
}
//ensure dest url is valid
if(destUri==NULL){
destUri=paction_uri;
}
//process dateTemplate
if(paction->advancedTemplate==TRUE){
destUri = ngx_http_openidc_parseString(r->pool, apr_pstrdup(r->pool, destUri), r);
}
if(paction->type==action_login){
destUri = apr_pstrcat(r->pool, destUri, "&nonce=", apr_table_get(r->headers_in, OIDC_RP_SESSIONID), NULL);
if(paction->base64UrlEncodeState) {
unsigned char base64UrlEncoded[4096];
memset(base64UrlEncoded,'\0',4096);
base64Url_encode(base64UrlEncoded, originUri, strlen(originUri));
destUri = apr_pstrcat(r->pool, destUri, "&state=", base64UrlEncoded, NULL);
}else {
destUri = apr_pstrcat(r->pool, destUri, "&state=", url_encode2(r->pool, originUri), NULL);
}
}
if (paction->responseHeaders!=NULL) {
ngx_http_openidc_setActionHeaders(r, r->headers_out, paction->responseHeaders, paction->templateEngineRef, originUri, FALSE);
}
ret = ngx_http_openidc_execUri(r,destUri,paction->isForward,paction->isPermanent,originUri);
return ret;
}else{ // allowing to set the response headers even if uri is not configured.
if (paction->responseHeaders!=NULL) {
ngx_http_openidc_setActionHeaders(r, r->headers_out, paction->responseHeaders, paction->templateEngineRef, originUri, FALSE);
}
if(paction->response!=NULL) {
return ngx_http_openidc_execCustomResponse(r, paction->response->code, paction->response->contentType, paction->response->body, paction->templateEngineRef);
}
}
}
return NGX_DECLINED;
}
int ngx_http_openidc_execUri(ngx_http_openidc_request_t* r, char* uri,int isForward, int isPermanent, char* originUri) {
if(uri!=NULL){
//execute
if(isForward){
if(originUri!=NULL){
ngx_http_openidc_setHeader(r->httpRequest, "X-MODAUTH-ORIGIN-URI", originUri);
}
// if(r->filename!=NULL){
// apr_table_setn(r->headers_in, "X-MODAUTH-ORIGIN-FILENAME", r->filename);
// }
int len = strlen(uri);
u_char* ngxUri = ngx_palloc(r->httpRequest->pool, len + 1);
ngx_cpystrn(ngxUri, (u_char*)uri, len + 1);
ngx_str_t internalRedirect = { len, ngxUri };
ngx_http_internal_redirect(r->httpRequest, &internalRedirect , &r->httpRequest->args);
return NGX_HTTP_OK;
}else if(isPermanent){
apr_table_setn(r->headers_out, "Location", uri);
return NGX_HTTP_MOVED_PERMANENTLY;
}else {
apr_table_setn(r->headers_out, "Location", uri);
return NGX_HTTP_MOVED_TEMPORARILY;
}
}
return NGX_DECLINED;
}
static void ngx_oidc_body_handler ( ngx_http_request_t *r ) {
ngx_int_t rc = NGX_OK;
// TODO: Read request body here
if (rc >= NGX_HTTP_SPECIAL_RESPONSE) {
ngx_http_finalize_request(r,0);
}
return;
}
static ngx_int_t ngx_http_openidc_getPostEntityINT(ngx_http_request_t *r) {
ngx_int_t rc;
//TODO: Add handler
rc = ngx_http_read_client_request_body(r, ngx_oidc_body_handler);
if (rc >= NGX_HTTP_SPECIAL_RESPONSE) {
return rc;
}
return NGX_DONE;
}
static char* ngx_http_openidc_getPostEntity(ngx_http_openidc_request_t* r, long* sz) {
char* buf=NULL;
ngx_http_openidc_getPostEntityINT(r->httpRequest);
*sz = 0;
return buf;
}
static char* ngx_http_openidc_getFullRequestUrl(ngx_http_openidc_request_t *req){
uri_components *url = &req->parsed_uri;
char* relativeUrl;
char* scheme=(char*)apr_table_get(req->headers_in, "X-Forwarded-Proto");
if(scheme==NULL) {
scheme=(char*)apr_table_get(req->headers_in, "X-REQUEST-SCHEME");
}
if(((strcmp(scheme,"http")!=0&&url->port!=80)||(strcmp(scheme,"https")!=0&&url->port!=443))&&url->port_str!=NULL){
relativeUrl=apr_pstrcat(req->pool,scheme,"://", req->hostname,":",url->port_str,req->unparsed_uri, NULL);
}else{
relativeUrl=apr_pstrcat(req->pool,scheme,"://", req->hostname,req->unparsed_uri, NULL);
}
return relativeUrl;
}
typedef int (*ngx_http_openidc_handler_func)(ngx_http_openidc_request_t*r, Config* config);
typedef struct ngx_http_openidc_handler_t{
ngx_http_openidc_handler_func handlerFunc;
}ngx_http_openidc_handler_t;
static const ngx_http_openidc_handler_t ngx_http_oidcHandlers[] = {
{oidc_index},
{oidc_version},
{oidc_rewrite_match},
{oidc_rewrite_pageactions},
{oidc_rewrite_actionmappings},
{oidc_config_core_status},
{oidc_headers}
};
static oauth_jwk* oauth_getSignatureValidationKey(pool*p, oauth_jwt_header* header, const char* issuer, const char* audience, void* data, char** error) {
oidc_config* oauthConfig = (oidc_config *)data;
int i;
if(header==NULL||header->algorithm==NULL||oauthConfig==NULL) {
if(error!=NULL) { *error = apr_pstrdup(p, "header or jwsKeys null"); }
return NULL;
}
oauth_jwk* jwk =oauthutil_newJWKObj(p);
if(header->keyID!=NULL) {
oidc_provider* oidcProvider = am_getOidcProviderByIssuer(oauthConfig->oidcProviderHash, issuer);
if(oidcProvider==NULL) {
if(error!=NULL) { *error = apr_pstrdup(p, "issuer is not configured"); }
return NULL;
}
oauth_jwskey* jwsKey = am_getJWSKeyByKeyID(oidcProvider->jwsKeys, header->keyID);
if(jwsKey==NULL) {
if(error!=NULL) { *error = apr_pstrdup(p, "jwsKey by keyID not found"); }
return NULL;
}
jwk->keyID = apr_pstrdup(p, jwsKey->id);
jwk->use = apr_pstrdup(p, jwsKey->use);
jwk->modulus = apr_pstrdup(p, jwsKey->modulus);
jwk->exponent = apr_pstrdup(p, jwsKey->exponent);
}else if(audience!=NULL){
relying_party* relyingParty = am_getRelyingPartyByClientID(oauthConfig->relyingPartyHash, audience);
if(relyingParty==NULL) {
if(error!=NULL) { *error = apr_pstrdup(p, "relyingParty not configured"); }
return NULL;
}
jwk->key = apr_pstrdup(p, relyingParty->clientSecret);
}
return jwk;
}
static const char* oauth_toupper(pool*p, char* src) {
if(src==NULL) return NULL;
char* s = apr_pstrdup(p, src);
char* cursor;
for ( cursor = s; *cursor!='\0'; cursor++ ) {
*cursor = toupper( (unsigned char)*cursor );
}
return s;
}
void ngx_http_openidc_addHeaderWithPrefix(ngx_http_openidc_request_t* r,
char* headerPrefix, int addHeaderToHttpRequest,
const char* header, const char* value) {
if(headerPrefix!=NULL) {
char* headerName = apr_psprintf(r->pool, "%s%s", headerPrefix, oauth_toupper(r->pool, (char*)header));
apr_table_set(r->headers_in, headerName, value);
if(addHeaderToHttpRequest) {
ngx_http_openidc_setHeader(r->httpRequest, headerName, value);
}
}
}
void ngx_http_openidc_processState(ngx_http_openidc_request_t* r) {
uri_components *url = &r->parsed_uri;
char tmp[OAUTH_IDTOKEN_MAX_SIZE];
// set session state
if(url_get_param(url->query,(char*)"session_state", tmp,OAUTH_IDTOKEN_MAX_SIZE)>0){
char* session_state = apr_pstrdup(r->pool,tmp);
if(session_state!=NULL) {
char* cookieDrop=cookie_cookieTemplateByName(r->pool, "session_state", session_state, NULL, -1, FALSE);
if(cookieDrop!=NULL){
apr_table_add(r->headers_out, "Set-Cookie", cookieDrop);
}
}
}
}
static ngx_inline ngx_uint_t
ngx_http_openidc_hash_str(u_char *src, size_t n)
{
ngx_uint_t key;
key = 0;
while (n--) {
key = ngx_hash(key, *src);
src++;
}
return key;
}
#define ngx_http_openidc_hash_literal(s) \
ngx_http_openidc_hash_str((u_char *) s, sizeof(s) - 1)
static ngx_int_t
ngx_http_openidc_set_content_headers(ngx_http_request_t *r, off_t contentLength, ngx_str_t contentType)
{
ngx_table_elt_t *h, *header;
u_char *p;
ngx_list_part_t *part;
ngx_http_request_t *pr;
ngx_uint_t i;
r->headers_in.content_length_n = contentLength;
if (ngx_list_init(&r->headers_in.headers, r->pool, 20,
sizeof(ngx_table_elt_t)) != NGX_OK) {
return NGX_ERROR;
}
// set content length
h = ngx_list_push(&r->headers_in.headers);
if (h == NULL) {
return NGX_ERROR;
}
h->key = ngx_http_openidc_content_length_header_key;
h->lowcase_key = ngx_pnalloc(r->pool, h->key.len);
if (h->lowcase_key == NULL) {
return NGX_ERROR;
}
ngx_strlow(h->lowcase_key, h->key.data, h->key.len);
r->headers_in.content_length = h;
p = ngx_palloc(r->pool, NGX_OFF_T_LEN);
if (p == NULL) {
return NGX_ERROR;
}
h->value.data = p;
h->value.len = ngx_sprintf(h->value.data, "%O", contentLength) - h->value.data;
h->hash = ngx_http_openidc_hash_literal("content-length");
// set content-type
h = ngx_list_push(&r->headers_in.headers);
if (h == NULL) {
return NGX_ERROR;
}
h->key = ngx_http_openidc_content_type_header_key;
h->lowcase_key = ngx_pnalloc(r->pool, h->key.len);
if (h->lowcase_key == NULL) {
return NGX_ERROR;
}
ngx_strlow(h->lowcase_key, h->key.data, h->key.len);
h->value = contentType;
h->hash = ngx_http_openidc_hash_literal("content-type");
r->headers_in.content_type = h;
return NGX_OK;
}
int ngx_http_openidc_processRequest(ngx_http_openidc_request_t* r, config_core* configCore,
oidc_config* oauthConfig, int addHeaderToHttpRequest, char* headerPrefix){
if(oauthConfig==NULL||oauthConfig->oidcProvider==NULL) return NGX_DECLINED;
if(oauthConfig->oidcProvider->issuer!=NULL) {
apr_hash_set(r->variableHash,"issuer", APR_HASH_KEY_STRING, apr_pstrdup(r->pool, oauthConfig->oidcProvider->issuer));
}
if(oauthConfig->oidcProvider->authorizationEndpoint!=NULL) {
apr_hash_set(r->variableHash,"authorization_endpoint", APR_HASH_KEY_STRING, apr_pstrdup(r->pool, oauthConfig->oidcProvider->authorizationEndpoint));
}
ngx_log_error(NGX_LOG_DEBUG, r->httpRequest->connection->log, 0, "oauth_processRequest");
uri_components *url = &r->parsed_uri;
char tmp[OAUTH_IDTOKEN_MAX_SIZE];
int oidcSessionFound = FALSE;
oauth_jwt_claim* claimObj = NULL;
char* error = NULL;
char* id_token=NULL;
char* authHeader = (char*)apr_table_get(r->headers_in, "Authorization");
if(authHeader==NULL) {
if(url_get_param(url->query,(char*)"id_token",tmp,OAUTH_IDTOKEN_MAX_SIZE)>0){
id_token = apr_pstrdup(r->pool,tmp);
}
}else{
char* start = strstr(authHeader, "Bearer ");
if(start!=NULL) {
id_token = url_decode2(r->pool, start + 7);
}
}
if(id_token!=NULL) {
oauth_jwt* jwt = oauthutil_parseAndValidateIDToken(r->pool, id_token, oauth_getSignatureValidationKey, oauthConfig, &error);
if(jwt==NULL||jwt->claim==NULL||jwt->claim->issuer==NULL||(strcmp(jwt->claim->issuer,oauthConfig->oidcProvider->issuer)!=0)) {
ngx_http_openidc_addHeaderWithPrefix(r, headerPrefix, addHeaderToHttpRequest, OIDC_STATUS_HEADER, "failure");
ngx_http_openidc_addHeaderWithPrefix(r, headerPrefix, addHeaderToHttpRequest, OIDC_DESC_HEADER, "oidc_parsing_failed");
if(error!=NULL) { apr_table_add(r->headers_out, "X-OIDC-ERROR", error); }
return NGX_DECLINED;
}
if(jwt->claim->issuer==NULL||oauthConfig->oidcProvider->issuer==NULL||(strcmp(jwt->claim->issuer,oauthConfig->oidcProvider->issuer)!=0)) {
ngx_http_openidc_addHeaderWithPrefix(r, headerPrefix, addHeaderToHttpRequest, OIDC_STATUS_HEADER, "failure");
ngx_http_openidc_addHeaderWithPrefix(r, headerPrefix, addHeaderToHttpRequest, OIDC_DESC_HEADER, "oidc_issuer_mismatch");
apr_table_add(r->headers_out, "X-OIDC-ERROR", "oidc_issuer_mismatch");
return NGX_DECLINED;
}
// check expiry
if(oauthConfig->oidcSession->age>0) {
jwt->claim->expiry = jwt->claim->issuedAt + (oauthConfig->oidcSession->age*86400);
}
if(configCore->cipherConfig!=NULL&&configCore->cipherConfig->crypto_passphrase!=NULL) {
const char* serializedClaim = oauthutil_serializeJWTClaimNoEncoding(r->pool, jwt->claim);
char* crypted = "";
int status = cu_encryptAndBase64urlEncode(r->pool, configCore->cipherConfig, &crypted, (unsigned char *) serializedClaim, &error);
if(status>0){
char* cookieDrop=cookie_cookieTemplate(r->pool, oauthConfig->oidcSession, crypted, NULL);
if(cookieDrop!=NULL){
apr_table_add(r->headers_out, "Set-Cookie", cookieDrop);
}
}else{
ngx_http_openidc_addHeaderWithPrefix(r, headerPrefix, addHeaderToHttpRequest, OIDC_STATUS_HEADER, "failure");
ngx_http_openidc_addHeaderWithPrefix(r, headerPrefix, addHeaderToHttpRequest, OIDC_DESC_HEADER, "oidc_parsing_failed");
apr_table_add(r->headers_out, "X-OIDC-ERROR", "oidc_claim_invalid");
return NGX_DECLINED;
}
}
claimObj = jwt->claim;
// set session state
ngx_http_openidc_processState(r);
}
if(claimObj==NULL&&configCore->cipherConfig!=NULL&&configCore->cipherConfig->crypto_passphrase!=NULL) { // check for cookie
char* oidc_session = cookie_getCookie(r->pool, r->headers_in, oauthConfig->oidcSession);
if(oidc_session!=NULL) {
char* decrypted = "";
int status = cu_base64urlDecodeAndDecrypt(r->pool, configCore->cipherConfig, &decrypted, oidc_session, &error);
if(status>0){
claimObj = oauthutil_deserializeJWTClaimNoDecoding(r->pool, decrypted);
}else{
ngx_http_openidc_addHeaderWithPrefix(r, headerPrefix, addHeaderToHttpRequest, OIDC_STATUS_HEADER, "failure");
ngx_http_openidc_addHeaderWithPrefix(r, headerPrefix, addHeaderToHttpRequest, OIDC_DESC_HEADER, "oidc_session_expired");
// delete current cookie
cookie_deleteCookie(r->pool, r->headers_in, oauthConfig->oidcSession, NULL);
return NGX_DECLINED;
}
oidcSessionFound = TRUE;
}
}
if(claimObj!=NULL) {
if(claimObj->expiry>apr_time_sec(apr_time_now())) {
ngx_http_openidc_addHeaderWithPrefix(r, headerPrefix, addHeaderToHttpRequest, OIDC_STATUS_HEADER, "success");
// set headers
if(claimObj->issuer!=NULL) {
// validate issuer
if(oauthConfig->oidcProvider->issuer!=NULL&&(strcmp(claimObj->issuer,oauthConfig->oidcProvider->issuer)!=0)) {
ngx_http_openidc_addHeaderWithPrefix(r, headerPrefix, addHeaderToHttpRequest, OIDC_STATUS_HEADER, "failure");
ngx_http_openidc_addHeaderWithPrefix(r, headerPrefix, addHeaderToHttpRequest, OIDC_DESC_HEADER, "oidc_issuer_mismatch");
apr_table_add(r->headers_out, "X-OIDC-ERROR", "oidc_issuer_mismatch");
return NGX_DECLINED;
}
ngx_http_openidc_addHeaderWithPrefix(r, headerPrefix, addHeaderToHttpRequest, OIDC_ISSUER_HEADER, claimObj->issuer);
}
if(claimObj->subject!=NULL) {
ngx_http_openidc_addHeaderWithPrefix(r, headerPrefix, addHeaderToHttpRequest, OIDC_SUBJECT_HEADER, claimObj->subject);
}
if(claimObj->audience!=NULL) {
ngx_http_openidc_addHeaderWithPrefix(r, headerPrefix, addHeaderToHttpRequest, OIDC_AUDIENCE_HEADER, claimObj->audience);
}
if(claimObj->roles!=NULL) {
char* rolesCsv = cu_serializeCsvFromStringArray(r->pool, claimObj->roles);
if(rolesCsv!=NULL) {
ngx_http_openidc_addHeaderWithPrefix(r, headerPrefix, addHeaderToHttpRequest, OIDC_ROLES_HEADER, rolesCsv);
}
}
if(claimObj->options!=NULL) {
//validate nonce
char* oidcNonce = apr_hash_get(claimObj->options,"nonce", APR_HASH_KEY_STRING);
char* rpSessionID = apr_table_get(r->headers_in, OIDC_RP_SESSIONID);
if(oidcNonce!=NULL&&rpSessionID!=NULL&&(strcmp(oidcNonce,rpSessionID)!=0)) {
ngx_http_openidc_addHeaderWithPrefix(r, headerPrefix, addHeaderToHttpRequest, OIDC_STATUS_HEADER, "failure");
ngx_http_openidc_addHeaderWithPrefix(r, headerPrefix, addHeaderToHttpRequest, OIDC_DESC_HEADER, "oidc_nonce_mismatch");
apr_table_add(r->headers_out, "X-OIDC-ERROR", "oidc_nonce_mismatch");
return NGX_DECLINED;
}
apr_hash_index_t *hi;
char* name=NULL,*value=NULL;
for (hi = apr_hash_first(r->pool, claimObj->options); hi; hi = apr_hash_next(hi)) {
apr_hash_this(hi,(const void**)&name, NULL, (void**)&value);
ngx_http_openidc_addHeaderWithPrefix(r, headerPrefix, addHeaderToHttpRequest, name, value);
}
}
}else{
ngx_http_openidc_addHeaderWithPrefix(r, headerPrefix, addHeaderToHttpRequest, OIDC_STATUS_HEADER, "failure");
ngx_http_openidc_addHeaderWithPrefix(r, headerPrefix, addHeaderToHttpRequest, OIDC_DESC_HEADER, "oidc_claim_expired");
if(oidcSessionFound==TRUE) {
cookie_deleteCookie(r->pool, r->headers_in, oauthConfig->oidcSession,NULL);
}
}
}
return NGX_DECLINED;
}
static ngx_int_t ngx_http_openidc_checkForAccess(ngx_http_request_t *httpRequest) {
char* hostname=NULL;
pool* p;
// care about only primary request
if (httpRequest != httpRequest->main) return NGX_DECLINED;
ngx_http_openidc_srv_conf_t* conf =(ngx_http_openidc_srv_conf_t*) ngx_http_get_module_srv_conf(httpRequest, ngx_http_openidc_module);
if(conf==NULL||conf->config==NULL||conf->config->configCore==NULL||conf->config->oidcConfig==NULL) return NGX_DECLINED;
// create a request pool.
if(apr_pool_create(&p, mainPool)!=APR_SUCCESS){
return NGX_DECLINED;
}
//sync config core
if(cfg_syncSelf(p,conf->config->configCore)>0){
ngx_http_openidc_postRefreshBind(p,conf->config);
}
//set method type
ngx_http_openidc_deleteHeader(httpRequest, (u_char *)"X-REQUEST-METHOD");
char* method = apr_pstrndup(p, (char*)httpRequest->method_name.data, httpRequest->method_name.len);
ngx_http_openidc_setHeader(httpRequest, "X-REQUEST-METHOD", method);
//set scheme
int isHttps = FALSE;
#if (NGX_SSL)
if (httpRequest->connection->ssl&&httpRequest->connection->ssl->connection) {
isHttps = TRUE;
}
#endif
ngx_http_openidc_deleteHeader(httpRequest, (u_char *)"X-REQUEST-SCHEME");
ngx_http_openidc_setHeader(httpRequest, "X-REQUEST-SCHEME", (isHttps) ? "https" : "http");
// create the request.
ngx_http_openidc_request_t* r = ngx_http_openidc_createRequest(p);
r->httpRequest = httpRequest;
//set url
char* uri = apr_pstrndup(r->pool, (char*)httpRequest->unparsed_uri.data, httpRequest->unparsed_uri.len);
r->unparsed_uri = apr_pstrdup(r->pool, uri);
while ((uri[0] == '/') && (uri[1] == '/')) {
++uri ;
}
apr_uri_parse(r->pool, uri, &r->parsed_uri);
r->uri = r->parsed_uri.path ? r->parsed_uri.path : apr_pstrdup(r->pool, "/");
//printf("%s, %d r->uri%s: internal=%d\n", __FILE__, __LINE__, r->uri, httpRequest->internal);
// set headers_in
ngx_http_openidc_setHeadersIn(httpRequest, r, conf->config->configCore->oidcHeaderPrefix);
//set hostname
ngx_table_elt_t* host = httpRequest->headers_in.host;
if (host!=NULL) {
hostname = apr_pstrndup(r->pool, (char*)host->value.data, host->value.len);
}else{
hostname = (char*)apr_table_get(r->headers_in, "Host");
}
r->hostname = hostname;
//client-ip
char* xff = (char*)apr_table_get(r->headers_in, "X-Forwarded-For");
if(xff==NULL) {
struct sockaddr_in *sin = (struct sockaddr_in *) httpRequest->connection->sockaddr;
if(sin!=NULL) {
r->connection_remote_ip = apr_pstrdup(r->pool, inet_ntoa(sin->sin_addr));
}else{
r->connection_remote_ip = apr_pstrdup(r->pool, "127.0.0.1");
}
}else{
char* second=NULL;
char* srccpy = apr_pstrdup(r->pool, xff);
r->connection_remote_ip = apr_strtok(srccpy, ",", &second);
}
// run preAuth
int retCode = ngx_http_openidc_preAuthorize(r, conf->config);
if(retCode!=NGX_DECLINED) {
apr_pool_destroy(p);
return retCode;
}
// generate unique sessionID;
// TODO: needs to be replace with ACS session
char* rpSessionID = cookie_getCookie(p, r->headers_in, conf->config->oidcConfig->rpSession);
if(rpSessionID==NULL) {
rpSessionID = cu_generateGuid(r->pool);
char* cookieDrop = cookie_cookieTemplate(r->pool, conf->config->oidcConfig->rpSession, rpSessionID, NULL);
if(cookieDrop!=NULL){
apr_table_add(r->headers_out, "Set-Cookie", cookieDrop);
}
}
apr_table_set(r->headers_in, OIDC_RP_SESSIONID, rpSessionID);
ngx_http_openidc_setHeader(r->httpRequest, OIDC_RP_SESSIONID, rpSessionID);
// Authorization phase
retCode = ngx_http_openidc_processRequest(r, conf->config->configCore, conf->config->oidcConfig, TRUE, conf->config->configCore->oidcHeaderPrefix);
if(retCode!=NGX_DECLINED) {
apr_table_do(ngx_http_openidc_addResponseHeaderCallback, httpRequest, r->headers_out, NULL);
retCode = ngx_http_openidc_sendResponse(r);
apr_pool_destroy(p);
return retCode;
}
// post Auth phase
path_mapping* pathmapping=am_getPathMapping_PostAuth(r->pool,conf->config->oidcConfig,r->unparsed_uri,r->connection_remote_ip,r->headers_in,NULL);
if(pathmapping!=NULL){
page_action* action=am_getMatchingPageAction(r->pool,pathmapping->pmactions,r->unparsed_uri,r->connection_remote_ip,r->headers_in,NULL);
char* originUri=ngx_http_openidc_getFullRequestUrl(r);
retCode = ngx_http_openidc_execPageAction(r, action,originUri);
apr_table_do(ngx_http_openidc_addResponseHeaderCallback, httpRequest, r->headers_out, NULL);
if(action!=NULL&&action->handler_internal!=NULL) {
r->handler = apr_pstrdup(r->pool, action->handler_internal);
int i;
int numHandlers=sizeof(ngx_http_oidcHandlers)/sizeof(ngx_http_openidc_handler_t);
for(i=0; i<numHandlers; i++){
retCode=(*ngx_http_oidcHandlers[i].handlerFunc)(r, conf->config);
if(retCode!=NGX_DECLINED) {
retCode = ngx_http_openidc_sendResponse(r);
break;
}
}
}
}
// release memory
apr_pool_destroy(p);
return retCode;
}
static ngx_int_t ngx_http_openidc_handler(ngx_http_request_t * httpRequest) {
char* hostname;
pool* p;
int retCode = NGX_DECLINED;
ngx_http_openidc_srv_conf_t* conf =(ngx_http_openidc_srv_conf_t*) ngx_http_get_module_srv_conf(httpRequest, ngx_http_openidc_module);
if(conf==NULL||conf->config==NULL||conf->config->configCore==NULL) return NGX_DECLINED;
// create a request pool.
if(apr_pool_create(&p, mainPool)!=APR_SUCCESS){
return NGX_DECLINED;
}
// create the request.
ngx_http_openidc_request_t* r = ngx_http_openidc_createRequest(p);
r->httpRequest = httpRequest;
//set url
char* uri = apr_pstrndup(r->pool, (char*)httpRequest->unparsed_uri.data, httpRequest->unparsed_uri.len);
r->unparsed_uri = apr_pstrdup(r->pool, uri);
if(rc_matchByStrings(p, "^/oidc", uri)!=0) {
// release memory
apr_pool_destroy(p);
return NGX_DECLINED;
}
while ((uri[0] == '/') && (uri[1] == '/')) {
++uri ;
}
apr_uri_parse(r->pool, uri, &r->parsed_uri);
r->uri = r->parsed_uri.path ? r->parsed_uri.path : apr_pstrdup(r->pool, "/");
// set headers_in
ngx_http_openidc_setHeadersIn(httpRequest, r, conf->config->configCore->oidcHeaderPrefix);
//set hostname
ngx_table_elt_t* host = httpRequest->headers_in.host;
if (host!=NULL) {
hostname = apr_pstrndup(r->pool, (char*)host->value.data, host->value.len);
}else{
hostname = (char*)apr_table_get(r->headers_in, "Host");
}
r->hostname = hostname;
//client-ip
struct sockaddr_in *sin = (struct sockaddr_in *) httpRequest->connection->sockaddr;
if(sin!=NULL) {
r->connection_remote_ip = apr_pstrdup(r->pool, inet_ntoa(sin->sin_addr));
}else{
r->connection_remote_ip = apr_pstrdup(r->pool, "127.0.0.1");
}
//sync config core
if(cfg_syncSelf(r->pool,conf->config->configCore)>0){
ngx_http_openidc_postRefreshBind(r->pool,conf->config);
}
path_mapping* pathmapping=am_getPathMapping_PostAuth(r->pool,conf->config->oidcConfig,r->unparsed_uri,r->connection_remote_ip,r->headers_in,NULL);
if(pathmapping!=NULL){
page_action* action=am_getMatchingPageAction(r->pool,pathmapping->pmactions,r->unparsed_uri,r->connection_remote_ip,r->headers_in,NULL);
if(action!=NULL&&action->handler_internal!=NULL) {
r->handler = apr_pstrdup(r->pool, action->handler_internal);
int i;
int numHandlers=sizeof(ngx_http_oidcHandlers)/sizeof(ngx_http_openidc_handler_t);
for(i=0; i<numHandlers; i++){
int retCode=(*ngx_http_oidcHandlers[i].handlerFunc)(r, conf->config);
if(retCode!=NGX_DECLINED) {
retCode = ngx_http_openidc_sendResponse(r);
break;
}
}
}
}
// release memory
apr_pool_destroy(p);
return retCode;
}
int oidc_index(ngx_http_openidc_request_t *r, Config* config) {
if (strcmp(r->handler, "oidc_index")) {
return NGX_DECLINED;
}
ngx_http_openidc_rputs("<HTML>\n",r);
ngx_http_openidc_rprintf(r,"<HEAD><TITLE>Tool Index</TITLE></HEAD>\n");
ngx_http_openidc_rputs("<BODY>\n",r);
ngx_http_openidc_rprintf(r,"<LEFT><H1>Tool Index</H1></LEFT><BR>\n");
ngx_http_openidc_rputs("<TABLE align='left'><tr>",r);
ngx_http_openidc_rputs("<td valign='top'><table><tr><td><b><font color='green'>Handlers</font></b></td></tr>",r);
ngx_http_openidc_rputs("<TR><TD><a href='/oidc/version'>Version Details</a></TD></TR>",r);
ngx_http_openidc_rputs("<TR><TD><a href='/oidc/config-status'>ConfigCore Details</a></TD></TR>",r);
ngx_http_openidc_rputs("<TR><TD><a href='/oidc/rewrite-pageactions'>OIDC Actions Details</a></TD></TR>",r);
ngx_http_openidc_rputs("<TR><TD><a href='/oidc/rewrite-actionmappings'>OIDC Config Details</a></TD></TR>",r);
ngx_http_openidc_rputs("<TR><TD><a href='/oidc/headers'>Show Headers</a></TD></TR>",r);
ngx_http_openidc_rputs("</table>",r);
ngx_http_openidc_rputs("</td>",r);
ngx_http_openidc_rputs("</table>",r);
ngx_http_openidc_rputs("</td>",r);
ngx_http_openidc_rputs("</tr></TABLE>",r);
ngx_http_openidc_rputs("</BODY></HTML>",r);
return NGX_OK;
}
int oidc_version(ngx_http_openidc_request_t *r, Config* config){
if (strcmp(r->handler, "oidc_version")) {
return NGX_DECLINED;
}
ngx_http_openidc_rputs("<HTML>\n",r);
ngx_http_openidc_rprintf(r,"<HEAD><TITLE>Version Info</TITLE></HEAD>\n");
ngx_http_openidc_rputs("<BODY>\n",r);
ngx_http_openidc_rputs("<TABLE>",r);
ngx_http_openidc_rprintf(r,"<TR><TD colspan='2'><b>Version Info</b></td></tr>\n");
ngx_http_openidc_rprintf1(r,"<TR><TD>Module: </td><td>%s</td></tr>\n",VERSION_ID);
ngx_http_openidc_rprintf1(r,"<TR><TD>LibCurl: </td><td>%s</td></tr>\n",hc_getInfo(r->pool));
ngx_http_openidc_rprintf1(r,"<TR><TD>RewriteCore: </td><td>PCRE/%s</td></tr>\n",rc_getInfo(r->pool));
ngx_http_openidc_rprintf1(r,"<TR><TD>Server: </td><td>%s</td></tr>\n",NGINX_VER);
ngx_http_openidc_rputs("</TABLE>",r);
return NGX_OK;
}
/*
* Rewrite Handlers
*/
static void rewrite_pageaction_display(ngx_http_openidc_request_t *r,page_action* pa,match_list* ml){
if(pa!=NULL){
ngx_http_openidc_rprintf1(r,"<td>%s",pa->id);
if(ml&&ml->name!=NULL){
ngx_http_openidc_rprintf1(r,"<br/>MatchList:%s",ml->name);
}
ngx_http_openidc_rprintf(r,"</td>");
ngx_http_openidc_rprintf1(r,"<td>%s</td>",pa->handler_internal);
ngx_http_openidc_rprintf1(r,"<td>%s</td>",SAFESTR(pa->uri));
ngx_http_openidc_rprintf1(r,"<td>%s</td>",SAFESTR(pa->regex));
ngx_http_openidc_rprintf1(r,"<td>%s</td>",pa->isForward!=1?"false":"true");
ngx_http_openidc_rprintf1(r,"<td>%s</td>",pa->isPermanent!=1?"false":"true");
ngx_http_openidc_rprintf1(r,"<td>%s</td>",pa->description);
}else{
ngx_http_openidc_rputs("<td colspan='5'> </td>",r);
}
}
static const char* authzoidc_getActionStr(header_actions action) {
if (action==header_add)
return "add";
else if (action==header_set)
return "set";
else if (action==header_append)
return "append";
else if (action==header_merge)
return "merge";
else if (action==header_unset)
return "unset";
else if (action==header_echo)
return "echo";
else if (action==header_edit)
return "edit";
return "null";
}
static const char* authzoidc_getActionTypeStr(action_types type) {
if (type==action_login)
return "login";
else if (type==action_denial)
return "denial";
else if (type==action_authorize)
return "authorize";
else if (type==action_callback)
return "callback";
return "null";
}
void authzoidc_displayActionHeader(ngx_http_openidc_request_t*r, action_header* hdr) {
if(hdr==NULL) return;
if(hdr->action==header_unset) {
ngx_http_openidc_rprintf2(r,"<tr><td> </td><td><li>%s {%s}</td></tr>",
authzoidc_getActionStr(hdr->action),hdr->name);
}
else {
if(hdr->regex!=NULL) {
ngx_http_openidc_rprintf4(r,"<tr><td> </td><td><li>%s {%s:%s} regex:%s</td></tr>",
authzoidc_getActionStr(hdr->action),hdr->name, hdr->value, hdr->regex);
}else{
ngx_http_openidc_rprintf3(r,"<tr><td> </td><td><li>%s {%s:%s}</td></tr>",
authzoidc_getActionStr(hdr->action),hdr->name, hdr->value);
}
}
}
static void rewrite_pageaction_displayAll(ngx_http_openidc_request_t *r,page_action* pa){
int i=0;
array_header* arry=NULL;
if(pa!=NULL){
ngx_http_openidc_rputs("<table>",r);
ngx_http_openidc_rprintf1(r,"<tr><td> </td><td><strong>%s</strong>",SAFESTR(pa->id));
if(pa->isDebug==1){ngx_http_openidc_rprintf(r," <font color='maroon'>DEBUG</font> ");}
if(pa->description!=NULL){ngx_http_openidc_rprintf1(r," [%s]</td></tr>",pa->description);}else{ngx_http_openidc_rprintf(r,"</td></tr>");}
if(pa->regex!=NULL){ngx_http_openidc_rprintf1(r,"<tr><td> </td><td>Regex: %s</td></tr>",SAFESTR(pa->regex));}
if(pa->oidcProvider!=NULL){ngx_http_openidc_rprintf1(r,"<tr><td> </td><td>OIDCProvider: %s</td></tr>",SAFESTR(pa->oidcProvider));}
if(pa->relyingParty!=NULL){ngx_http_openidc_rprintf1(r,"<tr><td> </td><td>RelyingParty: %s</td></tr>",SAFESTR(pa->relyingParty));}
if(pa->handler_internal!=NULL){ngx_http_openidc_rprintf1(r,"<tr><td> </td><td>Handler: %s</td></tr>",pa->handler_internal);}
if(pa->response!=NULL){ngx_http_openidc_rprintf3(r,"<tr><td> </td><td>Response[%d:%s]: <xmp>%s</xmp></td></tr>",pa->response->code, pa->response->contentType, pa->response->body);}
if(pa->uri!=NULL) { ngx_http_openidc_rprintf1(r,"<tr><td> </td><td>Uri:%s</td></tr>",pa->uri); }
ngx_http_openidc_rprintf1(r,"<tr><td> </td><td>isForward: %s</td></tr>",pa->isForward!=1?"false":"true");
ngx_http_openidc_rprintf1(r,"<tr><td> </td><td>isPermanent: %s</td></tr>",pa->isPermanent!=1?"false":"true");
ngx_http_openidc_rprintf1(r,"<tr><td> </td><td>type: %s</td></tr>", authzoidc_getActionTypeStr(pa->type));
if(pa->advancedTemplate==TRUE){
ngx_http_openidc_rprintf(r,"<tr><td> </td><td>advancedTemplate: true</td></tr>");
}
if(pa->base64UrlEncodeState==TRUE){
ngx_http_openidc_rprintf(r,"<tr><td> </td><td>base64UrlEncodeState: true</td></tr>");
}
if(pa->requestHeaders!=NULL){
ngx_http_openidc_rprintf1(r,"<tr><td> </td><td>RequestHeaders[%d]</td></tr>",pa->requestHeaders->nelts);
for(i=0; i<pa->requestHeaders->nelts; i++){
action_header* hdr = (action_header*)cu_getElement(pa->requestHeaders, i);
authzoidc_displayActionHeader(r,hdr);
}
}
if(pa->responseHeaders!=NULL){
ngx_http_openidc_rprintf1(r,"<tr><td> </td><td>ResponseHeaders[%d]</td></tr>",pa->responseHeaders->nelts);
for(i=0; i<pa->responseHeaders->nelts; i++){
action_header* hdr = (action_header*)cu_getElement(pa->responseHeaders, i);
authzoidc_displayActionHeader(r,hdr);
}
}
ngx_http_openidc_rputs("</table>",r);
}else{
ngx_http_openidc_rputs("NULL",r);
}
}
static void authzoidc_errorMessage(ngx_http_openidc_request_t *r){
ngx_http_openidc_rputs("<HTML>\n",r);
ngx_http_openidc_rprintf(r,"<HEAD><TITLE>Rewrite Page Actions - NULL</TITLE></HEAD>\n");
ngx_http_openidc_rprintf(r,"<body>ActionMappings are NULL</body>\n");
ngx_http_openidc_rprintf(r,"</html>\n");
}
static void authzoidc_pathmappings_displayMatchList(ngx_http_openidc_request_t *r,array_header* arr){
int i=0;
match_list* list=NULL;
if(arr!=NULL&&arr->nelts>0){
ngx_http_openidc_rprintf(r,"<br/>MatchLists:");
for(i=0;i<arr->nelts;i++){
list=(match_list*)cu_getElement(arr,i);
if(i!=0){ngx_http_openidc_rprintf(r,",");}
ngx_http_openidc_rprintf1(r,"%s",list->name);
}
}
}
static void authzoidc_pathmappings_display(ngx_http_openidc_request_t *r,array_header* arr,char* name){
int x=0;
path_mapping* pmap=NULL;
int i=0;
pathmapping_action* pmaction=NULL;
ngx_http_openidc_rprintf2(r,"<br><b><font color='blue'>Path Mappings - %s (%d)</font></b>",name,arr->nelts);
if(name,arr->nelts>0){
ngx_http_openidc_rputs("<TABLE border='1'>",r);
ngx_http_openidc_rputs("<tr><td>Path Regex</td><td>ID</td><td>handler</td><td>uri</td><td>Regex</td><td>isForward</td><td>isPermanent</td><td>Description</td></tr>",r);
for(x=0;x<arr->nelts;x++){
pmap=(path_mapping*)cu_getElement(arr,x);
if(pmap->pmactions!=NULL&&pmap->pmactions->nelts>0){
for(i=0;i<pmap->pmactions->nelts;i++){
if ( pmap->ignoreCase==TRUE ) {
ngx_http_openidc_rprintf1(r,"<tr><td><b>%s</b><br>IgnoreCase=true</br>",pmap->pathRegex);
}else{
ngx_http_openidc_rprintf1(r,"<tr><td><b>%s</b>",pmap->pathRegex);
}
authzoidc_pathmappings_displayMatchList(r,pmap->matchLists);
ngx_http_openidc_rprintf(r,"</td>");
pmaction=(pathmapping_action*)cu_getElement(pmap->pmactions,i);
rewrite_pageaction_display(r,pmaction->action,pmaction->matchList);
ngx_http_openidc_rputs("</td></tr>",r);
}
}
}
ngx_http_openidc_rputs("</TABLE>",r);
}
}
static void authzoidc_pathmapping_display_withnote(ngx_http_openidc_request_t *r,path_mapping* pathMap,page_action*action,char* note, apr_time_t startTime){
if(pathMap!=NULL){
ngx_http_openidc_rprintf2(r,"<tr><td>%s</td><td>%d us</td>",note, apr_time_now()-startTime);
ngx_http_openidc_rprintf1(r,"<td><font color='darkgreen'>%s</font>",pathMap->pathRegex);
authzoidc_pathmappings_displayMatchList(r,pathMap->matchLists);
ngx_http_openidc_rprintf(r,"</td>");
rewrite_pageaction_display(r,action,NULL);
}else{
ngx_http_openidc_rprintf1(r,"<tr><td>%s</td><td>(Default)</td>",note);
rewrite_pageaction_display(r,NULL,NULL);
}
ngx_http_openidc_rputs("</tr>",r);
}
static int authzoidc_printTableCallBack(void *rec, const char *key, const char *value){
ngx_http_openidc_request_t *r=(ngx_http_openidc_request_t*)rec;
if(strstr(key,"Cookie")==0) {
ngx_http_openidc_rprintf2(r,"<tr><td>%s = </td><td>%s</td></tr>\r\n",key,value);
}
return 1;
}
static void authzoidc_printTable(ngx_http_openidc_request_t *r,apr_table_t* table){
if(table!=NULL&&!apr_is_empty_table(table)){
ngx_http_openidc_rputs("<TABLE><tr><td valign='top'>Table Headers:</td><td><table>",r);
apr_table_do(authzoidc_printTableCallBack,(void*)r,table,NULL);
ngx_http_openidc_rputs("</table></td></tr></TABLE>",r);
}
}
static int authzoidc_pathMatchSection(ngx_http_openidc_request_t *r, Config* config){
oidc_config* actm=config->oidcConfig;
uri_components *url = &r->parsed_uri;
path_mapping* pathMap=NULL;
char* pathParam=NULL;
char* overlayParam=NULL;
char* headersInParam=NULL;
char* ipParam=NULL;
apr_table_t* headers_in=NULL, *r_headers=NULL;
page_action*action=NULL;
apr_time_t startTime;
if(actm==NULL){
authzoidc_errorMessage(r);
return NGX_OK;
}
pathParam=url_getParam(r->pool,url->query,"pathParam");
headersInParam=url_getParam(r->pool,url->query,"headersInParam");
ipParam=url_getParam(r->pool,url->query,"ipParam");
if(ipParam==NULL){
ipParam=r->connection_remote_ip;
}
ngx_http_openidc_rputs("Check Path Mapping:<br>",r);
ngx_http_openidc_rputs("<form><table>",r);
ngx_http_openidc_rprintf1(r,"<tr><td>IP:</td><td><input type='text' name='ipParam' size='30' value='%s'></td></tr>\r\n",SAFESTRBLANK(ipParam));
ngx_http_openidc_rprintf1(r,"<tr><td>Path:</td><td><input type='text' name='pathParam' size='80' value='%s'/></td></tr>",SAFESTRBLANK(pathParam));
ngx_http_openidc_rprintf1(r,"<tr><td valign='top'>HeadersIn:</td><td><textarea name='headersInParam' cols='60' rows='4'>%s</textarea></td></tr>\r\n",SAFESTRBLANK(headersInParam));
ngx_http_openidc_rputs("<tr><td colspan='2'><INPUT type='submit' value='Match' /></td></tr>\n",r);
ngx_http_openidc_rputs("</table></form>\n",r);
if(pathParam!=NULL){
headers_in=cu_parseNvpTableFromCsv(r->pool,"\n",":",headersInParam);
if(overlayParam!=NULL){
if(headers_in!=NULL){
//headers_in=apr_table_overlay(r->pool,headers_in,r->headers_in);
//apr_table_compress(headers_in,APR_OVERLAP_TABLES_SET);
r_headers=apr_table_copy(r->pool,r->headers_in);
apr_table_overlap(r_headers,headers_in,APR_OVERLAP_TABLES_SET);
headers_in=r_headers;
}else{
headers_in=r->headers_in;
}
}
ngx_http_openidc_rputs("<TABLE border='1' cellspacing='0' bordercolor='blue'>",r);
//postauth
startTime=apr_time_now();
pathMap=am_getPathMapping_PostAuth(r->pool,actm,pathParam,ipParam,headers_in,NULL);
if(pathMap!=NULL){
action=am_getMatchingPageAction(r->pool,pathMap->pmactions,r->unparsed_uri,ipParam,headers_in,NULL);
if(action!=NULL){authzoidc_pathmapping_display_withnote(r,pathMap,action,"PostAuth",startTime);}
}
ngx_http_openidc_rputs("</TABLE>",r);
authzoidc_printTable(r,headers_in);
}
return 1;
}
static char* authzoidc_getMatchIpDetails(pool*p,match_ip*ip){
char* ipDetails;
if(ip==NULL||ip->ip==NULL) return NULL;
ipDetails=apr_pstrdup(p,ip->ip);
if(ip->negate==TRUE){ipDetails=apr_pstrcat(p,ipDetails,"\tnegate=true",NULL);}
if(ip->isRegex==FALSE){ipDetails=apr_pstrcat(p,ipDetails,"\tisregex=false",NULL);};
return ipDetails;
}
static char* authzoidc_getMatchPathDetails(pool*p,match_path*path){
char* pathDetails;
if(path==NULL||path->path==NULL) return NULL;
pathDetails=apr_pstrdup(p,path->path);
if(path->negate==TRUE){pathDetails=apr_pstrcat(p,pathDetails,"\tnegate=true",NULL);}
return pathDetails;
}
static char* authzoidc_getHeaderDetails(pool*p,match_list_header*hdr){
char* hdrDetails;
if(hdr==NULL) return NULL;
hdrDetails=apr_pstrcat(p,hdr->name,"=",hdr->value,NULL);
if(hdr->delimAnd){hdrDetails=apr_pstrcat(p,hdrDetails,"\tdelimAnd=\"",hdr->delimAnd,"\"",NULL);}
if(hdr->negate==TRUE){hdrDetails=apr_pstrcat(p,hdrDetails,"\tnegate=true",NULL);}
if(hdr->isRegex==FALSE){hdrDetails=apr_pstrcat(p,hdrDetails,"\tisregex=false",NULL);};
return hdrDetails;
}
static char* authzoidc_timeString(pool*p, time_t t, const char* def){
if(t<=0) return (char*)def;
char tmp[40]={0};
ctime_r(&t, tmp);
return apr_psprintf(p, "%s[%d]", tmp, t);
}
static char* authzoidc_getEventColor(pool*p, match_event*e){
char*color=NULL;
time_t currentTime = time(NULL);
if(( e->start < currentTime )
&& ( currentTime < ( (e->end>0) ? e->end : TIME_MAX) )){
color = apr_pstrdup(p, "green");
}else if(e->start > currentTime){//Future events
color = apr_pstrdup(p, "yellow");
}else{//Past events
color = apr_pstrdup(p, "red");
}
return color;
}
static void authzoidc_printMatchListMatch(ngx_http_openidc_request_t *r,match_list_match* match){
int i=0;
//match_list_match_nvp* nvp=NULL;
match_list_header* hdr=NULL;
match_list_env* env=NULL;
if(match==NULL) return;
ngx_http_openidc_rprintf(r,"<table><tr><td valign='top'><li/></td>");
if(match->cascade==FALSE){
ngx_http_openidc_rprintf(r,"<td valign='top'>Cascade:</td><td align='left'>false</td></tr><tr><td> </td>");
}
if(match->host!=NULL){
ngx_http_openidc_rprintf1(r,"<td valign='top'>Host:</td><td align='left'>%s</td></tr><tr><td> </td>", match->host);
}
if(match->ip!=NULL){
ngx_http_openidc_rprintf1(r,"<td valign='top'>IP:</td><td align='left'>%s</td></tr><tr><td> </td>",
authzoidc_getMatchIpDetails(r->pool,match->ip));
}
if(match->path!=NULL){
ngx_http_openidc_rprintf1(r,"<td valign='top'>Path:</td><td align='left'>%s</td></tr><tr><td> </td>",
authzoidc_getMatchPathDetails(r->pool,match->path));
}
if(match->event!=NULL){
ngx_http_openidc_rprintf3(r, "<td valign='top'>Event:</td><td valign='top'><font color='%s'><li/></td><td><table><tr><td><i/>Start:</td><td>%s</td><td><i/>End:</td><td>%s</td></font></tr></tr></table></td></tr><td> </td>",
authzoidc_getEventColor(r->pool, match->event),
authzoidc_timeString(r->pool, match->event->start, "Unknown"),
authzoidc_timeString(r->pool, match->event->end, "Never") );
}
if(match->headerList!=NULL&&match->headerList->nelts>0){
ngx_http_openidc_rprintf(r,"<td valign='top'>Headers:</td><td>");
ngx_http_openidc_rprintf(r,"<table>");
for(i=0;i<match->headerList->nelts;i++){
hdr=(match_list_header*)cu_getElement(match->headerList,i);
ngx_http_openidc_rprintf1(r,"<tr><td valign='top'>%s</td></tr>",authzoidc_getHeaderDetails(r->pool,hdr));
}
ngx_http_openidc_rprintf(r,"</table>");
ngx_http_openidc_rprintf(r,"</td></tr>");
}
ngx_http_openidc_rprintf(r,"</table>");
}
static void authzoidc_matchLists(ngx_http_openidc_request_t *r,oidc_config* actm){
match_list* list=NULL;
shapr_hash_index_t * hi=NULL;
match_list_match* match=NULL;
int i=0;
void* val=NULL;
unsigned int cnt=0;
ngx_http_openidc_rputs("<TABLE>",r);
cnt=shapr_hash_count(actm->match_lists);
ngx_http_openidc_rprintf1(r,"<tr><td colspan='4'><font color='maroon'><strong>MatchLists [%d]:</strong></font></td></tr>",cnt);
if(cnt>0){
for (hi = shapr_hash_first(r->pool,actm->match_lists); hi; hi = shapr_hash_next(hi)) {
shapr_hash_this(hi, NULL, NULL, &val);
if(val!=NULL){
list=(match_list*)val;
ngx_http_openidc_rprintf1(r,"<tr><td width='15'> </td><td> </td><td valign='top'>%s</td><td>",list->name);
ngx_http_openidc_rputs("<table>",r);
for(i=0;i<list->list->nelts;i++){
match=(match_list_match*)cu_getElement(list->list,i);
ngx_http_openidc_rputs("<tr><td>",r);
authzoidc_printMatchListMatch(r,match);
ngx_http_openidc_rputs("</td></tr>",r);
}
ngx_http_openidc_rputs("</table>",r);
ngx_http_openidc_rputs("</td></tr>",r);
}
}
}
ngx_http_openidc_rputs("</TABLE>",r);
}
static void authzoidc_displayTemplateEngine(ngx_http_openidc_request_t *r,template_engine* tengine){
shapr_hash_index_t* hi;
template_eng_livetemplate* lt=NULL;
void* val, * key;
ngx_http_openidc_rputs("<TABLE>",r);
ngx_http_openidc_rprintf1(r,"<tr><td>Template Engine:</td><td>%s</td></tr>",tengine!=NULL?"VALID":"FAIL");
if(tengine!=NULL){
ngx_http_openidc_rputs("<tr><td colspan='2'><TABLE>",r);
ngx_http_openidc_rprintf(r,"<tr><td>Token:</td><td> Description</td><td> Test Result</td></tr>");
for(hi=shapr_hash_first(r->pool,tengine->templateHash);hi;hi=shapr_hash_next(hi)){
shapr_hash_this(hi,(const void**)&key,NULL,&val);
lt=(template_eng_livetemplate*)val;
if(lt->engineTemplate!=NULL){
ngx_http_openidc_rprintf2(r,"<tr><td><li/> %s:</td><td> %s</td></tr>",lt->engineTemplate->id,lt->engineTemplate->description);
}else{
ngx_http_openidc_rprintf(r,"<tr><td colspan='3'><li/> NULL Template</td></tr>");
}
}
ngx_http_openidc_rputs("<TABLE></td></tr>",r);
}
ngx_http_openidc_rputs("<TABLE>",r);
}
static void authzoidc_displayOidcProviders(ngx_http_openidc_request_t *r, shapr_hash_t* oidcProviderHash){
match_list* list=NULL;
shapr_hash_index_t * hi=NULL;
oidc_provider* oidcProvider=NULL;
int i=0;
void* val=NULL;
unsigned int cnt=0;
if(oidcProviderHash==NULL) return;
ngx_http_openidc_rputs("<TABLE>",r);
cnt=shapr_hash_count(oidcProviderHash);
ngx_http_openidc_rprintf1(r,"<tr><td colspan='4'><font color='maroon'><strong>OIDCProviders [%d]:</strong></font></td></tr>",cnt);
if(cnt>0){
for (hi = shapr_hash_first(r->pool,oidcProviderHash); hi; hi = shapr_hash_next(hi)) {
shapr_hash_this(hi, NULL, NULL, &val);
if(val!=NULL){
oidcProvider=(oidc_provider*)val;
if(oidcProvider!=NULL) {
ngx_http_openidc_rprintf1(r,"<tr><td><font color='black'><strong>ID</strong></font><td>%s</td></td></tr>", oidcProvider->id);
ngx_http_openidc_rprintf1(r,"<tr><td>Issuer</td><td>%s</td></tr>",oidcProvider->issuer);
ngx_http_openidc_rprintf1(r,"<tr><td>MetadataUrl</td><td>%s</td></tr>",oidcProvider->metadataUrl);
ngx_http_openidc_rprintf1(r,"<tr><td>AuthorizationEndpoint</td><td>%s</td></tr>",oidcProvider->authorizationEndpoint);
ngx_http_openidc_rprintf1(r,"<tr><td>JwksUri</td><td>%s</td></tr>",oidcProvider->jwksUri);
ngx_http_openidc_rprintf1(r,"<tr><td>Default</td><td>%s</td></tr>",BOOLTOSTR(oidcProvider->isDefault));
}
ngx_http_openidc_rputs("</td></tr>",r);
}
}
}
ngx_http_openidc_rputs("</TABLE>",r);
}
static void authzoidc_displayRelyingParties(ngx_http_openidc_request_t *r, shapr_hash_t* relyingPartyHash){
match_list* list=NULL;
shapr_hash_index_t * hi=NULL;
relying_party* relyingParty=NULL;
int i=0;
void* val=NULL;
unsigned int cnt=0;
if(relyingPartyHash==NULL) return;
ngx_http_openidc_rputs("<TABLE>",r);
cnt=shapr_hash_count(relyingPartyHash);
ngx_http_openidc_rprintf1(r,"<tr><td colspan='4'><font color='maroon'><strong>RelyingParties [%d]:</strong></font></td></tr>",cnt);
if(cnt>0){
for (hi = shapr_hash_first(r->pool,relyingPartyHash); hi; hi = shapr_hash_next(hi)) {
shapr_hash_this(hi, NULL, NULL, &val);
if(val!=NULL){
relyingParty=(relying_party*)val;
if(relyingParty!=NULL) {
ngx_http_openidc_rprintf1(r,"<tr><td><font color='black'><strong>id</strong></font><td>%s</td></td></tr>", relyingParty->id);
ngx_http_openidc_rprintf1(r,"<tr><td>Description</td><td>%s</td></tr>",relyingParty->description);
ngx_http_openidc_rprintf1(r,"<tr><td>ClientID</td><td>%s</td></tr>",relyingParty->clientID);
ngx_http_openidc_rprintf1(r,"<tr><td>ClientSecret</td><td>********</td></tr>",relyingParty->clientSecret);
ngx_http_openidc_rprintf1(r,"<tr><td>RedirectUri</td><td>%s</td></tr>",relyingParty->redirectUri);
ngx_http_openidc_rprintf1(r,"<tr><td>Issuer</td><td>%s</td></tr>",relyingParty->issuer);
ngx_http_openidc_rprintf1(r,"<tr><td>ValidateNonce</td><td>%s</td></tr>",BOOLTOSTR(relyingParty->validateNonce));
ngx_http_openidc_rprintf1(r,"<tr><td>PostLoginDefaultLandingPage</td><td>%s</td></tr>",relyingParty->postLoginDefaultLandingPage);
}
ngx_http_openidc_rputs("</td></tr>",r);
}
}
}
ngx_http_openidc_rputs("</TABLE>",r);
}
int oidc_rewrite_actionmappings(ngx_http_openidc_request_t *r, Config *config) {
if (strcmp(r->handler, "oidc_rewrite_actionmappings")) {
return NGX_DECLINED;
}
oidc_config* actm=config->oidcConfig;
int i=0;
pathmapping_action* pmaction=NULL;
array_header* arr;
if(actm==NULL){
authzoidc_errorMessage(r);
return NGX_OK;
}
//begin logic
ngx_http_openidc_rputs("<HTML>\n",r);
ngx_http_openidc_rprintf(r,"<HEAD><TITLE>OIDC Config</TITLE></HEAD>\n");
ngx_http_openidc_rputs("<BODY>\n",r);
authzoidc_displayOidcProviders(r, actm->oidcProviderHash);
authzoidc_displayRelyingParties(r, actm->relyingPartyHash);
ngx_http_openidc_rprintf(r,"<TABLE><tr><td><font color='black'><strong>Session</strong></font></td></tr>");
ngx_http_openidc_rprintf2(r,"<tr><td>RelyingParty</td><td>name=%s</td><td>expiry(days)=%d</td></tr>",actm->rpSession->name, actm->rpSession->age);
ngx_http_openidc_rprintf2(r,"<tr><td>OIDCProvider</td><td>name=%s</td><td>expiry(days)=%d</td></tr></TABLE>",actm->oidcSession->name, actm->oidcSession->age);
if(actm->accessToken) {
ngx_http_openidc_rprintf2(r,"<tr><td>AccessTokenCookie</td><td>name=%s</td><td>expiry(days)=%d</td></tr>",actm->accessToken->name, actm->accessToken->age);
}
authzoidc_displayTemplateEngine(r,actm->templateEngine);
//do path matching
authzoidc_pathMatchSection(r,config);
authzoidc_pathmappings_display(r,actm->path_mappings->postauth,"PostAuth");
//display matchlists
authzoidc_matchLists(r,actm);
// authzoidc_printTable(r,r->headers_in);
ngx_http_openidc_rputs("</BODY>",r);
ngx_http_openidc_rputs("</HTML>\n",r);
return NGX_OK;
}
int oidc_rewrite_pageactions(ngx_http_openidc_request_t *r, Config *config) {
if (strcmp(r->handler, "oidc_rewrite_pageactions")) {
return NGX_DECLINED;
}
shapr_hash_index_t * hi=NULL;
void* val=NULL;
const void *key=NULL;
page_action* paction=NULL;
oidc_config* actm=config->oidcConfig;
uri_components *url = &r->parsed_uri;
if(actm==NULL){
authzoidc_errorMessage(r);
return NGX_OK;
}
//begin logic
ngx_http_openidc_rputs("<HTML>\n",r);
ngx_http_openidc_rputs("<HEAD><TITLE>Rewrite Page Actions</TITLE></HEAD>\n",r);
ngx_http_openidc_rputs("<BODY>\n",r);
ngx_http_openidc_rputs("<TABLE border='0'>",r);
ngx_http_openidc_rputs("<tr><td> </td><td>",r);
for (hi = shapr_hash_first(r->pool,actm->page_actions); hi; hi = shapr_hash_next(hi)) {
shapr_hash_this(hi, &key, NULL, &val);
if(key!=NULL&&val!=NULL){
paction=(page_action*)val;
rewrite_pageaction_displayAll(r,paction);
ngx_http_openidc_rputs("<br>",r);
// ngx_http_openidc_rprintf1(r,"<td>%s</td>",key);
}
}
ngx_http_openidc_rputs("</td></tr></TABLE>",r);
ngx_http_openidc_rputs("</BODY>",r);
ngx_http_openidc_rputs("</HTML>\n",r);
return NGX_OK;
}
int oidc_rewrite_match(ngx_http_openidc_request_t *r, Config *config) {
if (strcmp(r->handler, "oidc_rewrite_match")) {
return NGX_DECLINED;
}
char* regexParam=NULL, *valueParam=NULL, *templateParam=NULL;
uri_components *url = &r->parsed_uri;
char* rcoreRet=NULL;
apr_time_t startTime;
//rewrite vars to support templating
array_header* pmatches=NULL;
char* elt=NULL;
int i=0;
//begin logic
regexParam=url_getParam(r->pool,url->query,"regexParam");
valueParam=url_getParam(r->pool,url->query,"valueParam");
templateParam=url_getParam(r->pool,url->query,"templateParam");
//display
ngx_http_openidc_rputs("<HTML>\n",r);
ngx_http_openidc_rputs("<HEAD><TITLE>Rewrite Match Testing</TITLE></HEAD>\n",r);
ngx_http_openidc_rputs("<BODY>\n",r);
ngx_http_openidc_rputs("<TABLE>",r);
ngx_http_openidc_rprintf1(r,"<tr><td>RewriteCore: </td><td>%s</td></tr>",rc_getInfo(r->pool));
ngx_http_openidc_rputs("<form>",r);
ngx_http_openidc_rputs("<tr><td>Value(Url): </td><td>",r);
ngx_http_openidc_rprintf1(r,"<input type='text' value='%s' name='valueParam' size='180'/>\r\n",
(valueParam!=NULL) ? cu_nonHtmlToHtmlChar(r->pool, valueParam) : SAFESTRBLANK(valueParam));
ngx_http_openidc_rputs("</td></tr>\r\n",r);
ngx_http_openidc_rputs("<tr><td>Regex: </td><td>",r);
ngx_http_openidc_rprintf1(r,"<input type='text' value='%s' name='regexParam' size='180'/>\r\n",
(regexParam!=NULL) ? cu_nonHtmlToHtmlChar(r->pool, regexParam) : SAFESTRBLANK(regexParam));
ngx_http_openidc_rputs("</td></tr>\r\n",r);
ngx_http_openidc_rputs("<tr><td>Template: </td><td>",r);
ngx_http_openidc_rprintf1(r,"<input type='text' value='%s' name='templateParam' size='180'/>\r\n",SAFESTRBLANK(templateParam));
ngx_http_openidc_rputs("</td></tr>\r\n",r);
ngx_http_openidc_rputs("<tr><td></td><td><INPUT type='submit' value='go!' /></td></tr>\r\n</form>",r);
if(regexParam!=NULL&&valueParam!=NULL){
startTime=apr_time_now();
rcoreRet=rc_matchByStringsPatternReturnDetails(r->pool,regexParam,valueParam,&pmatches);
startTime=apr_time_now()-startTime;
ngx_http_openidc_rprintf1(r,"<tr><td>Result: (%ld usecs)</td><td>",startTime);
if(rcoreRet!=NULL){
ngx_http_openidc_rprintf1(r,"FAILURE: %s</td></tr>",rcoreRet);
}else{
ngx_http_openidc_rputs("SUCCESS</td></tr>",r);
}
if(templateParam!=NULL){
ngx_http_openidc_rprintf1(r,"<tr><td></strong>Template Engine String</strong>:</td><td>%s</td></tr>",SAFESTR(te_templateString(r->pool,config->oidcConfig->templateEngine,templateParam,pmatches)));
}
if(pmatches!=NULL){
ngx_http_openidc_rprintf1(r,"<tr><td colspan='2'></strong>Found Matches (%d)</strong></td></tr>",pmatches->nelts);
if(pmatches->nelts>0){
ngx_http_openidc_rprintf(r,"<tr><td> </td><td><table>");
for(i=0;i<pmatches->nelts;i++){
elt=cu_getElement(pmatches,i);
ngx_http_openidc_rprintf2(r,"<tr><td><strong>$%d: </strong></td><td>%s</td></tr>",i,
cu_nonHtmlToHtmlChar(r->pool, elt));
}
ngx_http_openidc_rprintf(r,"</table></td></tr>");
}
}
}
ngx_http_openidc_rputs("</TABLE>",r);
ngx_http_openidc_rputs("</BODY>",r);
ngx_http_openidc_rputs("</HTML>\n",r);
return NGX_OK;
}
static int oidc_section_SharedHeap(const char* title, ngx_http_openidc_request_t *r,shared_heap* sheap){
shared_page* pg;
segment_header* seg;
int x;
if(sheap!=NULL){
ngx_http_openidc_rprintf1(r,"\n<TR><TD colspan='2'><b>Shared Heap Page - %s </b></TD></TR>",title);
ngx_http_openidc_rprintf1(r,"<TR><TD>TimeStamp: </TD><TD>%s</TD></TR>",ctime(&(sheap->timestamp)));
ngx_http_openidc_rprintf1(r,"<TR><TD>FlipCount: </TD><TD>%d</TD></TR>",sheap->flipcount);
ngx_http_openidc_rprintf1(r,"<TR><TD>Cursor byte: </TD><TD>%d</TD></TR>",shdata_cursor(sheap));
ngx_http_openidc_rprintf1(r,"<TR><TD>Local Seg: </TD><TD>%d</TD></TR>",sheap->local_segment);
ngx_http_openidc_rprintf1(r,"<TR><TD>apr_shm_t* valid: </TD><TD>%s</TD></TR>",sheap->shm_main==NULL?"FALSE":"TRUE");
ngx_http_openidc_rprintf(r,"<TR><TD colspan='2'> <TD></TR>");
if(sheap->page!=NULL){
pg=sheap->page;
ngx_http_openidc_rprintf(r,"\n<TR><TD colspan='2'><b>------Shared Portion--|</b></TD></TR>");
ngx_http_openidc_rprintf(r,"\n<TR><TD colspan='2'>");
ngx_http_openidc_rprintf(r,"<TABLE>");
ngx_http_openidc_rprintf1(r,"\t<TR><TD width='5'> </TD><TD>TimeStamp: </TD><TD>%s</TD></TR>",ctime(&(pg->timestamp)));
ngx_http_openidc_rprintf1(r,"\t<TR><TD width='5'> </TD><TD>SegmentSize: </TD><TD>%d</TD></TR>",pg->segmentsize);
ngx_http_openidc_rprintf1(r,"\t<TR><TD width='5'> </TD><TD>FlipCount: </TD><TD>%d</TD></TR>",pg->flipcount);
ngx_http_openidc_rprintf1(r,"\t<TR><TD width='5'> </TD><TD>ItemsMax: </TD><TD>%d</TD></TR>",pg->itemmax);
ngx_http_openidc_rprintf2(r,"\t<TR><TD width='5'> </TD><TD>Front/Back Segment: <TD>%d/%d</TD></TR>",pg->frontsegment,pg->backsegment);
seg=&(sheap->page->segments[sheap->page->frontsegment]);
ngx_http_openidc_rprintf1(r,"\t<TR><TD width='5'> </TD><TD colspan='2'>* Items(%d)---</TD></TR>",seg->itemcount);
ngx_http_openidc_rprintf(r,"\t<TR><TD width='5'> </TD><TD colspan='2'>");
if(seg->itemcount>0){
ngx_http_openidc_rprintf(r,"\t\t<TABLE>");
for(x=0;x<seg->itemcount;x++){
ngx_http_openidc_rprintf1(r,"<TR><TD>ID: </TD><TD>%s</TD></TR>",seg->items[x].ITEMID);
ngx_http_openidc_rprintf1(r,"<TR><TD>INFO: </TD><TD>%s</TD></TR>",seg->items[x].INFO);
ngx_http_openidc_rprintf1(r,"<TR><TD>Offset: </TD><TD>%d</TD>",seg->items[x].offset);
ngx_http_openidc_rprintf1(r,"<TR><TD>Size: </TD><TD>%d</TD>",seg->items[x].size);
}
ngx_http_openidc_rprintf(r,"\t\t</TABLE>");
}
ngx_http_openidc_rprintf(r,"\t</TD></TR>");
ngx_http_openidc_rprintf(r,"\t</TABLE>");
ngx_http_openidc_rprintf(r,"\n</TD></TR>");
}
}else{
ngx_http_openidc_rprintf1(r,"\n<TR><TD colspan='2'>Shared Heap - %s - NULL</TD></TR>",title);
}
return 1;
}
int oidc_showHeaders(ngx_http_openidc_request_t *r, Config* config){
oidc_config* actm=config->oidcConfig;
if(actm==NULL){
authzoidc_errorMessage(r);
return NGX_OK;
}
//begin logic
ngx_http_openidc_rputs("<HTML>\n",r);
ngx_http_openidc_rprintf(r,"<HEAD><TITLE>Headers</TITLE></HEAD>\n");
ngx_http_openidc_rputs("<BODY>\n",r);
authzoidc_printTable(r,r->headers_in);
ngx_http_openidc_rputs("</BODY>",r);
ngx_http_openidc_rputs("</HTML>\n",r);
return NGX_OK;
}
int oidc_headers(ngx_http_openidc_request_t *r, Config *config) {
if (strcmp(r->handler, "oidc_headers")) {
return NGX_DECLINED;
}
return oidc_showHeaders(r,config);
}
int oidc_config_core_status(ngx_http_openidc_request_t *r, Config *config) {
if (strcmp(r->handler, "oidc_config_core_status")) {
return NGX_DECLINED;
}
ngx_http_openidc_rputs("<HTML>\n",r);
ngx_http_openidc_rprintf(r,"<HEAD><TITLE>Config Core Status</TITLE></HEAD>\n");
ngx_http_openidc_rputs("<BODY>\n",r);
ngx_http_openidc_rputs("<TABLE width='100%'>",r);
ngx_http_openidc_rprintf1(r,"<tr><td>HomeDir: </td><td>%s</td></tr>",SAFESTR(config->homeDir));
ngx_http_openidc_rprintf1(r,"<tr><td>ConfigFile: </td><td>%s</td></tr>",SAFESTR(config->oidcConfigFile));
ngx_http_openidc_rprintf1(r,"<tr><td>LogFile: </td><td>%s</td></tr>",SAFESTR(config->logFile));
if(config->configCore!=NULL){
int i=0;
config_core* core=config->configCore;
ngx_http_openidc_rprintf(r,"<tr><td colspan='2' align='left'><strong>Globals</strong></td></tr>");
ngx_http_openidc_rprintf1(r,"<tr><td>HomeDirectory: </td><td>%s</td></tr>",SAFESTR(core->globals->homeDir));
ngx_http_openidc_rprintf1(r,"<tr><td>PassPhrase: </td><td>%s</td></tr>", core->passPhrase ? "non null" : "NULL");
ngx_http_openidc_rprintf1(r,"<tr><td>DisableProcessRecovery: <td>%s</td></tr>",BOOLTOSTR(core->disableProcessRecovery));
ngx_http_openidc_rprintf1(r,"<tr><td>OIDCHeaderPrefix: <td>%s</td></tr>",SAFESTR(core->oidcHeaderPrefix));
ngx_http_openidc_rprintf(r,"<tr><td colspan='2' align='left'><strong>AutoRefresh settings</strong></td></tr>");
ngx_http_openidc_rprintf1(r,"<tr><td>RefreshWaitSeconds: <td>%d</td></tr>",core->refreshWaitSeconds);
if(core->globals->resourceService!=NULL){
ngx_http_openidc_rprintf(r,"<tr><td colspan='2' align='left'><strong>Resource Service</strong></td></tr>");
ngx_http_openidc_rprintf1(r,"<tr><td>Url: </td><td>%s</td></tr>",SAFESTR(core->globals->resourceService->uri));
ngx_http_openidc_rprintf1(r,"<tr><td>Timeout: </td><td>%d</td></tr>",core->globals->resourceService->timeoutSeconds);
}
oidc_section_SharedHeap("Config Core",r,config->configCore->sheap);
}else{
ngx_http_openidc_rprintf(r,"<tr><td>ConfigCore: </td><td>NULL</td></tr>");
}
ngx_http_openidc_rputs("</TABLE>",r);
ngx_http_openidc_rputs("</BODY></HTML>",r);
return NGX_OK;
}
static ngx_int_t ngx_http_openidc_subrequest_post_handler(ngx_http_request_t *r, void *data, ngx_int_t rc) {
ngx_http_request_t *pr;
ngx_http_openidc_subrequest_ctx_t* ctx;
pr = r->parent;
ctx = ngx_http_get_module_ctx(pr, ngx_http_openidc_module);
ctx->done = 1;
ctx->status = r->headers_out.status;
ctx->responseType = r->headers_out.content_type;
ctx->subrequest = r;
char tmp[8192]={0};
memcpy(tmp, r->upstream->buffer.pos, r->upstream->buffer.last - r->upstream->buffer.pos);
// printf("%s:%d body=[%s]\n", __FILE__, __LINE__, tmp);
size_t bodylen = r->upstream->buffer.last - r->upstream->buffer.pos;
ctx->responseBody.data = ngx_palloc(r->pool, bodylen);
ctx->responseBody.len = bodylen;
memcpy(ctx->responseBody.data, r->upstream->buffer.pos, bodylen);
return NGX_OK;
}
static ngx_int_t
ngx_http_openidc_set_subrequest_post_body(ngx_http_request_t * r, ngx_http_request_t * sr, const char* requestBody, ngx_str_t contentType) {
if(requestBody==NULL) return NGX_ERROR;
ngx_http_request_body_t *rb = NULL;
ngx_buf_t *b;
// set method
sr->method = NGX_HTTP_POST;
sr->method_name.data = (u_char *)"POST ";
sr->method_name.len = 4;
// create request body
rb = ngx_pcalloc(r->pool, sizeof(ngx_http_request_body_t));
if (rb == NULL) {
return NGX_ERROR;
}
b = ngx_calloc_buf(r->pool);
if (b == NULL) {
return NGX_ERROR;
}
b->temporary = 1;
/* b->memory = 1; */
b->start = b->pos = requestBody;
b->end = b->last = requestBody + strlen(requestBody);
rb->bufs = ngx_alloc_chain_link(r->pool);
if (rb->bufs == NULL) {
return NGX_ERROR;
}
rb->bufs->buf = b;
rb->bufs->next = NULL;
rb->buf = b;
/* set the 'Content-type' header */
ngx_int_t rc = ngx_http_openidc_set_content_headers(sr, rb->buf ? ngx_buf_size(rb->buf) : 0, contentType);
if (rc != NGX_OK) {
return NGX_ERROR;
}
sr->request_body = rb;
return NGX_OK;
}
static ngx_int_t ngx_http_openidc_preAuthorize(ngx_http_openidc_request_t* r, Config* config) {
ngx_http_post_subrequest_t *psr;
ngx_http_request_t *sr;
ngx_int_t rc;
uri_components *url = &r->parsed_uri;
char tmp[OAUTH_IDTOKEN_MAX_SIZE];
oidc_config* oidcConfig = config->oidcConfig;
ngx_http_openidc_subrequest_ctx_t* ctx = ngx_http_get_module_ctx(r->httpRequest, ngx_http_openidc_module);
if (ctx != NULL) {
ngx_chain_t out;
int bodylen;
ngx_buf_t* b;
ngx_int_t ret;
if (!ctx->done) {
return NGX_AGAIN;
}
if (ctx->status == NGX_HTTP_FORBIDDEN||ctx->status == NGX_HTTP_BAD_REQUEST) {
return ctx->status;
}
if (ctx->status == NGX_HTTP_UNAUTHORIZED) {
ngx_http_request_t* sr = ctx->subrequest;
ngx_table_elt_t* h = sr->headers_out.www_authenticate;
if (!h && sr->upstream) {
h = sr->upstream->headers_in.www_authenticate;
}
if (h) {
ngx_table_elt_t *ho = ngx_list_push(&r->httpRequest->headers_out.headers);
if (ho == NULL) {
return NGX_ERROR;
}
*ho = *h;
r->httpRequest->headers_out.www_authenticate = ho;
}
return ctx->status;
}
if (ctx->status == NGX_HTTP_OK){
// print
char tmp[8192]={0};
memcpy(tmp, ctx->responseBody.data, ctx->responseBody.len);
// printf("%s:%d body=[%s]\n", __FILE__, __LINE__, tmp);
char* responseBody = apr_pstrndup(r->pool, ctx->responseBody.data, ctx->responseBody.len);
if(responseBody!=NULL) {
Value* json = JSON_Parse(r->pool, responseBody);
if(json!=NULL) {
Value* idTokenObj = JSON_GetObjectItem(json, "id_token");
if(idTokenObj!=NULL) {
char* id_token = JSON_GetStringFromStringItem(idTokenObj);
if(id_token!=NULL) {
apr_table_set(r->headers_in, "Authorization", apr_pstrcat(r->pool, "Bearer ", id_token, NULL));
}
}
// set access_token as cookie
if(oidcConfig!=NULL&&oidcConfig->accessToken!=NULL) {
Value* accessTokenObj = JSON_GetObjectItem(json, "access_token");
if(accessTokenObj!=NULL) {
char* access_token = JSON_GetStringFromStringItem(accessTokenObj);
if(access_token!=NULL) {
char* cookieDrop=cookie_cookieTemplate(r->pool, oidcConfig->accessToken, access_token, NULL);
if(cookieDrop!=NULL){
apr_table_add(r->headers_out, "Set-Cookie", cookieDrop);
}
}
}
}
}
}
return NGX_DECLINED;
}
// default
ngx_http_finalize_request(r->httpRequest, ctx->status);
return ctx->status;
}else if(url_get_param(url->query, (char*)"code", tmp, OAUTH_IDTOKEN_MAX_SIZE)>0){
char* authorizationCode = apr_pstrdup(r->pool, tmp);
char* currentRedirectUri = ngx_http_openidc_getFullRequestUrl(r);
page_action* action = NULL;
// get callback action
path_mapping* pathmapping=am_getPathMapping_PostAuth(r->pool, oidcConfig, r->unparsed_uri,r->connection_remote_ip,r->headers_in,NULL);
if(pathmapping!=NULL){
action=am_getMatchingPageAction(r->pool,pathmapping->pmactions,r->unparsed_uri,r->connection_remote_ip,r->headers_in,NULL);
}
if(action==NULL||action->type!=action_callback||action->relyingParty==NULL||action->oidcProvider==NULL) {
return NGX_DECLINED;
}
//printf("%s:%d CurrentRedirectUri=[%s]\n", __FILE__, __LINE__, currentRedirectUri);
relying_party* relyingParty = am_getRelyingPartyById(oidcConfig->relyingPartyIdsHash, action->relyingParty);
if(relyingParty!=NULL) {
char* requestBody = apr_pstrcat(r->pool,
"grant_type=authorization_code",
"&code=", authorizationCode,
"&client_id=", relyingParty->clientID,
"&client_secret=", relyingParty->clientSecret,
NULL);
if(relyingParty->redirectUri!=NULL) {
requestBody = apr_pstrcat(r->pool, requestBody,
"&redirect_uri=", relyingParty->redirectUri,
NULL);
}
ngx_int_t rc = ngx_http_openidc_create_post_subrequest(r->httpRequest, oidc_authz_subrequest_type_oauth_token, requestBody);
if (rc != NGX_OK) {
return rc;
}
return NGX_AGAIN;
}
}
return NGX_DECLINED;
}
static ngx_int_t
ngx_http_openidc_create_post_subrequest(ngx_http_request_t * r, oidc_authz_sub_request_type sub_request_type, const char* requestBody) {
ngx_http_post_subrequest_t *psr;
ngx_http_request_t *sr;
ngx_int_t rc;
// create new context
ngx_http_openidc_subrequest_ctx_t* ctx = ngx_pcalloc(r->pool, sizeof(ngx_http_openidc_subrequest_ctx_t));
if (ctx == NULL) {
return NGX_ERROR;
}
ngx_http_set_ctx(r, ctx, ngx_http_openidc_module);
psr = ngx_palloc(r->pool, sizeof(ngx_http_post_subrequest_t));
if (psr == NULL) {
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
psr->handler = ngx_http_openidc_subrequest_post_handler;
psr->data = ctx;
ngx_str_t subrequest_uri = sub_request_type.uri;
// printf("subrequest_uri=%s\n", (const char*)subrequest_uri.data);
// printf("requestBody=%s\n", requestBody);
rc = ngx_http_subrequest(r, &subrequest_uri, NULL, &sr, psr, NGX_HTTP_SUBREQUEST_IN_MEMORY);
if (rc != NGX_OK) {
return NGX_ERROR;
}
/* allocate a buffer for your response body */
rc = ngx_http_openidc_set_subrequest_post_body(r, sr, requestBody, sub_request_type.content_type);
if (rc != NGX_OK) {
return rc;
}
return NGX_OK;
}
|
tarachandverma/ngx-openidc
|
src/shm_core/shm_data.c
|
#include <shm_data.h>
#include <signal.h>
#include <time.h>
#include <string.h>
#include <stdio.h>
#include <shm_dup.h>
#include "apache_macros.h"
#include <common_utils.h>
#include <log-utils/logging.h>
#include <oidc_globals.h>
static smutex_refresh_mutex* shdata_getMutex(pool *p){
smutex_refresh_mutex* mutex;
apr_status_t status;
mutex=apr_palloc(p,sizeof(smutex_refresh_mutex));
mutex->isRefreshing=0;
status = apr_thread_mutex_create(&(mutex->thread_mutex),APR_THREAD_MUTEX_DEFAULT, p);
if (status != APR_SUCCESS) {
return NULL;
}
return mutex;
}
static int shdata_getMutexLock(smutex_refresh_mutex* mutex){
apr_status_t status;
status=apr_thread_mutex_lock(mutex->thread_mutex);
if(status==APR_SUCCESS){
if(!(mutex->isRefreshing)){
mutex->isRefreshing=1;
apr_thread_mutex_unlock(mutex->thread_mutex);
return 1;
}
apr_thread_mutex_unlock(mutex->thread_mutex);
}
return 0;
}
static int shdata_isRefreshing(smutex_refresh_mutex* mutex){
return mutex->isRefreshing;
}
static void shdata_unLockMutex(smutex_refresh_mutex* mutex){
mutex->isRefreshing=0;
}
int shdata_syncself(pool* p, shared_heap* sheap, rfunc function, void* userdata){
APACHE_LOG_DEBUG("SHMCLIENT CHECK SYNC");
if(sheap!=NULL&&sheap->page!=NULL){
APACHE_LOG_DEBUG("SHMCLIENT CHECK SYNC1");
if(sheap->timestamp!=sheap->page->timestamp){
APACHE_LOG_DEBUG("CLIENT REFRESH");
if(!shdata_isRefreshing(sheap->refresh_mutex)){
if(shdata_getMutexLock(sheap->refresh_mutex)){
sheap->local_segment=sheap->page->frontsegment;
sheap->timestamp=sheap->page->timestamp;
sheap->flipcount++;
//do attach logic
APACHE_LOG_DEBUG("Attaching to new update");
if(function!=NULL){
(*function)(p,sheap,userdata);
}
shdata_unLockMutex(sheap->refresh_mutex);
return 2;
}
}
return 1;
}
APACHE_LOG_DEBUG("SHMCLIENT CHECK SYNC2");
}else{
return -1;
}
return 0;
}
char* shdata_32BitString_copy(shared_heap* sheap, char* str){
int slen;
char* nstr;
if(str==NULL){
return NULL;
}
slen=shdup_32BitString_size(str);
nstr=shdata_shpalloc(sheap,slen);
memset(nstr,'\0',slen);
memcpy(nstr,str,strlen(str));
//APACHE_LOG_DEBUG("reach1");
return nstr;
}
// Copies source array of native data types to sheap array.
array_header* array_headerToSheap(shared_heap* sheap, array_header* sarray){
array_header* dst;
dst=(array_header*)shdata_shpalloc(sheap, sizeof(array_header));
memcpy(dst,sarray,sizeof(array_header));
if(sarray->elts!=NULL){
dst->elts=shdata_shpalloc(sheap,(sarray->nelts*sarray->elt_size));
memcpy(dst->elts,(void*)(sarray->elts), (sarray->nelts*sarray->elt_size));
}else{
dst->elts=NULL;
}
dst->pool=NULL;
return dst;
}
shared_page* shdata_getNewSharedPage(pool* p, apr_shm_t** shm_t, int segmentsize, char* path){
int overheadsize,usersize, x;
shared_page* page;
apr_status_t rv;
overheadsize=sizeof(shared_page);
usersize=segmentsize*2;
char buf[200];
rv=apr_shm_create(shm_t,overheadsize+usersize,path,p);
lc_printLog("\n shdata_getNewSharedPage - apr_shm_create status : ec:%d desc:%s size %ld path %s \n",
rv, SAFESTR(apr_strerror(rv, buf, sizeof(buf))), (overheadsize+usersize), SAFESTR(path) );
#ifdef WIN32
if(rv==APR_EEXIST) { // try to attach it; seems windows specific behaviour
rv = apr_shm_attach(shm_t,path,p);
}
#endif
if(rv!=APR_SUCCESS){
//if failure then try to remove shm segment and try again
rv = apr_shm_attach(shm_t,path,p);
lc_printLog("\n shdata_getNewSharedPage - apr_shm_attach status : ec:%d desc:%s \n", rv, SAFESTR(apr_strerror(rv, buf, sizeof(buf))) );
if(rv==APR_SUCCESS){
rv = apr_shm_destroy(*shm_t);
lc_printLog("\n shdata_getNewSharedPage - apr_shm_destroy status : ec:%d desc:%s \n", rv, SAFESTR(apr_strerror(rv, buf, sizeof(buf))) );
rv=apr_shm_create(shm_t,overheadsize+usersize,path,p);
lc_printLog("\n shdata_getNewSharedPage - apr_shm_create status : ec:%d desc:%s \n", rv, SAFESTR(apr_strerror(rv, buf, sizeof(buf))) );
//if again failure..possible bad shm file...remove and retry
if(rv!=APR_SUCCESS){
rv=apr_file_remove(path,p);
lc_printLog("\n shdata_getNewSharedPage - apr_file_remove status : ec:%d desc:%s \n", rv, SAFESTR(apr_strerror(rv, buf, sizeof(buf))) );
if(rv==APR_SUCCESS){
rv=apr_shm_create(shm_t,overheadsize+usersize,path,p);
lc_printLog("\n shdata_getNewSharedPage - apr_shm_create status : ec:%d desc:%s \n", rv, SAFESTR(apr_strerror(rv, buf, sizeof(buf))) );
}
}
}else{ //if cannot attach blow file away and try again
rv=apr_file_remove(path,p);
lc_printLog("\n shdata_getNewSharedPage - apr_file_remove status : ec:%d desc:%s \n", rv, SAFESTR(apr_strerror(rv, buf, sizeof(buf))) );
if(rv==APR_SUCCESS){
rv=apr_shm_create(shm_t,overheadsize+usersize,path,p);
lc_printLog("\n shdata_getNewSharedPage - apr_shm_create status : ec:%d desc:%s \n", rv, SAFESTR(apr_strerror(rv, buf, sizeof(buf))) );
}
}
}
if(rv==APR_SUCCESS){
APACHE_LOG_DEBUG1("SHARED PAGES CREATED: Path=%s",path);
page=apr_shm_baseaddr_get(*shm_t);
page->itemmax=MAX_PAGE_ITEMS;
page->segmentsize=segmentsize;
page->timestamp=SHM_TIMESTAMP_INIT;
page->flipcount=0;
page->frontsegment=1;
page->backsegment=0;
page->data=(char*)(page+1);
page->cursor=page->data;
for(x=0;x<SEGMENTS_PER_PAGE;x++){
page->segments[x].itemcount=0;
}
return page;
}
APACHE_LOG_DEBUG("SHARED PAGE BAD");
return NULL;
}
static shared_page* shdata_attachToSharedPage(pool* p, apr_shm_t** shm_t, int segmentsize, char* path){
int overheadsize,usersize, x;
shared_page* page;
apr_status_t rv;
overheadsize=sizeof(shared_page);
usersize=segmentsize*2;
rv = apr_shm_attach(shm_t,path,p);
if(rv!=APR_SUCCESS){
APACHE_LOG_DEBUG("UNABLE TO ATTACH TO SHARED PAGE BAD");
}
if(rv==APR_SUCCESS){
APACHE_LOG_DEBUG1("SHARED PAGES CREATED: Path=%s",path);
page=apr_shm_baseaddr_get(*shm_t);
page->itemmax=MAX_PAGE_ITEMS;
page->segmentsize=segmentsize;
page->timestamp=SHM_TIMESTAMP_INIT;
page->flipcount=0;
page->frontsegment=1;
page->backsegment=0;
page->data=(char*)(page+1);
page->cursor=page->data;
for(x=0;x<SEGMENTS_PER_PAGE;x++){
page->segments[x].itemcount=0;
}
return page;
}
APACHE_LOG_DEBUG("SHARED PAGE BAD");
return NULL;
}
shared_page* shdata_getNewUnNamedSharedPage(pool* p, apr_shm_t** shm_t, int segmentsize, char* path){
int overheadsize,usersize, x;
shared_page* page;
apr_status_t rv;
overheadsize=sizeof(shared_page);
usersize=segmentsize*2;
char buf[200];
rv=apr_shm_create(shm_t,overheadsize+usersize,NULL,p);
lc_printLog("\n shdata_getNewUnNamedSharedPage - apr_shm_create with unnamed shm status : ec:%d desc:%s size %ld \n",
rv, SAFESTR(apr_strerror(rv, buf, sizeof(buf))), (overheadsize+usersize));
if(rv != APR_SUCCESS) {
if(rv == APR_ENOTIMPL && path != NULL) {
return shdata_getNewSharedPage(p, shm_t, segmentsize, path);
}
}
else {
APACHE_LOG_DEBUG("UNNAMED SHARED PAGES CREATED");
page=apr_shm_baseaddr_get(*shm_t);
page->itemmax=MAX_PAGE_ITEMS;
page->segmentsize=segmentsize;
page->timestamp=SHM_TIMESTAMP_INIT;
page->flipcount=0;
page->frontsegment=1;
page->backsegment=0;
page->data=(char*)(page+1);
page->cursor=page->data;
for(x=0;x<SEGMENTS_PER_PAGE;x++){
page->segments[x].itemcount=0;
}
return page;
}
APACHE_LOG_DEBUG("UNNAMED SHARED PAGE BAD");
return NULL;
}
shared_heap* shdata_sheap_make(pool* p, int segmentSize, char* path){
int x;
shared_heap* sheap;
apr_shm_t* shm_t;
//struct shmid_ds ds;
sheap=(shared_heap*)apr_palloc(p,sizeof(shared_heap));
#ifdef WIN32
sheap->page=shdata_getNewSharedPage(p,&shm_t,segmentSize,path);
#else
if(djrglobals_isUnnamedSHMEnabled() == FALSE && path != NULL) {
sheap->page=shdata_getNewSharedPage(p,&shm_t,segmentSize,path);
}
else {
sheap->page=shdata_getNewUnNamedSharedPage(p,&shm_t,segmentSize,path);
}
#endif
sheap->timestamp=-1;
sheap->flipcount=0;
sheap->local_segment=-1;
sheap->shm_main=shm_t;
sheap->refresh_mutex=shdata_getMutex(p);
if(sheap->page==NULL){return NULL;}
return sheap;
}
shared_heap* shdata_sheap_attach(pool* p, int segmentSize, char* path){
int x;
shared_heap* sheap;
apr_shm_t* shm_t;
//struct shmid_ds ds;
sheap=(shared_heap*)apr_palloc(p,sizeof(shared_heap));
sheap->page=shdata_attachToSharedPage(p,&shm_t,segmentSize,path);
sheap->timestamp=-1;
sheap->flipcount=0;
sheap->local_segment=-1;
sheap->shm_main=shm_t;
sheap->refresh_mutex=shdata_getMutex(p);
if(sheap->page==NULL){return NULL;}
return sheap;
}
char* shdata_getItem(shared_heap* sheap,const char* ID){
int x;
char* buf=NULL;
segment_header* sh;
sh=&(sheap->page->segments[sheap->local_segment]);
for(x=0;x<sh->itemcount;x++){
if(strcmp(sh->items[x].ITEMID,ID)==0){
buf=((char*)(sheap->page->data))+(sh->items[x].offset);
//printf("D:%ld, b: %ld, o:%d\n",sheap->page->data,buf, sh->items[x].offset);
return buf;
}
}
return buf;
}
int shdata_getFlipCount(shared_heap* sheap){
return sheap->page->flipcount;
}
time_t* shdata_getLastFlipTime(shared_heap* sheap){
return &(sheap->page->timestamp);
}
void shdata_PublishBackSeg(shared_heap* sheap){
int tmp;
tmp=sheap->page->backsegment;
sheap->page->backsegment=sheap->page->frontsegment;
sheap->page->frontsegment=tmp;
sheap->page->flipcount++;
APACHE_LOG_DEBUG1("PUBLISH PAGE: %d",sheap->page->flipcount);
sheap->page->timestamp=time(NULL);
}
void shdata_rollback(shared_heap* sheap){
int x,y;
page_item* item;
shared_page* p;
segment_header* sh;
APACHE_LOG_DEBUG("ROLLBACK BACKBUFFER SHEAP");
p=sheap->page;
sh=&(sheap->page->segments[sheap->page->backsegment]);
if(sh->itemcount>=MAX_PAGE_ITEMS){
y=MAX_PAGE_ITEMS-1;
}else{
y=sh->itemcount;
}
for(x=0;x<=y;x++){
item=&(sh->items[x]);
memset(item->ITEMID,'\0',PAGE_ITEM_CHARS);
memset(item->INFO,'\0',PAGE_ITEM_CHARS);
}
p->cursor=p->data+(p->backsegment*p->segmentsize);
sh->itemcount=0;
}
void shdata_BeginTagging(shared_heap* sheap){
shared_page* p=sheap->page;
p->cursor=p->data+(p->backsegment*p->segmentsize);
APACHE_LOG_DEBUG1("BEGIN TAGGING @ %d",p->cursor);
p->segments[p->backsegment].itemcount=0;
}
void shdata_OpenItemTag(shared_heap* sheap,const char* ID){
segment_header* sh=&(sheap->page->segments[sheap->page->backsegment]);
page_item* item;
item=&(sh->items[sh->itemcount]);
memset(item->ITEMID,'\0',PAGE_ITEM_CHARS);
memset(item->INFO,'\0',PAGE_ITEM_CHARS);
strcpy(item->ITEMID,ID);
item->offset=sheap->page->cursor-sheap->page->data;
}
void shdata_AppendInfo(shared_heap* sheap,char* info){
segment_header* sh=&(sheap->page->segments[sheap->page->backsegment]);
page_item* item=&(sh->items[sh->itemcount]);
strcat(item->INFO,info);
}
void shdata_CloseItemTag(shared_heap* sheap){
segment_header* sh=&(sheap->page->segments[sheap->page->backsegment]);
page_item* item;
item=&(sh->items[sh->itemcount]);
item->size=sheap->page->cursor-sheap->page->data-item->offset;
sh->itemcount++;
}
void shdata_CloseItemTagWithInfo(shared_heap* sheap, char* info){
segment_header* sh=&(sheap->page->segments[sheap->page->backsegment]);
page_item* item;
item=&(sh->items[sh->itemcount]);
strncpy(item->INFO,info,PAGE_ITEM_CHARS-1);
shdata_CloseItemTag(sheap);
}
int shdata_cursor(shared_heap* sheap){
if(sheap==NULL||sheap->page==NULL){
return -1;
}
return sheap->page->cursor-sheap->page->data;
}
char* shdata_shpalloc(shared_heap* sheap, int size){
shared_page* page;
char* retchar;
int spaceleft;
page=sheap->page;
spaceleft=page->segmentsize-(page->cursor-page->data)+(page->segmentsize*page->backsegment);
if(spaceleft<size){
APACHE_LOG_DEBUG("OUT OF SHEAP SPACE");
return NULL;
}
retchar=page->cursor;
page->cursor+=size;
return retchar;
}
char* shdata_shpcalloc(shared_heap* sheap, int size){
char* tmp;
tmp=shdata_shpalloc(sheap,size);
memset(tmp,0,size);
return tmp;
}
void* shdata_memcpy(shared_heap* sheap, void* src, int size){
void* ret=NULL;
if(src!=NULL&&size>0){
ret=shdata_shpcalloc(sheap,size);
memcpy(ret,src,size);
}
return ret;
}
static apr_sockaddr_t* shdata_copyAddr1(shared_heap* sheap,apr_sockaddr_t* addr){
apr_sockaddr_t* ret=NULL;
ret=(apr_sockaddr_t*)shdata_memcpy(sheap,addr,sizeof(apr_sockaddr_t));
ret->hostname=shdata_32BitString_copy(sheap,addr->hostname);
ret->hostname=shdata_32BitString_copy(sheap,addr->servname);
ret->ipaddr_ptr=shdata_memcpy(sheap,addr->ipaddr_ptr,addr->ipaddr_len);
ret->next=NULL;
return ret;
}
apr_sockaddr_t* shdata_sockAddrCpy(shared_heap* sheap, apr_sockaddr_t* addr){
apr_sockaddr_t* ret=NULL, *cur=NULL,*curShm=NULL;
if(addr!=NULL){
cur=addr;
ret=curShm=shdata_copyAddr1(sheap,addr);
while(cur->next!=NULL){
cur=cur->next;
curShm->next=shdata_copyAddr1(sheap,cur);
curShm=curShm->next;
}
}
return ret;
}
|
tarachandverma/ngx-openidc
|
src/config-core/config_bindings.h
|
#ifndef __TCREWRITE_CONFIG_BINDINGS__H_
#define __TCREWRITE_CONFIG_BINDINGS__H_
#include <sys/types.h>
#include "apache_typedefs.h"
typedef struct cfg_service_descriptor{
char* id;
char* name;
char* uri;
char* userColonPass;
long timeoutSeconds;
apr_hash_t * params;
}cfg_service_descriptor;
// old version of cfg_globals (pool version).
typedef struct cfg_globals{
char* homeDir;
char* logsDir;
cfg_service_descriptor* resourceService;
}cfg_globals;
cfg_service_descriptor* cb_newServiceDescriptorObj(pool* p);
cfg_globals* cb_newGlobalsObj(pool* p);
char* cb_initGlobals(pool* p,cfg_globals* globals);
char* cb_writeRemoteResourceToDisk(pool* p, char* homeDir, char* reqUri, char* resource,
long timeoutSeconds, char* userColonPass, apr_pool_t* tp, char**details, int* responseCode);
int cb_canAutoRefreshNow(pool* p, cfg_service_descriptor* resourceService, time_t lastRefreshTimestamp, time_t currentTimestamp, char* namespace,char**error);
#endif
|
tarachandverma/ngx-openidc
|
src/shm_core/shm_data.h
|
#ifndef __TCREWRITE_SHM_DATA__H_
#define __TCREWRITE_SHM_DATA__H_
#include <sys/types.h>
#include "apache_typedefs.h"
#include <apr_shm.h>
#ifdef __cplusplus
extern "C" {
#endif
#define MAX_PAGE_ITEMS 16
#define PAGE_ITEM_CHARS 128
#define SEGMENTS_PER_PAGE 2
//#define TOKEN_KEY_OFFSET 12
//#define SHM_BOOT_STATUS_UP_GREEN 1
//#define SHM_BOOT_STATUS_DOWN_BLUE 0
//#define SHM_BOOT_STATUS_FAILED_RED -1
#define SHM_TIMESTAMP_INIT -1
#define SHM_FAILHARD_SHEAP 16
typedef struct page_item{
int offset, size;
char ITEMID[PAGE_ITEM_CHARS];
char INFO[PAGE_ITEM_CHARS];
}page_item;
typedef struct segment_header{
page_item items[MAX_PAGE_ITEMS];
int itemcount;
}segment_header;
typedef struct shared_page{
time_t timestamp;
int segmentsize, flipcount;
char *cursor, *data;
int itemmax,frontsegment, backsegment;
segment_header segments[SEGMENTS_PER_PAGE];
}shared_page;
//for static use
typedef struct smutex_refresh_mutex{
apr_thread_mutex_t *thread_mutex;
sig_atomic_t isRefreshing;
}smutex_refresh_mutex;
//stored per process
typedef struct shared_heap{
shared_page* page;
apr_shm_t* shm_main;
time_t timestamp;
sig_atomic_t flipcount;
sig_atomic_t local_segment;
//for thread sync
smutex_refresh_mutex* refresh_mutex;
}shared_heap;
typedef int (*rfunc) (pool*, shared_heap*, void*);
int shdata_syncself(pool* p, shared_heap* sheap, rfunc function, void* userdata);
int shdata_cursor(shared_heap* sheap);
char* shdata_shpalloc(shared_heap* sheap, int size);
char* shdata_shpcalloc(shared_heap* sheap, int size);
void shdata_BeginTagging(shared_heap* sheap);
void shdata_CloseItemTag(shared_heap* sheap);
void shdata_CloseItemTagWithInfo(shared_heap* sheap, char* info);
void shdata_OpenItemTag(shared_heap* sheap,const char* ID);
void shdata_AppendInfo(shared_heap* sheap,char* info);
void shdata_PublishBackSeg(shared_heap* sheap);
void shdata_rollback(shared_heap* sheap);
int shdata_getFlipCount(shared_heap* sheap);
time_t* shdata_getLastFlipTime(shared_heap* sheap);
shared_heap* shdata_sheap_make(pool* p, int segmentSize, char* path);
shared_page* shdata_getNewSharedPage(pool* p, apr_shm_t** shm_t, int segmentsize, char* path);
shared_heap* shdata_sheap_attach(pool* p, int segmentSize, char* path);
char* shdata_getItem(shared_heap* sheap,const char* ID);
//sheap copy stuff
array_header* array_headerToSheap(shared_heap* sheap, array_header* sarray);
char* shdata_32BitString_copy(shared_heap* sheap, char* str);
apr_sockaddr_t* shdata_sockAddrCpy(shared_heap* sheap, apr_sockaddr_t* addr);
void* shdata_memcpy(shared_heap* sheap, void* src, int size);
#ifdef __cplusplus
}
#endif
#endif
|
tarachandverma/ngx-openidc
|
src/oidc-globals/oidc_version.h
|
<filename>src/oidc-globals/oidc_version.h
/*
* Created by <NAME> on 01/07/14.
*
*/
#ifndef __TCREWRITE_VERSION__H_
#define __TCREWRITE_VERSION__H_
#include <sys/types.h>
#define MODULE_COMPONENT_ID "ngx_openidc"
#define MODULE_VERSION_ID "0.0.5"
#define VERSION_ID MODULE_COMPONENT_ID" "MODULE_VERSION_ID
#endif // __TCREWRITE_VERSION__H_
/*
---------------------------------------------------------------------------------------------------
*
*
* Add new version, date, and short description here.
* ---------------------------------------------------------------------------------------------------
* 0.0.5 - 01/15/2018
*
* added support for multiple OIDC providers
* Changed by vermat
* ---------------------------------------------------------------------------------------------------
* 0.0.4 - 12/28/2017
*
* added support for multiple OIDC providers
* Changed by vermat
* ---------------------------------------------------------------------------------------------------
* 0.0.3 - 12/22/2017
*
* added new flag isLoginRedirect to directly send to OP login
* Changed by vermat
* ---------------------------------------------------------------------------------------------------
* 0.0.2 - 07/22/2017
*
* Fixed unit test
* Changed by vermat
* ---------------------------------------------------------------------------------------------------
* 0.0.1 - 02/03/2016
*
* First version.
* Changed by vermat
* ---------------------------------------------------------------------------------------------------
*/
|
tarachandverma/ngx-openidc
|
src/oidc-core/oidc_config_xml.h
|
#ifndef __TCREWRITE_ACTION_MAPPINGS_XML__H_
#define __TCREWRITE_ACTION_MAPPINGS_XML__H_
#include "apache_typedefs.h"
#include "oidc_core_constants.h"
#include "cookie.h"
typedef struct action_header_xml{
char* name;
char* value;
char* regex;
header_actions action;
}action_header_xml;
// custom response
typedef struct action_response_xml{
int code;
char* contentType;
char* body;
}action_response_xml;
typedef struct page_action_xml{
char *id,*directory,*description;
char* regex;
char* handler;
array_header* responseHeaders; // array of action_header_xml*
array_header* requestHeaders; // array of action_header_xml*
action_response_xml* response; // custom response
char* uri, *oidcProvider, *relyingParty;
int type;
int isDebug:1, isForward:1,isPermanent:1,advancedTemplate:1,base64UrlEncodeState:1;
}page_action_xml;
typedef struct pathmapping_action_xml{
char *id;
char* matchList;//matchlist name
}pathmapping_action_xml;
typedef struct path_mapping_xml{
char* pathRegex;
int ignoreCase;
array_header* postAuthActions;
array_header* matchLists;
}path_mapping_xml;
typedef struct relying_party_xml{
char* id;
char* description;
char *clientID;
char* clientSecret;
char* issuer;
int validateNonce;
char* redirectUri;
char* postLoginDefaultLandingPage;
int setCurrentPageAsState;
}relying_party_xml;
typedef struct oidc_provider_xml{
char* id;
char* metadataUrl;
char* issuer;
char* authorizationEndpoint;
char* tokenEndpoint;
char* jwksUri;
char* jwksJson;
int isDefault;
}oidc_provider_xml;
typedef struct oidc_config_xml{
int uid; // unique id for document
apr_hash_t* page_actions_hash;
array_header* path_mappings_arr;
array_header* match_list_arr;
Cookie* rpSession;
Cookie* oidcSession;
Cookie* accessToken;
apr_hash_t* relyingPartyHash;
array_header* oidcProviders;
}oidc_config_xml;
oidc_config_xml* amx_newObj(pool* p);
char* amx_loadConfFile(pool* p, char* file, oidc_config_xml* conf);
void amx_printAll(pool* p,oidc_config_xml* conf);
#endif
|
tarachandverma/ngx-openidc
|
src/config-core/config_bindings_shm.h
|
<filename>src/config-core/config_bindings_shm.h<gh_stars>10-100
#ifndef CONFIG_BINDINGS_SHM_H_
#define CONFIG_BINDINGS_SHM_H_
#include <shm_data.h>
#include <shm_apr.h>
#include <config-core/config_bindings.h>
typedef struct cbs_service_descriptor{
char* id;
char* name;
char* uri;
char* userColonPass;
long timeoutSeconds;
shapr_hash_t * params;
}cbs_service_descriptor;
typedef struct cbs_globals{
char* homeDir;
char* logsDir;
cbs_service_descriptor* resourceService;
int isRefresh;
}cbs_globals;
cbs_globals* cbs_copyGlobalsOnSheap(pool*p, shared_heap* sheap, cfg_globals* globals, int isRefresh);
char* cbs_getRemoteResourcePath(pool* p, cbs_globals* globals,char* resource,char**details);
char* cbs_getLocalResourcePath(pool* p, cbs_globals* globals,char* resource,char**details);
#endif /*CONFIG_BINDINGS_SHM_H_*/
|
tarachandverma/ngx-openidc
|
src/config-core/config_core.c
|
<filename>src/config-core/config_core.c<gh_stars>10-100
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <stdlib.h>
#include "config_core.h"
#include "xml_core.h"
#include "common_utils.h"
#include "oidc_globals.h"
#include "config_bindings_shm.h"
#include "oidc_version.h"
#include "logging.h"
config_core* configcore_newConfigCoreObj(pool* p){
config_core* ret=(config_core*)apr_palloc(p,sizeof(config_core));
ret->globals=cb_newGlobalsObj(p);
ret->oidcConfigFile=apr_pstrdup(p,"oidc-config.xml");
ret->service=cb_newServiceDescriptorObj(p);
ret->service->id=apr_pstrdup(p,"OIDC-CONFIG");
ret->service->name=apr_pstrdup(p,"oidcConfig");
apr_hash_set(ret->service->params,"config-xml",APR_HASH_KEY_STRING,ret->oidcConfigFile);
ret->sheapMapFile=apr_pstrdup(p, "/configcore.shm");
ret->sheapPageSize=64000;
ret->sheap=NULL;
ret->serviceConfig=NULL;
ret->passPhrase=NULL;
ret->disableProcessRecovery=FALSE;
ret->oidcHeaderPrefix=apr_pstrdup(p, "X-OIDC-");
ret->refreshWaitSeconds=0;
ret->cipherConfig = (oidc_cipher_cfg*)apr_palloc(p, sizeof(oidc_cipher_cfg));
ret->cipherConfig->crypto_passphrase = NULL;
ret->cipherConfig->decrypt_ctx=NULL;
ret->cipherConfig->encrypt_ctx=NULL;
ret->cipherConfig->p = p;
return ret;
}
typedef struct cfg_bundle{
config_core* cc;
void* userdata, *userdata2;
}cfg_bundle;
static int cfg_setCCAttributes(pool* p,char* xPath,int type,const char ** attributes,void* userdata){
int i;
cfg_bundle* bundle=(cfg_bundle*)userdata;
return 1;
}
static int cfg_setCCDisableProcessRecoveryBody(pool* p,char* xPath,int type,const char *body,void* userdata){
int len;
cfg_bundle* bundle=(cfg_bundle*)userdata;
bundle->cc->disableProcessRecovery=STRTOBOOL(body);
return 1;
}
static int cfg_setCCHeaderPrefixBody(pool* p,char* xPath,int type,const char *body,void* userdata){
int len;
cfg_bundle* bundle=(cfg_bundle*)userdata;
bundle->cc->oidcHeaderPrefix=apr_pstrdup(p, body);
return 1;
}
static int cfg_setCCRefreshWaitSecondsBody(pool* p,char* xPath,int type,const char *body,void* userdata){
int len;
cfg_bundle* bundle=(cfg_bundle*)userdata;
if(body!=NULL) {
bundle->cc->refreshWaitSeconds=atol(body);
}
return 1;
}
static int cfg_setCCPassPhraseBody(pool* p,char* xPath,int type,const char *body,void* userdata){
int len;
cfg_bundle* bundle=(cfg_bundle*)userdata;
bundle->cc->passPhrase=apr_pstrdup(p,body);
if(bundle->cc->passPhrase) {
bundle->cc->cipherConfig->crypto_passphrase=apr_pstrdup(p,body);
}
return 1;
}
static int cfg_setCCOIDCConfigFileBody(pool* p,char* xPath,int type,const char *body,void* userdata){
int len;
cfg_bundle* bundle=(cfg_bundle*)userdata;
bundle->cc->oidcConfigFile=apr_pstrdup(p,body);
if(bundle->cc->oidcConfigFile!=NULL){
apr_hash_set(bundle->cc->service->params,"config-xml",APR_HASH_KEY_STRING,bundle->cc->oidcConfigFile);
}
return 1;
}
static int cfg_setCCSheapMapFileBody(pool* p,char* xPath,int type,const char *body,void* userdata){
cfg_bundle* bundle=(cfg_bundle*)userdata;
bundle->cc->sheapMapFile=apr_pstrdup(p,body);
return 1;
}
static int cfg_setCCSheapPageSizeBody(pool* p,char* xPath,int type,const char *body,void* userdata){
cfg_bundle* bundle=(cfg_bundle*)userdata;
bundle->cc->sheapPageSize=atoi(body);
return 1;
}
static int cfg_setResourceServiceAttributes(pool* p,char* xPath,int type,const char ** attributes,void* userdata){
int i;
cfg_bundle* bundle=(cfg_bundle*)userdata;
cfg_service_descriptor* svc=NULL;
svc=bundle->cc->globals->resourceService=cb_newServiceDescriptorObj(p);
svc->id=apr_pstrdup(p,"RESOURCE_SERVICE");
svc->name=apr_pstrdup(p,"RESOURCE_SERVICE");
return 1;
}
static int cfg_setResourceServiceUriBody(pool* p,char* xPath,int type,const char *body,void* userdata){
cfg_bundle* bundle=(cfg_bundle*)userdata;
cfg_service_descriptor* svc=bundle->cc->globals->resourceService;
if(svc!=NULL){
svc->uri=apr_pstrdup(p,body);
}
return 1;
}
static int cfg_setResourceServiceParamAttributes(pool* p,char* xPath,int type,const char ** attributes,void* userdata){
int i;
cfg_bundle* bundle=(cfg_bundle*)userdata;
bundle->userdata2=NULL;
for (i = 0; attributes[i]; i += 2) {
if(strcmp(attributes[i],"name")==0){
bundle->userdata2=(void*)apr_pstrdup(p,attributes[i + 1]);
}
}
return 1;
}
static int cfg_setResourceServiceTimeoutBody(pool* p,char* xPath,int type,const char *body,void* userdata){
cfg_bundle* bundle=(cfg_bundle*)userdata;
cfg_service_descriptor* svc=bundle->cc->globals->resourceService;
if(svc!=NULL){
svc->timeoutSeconds=atol(body);
}
return 1;
}
static int cfg_setResourceServiceUserColonPassBody(pool* p,char* xPath,int type,const char *body,void* userdata){
cfg_bundle* bundle=(cfg_bundle*)userdata;
cfg_service_descriptor* svc=bundle->cc->globals->resourceService;
if(svc!=NULL){
svc->userColonPass=apr_pstrdup(p,body);
}
return 1;
}
char* configcore_loadConfigCoreFile(pool* p, char* file, config_core* conf){
char* result=NULL;
XmlCore* xCore;
cfg_bundle* bundle=(cfg_bundle*)apr_palloc(p,sizeof(cfg_bundle));
bundle->userdata=NULL;
bundle->userdata2=NULL;
bundle->cc=conf;
xCore=xc_getXmlCore(p);
xc_addXPathHandler(xCore,"/config-core",0,cfg_setCCAttributes,NULL,NULL, bundle);
xc_addXPathHandler(xCore,"/config-core/sheapMapFile",0,NULL,cfg_setCCSheapMapFileBody,NULL, bundle);
xc_addXPathHandler(xCore,"/config-core/sheapPageSize",0,NULL,cfg_setCCSheapPageSizeBody,NULL, bundle);
xc_addXPathHandler(xCore,"/config-core/disableProcessRecovery",0,NULL,cfg_setCCDisableProcessRecoveryBody,NULL, bundle);
xc_addXPathHandler(xCore,"/config-core/oidcHeaderPrefix",0,NULL,cfg_setCCHeaderPrefixBody,NULL, bundle);
xc_addXPathHandler(xCore,"/config-core/refreshWaitSeconds",0,NULL,cfg_setCCRefreshWaitSecondsBody,NULL, bundle);
xc_addXPathHandler(xCore,"/config-core/passPhrase",0,NULL,cfg_setCCPassPhraseBody,NULL, bundle);
xc_addXPathHandler(xCore,"/config-core/oidcConfigFile",0,NULL,cfg_setCCOIDCConfigFileBody,NULL, bundle);
xc_addXPathHandler(xCore,"/config-core/resourceService",0,cfg_setResourceServiceAttributes,NULL,NULL, bundle);
xc_addXPathHandler(xCore,"/config-core/resourceService/uri",0,NULL,cfg_setResourceServiceUriBody,NULL, bundle);
xc_addXPathHandler(xCore,"/config-core/resourceService/timeoutSeconds",0,NULL,cfg_setResourceServiceTimeoutBody,NULL, bundle);
xc_addXPathHandler(xCore,"/config-core/resourceService/userColonPass",0,NULL,cfg_setResourceServiceUserColonPassBody,NULL, bundle);
xc_addXPathHandler(xCore,"/config-core/resourceService/param",0,cfg_setResourceServiceParamAttributes,cfg_setResourceServiceTimeoutBody,NULL, bundle);
result=xc_beginParsingTextResponse(xCore,file);
return result;
}
static int cfg_onSheapPageFlip(pool* p, shared_heap* sheap, void* userdata){
config_core* configCore=(config_core*)userdata;
int i=0;
cfg_service_descriptor* svc=NULL;
char* error=NULL;
void* moduleConfig=NULL;
svc=configCore->service;
error=amc_postRefresh(p,configCore->sheap,configCore->globals,svc,&moduleConfig);
if(error==NULL){
//set as post initialized
if(moduleConfig!=NULL){
if(svc->name!=NULL){
configCore->serviceConfig = moduleConfig;
}
}
}
return 1;
}
int cfg_syncSelf(apr_pool_t* pool,config_core* configCore){
int ret=0;
if(configCore!=NULL&&(ret=shdata_syncself(pool,configCore->sheap,cfg_onSheapPageFlip,configCore))==2){
return 1;
}
return 0;
}
static void* cfg_initMessaging(pool* p, void* userdata){
config_core* configCore=(config_core*)userdata;
return (void*)NULL;
}
static char* cfg_refreshConfigCore(pool* p,config_core* conf){
int i;
cfg_service_descriptor* svc=NULL;
void* moduleConfig=NULL;
char* error=NULL;
// alerts_core* alertsCore=NULL;
// diagnostics_core* diagCore=NULL;
cbs_globals* cbshmGlobals=NULL;
char cbuf[APR_CTIME_LEN + 1];
long timeTakenMillis;
lc_openLogFile(p,conf->refreshLogFile);
lc_rotateLogFile();
apr_time_t t1 = apr_time_now();
apr_ctime(cbuf, t1);
lc_printLog("\n\t Refreshing config [%s]\n", cbuf); fflush(stdout);
if(conf->service!=NULL){
shdata_BeginTagging(conf->sheap);
//duplicate cfg_globals and globals on sheap
cbshmGlobals=cbs_copyGlobalsOnSheap(p,conf->sheap,conf->globals,TRUE);
svc=conf->service;
error=amc_refresh(p,conf->sheap,cbshmGlobals,svc,&moduleConfig);
if(error!=NULL){
return apr_pstrcat(p,"[",svc->id,"] Service failed to refresh: ",error,NULL);
}else{
//set as initialized
if(moduleConfig!=NULL){
if(svc->name!=NULL){
conf->serviceConfig = moduleConfig;
}
}
}
//publish bash segment
if(error==NULL){
shdata_PublishBackSeg(conf->sheap);
cfg_syncSelf(p,conf);
}
}
timeTakenMillis = ((apr_time_now() - t1) / 1000);
lc_printLog("\n\t Refresh complete [time taken : %d milliseconds]\n", timeTakenMillis); fflush(stdout);
lc_closeLogFile();
return error;
}
static char* cfg_handleMessageRecieved(pool* p, cfgm_connection* cmConn,cfgm_wire_message* msg,void* localConfig, void* userdata){
char* result=NULL;
config_core* configCore=(config_core*)userdata;
//now we can do out actions that we would like to do...like refresh the config core:)
if(cfgm_isRefreshMessage(msg)){
result=cfg_refreshConfigCore(p,configCore);
if(result==NULL){
lc_printLog("Refresh succeded\n"); fflush(stdout);
}else{
lc_printLog("Refresh failed:%s\n", result); fflush(stdout);
}
}
return NULL;
}
char* configcore_initializeConfigCore(pool* p,config_core* conf){
int i=0;
cfg_service_descriptor* svc=NULL;
char* error=NULL;
char* sheapfile=apr_pstrcat(p,conf->globals->homeDir,conf->sheapMapFile,NULL);
void* moduleConfig=NULL;
char* errorRet=NULL;
cbs_globals* cbshmGlobals=NULL;
char buf[100];
apr_status_t status=0;
lc_printLog("Initializing Config Core \n\r");
lc_printLog("\tSetup filesystem");
cb_initGlobals(p,conf->globals);
lc_printLog("\tSheapFile:\t%s\n",sheapfile);
lc_printLog("\tSheapPageSize:\t%d\n",conf->sheapPageSize);
conf->sheap=shdata_sheap_make(p, conf->sheapPageSize,sheapfile);
if(conf->sheap==NULL){
return apr_pstrdup(p,"Could not create Config Core shared heap");
}
shdata_BeginTagging(conf->sheap);
//duplicate cfg_globals on sheap and merge global options.
cbshmGlobals=cbs_copyGlobalsOnSheap(p,conf->sheap,conf->globals,FALSE);
if(conf->service!=NULL){
lc_printLog("\tService Init-\n");
svc=conf->service;
if(svc->name!=NULL){
lc_printLog("\t\t%s [%s] Initializing...\n",svc->id, SAFESTRBLANK(svc->name));
}else{
lc_printLog("\t\t%s Initializing...\n",svc->id);
}
fflush(stdout);
error=amc_initialize(p,conf->sheap,cbshmGlobals,svc,&moduleConfig);
if(error!=NULL){
if(errorRet==NULL){
errorRet=apr_pstrdup(p,"�");
}else{
errorRet=apr_pstrcat(p,errorRet,"\r\n�",NULL);
}
errorRet=apr_pstrcat(p,errorRet,"[",svc->id,"] Service failed to initialize: ",error,NULL);
}else{
//set as initialized
if(moduleConfig!=NULL){
//set config by name
if(svc->name!=NULL){
conf->serviceConfig = moduleConfig;
}
}
}
fflush(stdout);
//publish bash segment
lc_printLog("\tPublishing Config Core Sheap...");
fflush(stdout);
shdata_PublishBackSeg(conf->sheap);
lc_printLog("OK\r\n");
cfg_syncSelf(p,conf);
if(conf->refreshWaitSeconds>0) {
lc_printLog("\tStarting Config Core Realm Process:\n");
lc_closeLogFile();//closing before forking
cfgm_initializeMessagingLoop(p, conf->globals->logsDir,NULL, conf,
cfg_initMessaging,cfg_handleMessageRecieved,
conf->disableProcessRecovery);
lc_openLogFile(p,conf->refreshLogFile);
}
}
return errorRet;
}
static void cfg_printServiceDescriptor(pool* p, cfg_service_descriptor*svc){
apr_hash_index_t *hi;
char *name,*val;
if(svc!=NULL){
if(svc->name!=NULL){
lc_printLog("\t�\t%s [%s]\n",svc->id,svc->name);
}else{
lc_printLog("\t�\t%s\n",svc->id);
}
lc_printLog("\t\tUri:\t%s\n",svc->uri);
lc_printLog("\t\tTimeoutSeconds:\t%d\n",svc->timeoutSeconds);
for (hi = apr_hash_first(p, svc->params); hi; hi = apr_hash_next(hi)) {
apr_hash_this(hi,(const void**)&name, NULL, (void**)&val);
lc_printLog("\t\t%s:\t%s\n",name,val);
}
lc_printLog("\r\n");
}else{
lc_printLog("!!! SERVICE IS NULL\n");
}
}
void configcore_printConfigCoreDetails(pool* p,config_core* conf){
// apr_hash_index_t *hi;
cfg_service_descriptor* svc=NULL;
// char *name,*val;
int i=0;
if(conf==NULL){
lc_printLog("Config-Core: NULL!!\n");
return;
}
lc_printLog("Config-Core:\n");
lc_printLog("�\tGlobals-\n");
lc_printLog("\t\tHomeDir:%s\n",conf->globals->homeDir);
lc_printLog("\t\tOIDCHeaderPrefix:%s\n",conf->oidcHeaderPrefix);
lc_printLog("\t\tEnableUnnamedSHM:%d\n",djrglobals_isUnnamedSHMEnabled());
lc_printLog("\t\tConfigCheckPhaseDelaySec:%d\n",djrglobals_getConfigCheckPhaseDelaySec());
lc_printLog("�\tSystem Services-\n");
if(conf->globals->resourceService!=NULL){
cfg_printServiceDescriptor(p,conf->globals->resourceService);
}else{
lc_printLog("�\tResourceService: NOT ACTIVATED\n");
}
lc_printLog("\t\tSheapMapFile:%s\n",conf->sheapMapFile);
lc_printLog("\t\tSheapPageSize:%d\n",conf->sheapPageSize);
lc_printLog("\t\tPassPhrase:%s\n",conf->passPhrase);
if(conf->service!=NULL){
lc_printLog("�\tServices-\n");
svc=conf->service;
cfg_printServiceDescriptor(p,svc);
}
}
void* configcore_getModuleConfigByName(config_core* conf,char* name){
return conf->serviceConfig;
}
|
tarachandverma/ngx-openidc
|
src/log-utils/logging.h
|
<filename>src/log-utils/logging.h
#ifndef __TCREWRITE_LOGGING__H_
#define __TCREWRITE_LOGGING__H_
#include <apr_file_io.h>
#include "apache_typedefs.h"
typedef struct mm_logger{
pool* p;
char* filepath;
apr_file_t* file;
long maxLogFileSizeMB;
}mm_logger;
mm_logger* logging_getLogger(pool* p,char* path,long maxLogFileSizeMB);
void logging_log(mm_logger* log,const char* a_format, ...);
void logging_printf(mm_logger* log,const char* a_format, ...);
void logging_setMaxFileSize(mm_logger* log,int maxLogFileSizeMB);
int logging_rotateLogFile(mm_logger* log);
int logging_closeLogger(mm_logger* log);
// static refresh log
int lc_openLogFile(apr_pool_t* p,char* filepath);
int lc_closeLogFile(void);
int lc_rotateLogFile();
int lc_truncateLogFile(void);
int lc_trimLogFile(void);
int lc_printLog(const char* format,...);
#endif
|
tarachandverma/ngx-openidc
|
src/oidc-globals/oidc_globals.h
|
#ifndef __TCREWRITE_GLOBALS__H_
#define __TCREWRITE_GLOBALS__H_
//Exposed functions for the Enable unnamed shared memory flag.
void djrglobals_setEnableUnnamedSHM(const char * arg);
int djrglobals_isUnnamedSHMEnabled();
//Exposed functions to set/get config check phase delay seconds.
void djrglobals_setConfigCheckPhaseDelaySec(const char * arg);
int djrglobals_getConfigCheckPhaseDelaySec();
#endif
|
tarachandverma/ngx-openidc
|
src/oidc-core/match_list.c
|
<filename>src/oidc-core/match_list.c
#include <xml_core.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <oidc-core/match_list.h>
#include <oidc-core/rewrite_core.h>
#include <common-utils/common_utils.h>
mlx_match_event* ml_newMatchEventObj(pool*p){
mlx_match_event*ret=(mlx_match_event*)apr_pcalloc(p,sizeof(mlx_match_event));
ret->start=ret->end=0;
return ret;
}
mlx_match_ip*ml_newMatchIpObj(pool*p){
mlx_match_ip* ip=apr_palloc(p,sizeof(mlx_match_ip));
ip->isRegex=TRUE;
ip->negate=FALSE;
ip->ip=NULL;
return ip;
}
mlx_match_path*ml_newMatchPathObj(pool*p){
mlx_match_path* ret=apr_palloc(p,sizeof(mlx_match_path));
ret->negate=FALSE;
ret->path=NULL;
return ret;
}
mlx_match_header* ml_newMatchHeaderObj(pool* p){
mlx_match_header* ret=apr_palloc(p,sizeof(mlx_match_header));
ret->name=NULL;
ret->value=NULL;
ret->delimAnd=NULL;
ret->negate=FALSE;
ret->isRegex=TRUE;
return ret;
}
mlx_match_env* ml_newMatchEnvObj(pool* p){
mlx_match_env* ret=(mlx_match_env*)apr_palloc(p,sizeof(mlx_match_env));
ret->name=NULL;
ret->value=NULL;
ret->negate=FALSE;
ret->isRegex=TRUE;
return ret;
}
mlx_ml_match* ml_newMatchListMatchObj(pool* p){
mlx_ml_match* ret=NULL;
ret=(mlx_ml_match*)apr_palloc(p,sizeof(mlx_ml_match));
ret->host=NULL;
ret->cascade=TRUE;
ret->ip=NULL;
ret->path=NULL;
ret->headerList=apr_array_make(p,2,sizeof(mlx_match_header*));
ret->event=NULL;
return ret;
}
// mlx_match_header* ml_newMatchHeaderObjExt(pool* p,char*name,char*value,char* delimAnd,char* isregex,char* negate){
// mlx_match_header* ret=apr_palloc(p,sizeof(mlx_match_header));
// ret->name=name?apr_pstrdup(p,name):NULL;
// ret->value=value?apr_pstrdup(p,value):NULL;
// ret->delimAnd=delimAnd?apr_pstrdup(p,delimAnd):NULL;
// ret->isRegex=isregex?STRTOBOOL(isregex):TRUE;
// ret->negate=negate?STRTOBOOL(negate):FALSE;
// return ret;
// }
// Return TRUE if all subset elements(string type) are found in a given set.
int ml_isSubsetFound(pool*p,array_header* subset, array_header* set,int isRegex){
int i,j,count;
char* e1,*e2;
int isValueMatch=FALSE;
if(subset==NULL||set==NULL||subset->nelts>set->nelts) return FALSE;
for(i=0,count=0;i<subset->nelts;i++){
e1=cu_getElement(subset,i);
for(j=0;j<set->nelts;j++){
e2=cu_getElement(set,j);
isValueMatch=isRegex?(rc_matchByStringsReturnDetails(p,e1,e2)==NULL):(strcmp(e1,e2)==0);
if(isValueMatch){
count++;
break;
}
}
}
if(count==subset->nelts) return TRUE;
return FALSE;
}
// Return TRUE if none of subset elements(string type) are found in a given set.
int ml_isNegateSubsetFound(pool*p,array_header* subset, array_header* set, int isRegex){
int i,j;
char* e1,*e2;
int isValueMatch=FALSE;
if(subset==NULL||set==NULL) return FALSE;
for(i=0;i<subset->nelts;i++){
e1=cu_getElement(subset,i);
for(j=0;j<set->nelts;j++){
e2=cu_getElement(set,j);
isValueMatch=isRegex?(rc_matchByStringsReturnDetails(p,e1,e2)==NULL):(strcmp(e1,e2)==0);
if(isValueMatch){
return FALSE;
}
}
}
return TRUE;
}
int matchList_isMatched(pool*p,char* regex, char* value, int isRegex)
{
return (isRegex==TRUE
?(rc_matchByStringsReturnDetails(p,regex,value)==NULL)
:(strcmp(regex,value)==0));
}
int matchList_isHostMatched(pool*p, char* matchHost, apr_table_t *headers_in){
if ( matchHost==NULL || headers_in==NULL ) return TRUE;
char* host = (char*)apr_table_get(headers_in, "Host");
return ( host==NULL || (rc_matchByStringsReturnDetails(p, matchHost, host)==NULL) );
}
void ml_printMatchList(pool* p, array_header* arr){
int i=0, j=0;
mlx_ml_match* match=NULL;
mlx_match_header* hdr=NULL;
mlx_match_env* env=NULL;
if(arr!=NULL&&arr->nelts>0){
printf("\r\n\t\t -- MatchList[%d]",arr->nelts);
for(i=0;i<arr->nelts;i++){
match=(mlx_ml_match*)cu_getElement(arr,i);
printf("\r\n\t>\t");
if(match->host!=NULL){
printf("Host: %s ",match->host);
}
if(match->ip!=NULL&&match->ip->ip!=NULL){
printf("IP: %s ",match->ip->ip);
printf("\tisregex: %s ",BOOLTOSTR(match->ip->isRegex));
printf("\tnegate: %s ",BOOLTOSTR(match->ip->negate));
printf("\n");
}
if(match->headerList!=NULL&&match->headerList->nelts>0){
printf("Headers [%d]",match->headerList->nelts);
for(j=0;j<match->headerList->nelts;j++){
hdr=(mlx_match_header*)cu_getElement(match->headerList,j);
printf("\r\n\t\t\t %s = %s",hdr->name,hdr->value);
if(hdr->delimAnd) printf("\r\n\t\t\t delimAnd = \"%s\"",hdr->delimAnd);
printf("\tisregex: %s ",BOOLTOSTR(hdr->isRegex));
printf("\tnegate: %s ",BOOLTOSTR(hdr->negate));
printf("\n");
}
}
printf("\r\n");
}
}
}
|
tarachandverma/ngx-openidc
|
src/oidc-core/oidc_config_core.h
|
#ifndef __TCREWRITE_ACTION_MAPPINGS_CORE__H_
#define __TCREWRITE_ACTION_MAPPINGS_CORE__H_
#include "apache_typedefs.h"
#include "config_bindings_shm.h"
char* amc_initialize(pool* p,shared_heap* sheap,cbs_globals* globals,cfg_service_descriptor* svcdesc,void** userdata);
char* amc_refresh(pool* p,shared_heap* sheap,cbs_globals* globals,cfg_service_descriptor* svcdesc,void** userdata);
char* amc_postRefresh(pool* p,shared_heap* sheap,cfg_globals* globals,cfg_service_descriptor* svcdesc,void** userdata);
#endif
|
tarachandverma/ngx-openidc
|
src/config-core/config_messaging.h
|
<gh_stars>10-100
#ifndef __TCREWRITE_CONFIG_MESSAGING__H_
#define __TCREWRITE_CONFIG_MESSAGING__H_
#include <sys/types.h>
#include "apache_typedefs.h"
#include <config-core/config_messaging_parsing.h>
#include "apr_thread_proc.h"
typedef struct cfgm_connection{
cfgm_wire_header* wireHeader;
}cfgm_connection;
typedef char* (*cfgm_message_recieved_func) (pool*,cfgm_connection*,cfgm_wire_message*,void*, void*);
typedef void* (*cfgm_init_messaging_func)(pool*,void*);
apr_proc_t* cfgm_initializeMessagingLoop(pool* p, char* homeDir, void* messageBroker, void* userdata,
cfgm_init_messaging_func initFunc, cfgm_message_recieved_func msgRecFunc,
int disableProcessRecovery);
cfgm_connection* cfgm_newConnectionObj(pool* p);
int cfgm_isRefreshMessage(cfgm_wire_message* msg);
#endif
|
tarachandverma/ngx-openidc
|
src/oidc-core/match_list.h
|
#ifndef MATCH_LIST_H_
#define MATCH_LIST_H_
typedef struct mlx_match_event{
time_t start;
time_t end;
}mlx_match_event;
typedef struct mlx_match_header{
char* name;
char* value;
char* delimAnd;
int negate;
int isRegex;
}mlx_match_header;
typedef struct mlx_match_ip{
char* ip;
int negate;
int isRegex;
}mlx_match_ip;
typedef struct mlx_match_path{
char* path;
int negate;
}mlx_match_path;
typedef struct mlx_match_env{
char* name;
char* value;
int negate;
int isRegex;
}mlx_match_env;
typedef struct mlx_ml_match{
char* host;
int cascade;
mlx_match_path* path;
mlx_match_ip* ip;
array_header* headerList;
mlx_match_event* event;
}mlx_ml_match;
typedef struct mlx_matchlist{
char* name;
array_header* matches;
}mlx_matchlist;
mlx_match_event* ml_newMatchEventObj(pool*p);
mlx_match_ip*ml_newMatchIpObj(pool*p);
mlx_match_path*ml_newMatchPathObj(pool*p);
mlx_match_header* ml_newMatchHeaderObj(pool* p);
mlx_match_env* ml_newMatchEnvObj(pool* p);
mlx_ml_match* ml_newMatchListMatchObj(pool* p);
// mlx_match_header* ml_newMatchHeaderObjExt(pool* p,char*name,char*value,char* delimAnd,char* negate,char* isregex);
int ml_isSubsetFound(pool*p,array_header* subset, array_header* set,int isRegex);
int ml_isNegateSubsetFound(pool*p,array_header* subset, array_header* set, int isRegex);
int matchList_isMatched(pool*p,char* regex, char* value, int isRegex);
int matchList_isHostMatched(pool*p, char* matchHost, apr_table_t *headers_in);
void ml_printMatchList(pool* p, array_header* arr);
#endif /*MATCH_LIST_H_*/
|
tarachandverma/ngx-openidc
|
src/doc-parser-core/doc_parser_utils.h
|
<reponame>tarachandverma/ngx-openidc
#ifndef DOC_PARSER_UTILS_H_
#define DOC_PARSER_UTILS_H_
#include <config-core/config_bindings_shm.h>
char* docp_getRemoteResourcePath(pool* p, char* resource,cbs_service_descriptor *rs,char* homeDir,char**details);
char* docp_getLocalResourcePath(pool*p,char* resource,char* homeDir);
char* docp_getRemoteResourcePathEx(pool* p, char* resourceUri, char* homeDir,char**details);
#endif /*DOC_PARSER_UTILS_H_*/
|
tarachandverma/ngx-openidc
|
src/service-utils/http-utils/http_client.c
|
#include <http-utils/http_client.h>
//curl stuff
#include <curl/curl.h>
//#include <curl/types.h>
#include <curl/easy.h>
void hc_init(){
curl_global_init(CURL_GLOBAL_ALL);
}
char* hc_getInfo(apr_pool_t* p){
return curl_version();
}
void hc_cleanup(){
curl_global_cleanup();
}
int hc_is200_OK(http_util_result* ret){
return ret!=NULL&&ret->responseCode==200;
}
static size_t hc_memory_callback(void* ptr,size_t size, size_t nmemb, void* data){
size_t realsize=size*nmemb;
http_util_result* res=(http_util_result*)data;
char* tmp=NULL;
if(res->size<=0){
res->size=realsize;
res->data=apr_pcalloc(res->p,realsize+1);
memcpy(res->data,ptr,realsize);
//res->data=(char*)apr_pstrndup(res->p,ptr,realsize);
}else{
tmp=apr_pcalloc(res->p,res->size+realsize+1);
memcpy(tmp,res->data,res->size);
res->data=tmp;
memcpy(tmp+res->size,ptr,realsize);
res->size+=realsize;
//res->data=(char*)apr_pstrcat(res->p,res->data,apr_pstrndup(res->p,(char*)ptr,realsize),NULL);
}
return realsize;
}
static http_util_result* hc_createNewHttpUtilResult(apr_pool_t *p){
http_util_result* ret=ret=apr_pcalloc(p,sizeof(http_util_result));
ret->p=p;
ret->data=NULL;
ret->content_type=NULL;
ret->size=0;
ret->totalTime=0.0;
ret->responseCode=-1;
ret->headers_out=NULL;
return ret;
}
static void hc_setBasicAuthOpts(CURL *curl_handle,char* userAndPass){
curl_easy_setopt(curl_handle,CURLOPT_HTTPAUTH,CURLAUTH_BASIC);
curl_easy_setopt(curl_handle,CURLOPT_USERPWD,userAndPass);
}
http_util_result* hc_head_verbose(apr_pool_t *p,char* uri,long timeout,char* userColonPass,char** error){
CURL *curl_handle=NULL;
CURLcode res;
http_util_result* ret=hc_createNewHttpUtilResult(p);
curl_handle=curl_easy_init();
curl_easy_setopt(curl_handle, CURLOPT_URL,uri);
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION,hc_memory_callback);
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA,ret);
curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, HTTP_USER_AGENT);
curl_easy_setopt(curl_handle, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, timeout);
curl_easy_setopt(curl_handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_easy_setopt(curl_handle, CURLOPT_CUSTOMREQUEST, "HEAD");
/*SSL Options*/
//Allow connect to server using self signed certificate
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, FALSE);
//Allow connect to server with cert hostname (CN) not matching connect string
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 0);
if(userColonPass!=NULL){
hc_setBasicAuthOpts(curl_handle,userColonPass);
}
//perform
res=curl_easy_perform(curl_handle);
if(error!=NULL&&res!=CURLE_OK&&res!=CURLE_PARTIAL_FILE){
*error=apr_pstrdup(p,curl_easy_strerror(res));
}
//get option info
res = curl_easy_getinfo(curl_handle, CURLINFO_TOTAL_TIME, &(ret->totalTime));
res = curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, &(ret->responseCode));
res = curl_easy_getinfo(curl_handle, CURLINFO_CONTENT_TYPE, &(ret->content_type));
if(ret->content_type!=NULL){
ret->content_type=apr_pstrdup(p,ret->content_type);
}
curl_easy_cleanup(curl_handle);
if(ret!=NULL&&ret->responseCode!=0){
return ret;
}
return NULL;
}
typedef struct header_cyc{
struct curl_slist * slist;
apr_pool_t* p;
}header_cyc;
static int hc_bind_headers(void *rec, const char *key, const char *value){
header_cyc* hcyc=(header_cyc*)rec;
char* val=NULL;
if(key!=NULL){
if(value!=NULL){
val=apr_pstrcat(hcyc->p,key,":",value,NULL);
}else{
val=apr_pstrcat(hcyc->p,key,":",NULL);
}
// fprintf(stderr,"Header: %s\n",val);
// fflush(stderr);
hcyc->slist = curl_slist_append(hcyc->slist, val);
}
return 1;
}
typedef struct header_out_pack{
apr_table_t* headers_out;
apr_pool_t* pool;
int cnt;
}header_out_pack;
static char* hc_getTrimmedStr(apr_pool_t* p, char* str){
char* start=NULL,*end=NULL;
int len=0,size=0;
if(str==NULL){
return NULL;
}
start=str;
while(*start!='\0'&&(*start==' '||*start=='\t'||*start=='\n'||*start=='\r')){
start++;
}
len=strlen(str);
end=&(str[len-1]);
while(*end!='\0'&&(*end==' '||*end=='\t'||*end=='\n'||*end=='\r')){
end--;
}
size=end-start+1;
if(size<=0){return NULL;}
return apr_pstrndup(p,start,size);
}
static int hc_isContentChunked(apr_pool_t*p, char* contentType){
char* tmp=hc_getTrimmedStr(p,contentType);
return (tmp!=NULL&&strcasecmp(tmp,"chunked")==0)?TRUE:FALSE;
}
static size_t hc_bind_headers_out(void *ptr, size_t size, size_t nmemb, void *userdata){
size_t retSize=size*nmemb;
char* data=NULL;
char* p1=NULL, *p2=NULL, *cursor=NULL, *cend=NULL;
http_util_result* ret=(http_util_result*)userdata;
data=(char*)apr_pstrndup(ret->p,ptr,retSize);
cursor=strstr(data,":");
if(cursor!=NULL){
*cursor='\0';
cursor++;
cend=strstr(cursor,"\r");
if(cend!=NULL){
*cend='\0';
//
if(1/*strcasecmp(data,"location")==0||strcasecmp(data,"set-cookie")==0
||strcasecmp(data,"set-cookie2")==0||strcasecmp(data,"www-authenticate")==0
||strcasecmp(data,"content-encoding")==0||strcasecmp(data,"vary")==0
||strcasecmp(data,"content-disposition")==0
||strcasecmp(data,"content-transfer-encoding")==0
||(strcasecmp(data,"transfer-encoding")==0&&!hc_isContentChunked(ret->p,cursor))*/){
apr_table_setn(ret->headers_out,apr_pstrdup(ret->p,data),cursor);
}else{
apr_table_setn(ret->headers_out,apr_pstrcat(ret->p,"X-P-",data,NULL),cursor);
}
}
}
return retSize;
}
static void hc_setup_headerbind(apr_pool_t *p,CURL *curl_handle,http_util_result* ret,apr_table_t * headers_in){
header_cyc headcyc;
if(headers_in!=NULL){
headcyc.p=p;
headcyc.slist=NULL;
apr_table_do(hc_bind_headers,&headcyc,headers_in,NULL);
if(headcyc.slist!=NULL){
curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, headcyc.slist);
}
//capture headers out
ret->headers_out=apr_table_make(p,8);
curl_easy_setopt(curl_handle, CURLOPT_HEADERFUNCTION, hc_bind_headers_out);
curl_easy_setopt(curl_handle, CURLOPT_WRITEHEADER,ret);
}
}
http_util_result* hc_get_verbose(apr_pool_t *p,char* uri,long timeout,char* userColonPass, apr_table_t * headers_in,char** error){
CURL *curl_handle=NULL;
CURLcode res;
// header_cyc headcyc;
// header_out_pack houtp;
// apr_table_t* headers_out=NULL;
http_util_result* ret=hc_createNewHttpUtilResult(p);
curl_handle=curl_easy_init();
// curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl_handle, CURLOPT_URL,uri);
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION,hc_memory_callback);
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA,ret);
curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, HTTP_USER_AGENT);
curl_easy_setopt(curl_handle, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, timeout);
curl_easy_setopt(curl_handle, CURLOPT_CONNECTTIMEOUT, 5);
hc_setup_headerbind(p,curl_handle,ret,headers_in);
/*SSL Options*/
//Allow connect to server using self signed certificate
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, FALSE);
//Allow connect to server with cert hostname (CN) not matching connect string
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 0);
if(userColonPass!=NULL){
hc_setBasicAuthOpts(curl_handle,userColonPass);
}
//perform
res=curl_easy_perform(curl_handle);
if(error!=NULL&&res!=CURLE_OK){
*error=apr_pstrdup(p,curl_easy_strerror(res));
}
//get option info
res = curl_easy_getinfo(curl_handle, CURLINFO_TOTAL_TIME, &(ret->totalTime));
res = curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, &(ret->responseCode));
res = curl_easy_getinfo(curl_handle, CURLINFO_CONTENT_TYPE, &(ret->content_type));
if(ret->content_type!=NULL){
ret->content_type=apr_pstrdup(p,ret->content_type);
}
curl_easy_cleanup(curl_handle);
// fprintf(stderr,"Response: %d\n",ret->responseCode);
// fprintf(stderr,"ResponseSize: %d\n",ret->size);
// fflush(stderr);
if(ret!=NULL&&ret->responseCode!=0){
return ret;
}
return NULL;
}
http_util_result* hc_get_verbose2(apr_pool_t *p,char* uri,long timeout,long connectionTimeout,char* userColonPass, apr_table_t * headers_in,char** error){
CURL *curl_handle=NULL;
CURLcode res;
// header_cyc headcyc;
// header_out_pack houtp;
// apr_table_t* headers_out=NULL;
http_util_result* ret=hc_createNewHttpUtilResult(p);
curl_handle=curl_easy_init();
// curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl_handle, CURLOPT_URL,uri);
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION,hc_memory_callback);
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA,ret);
curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, HTTP_USER_AGENT);
curl_easy_setopt(curl_handle, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, timeout);
curl_easy_setopt(curl_handle, CURLOPT_CONNECTTIMEOUT, connectionTimeout);
hc_setup_headerbind(p,curl_handle,ret,headers_in);
/*SSL Options*/
//Allow connect to server using self signed certificate
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, FALSE);
//Allow connect to server with cert hostname (CN) not matching connect string
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 0);
if(userColonPass!=NULL){
hc_setBasicAuthOpts(curl_handle,userColonPass);
}
//perform
res=curl_easy_perform(curl_handle);
if(error!=NULL&&res!=CURLE_OK){
*error=apr_pstrdup(p,curl_easy_strerror(res));
}
//get option info
res = curl_easy_getinfo(curl_handle, CURLINFO_TOTAL_TIME, &(ret->totalTime));
res = curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, &(ret->responseCode));
res = curl_easy_getinfo(curl_handle, CURLINFO_CONTENT_TYPE, &(ret->content_type));
if(ret->content_type!=NULL){
ret->content_type=apr_pstrdup(p,ret->content_type);
}
curl_easy_cleanup(curl_handle);
// fprintf(stderr,"Response: %d\n",ret->responseCode);
// fprintf(stderr,"ResponseSize: %d\n",ret->size);
// fflush(stderr);
if(ret!=NULL&&ret->responseCode!=0){
return ret;
}
return NULL;
}
http_ssl_options* hc_createNewHttpSSLOptions(apr_pool_t *p) {
http_ssl_options* ret=ret=apr_palloc(p,sizeof(http_ssl_options));
ret->certType=NULL;
ret->certFile=NULL;
ret->passPhrase=NULL;
ret->keyType=NULL;
ret->keyName=NULL;
ret->caCertFile=NULL;
return ret;
}
http_util_result* hc_ssl_get_verbose(apr_pool_t *p,char* uri,long timeout,long connectionTimeout,char* userColonPass, http_ssl_options* sslOptions, apr_table_t * headers_in, char** error) {
CURL *curl_handle=NULL;
CURLcode res;
// header_cyc headcyc;
// header_out_pack houtp;
// apr_table_t* headers_out=NULL;
http_util_result* ret=hc_createNewHttpUtilResult(p);
curl_handle=curl_easy_init();
// curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl_handle, CURLOPT_URL,uri);
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION,hc_memory_callback);
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA,ret);
curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, HTTP_USER_AGENT);
curl_easy_setopt(curl_handle, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, timeout);
curl_easy_setopt(curl_handle, CURLOPT_CONNECTTIMEOUT, connectionTimeout);
hc_setup_headerbind(p,curl_handle,ret,headers_in);
/*SSL Options*/
if(sslOptions!=NULL) {
/* since PEM is default, we needn't set it for PEM */
if(sslOptions->certType!=NULL) {
curl_easy_setopt(curl_handle,CURLOPT_SSLCERTTYPE,sslOptions->certType);
}
/* set the cert for client authentication */
if(sslOptions->certFile!=NULL) {
curl_easy_setopt(curl_handle,CURLOPT_SSLCERT,sslOptions->certFile);
}
/* ket passphrase */
if(sslOptions->passPhrase!=NULL) {
curl_easy_setopt(curl_handle,CURLOPT_SSLKEYPASSWD,sslOptions->passPhrase);
}
/* if we use a key stored in a crypto engine,
we must set the key type to "ENG" */
if(sslOptions->keyType!=NULL) {
curl_easy_setopt(curl_handle,CURLOPT_SSLKEYTYPE,sslOptions->keyType);
}
/* set the private key (file or ID in engine) */
if(sslOptions->keyName!=NULL) {
curl_easy_setopt(curl_handle,CURLOPT_SSLKEY,sslOptions->keyName);
}
if(sslOptions->caCertFile!=NULL) {
/* set the file with the certs vaildating the server */
curl_easy_setopt(curl_handle,CURLOPT_CAINFO,sslOptions->caCertFile);
/* disconnect if we can't validate server's cert */
curl_easy_setopt(curl_handle,CURLOPT_SSL_VERIFYPEER,1L);
}else{
//Allow connect to server using self signed certificate
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, FALSE);
//Allow connect to server with cert hostname (CN) not matching connect string
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 0);
}
}else{
//Allow connect to server using self signed certificate
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, FALSE);
//Allow connect to server with cert hostname (CN) not matching connect string
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 0);
}
if(userColonPass!=NULL){
hc_setBasicAuthOpts(curl_handle,userColonPass);
}
//perform
res=curl_easy_perform(curl_handle);
if(error!=NULL&&res!=CURLE_OK){
*error=apr_pstrdup(p,curl_easy_strerror(res));
}
//get option info
res = curl_easy_getinfo(curl_handle, CURLINFO_TOTAL_TIME, &(ret->totalTime));
res = curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, &(ret->responseCode));
res = curl_easy_getinfo(curl_handle, CURLINFO_CONTENT_TYPE, &(ret->content_type));
if(ret->content_type!=NULL){
ret->content_type=apr_pstrdup(p,ret->content_type);
}
curl_easy_cleanup(curl_handle);
// fprintf(stderr,"Response: %d\n",ret->responseCode);
// fprintf(stderr,"ResponseSize: %d\n",ret->size);
// fflush(stderr);
if(ret!=NULL&&ret->responseCode!=0){
return ret;
}
return NULL;
}
http_util_result* hc_get(apr_pool_t *p,char* uri,long timeout){
return hc_get_verbose(p,uri,timeout,NULL,NULL,NULL);
}
http_util_result* hc_post_verbose(apr_pool_t *p,char* uri,long timeout,char* userColonPass,const char* postData,int postDataLen, apr_table_t * headers_in){
CURL *curl_handle=NULL;
CURLcode res;
http_util_result* ret=hc_createNewHttpUtilResult(p);
curl_handle=curl_easy_init();
curl_easy_setopt(curl_handle, CURLOPT_POST,1);
//curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1);
if(postData!=NULL){
curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS , postData) ;
curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDSIZE , postDataLen) ;
// fprintf(stderr,"PostSize: %d\n",postDataLen);
// fflush(stderr);
//curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDSIZE , strlen(postData)) ;
}else{
curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDSIZE , 0);
}
curl_easy_setopt(curl_handle, CURLOPT_URL,uri);
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION,hc_memory_callback);
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA,ret);
curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, HTTP_USER_AGENT);
curl_easy_setopt(curl_handle, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, timeout);
curl_easy_setopt(curl_handle, CURLOPT_CONNECTTIMEOUT, 5);
hc_setup_headerbind(p,curl_handle,ret,headers_in);
/*SSL Options*/
//Allow connect to server using self signed certificate
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, FALSE);
//Allow connect to server with cert hostname (CN) not matching connect string
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 0);
if(userColonPass!=NULL){
hc_setBasicAuthOpts(curl_handle,userColonPass);
}
//perform
curl_easy_perform(curl_handle);
//get option info
res = curl_easy_getinfo(curl_handle, CURLINFO_TOTAL_TIME, &(ret->totalTime));
res = curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, &(ret->responseCode));
res = curl_easy_getinfo(curl_handle, CURLINFO_CONTENT_TYPE, &(ret->content_type));
if(ret->content_type!=NULL){
ret->content_type=apr_pstrdup(p,ret->content_type);
}
curl_easy_cleanup(curl_handle);
// fprintf(stderr,"Response: %d\n",ret->responseCode);
// fprintf(stderr,"ResponseSize: %d\n",ret->size);
// fflush(stderr);
if(ret!=NULL&&ret->responseCode!=0){
return ret;
}
return NULL;
}
http_util_result* hc_ssl_post_verbose(apr_pool_t *p,char* uri,long timeout,char* userColonPass,const char* postData,int postDataLen, http_ssl_options* sslOptions, apr_table_t * headers_in){
CURL *curl_handle=NULL;
CURLcode res;
http_util_result* ret=hc_createNewHttpUtilResult(p);
curl_handle=curl_easy_init();
curl_easy_setopt(curl_handle, CURLOPT_POST,1);
//curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1);
if(postData!=NULL){
curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS , postData) ;
curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDSIZE , postDataLen) ;
// fprintf(stderr,"PostSize: %d\n",postDataLen);
// fflush(stderr);
//curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDSIZE , strlen(postData)) ;
}else{
curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDSIZE , 0);
}
curl_easy_setopt(curl_handle, CURLOPT_URL,uri);
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION,hc_memory_callback);
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA,ret);
curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, HTTP_USER_AGENT);
curl_easy_setopt(curl_handle, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, timeout);
curl_easy_setopt(curl_handle, CURLOPT_CONNECTTIMEOUT, 5);
hc_setup_headerbind(p,curl_handle,ret,headers_in);
/*SSL Options*/
/*SSL Options*/
if(sslOptions!=NULL) {
/* since PEM is default, we needn't set it for PEM */
if(sslOptions->certType!=NULL) {
curl_easy_setopt(curl_handle,CURLOPT_SSLCERTTYPE,sslOptions->certType);
}
/* set the cert for client authentication */
if(sslOptions->certFile!=NULL) {
curl_easy_setopt(curl_handle,CURLOPT_SSLCERT,sslOptions->certFile);
}
/* ket passphrase */
if(sslOptions->passPhrase!=NULL) {
curl_easy_setopt(curl_handle,CURLOPT_SSLKEYPASSWD,sslOptions->passPhrase);
}
/* if we use a key stored in a crypto engine,
we must set the key type to "ENG" */
if(sslOptions->keyType!=NULL) {
curl_easy_setopt(curl_handle,CURLOPT_SSLKEYTYPE,sslOptions->keyType);
}
/* set the private key (file or ID in engine) */
if(sslOptions->keyName!=NULL) {
curl_easy_setopt(curl_handle,CURLOPT_SSLKEY,sslOptions->keyName);
}
if(sslOptions->caCertFile!=NULL) {
/* set the file with the certs vaildating the server */
curl_easy_setopt(curl_handle,CURLOPT_CAINFO,sslOptions->caCertFile);
/* disconnect if we can't validate server's cert */
curl_easy_setopt(curl_handle,CURLOPT_SSL_VERIFYPEER,1L);
}else{
//Allow connect to server using self signed certificate
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, FALSE);
//Allow connect to server with cert hostname (CN) not matching connect string
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 0);
}
}else{
//Allow connect to server using self signed certificate
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, FALSE);
//Allow connect to server with cert hostname (CN) not matching connect string
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 0);
}
if(userColonPass!=NULL){
hc_setBasicAuthOpts(curl_handle,userColonPass);
}
//perform
curl_easy_perform(curl_handle);
//get option info
res = curl_easy_getinfo(curl_handle, CURLINFO_TOTAL_TIME, &(ret->totalTime));
res = curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, &(ret->responseCode));
res = curl_easy_getinfo(curl_handle, CURLINFO_CONTENT_TYPE, &(ret->content_type));
if(ret->content_type!=NULL){
ret->content_type=apr_pstrdup(p,ret->content_type);
}
curl_easy_cleanup(curl_handle);
// fprintf(stderr,"Response: %d\n",ret->responseCode);
// fprintf(stderr,"ResponseSize: %d\n",ret->size);
// fflush(stderr);
if(ret!=NULL&&ret->responseCode!=0){
return ret;
}
return NULL;
}
typedef struct http_put_data{
size_t len;
char* data;
char* cursor;
}http_put_data;
static http_put_data* http_newPutDataObj(apr_pool_t *p, char* str, int datalen){
http_put_data* ret=NULL;
ret=apr_palloc(p,sizeof(http_put_data));
ret->len=datalen;
ret->data=str;
ret->cursor=str;
return ret;
}
size_t http_put_callback(void *buffer, size_t size, size_t nmemb, void *userp){
http_put_data* putData=(http_put_data*)userp;
int copyBytes=0;
//max size to out buffer can hold
int maxbytes = size*nmemb;
if(putData->len>0){
if(putData->len>maxbytes){
copyBytes=maxbytes;
}else{
copyBytes=putData->len;
}
memcpy(buffer,putData->cursor,copyBytes);
//printf("out:%s,%d", buffer,putData->len);
putData->cursor+=copyBytes;
putData->len-=copyBytes;
return copyBytes;
}else{
return 0;
}
}
http_util_result* hc_put_verbose2(apr_pool_t *p,char* uri,long timeout,char* userColonPass, const char* putData,int putDataLen, apr_table_t * headers_in){
CURL *curl_handle=NULL;
CURLcode res;
http_util_result* ret=hc_createNewHttpUtilResult(p);
http_put_data* putObj=NULL;
curl_handle=curl_easy_init();
if(putData!=NULL){
putObj=http_newPutDataObj(p,(char*)putData,putDataLen);
curl_easy_setopt(curl_handle, CURLOPT_READFUNCTION,http_put_callback);
curl_easy_setopt(curl_handle, CURLOPT_READDATA,putObj);
curl_easy_setopt(curl_handle, CURLOPT_INFILESIZE,putObj->len);
}else{
curl_easy_setopt(curl_handle, CURLOPT_INFILESIZE,0);
}
curl_easy_setopt(curl_handle, CURLOPT_UPLOAD, TRUE);
curl_easy_setopt(curl_handle, CURLOPT_PUT, TRUE);
curl_easy_setopt(curl_handle, CURLOPT_URL,uri);
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION,hc_memory_callback);
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA,ret);
curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, HTTP_USER_AGENT);
curl_easy_setopt(curl_handle, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, timeout);
curl_easy_setopt(curl_handle, CURLOPT_CONNECTTIMEOUT, 5);
hc_setup_headerbind(p,curl_handle,ret,headers_in);
/*SSL Options*/
//Allow connect to server using self signed certificate
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, FALSE);
//Allow connect to server with cert hostname (CN) not matching connect string
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 0);
if(userColonPass!=NULL){
hc_setBasicAuthOpts(curl_handle,userColonPass);
}
//perform
curl_easy_perform(curl_handle);
//get option info
res = curl_easy_getinfo(curl_handle, CURLINFO_TOTAL_TIME, &(ret->totalTime));
res = curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, &(ret->responseCode));
res = curl_easy_getinfo(curl_handle, CURLINFO_CONTENT_TYPE, &(ret->content_type));
if(ret->content_type!=NULL){
ret->content_type=apr_pstrdup(p,ret->content_type);
}
curl_easy_cleanup(curl_handle);
if(ret!=NULL&&ret->responseCode!=0){
return ret;
}
return NULL;
}
http_util_result* hc_put_verbose(apr_pool_t *p,char* uri,long timeout,char* userColonPass, char* putData){
CURL *curl_handle=NULL;
CURLcode res;
http_util_result* ret=hc_createNewHttpUtilResult(p);
http_put_data* putObj=NULL;
//struct curl_slist *slist = NULL;
//slist = curl_slist_append(slist, "Accept: text/xml");
//slist = curl_slist_append(slist, "Content-Type: text/xml");
//slist = curl_slist_append(slist, "Expect:");
curl_handle=curl_easy_init();
//curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1);
//curl_easy_setopt(curl_handle, CURLOPT_CUSTOMREQUEST, "PUT");
//curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, slist);
if(putData!=NULL){
putObj=http_newPutDataObj(p,putData,strlen(putData));
curl_easy_setopt(curl_handle, CURLOPT_READFUNCTION,http_put_callback);
curl_easy_setopt(curl_handle, CURLOPT_READDATA,putObj);
curl_easy_setopt(curl_handle, CURLOPT_INFILESIZE,putObj->len);
}else{
curl_easy_setopt(curl_handle, CURLOPT_INFILESIZE,0);
}
curl_easy_setopt(curl_handle, CURLOPT_UPLOAD, TRUE);
curl_easy_setopt(curl_handle, CURLOPT_PUT, TRUE);
curl_easy_setopt(curl_handle, CURLOPT_URL,uri);
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION,hc_memory_callback);
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA,ret);
curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, HTTP_USER_AGENT);
curl_easy_setopt(curl_handle, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, timeout);
curl_easy_setopt(curl_handle, CURLOPT_CONNECTTIMEOUT, 5);
/*SSL Options*/
//Allow connect to server using self signed certificate
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, FALSE);
//Allow connect to server with cert hostname (CN) not matching connect string
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 0);
if(userColonPass!=NULL){
hc_setBasicAuthOpts(curl_handle,userColonPass);
}
//perform
curl_easy_perform(curl_handle);
//get option info
res = curl_easy_getinfo(curl_handle, CURLINFO_TOTAL_TIME, &(ret->totalTime));
res = curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, &(ret->responseCode));
res = curl_easy_getinfo(curl_handle, CURLINFO_CONTENT_TYPE, &(ret->content_type));
if(ret->content_type!=NULL){
ret->content_type=apr_pstrdup(p,ret->content_type);
}
curl_easy_cleanup(curl_handle);
if(ret!=NULL&&ret->responseCode!=0){
return ret;
}
return NULL;
}
http_util_result* hc_delete_verbose(apr_pool_t *p,char* uri,long timeout,char* userColonPass){
CURL *curl_handle=NULL;
CURLcode res;
http_util_result* ret=hc_createNewHttpUtilResult(p);
curl_handle=curl_easy_init();
curl_easy_setopt(curl_handle, CURLOPT_URL,uri);
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION,hc_memory_callback);
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA,ret);
curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, HTTP_USER_AGENT);
curl_easy_setopt(curl_handle, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, timeout);
curl_easy_setopt(curl_handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_easy_setopt(curl_handle, CURLOPT_CUSTOMREQUEST, "DELETE");
/*SSL Options*/
//Allow connect to server using self signed certificate
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, FALSE);
//Allow connect to server with cert hostname (CN) not matching connect string
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 0);
if(userColonPass!=NULL){
hc_setBasicAuthOpts(curl_handle,userColonPass);
}
//perform
curl_easy_perform(curl_handle);
//get option info
res = curl_easy_getinfo(curl_handle, CURLINFO_TOTAL_TIME, &(ret->totalTime));
res = curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, &(ret->responseCode));
res = curl_easy_getinfo(curl_handle, CURLINFO_CONTENT_TYPE, &(ret->content_type));
if(ret->content_type!=NULL){
ret->content_type=apr_pstrdup(p,ret->content_type);
}
curl_easy_cleanup(curl_handle);
if(ret!=NULL&&ret->responseCode!=0){
return ret;
}
return NULL;
}
http_util_result* hc_method(apr_pool_t *p,const char* methodName,char* uri,long timeout,char* userColonPass,const char* data,int dataLen, apr_table_t * headers_in){
CURL *curl_handle=NULL;
CURLcode res;
http_util_result* ret=hc_createNewHttpUtilResult(p);
curl_handle=curl_easy_init();
curl_easy_setopt(curl_handle, CURLOPT_POST,1);
curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl_handle, CURLOPT_CUSTOMREQUEST, methodName);
if(data!=NULL){
curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS , data) ;
curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDSIZE , dataLen) ;
// fprintf(stderr,"PostSize: %d\n",postDataLen);
// fflush(stderr);
//curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDSIZE , strlen(postData)) ;
}else{
curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDSIZE , 0);
}
curl_easy_setopt(curl_handle, CURLOPT_URL,uri);
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION,hc_memory_callback);
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA,ret);
curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, HTTP_USER_AGENT);
curl_easy_setopt(curl_handle, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, timeout);
curl_easy_setopt(curl_handle, CURLOPT_CONNECTTIMEOUT, 5);
hc_setup_headerbind(p,curl_handle,ret,headers_in);
/*SSL Options*/
//Allow connect to server using self signed certificate
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, FALSE);
//Allow connect to server with cert hostname (CN) not matching connect string
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 0);
if(userColonPass!=NULL){
hc_setBasicAuthOpts(curl_handle,userColonPass);
}
//perform
curl_easy_perform(curl_handle);
//get option info
res = curl_easy_getinfo(curl_handle, CURLINFO_TOTAL_TIME, &(ret->totalTime));
res = curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, &(ret->responseCode));
res = curl_easy_getinfo(curl_handle, CURLINFO_CONTENT_TYPE, &(ret->content_type));
if(ret->content_type!=NULL){
ret->content_type=apr_pstrdup(p,ret->content_type);
}
curl_easy_cleanup(curl_handle);
fprintf(stderr,"Response: %d\n",ret->responseCode);
fprintf(stderr,"Response: data: %s\n",ret->data);
fprintf(stderr,"ResponseSize: %d\n",ret->size);
fprintf(stderr,"ResponseSize STR: %d\n",strlen(ret->data));
//fflush(stderr);
if(ret!=NULL&&ret->responseCode!=0){
return ret;
}
return NULL;
}
|
tarachandverma/ngx-openidc
|
src/config-core/config_bindings.c
|
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <stdlib.h>
#include <config-core/config_bindings.h>
#include <common_utils.h>
#include <http-utils/http_client.h>
#include "rewrite_core.h"
#ifndef __USE_GNU
#define __USE_GNU
#endif
#include <dlfcn.h>
#define URI_POSTFIX_AUTOREFRESH_TIMESTAMP "autoRefreshTimestamp.txt"
cfg_service_descriptor* cb_newServiceDescriptorObj(pool* p){
cfg_service_descriptor* ret=(cfg_service_descriptor*)apr_palloc(p,sizeof(cfg_service_descriptor));
ret->id=NULL;
ret->name=NULL;
ret->uri=NULL;
ret->userColonPass=NULL;
ret->timeoutSeconds=2;
ret->params=apr_hash_make(p);
return ret;
}
cfg_globals* cb_newGlobalsObj(pool* p){
cfg_globals* ret=(cfg_globals*)apr_pcalloc(p,sizeof(cfg_globals));
ret->homeDir=NULL;
ret->logsDir=NULL;
ret->resourceService=NULL;
return ret;
}
char* cb_initGlobals(pool* p,cfg_globals* globals){
if(globals->logsDir!=NULL){
apr_dir_make_recursive(globals->logsDir,APR_OS_DEFAULT,p);
}
return NULL;
}
char* cb_writeRemoteResourceToDisk(pool* p, char* homeDir, char* reqUri, char* resource, long timeoutSeconds, char* userColonPass,
apr_pool_t* tp, char**details, int* responseCode){
char* ret=NULL, * bakFile=NULL,* filename=NULL;
http_util_result* result=NULL;
//file vars
apr_file_t* file=NULL;
apr_status_t status;
apr_size_t file_written;
char* errorMsg=NULL;
if(resource==NULL) return NULL;
result=hc_get_verbose(p,reqUri,timeoutSeconds,userColonPass,NULL,&errorMsg);
if(hc_is200_OK(result)){
//write file to filesystem
if(result->size>0){
bakFile=apr_pstrcat(tp,homeDir,"/",resource,".part",NULL);
status=apr_file_open(&file,bakFile,APR_WRITE|APR_CREATE|APR_TRUNCATE,APR_OS_DEFAULT,tp);
if(apr_file_write_full(file,result->data,result->size,&file_written)==APR_SUCCESS){
filename=apr_pstrcat(p,homeDir,"/",resource,NULL);
apr_file_close(file);
if(apr_file_rename(bakFile,filename,tp)==APR_SUCCESS){
ret=filename;
}
}else{
apr_file_close(file);
if(details!=NULL){
*details=apr_pstrcat(p,"Failure to write file:",SAFESTR(bakFile),NULL);
}
}
}
}else{
if(details!=NULL){
*details=apr_pstrcat(p,"Failure to write file (Response Code!=200): ",SAFESTR(resource),",",SAFESTR(errorMsg),NULL);
}
if(responseCode!=NULL&&result!=NULL){
*responseCode=result->responseCode;
}
}
return ret;
}
int cb_canAutoRefreshNow(pool* p, cfg_service_descriptor* resourceService, time_t lastRefreshTimestamp, time_t currentTimestamp, char* namespace,char**error){
http_util_result* httpResult=NULL;
char* endptr=NULL;
char* reqQuery=NULL;
long long value=-1;
if(resourceService==NULL) return FALSE;
reqQuery=apr_pstrcat(p,resourceService->uri,namespace,"/",URI_POSTFIX_AUTOREFRESH_TIMESTAMP,NULL);
httpResult=hc_get_verbose2(p,reqQuery,resourceService->timeoutSeconds,5,resourceService->userColonPass,NULL,error);
if(httpResult==NULL||httpResult->data==NULL||!hc_is200_OK(httpResult)) return FALSE;
time_t autoRefreshTimestamp = cu_dateStringToSeconds(httpResult->data);
if(autoRefreshTimestamp<0 || currentTimestamp<autoRefreshTimestamp) return FALSE;
return TRUE;
}
|
tarachandverma/ngx-openidc
|
src/json-api-core/unit-test/json_api_core_unit_test.c
|
<gh_stars>10-100
#include <stdlib.h>
#include <apr_general.h>
#include <apr_pools.h>
#include <stdio.h>
#include <assert.h>
#include "CuTest.h"
#include "json_parser.h"
#include "json_api.h"
#include "common_utils.h"
// Used by some code below as an example datatype.
struct record {const char *precision;double lat,lon;const char *address,*city,*state,*zip,*country; };
// Create a bunch of objects as demonstration.
void JSON_CreateObject_test(mm_logger* logger, CuTest*tc) {
pool*p = logger->pool;
Value *root,*fmt,*img,*thm,*fld;char *out;int i; // declare a few.
// Here we construct some JSON standards, from the JSON site.
// Our "Video" datatype:
root=JSON_CreateObject(p);
JSON_AddItemToObject(p,root, "name", JSON_CreateString(p,"Jack (\"Bee\") Nimble"));
JSON_AddItemToObject(p,root, "format", fmt=JSON_CreateObject(p));
JSON_AddStringToObject(p,fmt,"type", "rect");
JSON_AddNumberToObject(p,fmt,"width", 1920);
JSON_AddNumberToObject(p,fmt,"height", 1080);
JSON_AddFalseToObject (p,fmt,"interlace");
JSON_AddNumberToObject(p,fmt,"frame rate", 24);
out=JSON_Serialize(p,root);
CuAssertPtrNotNullMsg(tc,"Failed to serialize data from JSON_CreateObject_test", out);
}
// Create a bunch of objects as demonstration.
void JSON_CreateArray_test(mm_logger* logger, CuTest*tc) {
pool*p = logger->pool;
Value *root,*fmt,*img,*thm,*fld;char *out;int i; // declare a few.
// Our matrix:
int numbers[3][3]={{0,-1,0},{1,0,0},{0,0,1}};
root=JSON_CreateArray(p);
for (i=0;i<3;i++) JSON_AddItemToArray(p,root,JSON_CreateIntArray(p,numbers[i],3));
out=JSON_Serialize(p,root);
CuAssertPtrNotNullMsg(tc,"Failed to serialize data from JSON_CreateArray_test", out);
}
// Create a bunch of objects as demonstration.
void JSON_CreateStringArray_test(mm_logger* logger, CuTest*tc) {
pool*p = logger->pool;
Value *root,*fmt,*img,*thm,*fld;char *out;int i; // declare a few.
// Our "days of the week" array:
const char *strings[7]={"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
root=JSON_CreateStringArray(p,strings,7);
out=JSON_Serialize(p,root);
CuAssertPtrNotNullMsg(tc,"Failed to serialize data from JSON_CreateStringArray_test", out);
}
// Create a bunch of objects as demonstration.
void JSON_AddItemToObject_test(mm_logger* logger, CuTest*tc) {
pool*p = logger->pool;
Value *root,*fmt,*img,*thm,*fld;char *out;int i; // declare a few.
// Our "gallery" item:
int ids[4]={116,943,234,38793};
root=JSON_CreateObject(p);
JSON_AddItemToObject(p,root, "Image", img=JSON_CreateObject(p));
JSON_AddNumberToObject(p,img,"Width",800);
JSON_AddNumberToObject(p,img,"Height",600);
JSON_AddStringToObject(p,img,"Title","View from 15th Floor");
JSON_AddItemToObject(p,img, "Thumbnail", thm=JSON_CreateObject(p));
JSON_AddStringToObject(p,thm, "Url", "http://www.example.com/image/481989943");
JSON_AddNumberToObject(p,thm,"Height",125);
JSON_AddStringToObject(p,thm,"Width","100");
JSON_AddItemToObject(p,img,"IDs", JSON_CreateIntArray(p,ids,4));
out=JSON_Serialize(p,root);
CuAssertPtrNotNullMsg(tc,"Failed to serialize data from JSON_AddItemToObject_test", out);
}
// Create a bunch of objects as demonstration.
void JSON_AddItemToArray_test(mm_logger* logger, CuTest*tc) {
pool*p = logger->pool;
Value *root,*fmt,*img,*thm,*fld;char *out;int i; // declare a few.
// Our array of "records":
struct record fields[2]={
{"zip",37.7668,-1.223959e+2,"","SAN FRANCISCO","CA","94107","US"},
{"zip",37.371991,-1.22026e+2,"","SUNNYVALE","CA","94085","US"}};
root=JSON_CreateArray(p);
for (i=0;i<2;i++)
{
JSON_AddItemToArray(p,root,fld=JSON_CreateObject(p));
JSON_AddStringToObject(p,fld, "precision", fields[i].precision);
JSON_AddNumberToObject(p,fld, "Latitude", fields[i].lat);
JSON_AddNumberToObject(p,fld, "Longitude", fields[i].lon);
JSON_AddStringToObject(p,fld, "Address", fields[i].address);
JSON_AddStringToObject(p,fld, "City", fields[i].city);
JSON_AddStringToObject(p,fld, "State", fields[i].state);
JSON_AddStringToObject(p,fld, "Zip", fields[i].zip);
JSON_AddStringToObject(p,fld, "Country", fields[i].country);
}
out=JSON_Serialize(p,root);
CuAssertPtrNotNullMsg(tc,"Failed to serialize data from JSON_AddItemToArray_test", out);
}
void jsonapi_deserializeJsonStringMap_test(mm_logger* logger, CuTest*tc) {
pool*p = logger->pool;
const char* requestBody = "{\"username\":\"testuser\",\"password\":\"<PASSWORD>\",\"savelogin\":\"true\",\"template\":\"default\", \"realm\":\"test\", \"url\":\"http%3A%2F%2Fonline.s.dev.wsj.com%2Fmyaccount\"}\r\n";
apr_hash_t* params=jsonapi_deserializeJsonStringMap(p, requestBody);
CuAssertPtrNotNullMsg(tc,"Unable to desrializeString map using jsonapi_deserializeJsonStringMap", params);
}
void jsonapi_getJsonIdentityFromParams_test(mm_logger* logger, CuTest*tc) {
pool*p = logger->pool;
const char* requestBody = "{\"username\":\"testuser\",\"password\":\"<PASSWORD>\",\"savelogin\":\"true\",\"template\":\"default\", \"realm\":\"test\", \"url\":\"http%3A%2F%2Fonline.s.dev.wsj.com%2Fmyaccount\"}\r\n";
apr_hash_t* params=jsonapi_deserializeJsonStringMap(p, requestBody);
CuAssertPtrNotNullMsg(tc,"Unable to desrializeString map using jsonapi_deserializeJsonStringMap", params);
jsonIdentity* identity=jsonapi_getJsonIdentityFromParams(p, params);
CuAssertPtrNotNullMsg(tc,"Unable to build json_identity in jsonapi_getJsonIdentityFromParams", params);
//preconditions
statusMessage* statusMsg=jsonapi_preconditionFailureStatus(p,identity);
CuAssertPtrNotNullMsg(tc,"statusMsg is null", statusMsg);
jsonapi_statusMessageAddEntry(p,statusMsg,"username","parameter","The user does not exist or password does not match.","invalid-credentials");
int count = jsonapi_getStatusErrorCount(p,statusMsg->entries);
CuAssertIntEquals(tc,1,count);
}
static jsonSession* jsonapiunittest_createMockJsonSession(pool*p){
char *tmp;
jsonSession* jsonSess=jsonapi_newJsonSessionObj(p);
apr_hash_t* tokenMap=NULL;
tokenMap=apr_hash_make(p);
apr_hash_set(tokenMap,JSON_TOKEN_USER,APR_HASH_KEY_STRING,"dj_chandt");
apr_hash_set(tokenMap,JSON_TOKEN_PASSWORD,APR_HASH_KEY_STRING,"<PASSWORD>");
apr_hash_set(tokenMap,JSON_TOKEN_UUID,APR_HASH_KEY_STRING,"dj_chandt");
apr_hash_set(tokenMap,JSON_TOKEN_TIMESTAMP,APR_HASH_KEY_STRING,apr_ltoa(p,time(NULL)));
apr_hash_set(tokenMap,JSON_TOKEN_SAVE_LOGIN,APR_HASH_KEY_STRING,apr_pstrdup(p,"true"));
apr_hash_set(tokenMap,JSON_TOKEN_REALM,APR_HASH_KEY_STRING,"default");
apr_hash_set(tokenMap,JSON_TOKEN_TEMPLATE,APR_HASH_KEY_STRING,"default");
jsonSess->token=astru_serializeStringMapEscapeQuote(p,tokenMap);
jsonSess->profileMsg=jsonapi_newProfileMessageObj(p);
tmp=apr_pstrdup(p,"success");
jsonapi_profileMessageAddEntry(p,jsonSess->profileMsg, "result",tmp);
tmp=SAFEDUP(p,"dj_chandt");
jsonapi_profileMessageAddEntry(p,jsonSess->profileMsg, "username",tmp);
tmp=SAFEDUP(p,"dj_chandt");
jsonapi_profileMessageAddEntry(p,jsonSess->profileMsg, "uuid", tmp);
return jsonSess;
}
void jsonapi_profileMessageToJson_test(mm_logger* logger, CuTest*tc) {
pool*p = logger->pool;
jsonSession* jsonSess = jsonapiunittest_createMockJsonSession(p);
CuAssertPtrNotNullMsg(tc,"jsonSess is null", jsonSess);
char* responseBody=jsonapi_profileMessageToJson(p, jsonSess->profileMsg);
CuAssertPtrNotNullMsg(tc,"statusMsg is null", responseBody);
}
void jsonapi_statusMessageToJson_test(mm_logger* logger, CuTest*tc) {
pool*p = logger->pool;
const char* requestBody = "{\"username_missing\":\"testuser\",\"password_missing\":\"<PASSWORD>\",\"savelogin\":\"true\",\"template_missing\":\"default\", \"realm_missing\":\"test\", \"url_missing\":\"http%3A%2F%2Fonline.s.dev.wsj.com%2Fmyaccount\"}\r\n";
apr_hash_t* params=jsonapi_deserializeJsonStringMap(p, requestBody);
CuAssertPtrNotNullMsg(tc,"Unable to desrializeString map in jsonapi_statusMessageToJson_test", params);
jsonIdentity* identity=jsonapi_getJsonIdentityFromParams(p, params);
//preconditions
statusMessage* statusMsg=jsonapi_preconditionFailureStatus(p,identity);
CuAssertPtrNotNullMsg(tc,"statusMsg is null", statusMsg);
char* responseBody=jsonapi_statusMessageToJson(p, statusMsg);
CuAssertPtrNotNullMsg(tc,"statusMsg is null", responseBody);
}
CuSuite* jsonapi_GetSuite() {
CuSuite* suite = CuSuiteNew();
SUITE_ADD_TEST(suite, JSON_CreateObject_test);
SUITE_ADD_TEST(suite, JSON_CreateArray_test);
SUITE_ADD_TEST(suite, JSON_CreateStringArray_test);
SUITE_ADD_TEST(suite, JSON_AddItemToObject_test);
SUITE_ADD_TEST(suite, JSON_AddItemToArray_test);
SUITE_ADD_TEST(suite, jsonapi_deserializeJsonStringMap_test);
SUITE_ADD_TEST(suite, jsonapi_getJsonIdentityFromParams_test);
SUITE_ADD_TEST(suite, jsonapi_profileMessageToJson_test);
SUITE_ADD_TEST(suite, jsonapi_statusMessageToJson_test);
return suite;
}
|
tarachandverma/ngx-openidc
|
src/xml-core/token_utils.h
|
/*
* Created by <NAME> on 01/04/14.
*
*/
#ifndef __TCREWRITE_TOKEN_UTILS__H_
#define __TCREWRITE_TOKEN_UTILS__H_
#include "apache_typedefs.h"
typedef struct {
char* text;
char* delim;
int delim_len;
size_t offset;
pool* p;
} Tokener;
Tokener* tu_getTokenizer (pool* p, char* text, char* delim);
char *tu_next_token(Tokener* tok);
char *tu_remaining_text (Tokener* tok);
#endif
|
tarachandverma/ngx-openidc
|
src/apache-utils/apache_macros.h
|
/*
* Created by <NAME> on 01/04/14.
*
*/
#ifndef __TCREWRITE_APACHE_MACROS__H_
#define __TCREWRITE_APACHE_MACROS__H_
#define SAFESTR(str) (str!=NULL?str:"NULL")
#define SAFESTRBLANK(str) (str!=NULL?str:"")
#define SAFESTRELSE(str,elstr) (str!=NULL?str:elstr)
#define SAFESTRLEN(str) (str!=NULL?strlen(str):0)
#define BOOLTOSTR(bol) (bol!=1?"FALSE":"TRUE")
#define STRTOBOOL(str) ((str!=NULL&&(strcmp(str,"true")==0||strcmp(str,"TRUE")==0||strcmp(str,"on")==0))?1:0)
#define SAFEDUP(p,str) (str==NULL?NULL:apr_pstrdup(p,str))
#define str(s) #s
#define PIDWRAP(msg) "INFO: ID>%d< " msg "" , getpid ()
#define PIDWRAPC(msg) "CRITICAL: ID>%d< " msg "" , getpid ()
#define APACHE_LOG_DEBUG(msg)
#define APACHE_LOG_DEBUG1(msg, arg1)
#define APACHE_FREE_CHAR_ARRAY(arr)
#define AP_LOG_CRITICAL1(req,msg,arg){ap_log_error(APLOG_MARK, APLOG_CRIT,APR_SUCCESS, req->server, PIDWRAPC(msg),arg);}
#define AP_LOG_ERROR(req,msg){ap_log_error(APLOG_MARK, APLOG_INFO,APR_SUCCESS,req->server, PIDWRAP(msg));}
#define AP_LOG_ERROR1(req,msg,arg){ap_log_error(APLOG_MARK, APLOG_INFO,APR_SUCCESS,req->server, PIDWRAP(msg),arg);}
#define AP_LOG_ERROR2(req,msg,arg,arg1){ap_log_error(APLOG_MARK, APLOG_INFO,APR_SUCCESS,req->server,PIDWRAP(msg),arg,arg1);}
#define AP_LOG_ERROR3(req,msg,arg,arg1,arg2){ap_log_error(APLOG_MARK, APLOG_INFO,APR_SUCCESS,req->server,PIDWRAP(msg),arg,arg1,arg2);}
#define AP_RPRINTF(req,arg1){ap_rprintf(req,arg1);}
#define AP_RPRINTF1(req,tem,arg1){ap_rprintf(req,tem,arg1);}
#define AP_RPRINTF2(req,tem,arg1,arg2){ap_rprintf(req,tem,arg1,arg2);}
#define AP_RPRINTF3(req,tem,arg1,arg2,arg3){ap_rprintf(req,tem,arg1,arg2,arg3);}
#define AP_RPRINTF4(req,tem,arg1,arg2,arg3,arg4){ap_rprintf(req,tem,arg1,arg2,arg3,arg4);}
#define AP_RPRINTF5(req,tem,arg1,arg2,arg3,arg4,arg5){ap_rprintf(req,tem,arg1,arg2,arg3,arg4,arg5);}
#endif
|
tarachandverma/ngx-openidc
|
src/url-utils/url_utils.c
|
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include "url_utils.h"
#define MAX_VAR_SIZE 256
#define URL_MAX_VAR_SIZE 1280
const int STAGE=0;
const int STEP=1;
const int CURSOR=2;
int c_to_hex(char c) {
return 0xF & (('0' <= c && c <= '9')? (c - '0') : (toupper(c) - 'A' + 10));
}
int containsValidSlots(int slotsneeded, int slotlen){
return slotsneeded<slotlen;
}
int marshallError(char* dst,int cursor){
dst[cursor]='\0';
return -cursor;
}
void resetUrlState(int state[]){
state[STAGE]=0;
state[STEP]=0;
state[CURSOR]=0;
}
int validHex(char* ch){
return ((int)*ch>=48&&(int)*ch<=57)||((int)*ch>=65&&(int)*ch<=70)||((int)*ch>=97&&(int)*ch<=102);
}
void url_stream_decode(const char *ch,char* dest, int state[]){
//printf("%c,%d\n",*ch,state[CURSOR]);
if(state[STAGE]==0){
if(*ch=='+'){
dest[state[CURSOR]++]=' ';
}else if(*ch=='%'){
state[STAGE]=1;
}else{
dest[state[CURSOR]++]=*ch;
}
}else if(state[STAGE]==1){
state[STAGE]=2;
}else if (state[STAGE]==2){
//printf("Make char %c:%d, %c:%d\n",*(ch-1),(int)(*(ch-1)),*ch,(int)(*ch));
if(validHex((char*)ch)&&validHex((char *)(ch-1))){
dest[state[CURSOR]++] = (c_to_hex(*(ch-1)) << 4) + c_to_hex(*ch);
}
state[STAGE]=0;
}
}
int url_get_param(const char *queryString, const char *paramName, char *dest, int dlen){
int stage,paramLen,cursor,maxslots;
int decodeState[3];
if(paramName==NULL||queryString==NULL) return -1;
paramLen=strlen(paramName);
stage=-1;
cursor=0;
maxslots=dlen-1;
resetUrlState(decodeState);
//printf("orig maxslots:%d,%d,%d,%d\n",maxslots,dlen,decodeState[STEP],decodeState[CURSOR]);
while(*queryString){
if(stage==-1){
//find param
if(!cursor){
if(*queryString==paramName[cursor]){
cursor++;
}else{
//this is not the param we are looking for..reset
stage=-21;
}
}else{
if(*queryString==paramName[cursor]){
cursor++;
}else{
//this is not the param we are looking for..reset
stage=-21;
}
}
if(paramLen==cursor){
//printf("FOUND\n");
stage=-2;
}
}else if(stage==-2){
//find equals sign
if(*queryString=='='){
stage=-3;
}else{
//could not find equals...must reset to nearest &
stage=-21;
}
}else if(stage==-21){
if(*queryString=='?'||*queryString=='&'){
stage=-1;
cursor=0;
}
}else if(stage==-3){
//fill buffer until end
if(decodeState[CURSOR]>=maxslots){
//printf("cursor:%d, slots:%d",decodeState[CURSOR],maxslots);
decodeState[CURSOR]=-decodeState[CURSOR];
break;
}else if(*queryString!='\0'&&*queryString!='&'){
url_stream_decode(queryString,dest,decodeState);
}else{
stage=4;
}
}
queryString++;
}
if(decodeState[CURSOR]>=0){
dest[decodeState[CURSOR]]='\0';
}else{
dest[-decodeState[CURSOR]]='\0';
}
return decodeState[CURSOR];
}
/* Decodes a url encoded cstring given as src
*and places result into dst
*
*@returns length of decoded string on success, -length of
*what was decoded on failure
*/
int url_decode(const char *src, char *dst, int dlen){
int maxSlots;
int decodeState[3];
if (!src || !dst)
return 0;
maxSlots=dlen-1;
resetUrlState(decodeState);
while (*src) {
if(decodeState[CURSOR]>=maxSlots){
//printf("cursor:%d, slots:%d",decodeState[CURSOR],maxSlots);
decodeState[CURSOR]=-decodeState[CURSOR];
break;
}else if(*src!='\0'){
url_stream_decode(src,dst,decodeState);
}
src++;
}
if(decodeState[CURSOR]>=0){
dst[decodeState[CURSOR]]='\0';
}else{
dst[-decodeState[CURSOR]]='\0';
}
return decodeState[CURSOR];
}
/**
*Encodes a url encoded cstring given as src
*and places result into dst
*
*@returns length of Encoded string on success, -length of
*what was Encoded on failure
*/
int url_encode(const char *src, char *dst, int dlen) {
int i, j, len;
int maxslots=dlen-1;
char c;
static const char hc[] = "0123456789ABCDEF";
len = strlen(src);
j = 0;
// for (i = 0; i < len, j<dlen; i++) {
for (i = 0; i < len; i++) {
switch (c = src[i]) {
case ' ':
if(containsValidSlots(j,maxslots)){
dst[j++] = '+';
}else{
return marshallError(dst,j);
}
break;
case '!': case '"': case '#': case '$': case '%': case '&': case '(': case ')':
case '+': case ',': case ':': case ';': case '<': case '=': case '>': case '?':
case '[': case '\'': case '\\': case ']': case '^': case '`': case '{': case '|':
case '}': case '~': case '/': case '@':
if(containsValidSlots(j+2,maxslots)){
dst[j++] = '%';
dst[j++] = hc[(c >> 4) & 0xF];
dst[j++] = hc[c & 0xF];
}else{
return marshallError(dst,j);
}
break;
default:
if (iscntrl(c) || !isascii(c)) {
if(containsValidSlots(j+2,maxslots)){
dst[j++] = '%';
dst[j++] = hc[(c >> 4) & 0xF];
dst[j++] = hc[c & 0xF];
}else{
return marshallError(dst,j);
}
}
else
if(containsValidSlots(j,maxslots)){
dst[j++] = c;
}else{
return marshallError(dst,j);
}
}
}
dst[j] = '\0';
return j;
}
char b64string[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
long base64_encode (char *to, char *from, unsigned int len){
char *fromp = from;
char *top = to;
unsigned char cbyte;
unsigned char obyte;
char end[3];
for (; len >= 3; len -= 3) {
cbyte = *fromp++;
*top++ = b64string[(int)(cbyte >> 2)];
obyte = (cbyte << 4) & 0x30; /* 0011 0000 */
cbyte = *fromp++;
obyte |= (cbyte >> 4); /* 0000 1111 */
*top++ = b64string[(int)obyte];
obyte = (cbyte << 2) & 0x3C; /* 0011 1100 */
cbyte = *fromp++;
obyte |= (cbyte >> 6); /* 0000 0011 */
*top++ = b64string[(int)obyte];
*top++ = b64string[(int)(cbyte & 0x3F)];/* 0011 1111 */
}
if (len) {
end[0] = *fromp++;
if (--len) end[1] = *fromp++; else end[1] = 0;
end[2] = 0;
cbyte = end[0];
*top++ = b64string[(int)(cbyte >> 2)];
obyte = (cbyte << 4) & 0x30; /* 0011 0000 */
cbyte = end[1];
obyte |= (cbyte >> 4);
*top++ = b64string[(int)obyte];
obyte = (cbyte << 2) & 0x3C; /* 0011 1100 */
if (len) *top++ = b64string[(int)obyte];
else *top++ = '=';
*top++ = '=';
}
*top = 0;
return top - to;
}
char b64Urlstring[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
long base64Url_encode (char *to, char *from, unsigned int len){
char *fromp = from;
char *top = to;
unsigned char cbyte;
unsigned char obyte;
char end[3];
for (; len >= 3; len -= 3) {
cbyte = *fromp++;
*top++ = b64Urlstring[(int)(cbyte >> 2)];
obyte = (cbyte << 4) & 0x30; /* 0011 0000 */
cbyte = *fromp++;
obyte |= (cbyte >> 4); /* 0000 1111 */
*top++ = b64Urlstring[(int)obyte];
obyte = (cbyte << 2) & 0x3C; /* 0011 1100 */
cbyte = *fromp++;
obyte |= (cbyte >> 6); /* 0000 0011 */
*top++ = b64Urlstring[(int)obyte];
*top++ = b64Urlstring[(int)(cbyte & 0x3F)];/* 0011 1111 */
}
if (len) {
end[0] = *fromp++;
if (--len) end[1] = *fromp++; else end[1] = 0;
end[2] = 0;
cbyte = end[0];
*top++ = b64Urlstring[(int)(cbyte >> 2)];
obyte = (cbyte << 4) & 0x30; /* 0011 0000 */
cbyte = end[1];
obyte |= (cbyte >> 4);
*top++ = b64Urlstring[(int)obyte];
obyte = (cbyte << 2) & 0x3C; /* 0011 1100 */
if (len) *top++ = b64Urlstring[(int)obyte];
}
*top = 0;
return top - to;
}
#define badchar(c,p) (!(p = memchr(b64string, c, 64)))
long base64_decode (char *to, char *from, unsigned int len){
char *fromp = from;
char *top = to;
char *p;
unsigned char cbyte;
unsigned char obyte;
int padding = 0;
for (; len >= 4; len -= 4) {
if ((cbyte = *fromp++) == '=') cbyte = 0;
else {
if (badchar(cbyte, p)) return -1;
cbyte = (p - b64string);
}
obyte = cbyte << 2; /* 1111 1100 */
if ((cbyte = *fromp++) == '=') cbyte = 0;
else {
if (badchar(cbyte, p)) return -1;
cbyte = p - b64string;
}
obyte |= cbyte >> 4; /* 0000 0011 */
*top++ = obyte;
obyte = cbyte << 4; /* 1111 0000 */
if ((cbyte = *fromp++) == '=') { cbyte = 0; padding++; }
else {
padding = 0;
if (badchar (cbyte, p)) return -1;
cbyte = p - b64string;
}
obyte |= cbyte >> 2; /* 0000 1111 */
*top++ = obyte;
obyte = cbyte << 6; /* 1100 0000 */
if ((cbyte = *fromp++) == '=') { cbyte = 0; padding++; }
else {
padding = 0;
if (badchar (cbyte, p)) return -1;
cbyte = p - b64string;
}
obyte |= cbyte; /* 0011 1111 */
*top++ = obyte;
}
*top = 0;
if (len) return -1;
return (top - to) - padding;
}
long base64Url_decode (char *to, char *from, unsigned int len){
char *fromp = from;
char *top = to;
char *p;
unsigned char cbyte;
unsigned char obyte;
int padding = 0;
char padded_src[URL_MAX_VAR_SIZE];
// add padding
if(len%4) {
memcpy(padded_src, from, len);
memcpy(padded_src+len, "====", 4);
fromp = padded_src;
len+=4;
}
for (; len >= 4; len -= 4) {
if ((cbyte = *fromp++) == '=') cbyte = 0;
else {
if(cbyte=='-') { cbyte='+'; } else if(cbyte=='_') { cbyte='/'; }
if (badchar(cbyte, p)) return -1;
cbyte = (p - b64string);
}
obyte = cbyte << 2; /* 1111 1100 */
if ((cbyte = *fromp++) == '=') cbyte = 0;
else {
if(cbyte=='-') { cbyte='+'; } else if(cbyte=='_') { cbyte='/'; }
if (badchar(cbyte, p)) return -1;
cbyte = p - b64string;
}
obyte |= cbyte >> 4; /* 0000 0011 */
*top++ = obyte;
obyte = cbyte << 4; /* 1111 0000 */
if ((cbyte = *fromp++) == '=') { cbyte = 0; padding++; }
else {
padding = 0;
if(cbyte=='-') { cbyte='+'; } else if(cbyte=='_') { cbyte='/'; }
if (badchar (cbyte, p)) return -1;
cbyte = p - b64string;
}
obyte |= cbyte >> 2; /* 0000 1111 */
*top++ = obyte;
obyte = cbyte << 6; /* 1100 0000 */
if ((cbyte = *fromp++) == '=') { cbyte = 0; padding++; }
else {
padding = 0;
if(cbyte=='-') { cbyte='+'; } else if(cbyte=='_') { cbyte='/'; }
if (badchar (cbyte, p)) return -1;
cbyte = p - b64string;
}
obyte |= cbyte; /* 0011 1111 */
*top++ = obyte;
}
// handle the remaining bytes
*top = 0;
return (top - to) - padding;
}
char* url_getParam(pool* p, char* queryString,const char* name){
char tmp[URL_MAX_VAR_SIZE];
if(url_get_param(queryString,name,tmp,URL_MAX_VAR_SIZE)>0){
return apr_pstrdup(p,tmp);
}
return NULL;
}
char* url_addParam(pool* p, char* url, char* pName, char* pVal){
char tmp[URL_MAX_VAR_SIZE];
char* ret=NULL;
if(pName==NULL||pVal==NULL||url==NULL){
return url;
}
if(url_encode(pVal,tmp,URL_MAX_VAR_SIZE)>0){
ret=apr_pstrcat(p,url,"?",pName,"=",tmp,NULL);
}else{
ret=url;
}
return ret;
}
//This appends param to query string.
char* url_appendParamToQuery(pool*p, char*query, char*pName,char*pVal){
char* tmp;
if(pName==NULL||pVal==NULL) return query;//return query as is
tmp=url_encode2(p,pVal);
if(query==NULL) {return apr_pstrcat(p,pName,"=",tmp,NULL);}
return apr_pstrcat(p,query,"&",pName,"=",tmp,NULL);
}
char* url_encode2(pool* p, char* src){
int dlen=0;
int slen=0;
char* tmp=NULL;
if(src==NULL) return NULL;
slen=strlen(src);
if(slen==0) return NULL;
dlen=(slen*3)+1;
tmp=apr_pcalloc(p,dlen);
url_encode(src,tmp,dlen);
return apr_pstrdup(p,tmp);
}
char* url_decode2(pool* p, char* src){
int dlen=0;
int slen=0;
char* tmp=NULL;
if(src==NULL) return NULL;
slen=strlen(src);
if(slen==0) return NULL;
dlen=slen+1;
tmp=apr_pcalloc(p,dlen);
url_decode(src,tmp,dlen);
return apr_pstrdup(p,tmp);
}
|
tarachandverma/ngx-openidc
|
src/oidc-core/oidc_config.h
|
<reponame>tarachandverma/ngx-openidc
#ifndef __TCREWRITE_ACTION_MAPPINGS__H_
#define __TCREWRITE_ACTION_MAPPINGS__H_
#include <apr_general.h>
#include <apr_pools.h>
#include <apr_tables.h>
#include <apache_typedefs.h>
#include <shm_data.h>
#include <shm_apr.h>
#include <template-core/template_engine.h>
#include <config-core/config_bindings_shm.h>
#include <json-api-core/json_parser.h>
#include "oidc_core_constants.h"
#include "cookie.h"
#define TIME_MAX (~ (~ (time_t) 0 << (sizeof (time_t) * CHAR_BIT - 1)))
typedef struct oauth_jwskey{
char* id;
char* type;
char* algorithm;
char* use;
char* modulus;
char* exponent;
char* x5c;
}oauth_jwskey;
typedef struct match_event{
time_t start;
time_t end;
}match_event;
typedef struct match_ip{
char* ip;
unsigned short negate;
unsigned short isRegex;
}match_ip;
typedef struct match_path{
char* path;
unsigned short negate;
}match_path;
typedef struct match_list_header{
char* name;
char* value;
char* delimAnd;
unsigned short negate;
unsigned short isRegex;
}match_list_header;
typedef struct match_list_env{
char* name;
char* value;
unsigned short negate;
unsigned short isRegex;
}match_list_env;
typedef struct match_list_match{
match_ip* ip;
match_path*path;
array_header* headerList;
match_event*event;
char* host;
int cascade;
}match_list_match;
typedef struct match_list{
char* name;
array_header* list;
}match_list;
typedef struct action_header{
char* name;
char* value;
char* regex;
header_actions action;
}action_header;
typedef struct action_uri{
char* uri;
int weight;
}action_uri;
// custom response
typedef struct action_response{
int code;
char* contentType;
char* body;
}action_response;
typedef struct page_action{
char *id, *description;
char* regex;
char* handler_internal;
template_engine* templateEngineRef;
array_header* requestHeaders; // array of action_header*
array_header* responseHeaders; // array of action_header*
action_response* response;
char* uri, *oidcProvider, *relyingParty;
int type;
unsigned int isForward:1,isPermanent:1,isDebug:1, advancedTemplate:1,base64UrlEncodeState:1;
}page_action;
typedef struct pathmapping_action{
page_action *action;
match_list* matchList;
}pathmapping_action;
typedef struct path_mapping{
char* pathRegex;
int ignoreCase;
array_header* pmactions;//array of pathmapping_action
array_header* matchLists;
}path_mapping;
typedef struct path_mappings_rec{
array_header* postauth;
}path_mappings_rec;
typedef struct relying_party{
char* id;
char* description;
char *clientID;
char* clientSecret;
char* issuer;
int validateNonce;
char* redirectUri;
char* postLoginDefaultLandingPage;
}relying_party;
typedef struct oidc_providerl{
char* id;
char* metadataUrl;
char* issuer;
char* authorizationEndpoint;
char* tokenEndpoint;
char* jwksUri;
shapr_hash_t* jwsKeys;
int isDefault;
}oidc_provider;
typedef struct oidc_config{
shapr_hash_t* page_actions;
path_mappings_rec* path_mappings;
shapr_hash_t* match_lists;
template_engine* templateEngine;
Cookie* rpSession;
Cookie* oidcSession;
Cookie* accessToken;
shapr_hash_t* relyingPartyHash;
shapr_hash_t* relyingPartyIdsHash;
shapr_hash_t* oidcProviderHash;
shapr_hash_t* oidcProviderIdsHash;
oidc_provider* oidcProvider;
}oidc_config;
char* am_build(pool* p,shared_heap* sheap,int isRefresh,cbs_globals* globals,char* filepath);
oidc_config* am_fetchFromSheap(shared_heap* sheap);
page_action* am_getPageActionById(oidc_config* actmap,char* id);
path_mapping* am_getPathMapping_PostAuth(pool* p,oidc_config* actmap,char* path,char* ip, apr_table_t* headers, apr_table_t* subprocess_env);
page_action* am_getMatchingPageAction(pool* p,array_header* pactions,char* path,char* ip, apr_table_t* headers, apr_table_t* subprocess_env);
match_list_match* am_isMatchListMatch(pool* p, match_list* matchlist, char* path, char* ip,apr_table_t *headers_in, apr_table_t* subprocess_env);
void am_printAll(pool* p, oidc_config* oidcConfig);
oauth_jwskey* am_getJWSKeyByKeyID(shapr_hash_t* keyHash, char* keyID);
relying_party* am_getRelyingPartyByClientID(shapr_hash_t* relyingPartyHash, const char* clientID);
relying_party* am_getRelyingPartyById(shapr_hash_t* relyingPartyIdsHash, const char* id);
relying_party* am_getRelyingPartyByRedirectUri(pool*p, shapr_hash_t* relyingPartyHash, const char* currentRedirectUri);
oidc_provider* am_getOidcProviderByIssuer(shapr_hash_t* oidcProviderHash, const char* issuer);
oidc_provider* am_getOidcProviderById(shapr_hash_t* oidcProviderIdsHash, const char* id);
typedef struct oauth_jwt_header {
char* algorithm;
char* type;
char* keyID;
}oauth_jwt_header;
typedef struct oauth_jwt_claim {
char* issuer;
char* scope;
char* subject;
char* audience;
time_t expiry;
time_t issuedAt;
time_t auth_time;
apr_hash_t* options;
array_header* roles;
}oauth_jwt_claim;
typedef struct oauth_jwt {
oauth_jwt_header* header;
oauth_jwt_claim* claim;
char* signature;
}oauth_jwt;
// JSON Web Key
typedef struct oauth_jwk{
char* algorithm;
char* use;
char* keyID;
char* key; // symmetric key
char* modulus; // rsa public key modulus
char* exponent; // rsa public key exponent
}oauth_jwk;
// JWT routines
oauth_jwt_header* oauthutil_newJWTHeaderObj(pool* p);
const char* oauthutil_serializeJWTHeader(pool* p, oauth_jwt_header* hdr);
oauth_jwt_header* oauthutil_deserializeJWTHeader(pool* p, char* encodedHeader);
oauth_jwt_claim* oauthutil_newJWTClaimObj(pool* p);
const char* oauthutil_serializeJWTClaim(pool* p, oauth_jwt_claim* claim);
oauth_jwt_claim* oauthutil_deserializeJWTClaim(pool* p, char* encodedClaim);
oauth_jwt_claim* oauthutil_deserializeJWTClaimNoDecoding(pool* p, char* claimJson);
oauth_jwt* oauthutil_newJWTObj(pool* p);
const char* oauthutil_serializeJWT(pool*p, oauth_jwt* jwt, const char* secretKey) ;
typedef const char* (*getClientSecretKeyByClientId_func)(pool*p, char* client_id, void* data);
oauth_jwt* oauthutil_parseAndValidateJWT(pool* p, const char* src, getClientSecretKeyByClientId_func getClientSecretKeyByClientIdFunc, void* data);
void oauthutil_printJWT(pool* p, oauth_jwt* jwt);
//ID Token ( JWT format)
oauth_jwk* oauthutil_newJWKObj(pool *p);
const char* oauthutil_generateIDToken(pool* p, oauth_jwt_header* header, oauth_jwt_claim* claim, const char* secretKey) ;
typedef oauth_jwk* (*getJSONWebKey_func)(pool*p, oauth_jwt_header* header, const char* issuer, const char* audience, void* data, char** error);
oauth_jwt* oauthutil_parseIDToken(pool* p, const char* src, char** payloadP, char** error);
oauth_jwt* oauthutil_parseAndValidateIDToken(pool* p, const char* src, getJSONWebKey_func getJSONWebKeyFunc, void* data, char** error);
void oauthutil_printIDToken(pool* p, oauth_jwt* IDToken);
const char* oauthutil_serializeJWTClaimNoEncoding(pool* p, oauth_jwt_claim* claim);
const char* am_getActionTypeStr(action_types type) ;
#endif //__TCREWRITE_ACTION_MAPPINGS__H_
|
tarachandverma/ngx-openidc
|
src/apache-utils/apache_typedefs.h
|
<reponame>tarachandverma/ngx-openidc
/*
* Created by <NAME> on 01/04/14.
*
*/
#ifndef __TCREWRITE_APACHE_TYPEDEFS__H_
#define __TCREWRITE_APACHE_TYPEDEFS__H_
#include <apr_network_io.h>
#include <apr_strings.h>
#include <apr_tables.h>
#include <apr_hash.h>
#include <apache_macros.h>
#include <apr_general.h>
#include <apr_pools.h>
#include <apr_uri.h>
typedef struct apr_pool_t pool;
typedef struct apr_pool_t ap_pool;
typedef struct apr_array_header_t array_header;
typedef apr_uri_t uri_components;
typedef struct apr_table_t table;
#endif
|
tarachandverma/ngx-openidc
|
src/log-utils/logging.c
|
<reponame>tarachandverma/ngx-openidc
#include <unistd.h>
#include <apr_time.h>
#include <sys/stat.h>
#include "logging.h"
#include "common_utils.h"
#define BUFFERSIZE 2048
mm_logger* logging_getLogger(pool* p,char* path,long maxLogFileSizeMB){
apr_status_t rc;
if(path==NULL) return NULL;
mm_logger* ret=(mm_logger*)apr_pcalloc(p,sizeof(mm_logger));
ret->filepath=apr_pstrdup(p,path);
ret->maxLogFileSizeMB=maxLogFileSizeMB;
if((rc=apr_file_open(&(ret->file),path,APR_READ|APR_WRITE|APR_CREATE|APR_APPEND,APR_OS_DEFAULT,p))!=APR_SUCCESS){
return NULL;
}
ret->p=p;
return ret;
}
void logging_log(mm_logger* log,const char* a_format, ...){
va_list va;
//int i=0;
apr_time_t tnow;
char tbuf[64];
char buffer[BUFFERSIZE];
memset(buffer, '\0', BUFFERSIZE);
if(log->maxLogFileSizeMB>0) logging_rotateLogFile(log);
va_start(va, a_format);
vsnprintf(buffer, BUFFERSIZE-1, a_format, va);
tnow=apr_time_now();
memset(tbuf,'\0',64);
apr_ctime(tbuf,tnow);
apr_file_printf(log->file,"%s mm.monitor.refresh [%d] %s\r\n",tbuf,getpid(),buffer);
va_end(va);
}
int logging_rotateLogFile(mm_logger* log){
mm_logger* ltmp;
apr_finfo_t finfo;
apr_time_t tnow;
apr_time_exp_t texp;
apr_status_t st;
apr_size_t tbuflen,tbufmax=64;
char tbuf[64],*newPath;
st=apr_stat(&finfo,log->filepath,APR_FINFO_SIZE,log->p);
if(finfo.size > log->maxLogFileSizeMB*1024*1024){
apr_file_printf(log->file,"Monitor File Size [%dB], Max Value [%dB].\r\n",finfo.size,log->maxLogFileSizeMB*1024*1024);
logging_closeLogger(log);
log->file=NULL;
tnow=apr_time_now();
memset(tbuf,'\0',64);
apr_time_exp_lt(&texp,tnow);
apr_strftime(tbuf,&tbuflen,tbufmax,"%F-%H_%M_%S",&texp);
newPath=apr_psprintf(log->p,"%s.%s.%d",log->filepath,tbuf,texp.tm_usec);
apr_file_rename(log->filepath,newPath,log->p);
ltmp=logging_getLogger(log->p,log->filepath,log->maxLogFileSizeMB);
log->file=ltmp->file;
return TRUE;
}
return FALSE;
}
void logging_printf(mm_logger* log,const char* a_format, ...){
va_list va;
//int i=0;
//apr_time_t tnow;
//char tbuf[64];
char buffer[BUFFERSIZE];
memset(buffer, '\0', BUFFERSIZE);
va_start(va, a_format);
vsnprintf(buffer, BUFFERSIZE-1, a_format, va);
apr_file_printf(log->file,"%s\r\n",buffer);
va_end(va);
}
//Returns True if file successully closed.
int logging_closeLogger(mm_logger* log){
apr_status_t rc;
if(log==NULL) return FALSE;
if((rc=apr_file_close(log->file))!=APR_SUCCESS){
return FALSE;
}
return TRUE;
}
void logging_setMaxFileSize(mm_logger* log,int maxLogFileSizeMB){
log->maxLogFileSizeMB=maxLogFileSizeMB;
}
// startup logs
// startup log
#define MAX_LOGFILE_SIZE 51200
typedef struct process_logger {
mm_logger logger;
apr_status_t status;
int pid;
}process_logger;
static process_logger refreshLogger;
int lc_openLogFile(apr_pool_t* p,char* filepath){
if(filepath==NULL){
//printf("\nLogfile name not specified \n");
return FALSE;
}
refreshLogger.status=apr_file_open(&refreshLogger.logger.file,filepath,APR_APPEND | APR_WRITE | APR_CREATE,APR_OS_DEFAULT,p);
if(refreshLogger.status!=APR_SUCCESS){
//printf("\nFailed to open logfile - %s\n", filepath);
}
refreshLogger.logger.p=p;
refreshLogger.logger.filepath=apr_pstrdup(p,filepath);
refreshLogger.logger.maxLogFileSizeMB=2;
refreshLogger.pid=getpid();
return refreshLogger.status;
}
int lc_closeLogFile(void){
int cur_pid=getpid();
if(refreshLogger.status!=APR_SUCCESS||cur_pid!=refreshLogger.pid){
//printf("\nFailed to close logfile - %s\n", filepath);
return FALSE;
}
apr_file_close(refreshLogger.logger.file);
refreshLogger.status=-1;
return APR_SUCCESS;
}
int lc_rotateLogFile(){
apr_status_t status=0;
int cur_pid;
cur_pid=getpid();
if(refreshLogger.status!=APR_SUCCESS||cur_pid!=refreshLogger.pid){
//printf("\nLogfile has not been opened.\n");
return FALSE;
}
lc_closeLogFile();
apr_time_t tnow;
apr_time_exp_t texp;
apr_size_t tbuflen,tbufmax=64;
char tbuf[64],*renamedPath;
tnow=apr_time_now();
memset(tbuf,'\0',64);
apr_time_exp_lt(&texp,tnow);
apr_strftime(tbuf,&tbuflen,tbufmax,"%F-%H_%M_%S",&texp);
renamedPath=apr_psprintf(refreshLogger.logger.p,"%s.%s.%d",refreshLogger.logger.filepath,tbuf,texp.tm_usec);
status = apr_file_rename(refreshLogger.logger.filepath,renamedPath,refreshLogger.logger.p);
// open a new file
status = lc_openLogFile(refreshLogger.logger.p, refreshLogger.logger.filepath);
return status;
}
int lc_truncateLogFile(void){
apr_status_t status=0;
int cur_pid=getpid();
if(refreshLogger.status!=APR_SUCCESS||cur_pid!=refreshLogger.pid){
//printf("\nLogfile has not been opened.\n");
return FALSE;
}
status=apr_file_trunc(refreshLogger.logger.file,0);
//if(status!=APR_SUCCESS)
//printf("\nFailed to truncate logfile - %s\n", refreshLogger.filepath);
return status;
}
int lc_trimLogFile(void){
//To ensure that logfile size never grows to a crazy size
struct stat file_stat;
int rc = stat(refreshLogger.logger.filepath,&file_stat);
if(rc == 0 && file_stat.st_size > MAX_LOGFILE_SIZE){
lc_rotateLogFile();
return TRUE;
}
return FALSE;
}
int lc_printLog(const char* format,...){
va_list ap;
apr_size_t out_bytes;
char logs[1024];
apr_status_t status=0;
int cur_pid;
//Print to stdout to keep current behaviour
va_start(ap,format);
vfprintf(stdout,format,ap);
va_end(ap);
va_start(ap,format);
vsprintf(logs,format,ap);
va_end(ap);
lc_trimLogFile();
cur_pid=getpid();
if(refreshLogger.status!=APR_SUCCESS||cur_pid!=refreshLogger.pid){
//printf("\nLogfile has not been opened by this pool.\n");
return FALSE;
}
status=apr_file_write_full(refreshLogger.logger.file,logs,strlen(logs),&out_bytes);
//if(status!=APR_SUCCESS)
//printf("\nFailed to write logfile - %s\n", refreshLogger.filepath);
return status;
}
|
tarachandverma/ngx-openidc
|
src/common-utils/cookie.h
|
#ifndef _COOKIE_H_
#define _COOKIE_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <sys/types.h>
#include <shm_data.h>
#include <shm_apr.h>
typedef struct Cookie {
char* name; // Cookie
int nameLen; // Cookie name length
int age; // in Days
unsigned int httpOnly; // httpOnly support.
int secure; // httpOnly; Secure support.
}Cookie;
//Creater methods
Cookie* cookie_newObj(pool*p);
Cookie* cookie_createCookieByName(pool*p, char*name);
Cookie* cookie_cookieDup(pool*p, Cookie*src);
//Accessor Methods
void cookie_setCookieName(pool*p, Cookie*cookie, char*name);
char* cookie_getCookieName(Cookie*cookie) ;
void cookie_setCookieLifeTime(Cookie* cookie, int lifeTime);
int cookie_getCookieLifeTime(Cookie* cookie);
void cookie_setCookieHttpOnlyflag(Cookie* cookie, unsigned int httpOnly);
unsigned int cookie_getCookieHttpOnlyflag(Cookie* cookie);
void cookie_setCookieSecureHttpOnlyflag(Cookie* cookie, int secure);
//Cookie sheap methods
Cookie* cookie_newShmObj(shared_heap*sheap);
Cookie* cookie_cookieShmDup(shared_heap*sheap, Cookie*src);
//Cookie utility methods
int cookie_convertDaysToSeconds(int days);
char* cookie_cookieTemplate(pool* p, Cookie* cookie, char *ivalue, char *iDomain);
char* cookie_cookieTemplateByName(pool* p,char* icookiename, char *ivalue,
char *idomain, long maxAge, unsigned int httpOnly);
char* cookie_cookieUntemplate(pool* p,char* src);
char* cookie_getGMTDate(pool* p, int secondsInFuture);
char *cookie_getCookie(pool* p, apr_table_t* headers_in, Cookie* cookie);
char *cookie_getCookieByName(pool* p, apr_table_t* headers_in, char *cookie_name, int cookie_name_len);
void cookie_deleteCookie(pool* p, apr_table_t* err_headers_out, Cookie* cookie, char* domain);
void cookie_deleteCookieByName(pool* p, apr_table_t* err_headers_out, char* cookie_name, char* domain);
char* cookie_parseCookie(pool* p, char* name, char* cookies);
#ifdef __cplusplus
}
#endif
#endif //_COOKIE_H_
|
tarachandverma/ngx-openidc
|
src/shm_core/shm_dup.c
|
#include <string.h>
#include <shm_dup.h>
#include <math.h>
int shdup_32BitString_size(char* str){
int tmp, mod;
if(str==NULL) return 0;
tmp=strlen(str)+1;
mod=tmp%4;
if(mod>0){
tmp=tmp-mod+4;
}
return tmp;
}
int shdup_arrayheader_size(array_header* arr){
int sz=0;
sz+=sizeof(array_header);
sz+=arr->elt_size*arr->nelts;
return sz;
}
/**
* Copies str to icharbuf and returns the beginning of the new string. icharbuf is updated rollingly
*/
char* shdup_32BitString_copy(char** icharbuf, char* str){
int slen;
char* buf;
if(str==NULL){
return NULL;
}
buf=*icharbuf;
slen=shdup_32BitString_size(str);
memset(buf,'\0',(int)slen);
memcpy(buf,str, strlen(str));
*icharbuf+=(int)slen;
return buf;
}
|
tarachandverma/ngx-openidc
|
src/config-core/config_messaging.c
|
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <stdlib.h>
#include <common_utils.h>
#include <config-core/config_messaging.h>
#include <config-core/config_core.h>
#include <config-core/config_messaging_parsing.h>
#include <log-utils/logging.h>
#include <http-utils/http_client.h>
#include "xml_core.h"
#ifdef NGX_HTTP_OPENIDC
#else // APACHE
#include <ap_mpm.h>
#endif
cfgm_connection* cfgm_newConnectionObj(pool* p){
cfgm_connection* ret=(cfgm_connection*)apr_palloc(p,sizeof(cfgm_connection));
ret->wireHeader=cfgm_newWireHeader(p);
return ret;
}
static char* cfgm_getMessageType(cfgm_wire_message* msg){
if(msg!=NULL){
return msg->type;
}
return NULL;
}
static char* cfgm_getMessageNodeName(cfgm_wire_message* msg){
if(msg!=NULL&&msg->header!=NULL){
return msg->header->nodeName;
}
return NULL;
}
int cfgm_isRefreshMessage(cfgm_wire_message* msg){
return (msg!=NULL&&(strcmp(msg->type,"AUTO-REFRESH")==0));
}
static cfgm_wire_message* cfgm_generateAutoRefreshMessage(pool* p){
cfgm_wire_header* wireHeader=cfgm_newWireHeader(p);
cfgm_wire_message* msg=cfgm_newWireMessageType(p,"AUTO-REFRESH",wireHeader);
return msg;
}
typedef struct next_refresh_info{
time_t nextRefreshTimestamp;
}next_refresh_info;
static int cfgm_setRefreshTimestampAttribute(pool* p,char* xPath,int type,const char ** attributes,void* userdata){
int i;
next_refresh_info* refreshInfo=(next_refresh_info*)userdata;
for(i=0;attributes[i]; i += 2) {
if(strcmp(attributes[i],"nextRefreshTime")==0){
refreshInfo->nextRefreshTimestamp=cu_dateStringToSeconds((char*)attributes[i + 1]);
}
}
return 1;
}
static int cfgm_canAutoRefreshNow(pool* p, cfg_service_descriptor* resourceService, char*oidcConfigFile, const time_t lastRefreshTimestamp, mm_logger* logger){
http_util_result* httpResult=NULL;
char* reqQuery=NULL;
char* error = NULL;
time_t currentTimestamp;
XmlCore* xCore=NULL;
char* result=NULL;
if(resourceService==NULL) return FALSE;
currentTimestamp = time(NULL);
reqQuery=apr_pstrcat(p,resourceService->uri,"/",oidcConfigFile, NULL);
httpResult=hc_get_verbose2(p,reqQuery,resourceService->timeoutSeconds,5,resourceService->userColonPass,NULL,&error);
if(httpResult==NULL||httpResult->data==NULL||!hc_is200_OK(httpResult)) {
logging_log(logger,"Refresh httpResult Error: %s", (error!=NULL) ? error : "unknown");
return FALSE;
}
next_refresh_info refreshInfo;
refreshInfo.nextRefreshTimestamp = -1;
xCore=xc_getXmlCore(p);
xc_addXPathHandler(xCore,"/oidcConfig",0,cfgm_setRefreshTimestampAttribute,NULL,NULL, &refreshInfo);
result=xc_parseFromStringSourceTextResponse(xCore, httpResult->data);
if(result!=NULL) {
logging_log(logger,"Refresh error : %s", result);
return FALSE;
}
if(refreshInfo.nextRefreshTimestamp<0) {
logging_log(logger,"Refresh nextRefresh not configued");
return TRUE;
}
logging_log(logger,"Refresh lastRefreshTimestamp:%d, refreshTimestamp : %d, currentTimestamp:%d",lastRefreshTimestamp,refreshInfo.nextRefreshTimestamp, currentTimestamp);
if( (lastRefreshTimestamp<refreshInfo.nextRefreshTimestamp) && (refreshInfo.nextRefreshTimestamp<=currentTimestamp)) return TRUE;
logging_log(logger,"Refresh refreshTimestamp : %d is tool old or already processed", refreshInfo.nextRefreshTimestamp);
return FALSE;
}
static void cfgm_internalMessagingLoop(pool* p, char* logsDir, void* localConfig, void* userdata,cfgm_message_recieved_func msgRecFunc){
#define BUFSIZE 256
cfgm_connection* cmConn=cfgm_newConnectionObj(p);
cfgm_wire_message* msg=NULL;
char* error=NULL;
apr_status_t rc;
apr_time_t lastHello=0;
char errorbuf[512];
int errorCode = 0,maxLogFileSizeMB=2;
time_t lastAutoRefreshTimestamp = time(NULL); // startup time
sprintf(errorbuf,"%s/monitor.log",logsDir);
mm_logger* logger=logging_getLogger(p,errorbuf,maxLogFileSizeMB);
cfg_service_descriptor* resourceService=((config_core*)userdata)->globals->resourceService;
int refreshWaitSeconds = ((config_core*)userdata)->refreshWaitSeconds;
char* oidcConfigFile=((config_core*)userdata)->oidcConfigFile;
//start wait for message loop
while(1){
logging_log(logger,"AutoRefreshing...");
if(cfgm_canAutoRefreshNow(p, resourceService, oidcConfigFile, lastAutoRefreshTimestamp, logger)){
msg=cfgm_generateAutoRefreshMessage(p);
if(msg!=NULL){
logging_log(logger,"AutoRefresh processing message: %s (%s)",cfgm_getMessageType(msg),cfgm_getMessageNodeName(msg));
//internal hello handling
if(msgRecFunc!=NULL){
(*msgRecFunc)(p,NULL,msg,localConfig,userdata);
}
logging_log(logger,"AutoRefresh complete");
lastAutoRefreshTimestamp = time(NULL); // update with current timestamp;
}
}
usleep(refreshWaitSeconds*1000*1000);
}
}
typedef struct openidc_messaging_proc_rec{
char* logDir;
void* userdata;
cfgm_init_messaging_func initFunc;
cfgm_message_recieved_func msgRecFunc;
apr_proc_t* proc;
}openidc_messaging_proc_rec;
static openidc_messaging_proc_rec*cfgm_newMessagingProcRecObj(pool* p, char* logDir,
void* userdata,
cfgm_init_messaging_func initFunc, cfgm_message_recieved_func msgRecFunc){
openidc_messaging_proc_rec* mpr=(openidc_messaging_proc_rec*)apr_palloc(p,sizeof(openidc_messaging_proc_rec));
mpr->logDir = logDir;
mpr->userdata = userdata;
mpr->initFunc = initFunc;
mpr->msgRecFunc = msgRecFunc;
mpr->proc = (apr_proc_t*)apr_palloc(p,sizeof(apr_proc_t));
return mpr;
}
pool* root_mpr_pool = NULL; // root process pool created by root process
void cfgm_startMessagingProcess(openidc_messaging_proc_rec*msg,int disableProcessRecovery);
#if 0/*APR_HAS_OTHER_CHILD && !NGX_HTTP_OPENIDC*/
static void cfgm_messageProcessRestartCallback(int reason, void *data, apr_wait_t status) {
openidc_messaging_proc_rec* mpr = (openidc_messaging_proc_rec*)data;
int mpm_state;
int stopping;
switch (reason) {
case APR_OC_REASON_DEATH:
apr_proc_other_child_unregister(data);
/* If apache is not terminating or restarting,
* restart the message processer
*/
stopping = 1; /* if MPM doesn't support query,
* assume we shouldn't restart message process
*/
if (ap_mpm_query(AP_MPMQ_MPM_STATE, &mpm_state) == APR_SUCCESS &&
mpm_state != AP_MPMQ_STOPPING) {
stopping = 0;
}
if (!stopping) {
ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL, "openidc refresh recieved APR_OC_REASON_DEATH, restarting");
if(mpr!=NULL){
cfgm_startMessagingProcess(mpr,FALSE);
}
}
break;
case APR_OC_REASON_RESTART:
/* don't do anything; server is stopping or restarting */
apr_proc_other_child_unregister(data);
break;
case APR_OC_REASON_LOST:
/* Restart the child messaging processor as we lost it */
apr_proc_other_child_unregister(data);
ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL, "openidc refresh recieved APR_OC_REASON_LOST");
cfgm_startMessagingProcess(mpr, FALSE);
break;
case APR_OC_REASON_UNREGISTER:
/* we get here when child message processor is cleaned up; it gets cleaned
* up when pconf gets cleaned up
*/
if(mpr!=NULL&&mpr->proc!=NULL){
kill(mpr->proc->pid, SIGHUP); /* send signal to message processor to die */
}
break;
}
}
#endif
void cfgm_startMessagingProcess(openidc_messaging_proc_rec*mpr, int disableProcessRecovery){
apr_status_t rv;
void* localConfig=NULL;
if((rv=apr_proc_fork(mpr->proc,root_mpr_pool))==APR_INCHILD){
if(mpr->initFunc!=NULL){
localConfig=(*mpr->initFunc)(root_mpr_pool,mpr->userdata);
}
cfgm_internalMessagingLoop(root_mpr_pool,mpr->logDir, localConfig, mpr->userdata,mpr->msgRecFunc);
exit(1);
}else{
apr_pool_note_subprocess (root_mpr_pool,mpr->proc,APR_KILL_AFTER_TIMEOUT);
if ( !disableProcessRecovery ) {
#if 0/*APR_HAS_OTHER_CHILD && !NGX_HTTP_OPENIDC*/
apr_proc_other_child_register(mpr->proc, cfgm_messageProcessRestartCallback, mpr, NULL, root_mpr_pool);
#endif
}
}
}
apr_proc_t* cfgm_initializeMessagingLoop(pool* p, char* logDir, void* messageBroker, void* userdata,
cfgm_init_messaging_func initFunc, cfgm_message_recieved_func msgRecFunc,
int disableProcessRecovery){
root_mpr_pool = p;
openidc_messaging_proc_rec* mpr = cfgm_newMessagingProcRecObj(root_mpr_pool, logDir, userdata, initFunc, msgRecFunc);
cfgm_startMessagingProcess(mpr, disableProcessRecovery);
return mpr->proc;
}
|
tarachandverma/ngx-openidc
|
src/json-api-core/json_parser.h
|
#ifndef JSON_PARSER_H
#define JSON_PARSER_H
#include "apache_typedefs.h"
#ifdef __cplusplus
extern "C"
{
#endif
enum {
JSON_False=0,
JSON_True=1,
JSON_NULL=2,
JSON_Number=3,
JSON_String=4,
JSON_Array=5,
JSON_Object=6
};
#define JSON_IsReference 256
//Forward declaration.
typedef struct Value Value;
// Supply a block of JSON, and this returns a JSON object you can interrogate.
Value* JSON_Parse(pool* p, const char *value);
// Render a JSON entity to text for transfer/storage.
char* JSON_Serialize(pool* p, Value *item);
// Render a JSON entity to text for transfer/storage without any formatting.
char* JSON_SerializeUnformatted(pool* p,Value *item);
// Returns the number of items in an array (or object).
int JSON_GetArraySize(Value *array);
// Retrieve item number "item" from array "array". Returns NULL if unsuccessful.
Value* JSON_GetArrayItem(Value *array,int item);
// Get item "string" from object. Case insensitive.
Value* JSON_GetObjectItem(Value *object,const char *string);
typedef void (*peek_item_callback) (Value* value, void* data);
void JSON_IterateObjectItemCallback(Value *object, void* data, peek_item_callback peekItemCallback);
// Get item string.
const char* JSON_GetItemString(Value *item);
// Get string fron string type item.
const char* JSON_GetStringFromStringItem(Value *item);
// Get number fron number item.
int JSON_GetNumberFromNumberItem(Value *item);
// Get double fron number item.
double JSON_GetDoubleFromNumberItem(Value *item);
// Get item type.
int JSON_GetItemType(Value *item);
// These calls create a JSON item of the appropriate type.
Value* JSON_CreateNull(pool* p);
Value* JSON_CreateTrue(pool* p);
Value* JSON_CreateFalse(pool* p);
Value* JSON_CreateNumber(pool* p,double num);
Value* JSON_CreateString(pool* p,const char *string);
Value* JSON_CreateArray(pool* p);
Value* JSON_CreateObject(pool* p);
// These utilities create an Array of count items.
Value* JSON_CreateIntArray(pool* p,int *numbers,int count);
Value* JSON_CreateFloatArray(pool* p,float *numbers,int count);
Value* JSON_CreateDoubleArray(pool* p,double *numbers,int count);
Value* JSON_CreateStringArray(pool* p,const char **strings,int count);
// Append item to the specified array/object.
void JSON_AddItemToArray(pool* p,Value *array, Value *item);
void JSON_AddItemToObject(pool* p,Value *object,const char *string,Value *item);
// Append reference to item to the specified array/object. Use this when you want to add an existing JSON to a new JSON, but don't want to corrupt your existing JSON.
void JSON_AddItemReferenceToArray(pool* p,Value *array, Value *item);
void JSON_AddItemReferenceToObject(pool* p,Value *object,const char *string,Value *item);
// Remove/Detatch items from Arrays/Objects.
Value* JSON_DetachItemFromArray(Value *array,int which);
void JSON_DeleteItemFromArray(Value *array,int which);
Value* JSON_DetachItemFromObject(Value *object,const char *string);
void JSON_DeleteItemFromObject(Value *object,const char *string);
// Update array items.
void JSON_ReplaceItemInArray(Value *array,int which,Value *newitem);
void JSON_ReplaceItemInObject(pool* p,Value *object,const char *string,Value *newitem);
#define JSON_AddNullToObject(p,object,name) JSON_AddItemToObject(p,object, name, JSON_CreateNull(p))
#define JSON_AddTrueToObject(p,object,name) JSON_AddItemToObject(p,object, name, JSON_CreateTrue(p))
#define JSON_AddFalseToObject(p,object,name) JSON_AddItemToObject(p,object, name, JSON_CreateFalse(p))
#define JSON_AddNumberToObject(p,object,name,n) JSON_AddItemToObject(p,object, name, JSON_CreateNumber(p,n))
#define JSON_AddStringToObject(p,object,name,s) JSON_AddItemToObject(p,object, name, JSON_CreateString(p,s))
#ifdef __cplusplus
}
#endif
#endif // #if JSON_PARSER_H
|
tarachandverma/ngx-openidc
|
src/template-core/template_engine.h
|
#ifndef TEMPLATE_ENGINE_H_
#define TEMPLATE_ENGINE_H_
#include <apache_typedefs.h>
#include <shm_apr.h>
#include <shm_data.h>
#include "config_bindings.h"
#include "template_handler_url.h"
#include "config_bindings_shm.h"
typedef char* (*tengine_template_init)(pool*,shared_heap*,cbs_globals*,void**);
typedef char* (*tengine_template_getToken)(pool*,void*,char*);
typedef struct template_engine{
shapr_hash_t* templateHash;
}template_engine;
typedef struct template_eng_template{
char* id;
char* description;
tengine_template_init initFunc;
tengine_template_getToken tokenFunc;
}template_eng_template;
typedef struct template_eng_livetemplate{
void* config;
template_eng_template* engineTemplate;
}template_eng_livetemplate;
template_engine* te_newEngineObj(shared_heap* sheap);
char* te_initialize(pool* p,shared_heap* sheap,cbs_globals* globals,template_engine* teng);
char* te_getToken(pool* p, template_engine* tengine,char* tid, char* src);
char* te_templateString(pool* p,template_engine* tengine,char* sourcestr,array_header* matches);
static const template_eng_template template_eng_templates[]={
{"U","Url Encode",NULL,temphand_url_encodeToken},
{"u","Url Decode",NULL,temphand_url_decodeToken},
{"B","Url Encode",NULL,temphand_base64_encodeToken},
{"b","Url Decode",NULL,temphand_base64_decodeToken}
};
#endif /*TEMPLATE_CORE_H_*/
|
tarachandverma/ngx-openidc
|
src/unit-test/runalltest.c
|
<reponame>tarachandverma/ngx-openidc
#include <stdlib.h>
#include <apr_general.h>
#include <apr_pools.h>
#include <stdio.h>
#include <assert.h>
#include <CuTest.h>
#include <logging.h>
// Declare xxx_GetSuite() from xxx module here
// i.e. CuSuite* prodDefinitions_GetSuite();
static int die(int exitCode, const char *message, apr_status_t reason) {
char msgbuf[80];
apr_strerror(reason, msgbuf, sizeof(msgbuf));
fprintf(stderr, "%s: %s (%d)\n", message, msgbuf, reason);
exit(exitCode);
return reason;
}
static void terminate()
{
apr_terminate();
}
static apr_pool_t* initializePool()
{
apr_status_t rc;
apr_pool_t *pool;
rc = apr_initialize();
rc==APR_SUCCESS || die(-2, "Could not initialize !", rc);
//atexit(terminate);
rc = apr_pool_create(&pool, NULL);
rc==APR_SUCCESS || die(-2, "Could not allocate pool", rc);
return pool;
}
static void destroyPool(apr_pool_t*p){
apr_pool_destroy(p);
}
CuSuite* oidccore_GetSuite();
void RunAllTests(void) {
CuString *output = CuStringNew();
CuSuite* suite = CuSuiteNew();
apr_pool_t*pool=NULL;
mm_logger* logger=NULL;
char* logsDir="./unit-test"; //Write the log in current directory.
char logBuff[512];
apr_status_t status;
int size=2;
setbuf(stdout, NULL);
printf("Initializing pool...");
pool=initializePool();
if(pool==NULL){
printf("FAILURE\r\n");
printf("Could not initialize pool\r\n");
}else{
printf("OK\r\n");
}
sprintf(logBuff,"%s/results.txt",logsDir);
//Remove any existing log file.
apr_file_remove(logBuff,pool);
printf("Initializing logger...");
logger=logging_getLogger(pool,logBuff,size);
if(logger==NULL){
printf("FAILURE\r\n");
printf("Could not initialize logger\r\n");
}else{
printf("OK\r\n");
}
printf("Check the results for unit test result in unit-test/results.txt \r\n");
/* Add a new suite from xxx module here
** i.e. CuSuiteAddSuite(suite, xxx_GetSuite());
*/
CuSuiteAddSuite(suite, oidccore_GetSuite());
//Run and print the summary
CuSuiteRun(logger,suite);
CuSuiteSummary(suite, output);
CuSuiteDetails(suite, output);
logging_printf(logger,"%s\n", output->buffer);
printf("%s\n", output->buffer);
// write the results to html
mm_logger* html=NULL;
sprintf(logBuff, "%s/summary.html", logsDir);
apr_file_remove(logBuff, pool);
printf("Writing to html...");
html=logging_getLogger(pool,logBuff,size);
if(html!=NULL){
CuSuiteResultsToHtml(suite, html);
}else{
printf("FAILURE:Could not initialize html document\r\n\r\n");
}
destroyPool(logger->p);
//Close the log file.
logging_closeLogger(logger);
}
int main(int argc, char**argv) {
RunAllTests();
return 0;
}
|
tarachandverma/ngx-openidc
|
src/oidc-core/oidc_config.c
|
#include <oidc-core/oidc_config.h>
#include <oidc-core/oidc_config_xml.h>
#include <oidc-core/rewrite_core.h>
#include <common_utils.h>
#include <oidc-core/match_list.h>
#include <doc_parser_utils.h>
#include <http-utils/http_client.h>
#define CONST_PATH_ACTION_DEF_ELTS 4
#define SHEAP_ITEM_ID_AUTHZ_OIDC "NGX_OPENIDC"
#define KEYBUFFSIZE 8192
static path_mappings_rec* am_newPathMappingObj(shared_heap* sheap){
path_mappings_rec* ret;
ret=(path_mappings_rec*)shdata_shpalloc(sheap,sizeof(path_mappings_rec));
ret->postauth=shapr_array_make (sheap,CONST_PATH_ACTION_DEF_ELTS,sizeof(path_mapping*));
return ret;
}
static oidc_config* am_newObj(shared_heap* sheap){
oidc_config* ret;
ret=(oidc_config*)shdata_shpalloc(sheap,sizeof(oidc_config));
ret->path_mappings=am_newPathMappingObj(sheap);
ret->page_actions=shapr_hash_make(sheap);
ret->match_lists=shapr_hash_make(sheap);
ret->templateEngine=NULL;
ret->relyingPartyHash=shapr_hash_make(sheap);
ret->relyingPartyIdsHash=shapr_hash_make(sheap);
ret->oidcProviderHash=shapr_hash_make(sheap);
ret->oidcProviderIdsHash=shapr_hash_make(sheap);
ret->oidcProvider=NULL;
return ret;
}
static page_action* am_newPageAction(shared_heap* sheap){
page_action* ret=NULL;
ret=(page_action*)shdata_shpalloc(sheap,sizeof(page_action));
ret->id=NULL;
ret->regex=NULL;
ret->handler_internal=NULL;
ret->description=NULL;
ret->isForward=0;
ret->isPermanent=0;
ret->type=action_authorize;
ret->isDebug=0;
ret->templateEngineRef=NULL;
ret->advancedTemplate=FALSE;
ret->requestHeaders=NULL;
ret->responseHeaders=NULL;
ret->response=NULL;
ret->uri=NULL;
ret->oidcProvider=NULL;
ret->relyingParty=NULL;
ret->base64UrlEncodeState=1;
return ret;
}
page_action* am_getPageActionById(oidc_config* actmap,char* id){
if(actmap==NULL||actmap->page_actions==NULL||id==NULL){return NULL;}
return shapr_hash_get(actmap->page_actions,id,APR_HASH_KEY_STRING);
}
match_list* am_getMatchListByName(oidc_config* actmap,char* name){
if(actmap==NULL||actmap->match_lists==NULL||name==NULL){return NULL;}
return shapr_hash_get(actmap->match_lists,name,APR_HASH_KEY_STRING);
}
pathmapping_action* am_getPathMappingAction(shared_heap* sheap,oidc_config* actmap,pathmapping_action_xml* pmaX){
pathmapping_action*ret=NULL;
if(actmap==NULL||actmap->page_actions==NULL||pmaX==NULL){return NULL;}
ret=(pathmapping_action*)shdata_shpcalloc(sheap,sizeof(pathmapping_action));
ret->action=am_getPageActionById(actmap,pmaX->id);
ret->matchList=am_getMatchListByName(actmap,pmaX->matchList);
return ret;
}
// char* am_getFormattedUrl(pool *p, char* cur, char* namespaceid){
// int x,queryStrState=0;
// int curlen=strlen(cur);
// for(x=0;x<curlen;x++){
// if(cur[x]=='?'){
// if(x==curlen-1){
// queryStrState=2;
// }else{
// queryStrState=1;
// }
// }
// }
// if(queryStrState==0){
// return apr_pstrcat(p,cur,"?mg=",namespaceid,NULL);
// }else if(queryStrState==1){
// return apr_pstrcat(p,cur,"&mg=",namespaceid,NULL);
// }else if(queryStrState==2){
// return apr_pstrcat(p,cur,"mg=",namespaceid,NULL);
// }
// }
static action_header* am_newActionHeaderObj(shared_heap* sheap, action_header_xml* hdrX,shapr_hash_t* matchLists){
action_header* ret=
(action_header*)shdata_shpcalloc(sheap, sizeof(action_header));
ret->name =
shdata_32BitString_copy(sheap, hdrX->name);
ret->value =
shdata_32BitString_copy(sheap, hdrX->value);
ret->regex =
shdata_32BitString_copy(sheap, hdrX->regex);
ret->action = hdrX->action;
return ret;
}
static array_header* am_copyActionHeaders(pool* p, shared_heap* sheap, array_header* actionHeadersX,shapr_hash_t* matchLists){
array_header* ret=NULL;
action_header_xml* hdrX=NULL;
int i=0;
if(actionHeadersX==NULL || actionHeadersX->nelts<1) return NULL;
ret = shapr_array_make(sheap, actionHeadersX->nelts, sizeof(action_header*));
for(i=0; i<actionHeadersX->nelts; i++){
action_header_xml* hdrX = (action_header_xml*)cu_getElement(actionHeadersX, i);
if(hdrX!=NULL&&hdrX->name!=NULL) {
action_header** pos = (action_header**)shapr_array_push(sheap, ret);
*pos = am_newActionHeaderObj(sheap, hdrX,matchLists);
}
}
return ret;
}
static action_response* am_copyActionResponse(shared_heap* sheap, action_response_xml* responseX){
action_response* ret = NULL;
if(responseX==NULL) return NULL;
ret= (action_response*)shdata_shpcalloc(sheap, sizeof(action_response));
ret->code = responseX->code;
ret->contentType = shdata_32BitString_copy(sheap, responseX->contentType);
ret->body = shdata_32BitString_copy(sheap, responseX->body);
return ret;
}
static char* am_build_pageActions(pool* p,shared_heap* sheap,cbs_globals* globals,oidc_config_xml* axml,shapr_hash_t* hash,template_engine* templateEngine,
shapr_hash_t* matchLists){
apr_hash_index_t * hi=NULL;
void *val=NULL;
page_action_xml* pax=NULL;
page_action* paction=NULL;
int i=0;
for (hi = apr_hash_first(p,axml->page_actions_hash); hi; hi = apr_hash_next(hi)) {
apr_hash_this(hi, NULL, NULL, &val);
if(val!=NULL){
pax=(page_action_xml*)val;
paction=am_newPageAction(sheap);
//set global structures
paction->templateEngineRef=templateEngine;
//transfer details
paction->isForward=pax->isForward;
paction->isPermanent=pax->isPermanent;
paction->type=pax->type;
paction->advancedTemplate=pax->advancedTemplate;
paction->id=shdata_32BitString_copy(sheap,pax->id);
paction->description=shdata_32BitString_copy(sheap,pax->description);
paction->regex=shdata_32BitString_copy(sheap,pax->regex);
paction->handler_internal=shdata_32BitString_copy(sheap,pax->handler);
paction->isDebug=pax->isDebug;
paction->requestHeaders=am_copyActionHeaders(p,sheap,pax->requestHeaders,matchLists);
paction->responseHeaders=am_copyActionHeaders(p,sheap,pax->responseHeaders,matchLists);
paction->response=am_copyActionResponse(sheap,pax->response);
paction->uri=shdata_32BitString_copy(sheap,pax->uri);
paction->oidcProvider=shdata_32BitString_copy(sheap,pax->oidcProvider);
paction->relyingParty=shdata_32BitString_copy(sheap,pax->relyingParty);
paction->base64UrlEncodeState=pax->base64UrlEncodeState;
shapr_hash_set(sheap,hash,pax->id,APR_HASH_KEY_STRING,paction);
}
}
return NULL;
}
static match_ip* am_newMatchIpFromXmlMatchIpObj(shared_heap*sheap,mlx_match_ip*matchIp){
match_ip*ret;
if(matchIp==NULL) return NULL;
ret=(match_ip*)shdata_shpalloc(sheap,sizeof(match_ip));
ret->ip=shdata_32BitString_copy(sheap,matchIp->ip);
ret->isRegex=matchIp->isRegex;
ret->negate=matchIp->negate;
return ret;
}
static match_path* am_newMatchPathFromXmlMatchPathObj(shared_heap*sheap,mlx_match_path*matchPath){
match_path*ret;
if(matchPath==NULL) return NULL;
ret=(match_path*)shdata_shpalloc(sheap,sizeof(match_path));
ret->path=shdata_32BitString_copy(sheap,matchPath->path);
ret->negate=matchPath->negate;
return ret;
}
static match_event* am_newMatchEventObj(shared_heap*sheap,mlx_match_event* e){
match_event* ret;
if(e==NULL) return NULL;
ret=(match_event*)shdata_shpalloc(sheap,sizeof(match_event));
ret->start=e->start;
ret->end=e->end;
return ret;
}
static match_list_match* am_copyMatchListMatch(shared_heap* sheap,mlx_ml_match* matchX){
match_list_match* ret=NULL;
//page_action_nvp_xml* nvpX=NULL;
//match_list_match_nvp* nvp=NULL, **nvpPlace=NULL;
mlx_match_header* hdrX=NULL;
match_list_header*hdr=NULL, **headerPlace;
mlx_match_env* envX=NULL;
match_list_env*env=NULL, **envPlace;
int i=0;
if(matchX==NULL) return NULL;
ret=(match_list_match*)shdata_shpalloc(sheap,sizeof(match_list_match));
ret->cascade=matchX->cascade;
ret->host=shdata_32BitString_copy(sheap,matchX->host);
ret->ip=am_newMatchIpFromXmlMatchIpObj(sheap,matchX->ip);
ret->path=am_newMatchPathFromXmlMatchPathObj(sheap,matchX->path);
ret->event=am_newMatchEventObj(sheap,matchX->event);
if(matchX->headerList!=NULL&&matchX->headerList->nelts>0){
ret->headerList=shapr_array_make(sheap,matchX->headerList->nelts,sizeof(match_list_header*));
for(i=0;i<matchX->headerList->nelts;i++){
hdrX=(mlx_match_header*)cu_getElement(matchX->headerList,i);
hdr=(match_list_header*)shdata_shpalloc(sheap,sizeof(match_list_header));
hdr->name=shdata_32BitString_copy(sheap,hdrX->name);
hdr->value=shdata_32BitString_copy(sheap,hdrX->value);
hdr->delimAnd=shdata_32BitString_copy(sheap,hdrX->delimAnd);
hdr->negate=hdrX->negate;
hdr->isRegex=hdrX->isRegex;
headerPlace=(match_list_header**)shapr_array_push(sheap,ret->headerList);
*headerPlace=hdr;
}
}else{
ret->headerList=NULL;
}
return ret;
}
static char* am_build_matchLists(pool* p,shared_heap* sheap,oidc_config_xml* axml,shapr_hash_t* hash){
mlx_matchlist* mlx=NULL;
match_list* ml=NULL;
mlx_ml_match* matchX=NULL;
match_list_match* match=NULL, **matchPos=NULL;
int i=0,j=0;
if(axml->match_list_arr==NULL||axml->match_list_arr->nelts==0){return NULL;}
for(i=0;i<axml->match_list_arr->nelts;i++){
mlx=(mlx_matchlist*)cu_getElement(axml->match_list_arr,i);
ml=(match_list*)shdata_shpalloc(sheap,sizeof(match_list));
ml->name=shdata_32BitString_copy(sheap,mlx->name);
if(mlx->matches!=NULL&&mlx->matches->nelts>0){
ml->list=shapr_array_make(sheap,mlx->matches->nelts,sizeof(match_list_match*));
for(j=0;j<mlx->matches->nelts;j++){
matchX=(mlx_ml_match*)cu_getElement(mlx->matches,j);
match=am_copyMatchListMatch(sheap,matchX);
matchPos=(match_list_match**)shapr_array_push(sheap,ml->list);
*matchPos=match;
}
}else{
ml->list=NULL;
}
shapr_hash_set(sheap,hash,ml->name,APR_HASH_KEY_STRING,ml);
}
return NULL;
}
static path_mapping* am_buildMapping(shared_heap* sheap,oidc_config* actmap, path_mapping_xml* pathX){
path_mapping* ret=NULL;
int i=0;
char* match=NULL;
match_list* mlist=NULL, **mlistPos;
pathmapping_action_xml* pmaX;
pathmapping_action* pma,**pos;
if(pathX==NULL||pathX->postAuthActions==NULL||pathX->postAuthActions->nelts<0){
return NULL;
}
ret=(path_mapping*)shdata_shpalloc(sheap,sizeof(path_mapping));
ret->pathRegex=shdata_32BitString_copy(sheap,pathX->pathRegex);
ret->ignoreCase=pathX->ignoreCase;
ret->pmactions=shapr_array_make(sheap,pathX->postAuthActions->nelts,sizeof(pathmapping_action*));
for(i=0;i<pathX->postAuthActions->nelts;i++){
pmaX=(pathmapping_action_xml*)cu_getElement(pathX->postAuthActions,i);
pma=am_getPathMappingAction(sheap,actmap,pmaX);
pos=shapr_array_push(sheap,ret->pmactions);
*pos=pma;
}
if(pathX->matchLists==NULL){
ret->matchLists=NULL;
}else{
ret->matchLists=shapr_array_make(sheap,pathX->matchLists->nelts,sizeof(match_list*));
//added linked match lists
for(i=0;i<pathX->matchLists->nelts;i++){
match=(char*)cu_getElement(pathX->matchLists,i);
mlist=shapr_hash_get(actmap->match_lists,match,APR_HASH_KEY_STRING);
if(mlist!=NULL){
mlistPos=(match_list**)shapr_array_push(sheap,ret->matchLists);
*mlistPos=mlist;
}
}
}
return ret;
}
static void am_addMapping(shared_heap* sheap,array_header* maparr,path_mapping* pmap){
path_mapping** pmapholder=NULL;
if(maparr!=NULL&&pmap!=NULL){
pmapholder=(path_mapping**)shapr_array_push(sheap,maparr);
*pmapholder=pmap;
}
}
static relying_party* am_newRelyingParty(shared_heap* sheap){
relying_party* ret=NULL;
ret=(relying_party*)shdata_shpalloc(sheap,sizeof(relying_party));
ret->id=NULL;
ret->clientID=NULL;
ret->clientSecret=NULL;
ret->description=NULL;
ret->issuer=NULL;
ret->redirectUri=NULL;
ret->postLoginDefaultLandingPage=NULL;
return ret;
}
static char* am_copyRelyingsParties(pool* p,shared_heap* sheap, apr_hash_t* relyingPartyHashX, shapr_hash_t* relyingPartyHash, shapr_hash_t* relyingPartyIdsHash){
apr_hash_index_t * hi=NULL;
void *val=NULL;
relying_party_xml* rpX=NULL;
relying_party* rp=NULL;
int i=0;
for (hi = apr_hash_first(p, relyingPartyHashX); hi; hi = apr_hash_next(hi)) {
apr_hash_this(hi, NULL, NULL, &val);
if(val!=NULL){
rpX=(relying_party_xml*)val;
rp=am_newRelyingParty(sheap);
//transfer details
rp->id=shdata_32BitString_copy(sheap,rpX->id);
rp->clientID=shdata_32BitString_copy(sheap,rpX->clientID);
rp->description=shdata_32BitString_copy(sheap,rpX->description);
rp->clientSecret=shdata_32BitString_copy(sheap,rpX->clientSecret);
rp->issuer=shdata_32BitString_copy(sheap,rpX->issuer);
rp->validateNonce = rpX->validateNonce;
rp->redirectUri=shdata_32BitString_copy(sheap,rpX->redirectUri);
rp->postLoginDefaultLandingPage=shdata_32BitString_copy(sheap,rpX->postLoginDefaultLandingPage);
shapr_hash_set(sheap,relyingPartyIdsHash,rp->id,APR_HASH_KEY_STRING,rp);
shapr_hash_set(sheap,relyingPartyHash,rp->clientID,APR_HASH_KEY_STRING,rp);
}
}
return NULL;
}
static char* oauthconf_downloadOIDCProviderMetadata(pool*p, shared_heap* sheap, char* homeDir, char* metadataUrl){
oidc_provider* oidcProvider=NULL;
char *error=NULL;
apr_file_t* file=NULL;
apr_status_t status;
char key[KEYBUFFSIZE];
apr_size_t bytes_read = KEYBUFFSIZE-1;
pool* tp=NULL;
if(metadataUrl==NULL) return NULL;
//setup filepool
if(apr_pool_create(&tp,p)!=APR_SUCCESS){
return NULL;
}
char* keyPath=docp_getRemoteResourcePathEx(tp,metadataUrl,homeDir,&error);
if(keyPath==NULL){
keyPath=docp_getLocalResourcePath(tp,metadataUrl,homeDir);
}
status = apr_file_open (&file, keyPath, APR_READ,APR_OS_DEFAULT,tp);
if(status!=APR_SUCCESS) {
//File open operation failed.
apr_pool_destroy(tp);
return NULL;
}
memset(key, '\0', KEYBUFFSIZE);
if( (status = apr_file_read(file, key, &bytes_read)) != APR_SUCCESS) {
//File read operation failed.
apr_pool_destroy(tp);
apr_file_close(file);
return NULL;
}
apr_file_close ( file );
apr_pool_destroy(tp);
return apr_pstrdup(p, key);
}
char* am_build(pool* p,shared_heap* sheap, int isRefresh,cbs_globals* globals,char* filepath){
apr_status_t status;
oidc_config_xml* axml=NULL;
oidc_config* ret=NULL;
char* result=NULL;
//stuff to handle config
pool* subp=NULL;
path_mapping_xml* pathx=NULL;
int x=0, i=0;
//stuff to map path mappings
path_mapping* pmap=NULL;
//Subdoc processing
char* homeDir=globals->homeDir;
cbs_service_descriptor *rs=globals->resourceService;
char* error=NULL;
apr_hash_index_t * hi=NULL;
//do on subpool
if((status=apr_pool_create(&subp,p))!=APR_SUCCESS){
return apr_pstrdup(p,"Could not create subpool");
}
axml=amx_newObj(subp);
result=amx_loadConfFile(subp,filepath,axml);
if(isRefresh==0){
amx_printAll(subp,axml);
}
//end
shdata_OpenItemTag(sheap,SHEAP_ITEM_ID_AUTHZ_OIDC);
ret=am_newObj(sheap);
//initialize template engine
ret->templateEngine=te_newEngineObj(sheap);
result=te_initialize(p,sheap,globals,ret->templateEngine);
//parse through matchlists in config
am_build_matchLists(p,sheap,axml,ret->match_lists);
//parse through page_actions in config
am_build_pageActions(p,sheap,globals,axml,ret->page_actions,ret->templateEngine,ret->match_lists);
//parse through path mappings in config;
for(x=0;x<axml->path_mappings_arr->nelts;x++){
pathx=(path_mapping_xml*)cu_getElement(axml->path_mappings_arr,x);
if(pathx->postAuthActions!=NULL&&pathx->postAuthActions->nelts>0){
pmap=am_buildMapping(sheap,ret,pathx);
if(pmap!=NULL){
am_addMapping(sheap,ret->path_mappings->postauth,pmap);
}
}
}
if(axml->oidcProviders==NULL||axml->oidcProviders->nelts==0) {
return apr_pstrdup(p,"oidcProviders are missing");
}
// set default to NULL
ret->oidcProvider = NULL;
// iterate thru all the providers
for(x=0;x<axml->oidcProviders->nelts;x++) {
oidc_provider_xml* oidcProviderX=(oidc_provider_xml*)cu_getElement(axml->oidcProviders,x);
if(oidcProviderX!=NULL){
oidc_provider* oidcProvider=(oidc_provider*)shdata_shpcalloc(sheap,sizeof(oidc_provider));
// copy one by one
// download oidcProvider url and read it.
oidcProvider=(oidc_provider*)shdata_shpcalloc(sheap,sizeof(oidc_provider));
oidcProvider->isDefault = oidcProviderX->isDefault;
oidcProvider->id=shdata_32BitString_copy(sheap,oidcProviderX->id);
char* jwksJson = NULL;
if(oidcProviderX->metadataUrl!=NULL) {
oidcProvider->metadataUrl=shdata_32BitString_copy(sheap,oidcProviderX->metadataUrl);
char* metadata = oauthconf_downloadOIDCProviderMetadata(p, sheap, homeDir, oidcProviderX->metadataUrl);
Value* json = JSON_Parse(p, metadata);
if(json==NULL) return NULL;
Value* item = JSON_GetObjectItem(json, "issuer");
char* issuer = (item!=NULL) ? (char*)JSON_GetStringFromStringItem(item) : NULL;
oidcProvider->issuer=shdata_32BitString_copy(sheap,issuer);
item = JSON_GetObjectItem(json, "authorization_endpoint");
char* authorizationEndpoint = (item!=NULL) ? (char*)JSON_GetStringFromStringItem(item) : NULL;
oidcProvider->authorizationEndpoint=shdata_32BitString_copy(sheap,authorizationEndpoint);
item = JSON_GetObjectItem(json, "token_endpoint");
char* tokenEndpoint = (item!=NULL) ? (char*)JSON_GetStringFromStringItem(item) : NULL;
oidcProvider->tokenEndpoint=shdata_32BitString_copy(sheap,tokenEndpoint);
item = JSON_GetObjectItem(json, "jwks_uri");
char* jwksUri = (item!=NULL) ? (char*)JSON_GetStringFromStringItem(item) : NULL;
oidcProvider->jwksUri=shdata_32BitString_copy(sheap,jwksUri);
// download JWT verification keys from url
if(oidcProvider->jwksUri!=NULL) {
http_util_result* httpResult=hc_get_verbose(p, oidcProvider->jwksUri, 10, NULL, NULL, error);
if(!hc_is200_OK(httpResult)) {
if(error!=NULL) { *error = apr_pstrdup(p, "jwsUri response and cache file both failed"); }
apr_pool_destroy (subp);
return NULL;
}
jwksJson = httpResult->data;
}
} else {
oidcProvider->issuer=shdata_32BitString_copy(sheap, oidcProviderX->issuer);
oidcProvider->authorizationEndpoint=shdata_32BitString_copy(sheap,oidcProviderX->authorizationEndpoint);
oidcProvider->tokenEndpoint=shdata_32BitString_copy(sheap,oidcProviderX->tokenEndpoint);
oidcProvider->jwksUri=shdata_32BitString_copy(sheap,oidcProviderX->jwksUri);
// download JWT verification keys from url
if(oidcProvider->jwksUri!=NULL) {
http_util_result* httpResult=hc_get_verbose(p, oidcProvider->jwksUri, 10, NULL, NULL, error);
if(!hc_is200_OK(httpResult)) {
if(error!=NULL) { *error = apr_pstrdup(p, "jwsUri response and cache file both failed"); }
apr_pool_destroy (subp);
return NULL;
}
jwksJson = httpResult->data;
} else {
jwksJson = shdata_32BitString_copy(sheap,oidcProviderX->jwksJson);
}
}
if(jwksJson!=NULL) {
Value* json = JSON_Parse(p, jwksJson);
if(json==NULL) {
if(error!=NULL) { *error = apr_pstrdup(p, "jwsUri response parsing failed"); }
apr_pool_destroy (subp);
return NULL;
}
Value* array = JSON_GetObjectItem(json, "keys");
if(array==NULL||JSON_GetItemType(array)!=JSON_Array) {
if(error!=NULL) { *error = apr_pstrdup(p, "keys object is not array"); }
apr_pool_destroy (subp);
return NULL;
}
int arrSz = JSON_GetArraySize(array);
oidcProvider->jwsKeys=shapr_hash_make(sheap);
// Retrieve item number "item" from array "array". Returns NULL if unsuccessful.
for (i=0; i<arrSz; i++) {
oauth_jwskey* jwsKey=(oauth_jwskey*)shdata_shpcalloc(sheap,sizeof(oauth_jwskey));
Value* element = JSON_GetArrayItem(array, i);
Value* keyIDObj = JSON_GetObjectItem(element, "kid");
const char* keyID = (keyIDObj) ? JSON_GetStringFromStringItem(keyIDObj) : NULL;
jwsKey->id = shdata_32BitString_copy(sheap,keyID);
Value* val = JSON_GetObjectItem(element, "kty");
char* type = (val) ? (char*)JSON_GetStringFromStringItem(val) : NULL;
jwsKey->type=shdata_32BitString_copy(sheap,type);
val = JSON_GetObjectItem(element, "alg");
char* algorithm = (val) ? (char*)JSON_GetStringFromStringItem(val) : NULL;
jwsKey->algorithm=shdata_32BitString_copy(sheap, algorithm);
val = JSON_GetObjectItem(element, "use");
char* use = (val) ? (char*)JSON_GetStringFromStringItem(val) : NULL;
jwsKey->use=shdata_32BitString_copy(sheap, use);
val = JSON_GetObjectItem(element, "n");
char* modulus = (val) ? (char*)JSON_GetStringFromStringItem(val) : NULL;
jwsKey->modulus=shdata_32BitString_copy(sheap, modulus);
val = JSON_GetObjectItem(element, "e");
char* exponent = (val) ? (char*)JSON_GetStringFromStringItem(val) : NULL;
jwsKey->exponent=shdata_32BitString_copy(sheap, exponent);
shapr_hash_set(sheap,oidcProvider->jwsKeys,jwsKey->id,APR_HASH_KEY_STRING,jwsKey);
}
}
shapr_hash_set(sheap,ret->oidcProviderHash,oidcProvider->issuer,APR_HASH_KEY_STRING,oidcProvider);
shapr_hash_set(sheap,ret->oidcProviderIdsHash,oidcProvider->id,APR_HASH_KEY_STRING,oidcProvider);
if(ret->oidcProvider==NULL) { // set the first valid one
ret->oidcProvider = oidcProvider;
}else if(oidcProvider->isDefault) { // override from default
ret->oidcProvider = oidcProvider;
}
}
}
ret->rpSession=
cookie_cookieShmDup(sheap,axml->rpSession);
ret->oidcSession=
cookie_cookieShmDup(sheap,axml->oidcSession);
ret->accessToken=
cookie_cookieShmDup(sheap,axml->accessToken);
am_copyRelyingsParties(p, sheap, axml->relyingPartyHash,ret->relyingPartyHash, ret->relyingPartyIdsHash);
shdata_CloseItemTagWithInfo(sheap,"Action Mappings");
apr_pool_destroy(subp);
return result;
}
oidc_config* am_fetchFromSheap(shared_heap* sheap){
return (oidc_config*)shdata_getItem(sheap, SHEAP_ITEM_ID_AUTHZ_OIDC);
}
static int am_isHeaderMatched(pool*p, match_list_header* hdr, char*header){
array_header* matchHeaderValues=NULL, *headerValues=NULL;
int isRegex=hdr->isRegex;
int negate=hdr->negate;
int hasDelim=(hdr->delimAnd==NULL)?FALSE:TRUE;
int isHeaderMatch=FALSE;
if(hdr->value==NULL) return FALSE;
if(header==NULL){
if(strcasecmp(hdr->value,"nil")==0) {
return TRUE;
}else {
return FALSE;
}
}
isHeaderMatch=matchList_isMatched(p,hdr->value, header, isRegex);
if(hasDelim){
matchHeaderValues=cu_parseStringArrayFromCsv(p, 4, hdr->delimAnd, hdr->value);
headerValues=cu_parseStringArrayFromCsv(p, 4, hdr->delimAnd, header);
if(matchHeaderValues==NULL||headerValues==NULL) return FALSE;
}
if(negate==FALSE){
if(!hasDelim&&isHeaderMatch||(hasDelim&&ml_isSubsetFound(p,matchHeaderValues,headerValues,isRegex))){
return TRUE;
}
}else{
if(!hasDelim&&isHeaderMatch==FALSE||(hasDelim&&ml_isNegateSubsetFound(p,matchHeaderValues,headerValues,isRegex))){
return TRUE;
}
}
return FALSE;
}
static int am_isIpMatched(pool*p, match_ip* matchIp, char*ip){
int isIpMatch;
if(matchIp==NULL||matchIp->ip==NULL||ip==NULL) return TRUE;
isIpMatch=matchList_isMatched(p,matchIp->ip, ip, matchIp->isRegex);
if(matchIp->negate==TRUE){isIpMatch=!isIpMatch;}
return isIpMatch;
}
static int am_isPathMatched(pool*p, match_path* matchPath, char*path){
int isPathMatch;
if(matchPath==NULL||matchPath->path==NULL||path==NULL) return TRUE;
isPathMatch=(rc_matchByStringsReturnDetails(p,matchPath->path,path)==NULL);
if(matchPath->negate==TRUE){isPathMatch=!isPathMatch;}
return isPathMatch;
}
static int am_isEventScheduled(pool*p, match_event* e){
int i;
time_t currentTime=time(NULL);
//No event configured
if(e==NULL) return TRUE;
if(( e->start < currentTime ) && ( currentTime < ( (e->end>0) ? e->end : TIME_MAX) ) ) {
return TRUE;
}
return FALSE;
}
match_list_match* am_isMatchListMatch(pool* p, match_list* matchlist, char* path, char* ip,apr_table_t *headers_in,apr_table_t* subprocess_env){
int i=0,j=0;
char* header=NULL;
//match_list_match_nvp* nvp=NULL;
match_list_header* matchHeader=NULL;
match_list_match* ret=NULL;
for(i=0;i<matchlist->list->nelts;i++){
ret=(match_list_match*)cu_getElement(matchlist->list,i);
//verify regex
if(matchList_isHostMatched(p, ret->host, headers_in)){
if(am_isEventScheduled(p,ret->event)){
if(am_isPathMatched(p,ret->path,path)){
if(am_isIpMatched(p,ret->ip,ip)){
//now verify headers
if(ret->headerList!=NULL&&ret->headerList->nelts>0) { //need to match headers
if(headers_in==NULL||apr_is_empty_table(headers_in)){ //no headers to match
return NULL;
}else{ //match headers
int cascade = ret->cascade;
for(j=0;j<ret->headerList->nelts;j++){
matchHeader=(match_list_header*)cu_getElement(ret->headerList,j);
header=(char*)apr_table_get(headers_in,matchHeader->name);
if(am_isHeaderMatched(p,matchHeader,header)==FALSE){
ret = NULL;
break;
}
}
/*
* Bug: As soon as any match headers failed to match
* above for loop used to return NULL from this function
* For backward compatibility, this bug is kept asis
* And can be triggered by setting by <match cascade="false"> tag
* in runtime.xml
* Fix: Cascade would allow next match to be matched
* if current match is failed to match.
*/
if ( cascade==TRUE && ret==NULL ) { continue; }
return ret;
}
}else{
return ret;
}
}
}
}
}
}
return NULL;
}
static match_list_match* am_isMatchListsMatch(pool* p, array_header* matchLists, char* path, char* ip,apr_table_t *headers_in,apr_table_t* subprocess_env){
match_list* list=NULL;
int i=0;
match_list_match* ret=NULL;
if(matchLists==NULL||matchLists->nelts==0){return NULL;}
for(i=0;i<matchLists->nelts;i++){
list=(match_list*)cu_getElement(matchLists,i);
ret=am_isMatchListMatch(p,list,path,ip,headers_in,subprocess_env);
if(ret!=NULL){return ret;}
}
return NULL;
}
static path_mapping* am_getPathMapping(pool* p,array_header* pgmaps,char* path,char* ip, apr_table_t* headers, apr_table_t* subprocess_env){
path_mapping* pmap=NULL;
int x=0;
if(pgmaps==NULL||path==NULL){return NULL;}
for(x=0;x<pgmaps->nelts;x++){
pmap=(path_mapping*)cu_getElement(pgmaps,x);
if(rc_matchByStrings(p, pmap->pathRegex, path)==0
||(pmap->ignoreCase==TRUE&&(rc_matchByStringsIgnoreCase(p, pmap->pathRegex, path)==0)) ){
if(pmap->matchLists==NULL||pmap->matchLists->nelts==0){
return pmap;
}else if(am_isMatchListsMatch(p,pmap->matchLists,path,ip,headers,subprocess_env)!=NULL){
return pmap;
}
}
}
return NULL;
}
page_action* am_getMatchingPageAction(pool* p,array_header* pmactions,char* path,char* ip, apr_table_t* headers, apr_table_t* subprocess_env){
pathmapping_action* pmaction=NULL;
int x=0;
if(pmactions==NULL||path==NULL){return NULL;}
for(x=0;x<pmactions->nelts;x++){
pmaction=(pathmapping_action*)cu_getElement(pmactions,x);
if(pmaction->matchList==NULL){
return pmaction->action;
}else if(am_isMatchListMatch(p,pmaction->matchList,path,ip,headers,subprocess_env)!=NULL){
return pmaction->action;
}
}
return NULL;
}
path_mapping* am_getPathMapping_PostAuth(pool* p,oidc_config* actmap,char* path,char* ip, apr_table_t* headers, apr_table_t* subprocess_env){
if(actmap==NULL||actmap->path_mappings==NULL) return NULL;
return am_getPathMapping(p,actmap->path_mappings->postauth,path,ip,headers,subprocess_env);
}
#define OAUTH_TOKEN_WILDCARDNULL(str) (str!=NULL?str:"*")
#define OAUTH_TOKEN_URLENCODE_WILDCARDNULL(p, str) (str!=NULL?url_encode2(p,str):"*")
oauth_jwt_header* oauthutil_newJWTHeaderObj(pool* p) {
return (oauth_jwt_header*)apr_pcalloc(p, sizeof(oauth_jwt_header));
}
const char* oauthutil_serializeJWTHeader(pool* p, oauth_jwt_header* hdr) {
Value* json = JSON_CreateObject(p);
JSON_AddStringToObject(p, json, "alg", hdr->algorithm);
JSON_AddStringToObject(p, json, "typ", (hdr->type!=NULL) ? hdr->type : "JWT");
if(hdr->keyID!=NULL) {
JSON_AddStringToObject(p, json, "kid", hdr->keyID);
}
char* headerJson = JSON_SerializeUnformatted(p, json);
unsigned char encodedHeader[OAUTH_BASE64_BUFSIZE];
memset(encodedHeader, '\0', OAUTH_BASE64_BUFSIZE);
base64Url_encode(encodedHeader, headerJson, strlen(headerJson));
return apr_pstrdup(p, encodedHeader);
}
oauth_jwt_header* oauthutil_deserializeJWTHeader(pool* p, char* encodedHeader) {
Value* json, *item;
oauth_jwt_header* header;
unsigned char headerJson[OAUTH_BASE64_BUFSIZE];
memset(headerJson, '\0', OAUTH_BASE64_BUFSIZE);
base64Url_decode(headerJson, encodedHeader, strlen(encodedHeader));
json = JSON_Parse(p, headerJson);
if(json==NULL) return NULL;
item = JSON_GetObjectItem(json, "alg");
header = oauthutil_newJWTHeaderObj(p);
header->algorithm = (item!=NULL) ? (char*)JSON_GetStringFromStringItem(item) : NULL;
item = JSON_GetObjectItem(json, "kid");
header->keyID = (item!=NULL) ? (char*)JSON_GetStringFromStringItem(item) : NULL;
item = JSON_GetObjectItem(json, "typ");
header->type = (item!=NULL) ? (char*)JSON_GetStringFromStringItem(item) : NULL;
return header;
}
oauth_jwt_claim* oauthutil_newJWTClaimObj(pool* p) {
return (oauth_jwt_claim*)apr_pcalloc(p, sizeof(oauth_jwt_claim));
}
const char* oauthutil_serializeJWTClaim(pool* p, oauth_jwt_claim* claim) {
Value* json = JSON_CreateObject(p);
if(claim->issuer!=NULL) {
JSON_AddStringToObject(p, json, "iss", claim->issuer);
}
if(claim->scope!=NULL) {
JSON_AddStringToObject(p, json, "scope", claim->scope);
}
if(claim->subject!=NULL) {
JSON_AddStringToObject(p, json, "sub", claim->subject);
}
if(claim->audience!=NULL) {
JSON_AddStringToObject(p, json, "aud", claim->audience);
}
if(claim->expiry>0) {
JSON_AddNumberToObject(p, json, "exp", claim->expiry);
}
if(claim->issuedAt>0){
JSON_AddNumberToObject(p, json, "iat", claim->issuedAt);
}
if(claim->auth_time>0){
JSON_AddNumberToObject(p, json, "auth_time", claim->auth_time);
}
if(claim->options!=NULL) {
apr_hash_index_t *hi;
char* name=NULL,*value=NULL;
for (hi = apr_hash_first(p, claim->options); hi; hi = apr_hash_next(hi)) {
apr_hash_this(hi,(const void**)&name, NULL, (void**)&value);
JSON_AddStringToObject(p, json, name, value);
}
}
if(claim->roles!=NULL){
int i;
Value* rolesArray = JSON_CreateArray(p);
JSON_AddItemToObject(p, json, "roles", rolesArray);
for(i=0;i<claim->roles->nelts;i++){
char* roleName = (char*)cu_getElement(claim->roles, i);
if(roleName!=NULL) {
JSON_AddItemToArray(p, rolesArray, JSON_CreateString(p, roleName));
}
}
}
char* claimJson = JSON_SerializeUnformatted(p, json);
unsigned char encodedClaim[OAUTH_BASE64_BUFSIZE];
memset(encodedClaim, '\0', OAUTH_BASE64_BUFSIZE);
base64Url_encode(encodedClaim, claimJson, strlen(claimJson));
return apr_pstrdup(p, encodedClaim);
}
static void oauthutil_itemCallback(Value* item, void* data) {
oauth_jwt_claim* claim = (oauth_jwt_claim*)data;
const char* name = (item!=NULL) ? JSON_GetItemString(item) : NULL ;
if(name==NULL) return;
if(JSON_GetItemType(item)==JSON_Number) {
if(strcmp(name,"exp")==0) {
claim->expiry = JSON_GetNumberFromNumberItem(item);
}else if(strcmp(name,"iat")==0) {
claim->issuedAt = JSON_GetNumberFromNumberItem(item);
}
}else if(JSON_GetItemType(item)==JSON_String) {// string
if(strcmp(name,"iss")==0) {
claim->issuer = (char*)JSON_GetStringFromStringItem(item);
}else if(strcmp(name,"scope")==0) {
claim->scope = (char*)JSON_GetStringFromStringItem(item);
}else if(strcmp(name,"sub")==0) {
claim->subject = (char*)JSON_GetStringFromStringItem(item);
}else if(strcmp(name,"aud")==0) {
claim->audience = (char*)JSON_GetStringFromStringItem(item);
}else{
apr_hash_set(claim->options,name, APR_HASH_KEY_STRING, JSON_GetStringFromStringItem(item));
}
}else if(JSON_GetItemType(item)==JSON_Array) {// string
int i;
if(strcmp(name,"roles")==0) {
char** place, *role;
int count = JSON_GetArraySize(item);
for (i=0; i < count; i++){
Value* el = JSON_GetArrayItem(item, i);
if (el!=NULL&&JSON_GetItemType(el)==JSON_String) {
role = (char*)JSON_GetStringFromStringItem(el);
if(role!=NULL){
place=(char**)apr_array_push(claim->roles);
*place=role;
}
}
}
}
}
}
oauth_jwt_claim* oauthutil_deserializeJWTClaim(pool* p, char* encodedClaim) {
Value* json, *item;
oauth_jwt_claim* claim;
unsigned char claimJson[OAUTH_BASE64_BUFSIZE];
memset(claimJson, '\0', OAUTH_BASE64_BUFSIZE);
base64Url_decode(claimJson, encodedClaim, strlen(encodedClaim));
json = JSON_Parse(p, claimJson);
if(json==NULL) return NULL;
claim = oauthutil_newJWTClaimObj(p);
claim->options = apr_hash_make(p);
claim->expiry = -1;
claim->issuedAt = -1;
claim->roles = apr_array_make(p,8,sizeof(char*));
JSON_IterateObjectItemCallback(json, claim, oauthutil_itemCallback);
return claim;
}
oauth_jwt_claim* oauthutil_deserializeJWTClaimNoDecoding(pool* p, char* claimJson) {
Value* json, *item;
oauth_jwt_claim* claim;
if(claimJson==NULL) return NULL;
json = JSON_Parse(p, claimJson);
if(json==NULL) return NULL;
claim = oauthutil_newJWTClaimObj(p);
claim->options = apr_hash_make(p);
claim->expiry = -1;
claim->issuedAt = -1;
claim->roles = apr_array_make(p,8,sizeof(char*));
JSON_IterateObjectItemCallback(json, claim, oauthutil_itemCallback);
return claim;
}
static const char* oauthutil_generateJWTSignature(pool*p, const char* algorithm, unsigned char* secretKey, char* payload) {
char* error = NULL;
const char* signature = NULL;
if(strcasecmp(algorithm,"HS256")==0){
signature = comu_generateHS256Signature(p, payload, secretKey, &error);
} else if(strcasecmp(algorithm,"RS256")==0){
signature = comu_rsa256Sign(p, payload, strlen(payload), secretKey, &error);
}
return signature;
}
oauth_jwt* oauthutil_newJWTObj(pool* p) {
return (oauth_jwt*)apr_pcalloc(p, sizeof(oauth_jwt));
}
static int oauthutil_verifyJWTSignature(pool*p, const char* algorithm, unsigned char* secretKey, char* payload, char* encodedSignature) {
char* error = NULL;
int verified = FALSE;
if(secretKey==NULL||payload==NULL) return FALSE;
//Generate signature
if(strcasecmp(algorithm,"HS256")==0){
verified = comu_verifyHS256Signature(p, payload, encodedSignature, secretKey, &error);
}else if(strcasecmp(algorithm,"RS256")==0){
verified = comu_rsa256Verify(p, payload,strlen(payload),secretKey, encodedSignature, &error);
}
return verified;
}
const char* oauthutil_serializeJWT(pool*p, oauth_jwt* jwt, const char* secretKey) {
if(jwt==NULL||jwt->header==NULL||jwt->claim==NULL) return NULL;
const char* encodedHeader = oauthutil_serializeJWTHeader(p, jwt->header);
const char* encodedClaim = oauthutil_serializeJWTClaim(p, jwt->claim);
// generate JWT
if(encodedHeader==NULL||encodedClaim==NULL) return NULL;
char* payload = apr_pstrcat(p, encodedHeader, ".", encodedClaim, NULL);
const char* signature = oauthutil_generateJWTSignature(p, jwt->header->algorithm, (unsigned char*)secretKey, payload);
return apr_pstrcat(p, payload, ".", signature, NULL);
}
oauth_jwt* oauthutil_parseAndValidateJWT(pool* p, const char* src, getClientSecretKeyByClientId_func getClientSecretKeyByClientIdFunc, void* data) {
char* srccpy = NULL;
char* token, *last, *payload;
char* encodedHeader = NULL;
char* encodedClaim = NULL;
int verified;
oauth_jwt* jwt = oauthutil_newJWTObj(p);
if (src == NULL) return NULL;
srccpy = apr_pstrdup(p, src);
token = apr_strtok(srccpy, ".", &last);
if (token != NULL) {
// header
encodedHeader = token;
jwt->header = oauthutil_deserializeJWTHeader(p, encodedHeader);
if(jwt->header==NULL||jwt->header->algorithm==NULL) return NULL;
// claim
token = apr_strtok(NULL, ".", &last);
if (token != NULL) {
encodedClaim = token;
jwt->claim = oauthutil_deserializeJWTClaim(p, encodedClaim);
if(jwt->claim==NULL||jwt->claim->issuer==NULL) return NULL;
} else {
return NULL;
}
// signature
token = apr_strtok(NULL, ".", &last);
if (token != NULL) {
jwt->signature = token;
} else {
return NULL;
}
if(getClientSecretKeyByClientIdFunc==NULL) return NULL;
const char* secretKey = (*getClientSecretKeyByClientIdFunc)(p, jwt->claim->issuer, data);
// printf("encodedHeader=%s, encodedClaim=%s encodedSignature=%s\r\n", encodedHeader, encodedClaim, jwt->signature);
payload = apr_pstrcat(p, encodedHeader, ".", encodedClaim, NULL);
verified = oauthutil_verifyJWTSignature(p, jwt->header->algorithm, (unsigned char*)secretKey, payload, jwt->signature);
if(verified==FALSE) return NULL;
}
return jwt;
}
void oauthutil_printJWT(pool* p, oauth_jwt* jwt) {
if(jwt==NULL||jwt->header==NULL||jwt->claim==NULL) return;
if(jwt->header!=NULL) {
printf("algorithm=%s\r\n", jwt->header->algorithm);
}
if(jwt->claim!=NULL) {
if(jwt->claim->issuer!=NULL) {
printf("issuer=%s\r\n", jwt->claim->issuer);
}
if(jwt->claim->scope!=NULL) {
printf("scope=%s\r\n", jwt->claim->scope);
}
if(jwt->claim->subject!=NULL) {
printf("subject=%s\r\n", jwt->claim->subject);
}
if(jwt->claim->audience!=NULL) {
printf("audience=%s\r\n", jwt->claim->audience);
}
if(jwt->claim->expiry>0) {
printf("expiry=%ld\r\n", jwt->claim->expiry);
}
if(jwt->claim->issuedAt>0) {
printf("issuedAt=%ld\r\n", jwt->claim->issuedAt);
}
if(jwt->claim->options!=NULL) {
apr_hash_index_t *hi;
char* name=NULL,*value=NULL;
for (hi = apr_hash_first(p, jwt->claim->options); hi; hi = apr_hash_next(hi)) {
apr_hash_this(hi,(const void**)&name, NULL, (void**)&value);
printf("%s=%s\r\n", name,value);
}
}
}
printf("signature = %s\r\n", jwt->signature);
}
// ID token ( openid) routines
// returns JWT formatted ID Token
const char* oauthutil_generateIDToken(pool* p, oauth_jwt_header* header, oauth_jwt_claim* claim, const char* secretKey) {
if(header==NULL || claim==NULL||secretKey==NULL) return NULL;
oauth_jwt* jwt = oauthutil_newJWTObj(p);
jwt->header = header;
jwt->claim = claim;
return oauthutil_serializeJWT(p, jwt, secretKey);
}
oauth_jwk* oauthutil_newJWKObj(pool *p){
oauth_jwk* jwk=(oauth_jwk*)apr_pcalloc(p, sizeof(oauth_jwk));
return jwk;
}
// parse JWT formatted ID Token
oauth_jwt* oauthutil_parseIDToken(pool* p, const char* src, char** payloadP, char** error){
char* srccpy = NULL;
char* token, *last;
char* encodedHeader = NULL;
char* encodedClaim = NULL;
if (src == NULL) {
if(error!=NULL) { *error = apr_pstrdup(p, "id_token is null"); }
return NULL;
}
srccpy = apr_pstrdup(p, src);
token = apr_strtok(srccpy, ".", &last);
if(token==NULL) {
if(error!=NULL) { *error = apr_pstrdup(p, "id_token.header is null"); }
return NULL;
}
oauth_jwt* jwt = oauthutil_newJWTObj(p);
// header
encodedHeader = token;
jwt->header = oauthutil_deserializeJWTHeader(p, encodedHeader);
// claim
token = apr_strtok(NULL, ".", &last);
if (token != NULL) {
encodedClaim = token;
jwt->claim = oauthutil_deserializeJWTClaim(p, encodedClaim);
} else {
if(error!=NULL) { *error = apr_pstrdup(p, "id_token.claim is null"); }
return NULL;
}
// signature
token = apr_strtok(NULL, ".", &last);
if (token != NULL) {
jwt->signature = token;
} else {
if(error!=NULL) { *error = apr_pstrdup(p, "id_token.signature is null"); }
return NULL;
}
if(payloadP!=NULL) { *payloadP = apr_pstrcat(p, encodedHeader, ".", encodedClaim, NULL); }
// printf("encodedHeader=%s, encodedClaim=%s encodedSignature=%s\r\n", encodedHeader, encodedClaim, jwt->signature);
return jwt;
}
// validates JWT formatted ID Token
oauth_jwt* oauthutil_parseAndValidateIDToken(pool* p, const char* src, getJSONWebKey_func getJSONWebKeyFunc, void* data, char** error){
char* payload = NULL;
oauth_jwt* jwt = oauthutil_parseIDToken(p, src, &payload, error);
if(jwt==NULL||payload==NULL) {
if(error!=NULL) { *error = apr_pstrdup(p, "id_token parsing failed"); }
return NULL;
}
if(jwt->header==NULL||jwt->header->algorithm==NULL) {
if(error!=NULL) { *error = apr_pstrdup(p, "id_token.header is null"); }
return NULL;
}
// claim
if(jwt->claim==NULL) {
if(error!=NULL) { *error = apr_pstrdup(p, "id_token.claim is null"); }
return NULL;
}
if(jwt->claim->issuer==NULL||jwt->claim->audience==NULL) {
if(error!=NULL) { *error = apr_pstrdup(p, "id_token.claim audience or issuer null"); }
return NULL;
}
// validate claim expiry
if(jwt->claim->expiry>0&&jwt->claim->expiry<apr_time_sec(apr_time_now())) {
if(error!=NULL) { *error = apr_pstrdup(p, "id_token.claim expired"); }
return NULL;
}
// signature
if(jwt->signature==NULL) {
if(error!=NULL) { *error = apr_pstrdup(p, "id_token.signature is null"); }
return NULL;
}
if(getJSONWebKeyFunc==NULL) {
if(error!=NULL) { *error = apr_pstrdup(p, "id_token.webkey function is null"); }
return NULL;
}
oauth_jwk* jwk = (*getJSONWebKeyFunc)(p, jwt->header, jwt->claim->issuer, jwt->claim->audience, data, error);
if(jwk==NULL) return NULL;
int verified=FALSE;
if(strcasecmp(jwt->header->algorithm,"HS256")==0){
verified = comu_verifyHS256Signature(p, payload, jwt->signature, jwk->key, error);
}else if(strcasecmp(jwt->header->algorithm,"RS256")==0){
if(jwk->modulus!=NULL&&jwk->exponent!=NULL) {
verified = comu_rsaVerifyByModulus(p, jwt->header->algorithm, payload,strlen(payload), jwk->modulus, jwk->exponent, jwt->signature, error);
}else if(jwk->key!=NULL) {
verified = comu_rsa256Verify(p, payload,strlen(payload), jwk->key, jwt->signature, error);
}
}
if(verified==FALSE) {
if(error!=NULL) { *error = apr_pstrdup(p, "id_token.signature failed"); }
return NULL;
}
return jwt;
}
const char* oauthutil_serializeJWTClaimNoEncoding(pool* p, oauth_jwt_claim* claim) {
Value* json = JSON_CreateObject(p);
if(claim->issuer!=NULL) {
JSON_AddStringToObject(p, json, "iss", claim->issuer);
}
if(claim->scope!=NULL) {
JSON_AddStringToObject(p, json, "scope", claim->scope);
}
if(claim->subject!=NULL) {
JSON_AddStringToObject(p, json, "sub", claim->subject);
}
if(claim->audience!=NULL) {
JSON_AddStringToObject(p, json, "aud", claim->audience);
}
if(claim->expiry>0) {
JSON_AddNumberToObject(p, json, "exp", claim->expiry);
}
if(claim->issuedAt>0){
JSON_AddNumberToObject(p, json, "iat", claim->issuedAt);
}
if(claim->options!=NULL) {
apr_hash_index_t *hi;
char* name=NULL,*value=NULL;
for (hi = apr_hash_first(p, claim->options); hi; hi = apr_hash_next(hi)) {
apr_hash_this(hi,(const void**)&name, NULL, (void**)&value);
JSON_AddStringToObject(p, json, name, value);
}
}
return JSON_SerializeUnformatted(p, json);
}
// prints JWT formatted ID Token
void oauthutil_printIDToken(pool* p, oauth_jwt* IDToken){
oauthutil_printJWT(p, IDToken);
}
static void am_printMatchList(pool* p, array_header* arr){
int i=0, j=0;
match_list_match* match=NULL;
match_list_header* hdr=NULL;
match_list_env* env=NULL;
if(arr!=NULL&&arr->nelts>0){
printf("\r\n\t\t -- MatchList[%d]",arr->nelts);
for(i=0;i<arr->nelts;i++){
match=(match_list_match*)cu_getElement(arr,i);
printf("\r\n\t>\t");
if(match->host!=NULL){
printf("Host: %s ",match->host);
}
if(match->ip!=NULL&&match->ip->ip!=NULL){
printf("IP: %s ",match->ip->ip);
printf("\tisregex: %s ",BOOLTOSTR(match->ip->isRegex));
printf("\tnegate: %s ",BOOLTOSTR(match->ip->negate));
printf("\n");
}
if(match->headerList!=NULL&&match->headerList->nelts>0){
printf("Headers [%d]",match->headerList->nelts);
for(j=0;j<match->headerList->nelts;j++){
hdr=(match_list_header*)cu_getElement(match->headerList,j);
printf("\r\n\t\t\t %s = %s",hdr->name,hdr->value);
if(hdr->delimAnd) printf("\r\n\t\t\t delimAnd = \"%s\"",hdr->delimAnd);
printf("\tisregex: %s ",BOOLTOSTR(hdr->isRegex));
printf("\tnegate: %s ",BOOLTOSTR(hdr->negate));
printf("\n");
}
}
printf("\r\n");
}
}
}
void am_printAll(pool* p, oidc_config* oidcConfig){
int x=0, i=0;
page_action* pa=NULL;
shapr_hash_index_t * hi=NULL;
void *val=NULL;
const void *key=NULL;
match_list* mlist=NULL;
char* includeXml=NULL;
printf("<OIDC Configuration>\r\n");
printf("Page Actions (%d)\r\n",shapr_hash_count (oidcConfig->page_actions));
for (hi = shapr_hash_first(p,oidcConfig->page_actions); hi; hi = shapr_hash_next(hi)) {
shapr_hash_this(hi, &key, NULL, &val);
printf("\t* %s",key);
if(val!=NULL){
pa=(page_action*)val;
if(pa->uri!=NULL){
printf(",{uri:%s",pa->uri);
}
if(pa->handler_internal!=NULL){
printf(",handler:%s",pa->handler_internal);
}
printf(",type=%s",am_getActionTypeStr(pa->type));
if(pa->oidcProvider!=NULL){
printf(",OidcProvider:%s",pa->oidcProvider);
}
if(pa->relyingParty!=NULL){
printf(",RelyingParty:%s",pa->relyingParty);
}
printf(", isForward:%d,description:%s}",pa->isForward,pa->description);
if(pa->requestHeaders!=NULL&&pa->requestHeaders->nelts>0){
printf("\r\n\t\t>Request headers [%d]\n", pa->requestHeaders->nelts);
for (i=0; i < pa->requestHeaders->nelts; i++){
action_header* hdr =
(action_header*)cu_getElement(pa->requestHeaders, i);
printf("\t\t\tHeader{name:%s, value:%s}\r\n", hdr->name, (hdr->value)?hdr->value:"null");
}
}
if(pa->responseHeaders!=NULL&&pa->responseHeaders->nelts>0){
printf("\r\n\t\t>Response headers [%d]\n", pa->responseHeaders->nelts);
for (i=0; i < pa->responseHeaders->nelts; i++){
action_header* hdr =
(action_header*)cu_getElement(pa->responseHeaders, i);
printf("\t\t\tHeader{name:%s, value:%s}\r\n", hdr->name, (hdr->value)?hdr->value:"null");
}
}
}
printf("\r\n");
}
printf("Match Lists (%d):\r\n",shapr_hash_count (oidcConfig->match_lists));
for(hi = shapr_hash_first(p,oidcConfig->match_lists); hi; hi = shapr_hash_next(hi)){
shapr_hash_this(hi, &key, NULL, &val);
mlist=(match_list*)val;
printf("\t* %s",mlist->name);
if(mlist->list->nelts>0){
am_printMatchList(p,mlist->list);
}
printf("\r\n");
}
if(oidcConfig->oidcProvider!=NULL) {
printf("ID: %s\r\n",oidcConfig->oidcProvider->id);
printf("Metadataurl: %s\r\n",oidcConfig->oidcProvider->metadataUrl);
printf("Issuer: %s\r\n",oidcConfig->oidcProvider->authorizationEndpoint);
printf("JWKSUri: %s\r\n",oidcConfig->oidcProvider->jwksUri);
printf("JWKSKeys (%d):\r\n",shapr_hash_count (oidcConfig->oidcProvider->jwsKeys));
for(hi = shapr_hash_first(p,oidcConfig->oidcProvider->jwsKeys); hi; hi = shapr_hash_next(hi)){
shapr_hash_this(hi, &key, NULL, &val);
oauth_jwskey* jwk=(oauth_jwskey*)val;
printf("\t\r\nkid=%s",jwk->id);
printf("\t\t\r\n* type=%s",jwk->type);
printf("\t\t\r\n* algorithm=%s",jwk->algorithm);
printf("\t\t\r\n* use=%s",jwk->use);
printf("\t\t\r\n* modulus=%s",jwk->modulus);
printf("\t\t\r\n* exponent=%s",jwk->exponent);
printf("\r\n");
}
}
if(oidcConfig->relyingPartyHash!=NULL) {
printf("RelyingParties (%d):\r\n",shapr_hash_count (oidcConfig->relyingPartyHash));
for(hi = shapr_hash_first(p,oidcConfig->relyingPartyHash); hi; hi = shapr_hash_next(hi)){
shapr_hash_this(hi, &key, NULL, &val);
relying_party* relyingRarty=(relying_party*)val;
printf("\t\r\nID=%s",relyingRarty->id);
printf("\t\r\n* clientID=%s",relyingRarty->clientID);
printf("\t\t\r\n* clientSecret=%s",relyingRarty->clientSecret);
printf("\t\t\r\n* description=%s",relyingRarty->description);
printf("\r\n");
}
}
}
oauth_jwskey* am_getJWSKeyByKeyID(shapr_hash_t* keyHash, char* keyID) {
if(keyHash==NULL || keyID==NULL) {return NULL;}
return (oauth_jwskey*)shapr_hash_get(keyHash, keyID, APR_HASH_KEY_STRING);
}
relying_party* am_getRelyingPartyByClientID(shapr_hash_t* relyingPartyHash, const char* clientID) {
if (relyingPartyHash==NULL || clientID==NULL) return NULL;
return (relying_party*)shapr_hash_get(relyingPartyHash, clientID, APR_HASH_KEY_STRING);
}
relying_party* am_getRelyingPartyById(shapr_hash_t* relyingPartyIdsHash, const char* id) {
if (relyingPartyIdsHash==NULL || id==NULL) return NULL;
return (relying_party*)shapr_hash_get(relyingPartyIdsHash, id, APR_HASH_KEY_STRING);
}
relying_party* am_getRelyingPartyByRedirectUri(pool*p, shapr_hash_t* relyingPartyHash, const char* currentRedirectUri) {
shapr_hash_index_t * hi=NULL;
void *val=NULL;
const void *key=NULL;
if (relyingPartyHash==NULL || currentRedirectUri==NULL) return NULL;
relying_party* defaultRelyingParty=NULL;
for(hi = shapr_hash_first(p, relyingPartyHash); hi; hi = shapr_hash_next(hi)){
shapr_hash_this(hi, &key, NULL, &val);
relying_party* relyingParty=(relying_party*)val;
if(defaultRelyingParty==NULL) { defaultRelyingParty = relyingParty ; } // save the first one
if(relyingParty!=NULL&&relyingParty->redirectUri!=NULL) {
if(strstr(currentRedirectUri, relyingParty->redirectUri)!=0) {
return relyingParty;
}
}
}
return defaultRelyingParty;
}
oidc_provider* am_getOidcProviderByIssuer(shapr_hash_t* oidcProviderHash, const char* issuer) {
if (oidcProviderHash==NULL || issuer==NULL) return NULL;
return (oidc_provider*)shapr_hash_get(oidcProviderHash, issuer, APR_HASH_KEY_STRING);
}
oidc_provider* am_getOidcProviderById(shapr_hash_t* oidcProviderIdsHash, const char* id) {
if (oidcProviderIdsHash==NULL || id==NULL) return NULL;
return (oidc_provider*)shapr_hash_get(oidcProviderIdsHash, id, APR_HASH_KEY_STRING);
}
const char* am_getActionTypeStr(action_types type) {
printf("YYYYYYYYYYYYY=%d", type);
if (type==action_login)
return "login";
else if (type==action_denial)
return "denial";
else if (type==action_authorize)
return "authorize";
else if (type==action_callback)
return "callback";
return "null";
}
|
tarachandverma/ngx-openidc
|
src/oidc-core/rewrite_core.c
|
<reponame>tarachandverma/ngx-openidc<filename>src/oidc-core/rewrite_core.c
#include <oidc-core/rewrite_core.h>
#include "common_utils.h"
#include "url_utils.h"
#ifdef NGX_TCREWRITE_PCRE
#include <pcre.h>
#include <pcreposix.h>
static void * oidc_pcre_malloc(size_t size);
static void oidc_pcre_free(void *ptr);
static pool* oidc_pcre_malloc_init(pool *new_pool);
static void oidc_pcre_malloc_done(pool *old_pool);
#else // APACHE PCRE
#include "httpd.h"
#if (AP_SERVER_MINORVERSION_NUMBER == 2 || AP_SERVER_MINORVERSION_NUMBER == 4)
#include <ap_config.h>
#include <ap_regex.h>
typedef ap_regex_t regex_t;
typedef ap_regmatch_t regmatch_t;
#define REG_ESPACE AP_REG_ESPACE
#define REG_ICASE AP_REG_ICASE
#define regcomp(arg1,arg2,arg3) ap_regcomp(arg1,arg2,arg3)
#define regfree(arg1) ap_regfree(arg1)
#define regexec(arg1,arg2,arg3,arg4,arg5) ap_regexec(arg1,arg2,arg3,arg4,arg5)
//apache2.2 has built-in pcre but we don't know which version it it, 64-bit compiler stll needs the declaration.
#ifdef __cplusplus
extern "C" const char *pcre_version(void);
#else
extern const char *pcre_version(void);
#endif
#else //#if AP_SERVER_MINORVERSION_NUMBER
#include <pcreposix.h>
#endif //#ifdef AP_SERVER_MINORVERSION_NUMBER
#endif //#ifdef NGX_TCREWRITE_PCRE
char* rc_getInfo(pool* p){
return apr_pstrcat(p,"[",REWRITE_CORE_VERSION,"], PCRE ",pcre_version(),NULL);
}
int rc_matchByStrings(pool* p, char* regex, char* value){
int ret=0;
regex_t *preg=NULL;
//do regex match
preg=apr_palloc(p,sizeof(regex_t));
#ifdef NGX_TCREWRITE_PCRE
// set custom pcre func for NGX_TCREWRITE_PCRE
pool *ip = (pool *) oidc_pcre_malloc_init(p);
#endif
ret=regcomp(preg,regex,0);
if(ret!=0){
#ifdef NGX_TCREWRITE_PCRE
// reset pcre func for NGX_PCRE
oidc_pcre_malloc_done(ip);
#endif
return -555;
}
ret=regexec(preg,value,0,NULL,0);
regfree(preg);
#ifdef NGX_TCREWRITE_PCRE
// reset pcre func for NGX_TCREWRITE_PCRE
oidc_pcre_malloc_done(ip);
#endif
return ret;
}
int rc_matchByStringsIgnoreCase(pool* p, char* regex, char* value){
int ret=0;
regex_t *preg=NULL;
//do regex match
preg=apr_palloc(p,sizeof(regex_t));
#ifdef NGX_TCREWRITE_PCRE
// set custom pcre func for NGX_TCREWRITE_PCRE
pool *ip = (pool *) oidc_pcre_malloc_init(p);
#endif
ret=regcomp(preg,regex,REG_ICASE);
if(ret!=0){
#ifdef NGX_TCREWRITE_PCRE
// reset pcre func for NGX_TCREWRITE_PCRE
oidc_pcre_malloc_done(ip);
#endif
return -555;
}
ret=regexec(preg,value,0,NULL,0);
regfree(preg);
#ifdef NGX_TCREWRITE_PCRE
// reset pcre func for NGX_TCREWRITE_PCRE
oidc_pcre_malloc_done(ip);
#endif
return ret;
}
int rc_matchByStringsPattern(pool* p, char* regex, char* value, array_header** matches){
int ret=0;
regex_t *preg=NULL;
regmatch_t pmatch[9];
int i=0;
memset(pmatch,-1, sizeof(pmatch));
//match vars
array_header* nmatches=NULL;
char** foundPlace=NULL, *found=NULL;
int chars=0;
//do regex match
preg=apr_palloc(p,sizeof(regex_t));
#ifdef NGX_TCREWRITE_PCRE
// set custom pcre func for NGX_TCREWRITE_PCRE
pool *ip = (pool *) oidc_pcre_malloc_init(p);
#endif
ret=regcomp(preg,regex,0);
if(ret!=0){
#ifdef NGX_TCREWRITE_PCRE
// reset pcre func for NGX_TCREWRITE_PCRE
oidc_pcre_malloc_done(ip);
#endif
return -555;
}
if(matches!=NULL){
ret=regexec(preg,value,9,pmatch,0);
if(pmatch[0].rm_so!=-1){
nmatches=apr_array_make(p,4,sizeof(char*));
for(i=0;i<9;i++){
if(pmatch[i].rm_so!=-1){
chars=pmatch[i].rm_eo-pmatch[i].rm_so;
found=apr_pstrndup(p,value+(int)pmatch[i].rm_so,chars);
foundPlace=(char**)apr_array_push(nmatches);
*foundPlace=found;
}
}
*matches=nmatches;
}
}else{
ret=regexec(preg,value,0,NULL,0);
}
regfree(preg);
#ifdef NGX_TCREWRITE_PCRE
// reset pcre func for NGX_TCREWRITE_PCRE
oidc_pcre_malloc_done(ip);
#endif
return ret;
}
char* rc_matchByStringsPatternReturnDetails(pool* p, char* regex, char* value, array_header** matches){
int ret=0;
ret=rc_matchByStringsPattern(p,regex,value,matches);
if(ret==-555){
return apr_pstrdup(p,"error - compiling regex");
}
if(ret!=0){
if(ret==REG_ESPACE){
return apr_pstrdup(p,"error - matching took excessive memory");
}else{
return apr_pstrdup(p,"NO MATCH");
}
}
return NULL;
}
char* rc_matchByStringsReturnDetails(pool* p, char* regex, char* value){
int ret=0;
ret=rc_matchByStrings(p,regex,value);
if(ret==-555){
return apr_pstrdup(p,"error - compiling regex");
}
if(ret!=0){
if(ret==REG_ESPACE){
return apr_pstrdup(p,"error - matching took excessive memory");
}else{
return apr_pstrdup(p,"NO MATCH");
}
}
return NULL;
}
int rc_isRegexValid(pool* p,char* regex){
if(regex==NULL||rc_matchByStrings(p,regex,"")==-555){
return 0;
}
return 1;
}
#ifdef NGX_TCREWRITE_PCRE
pool* oidc_pcre_pool=NULL;
static void *(*old_pcre_malloc)(size_t);
static void (*old_pcre_free)(void *ptr);
/* XXX: work-around to nginx regex subsystem, must init a memory pool
* * to use PCRE functions. As PCRE still has memory-leaking problems,
* * and nginx overwrote pcre_malloc/free hooks with its own static
* * functions, so nobody else can reuse nginx regex subsystem... */
static void * oidc_pcre_malloc(size_t size)
{
if (oidc_pcre_pool) {
return apr_palloc(oidc_pcre_pool, size);
}
fprintf(stderr, "error: iota pcre malloc failed due to empty pcre pool");
return NULL;
}
static void oidc_pcre_free(void *ptr)
{
if (oidc_pcre_pool) {
//apr_pool_clear(ptr);
return;
}
fprintf(stderr, "error: iota pcre free failed due to empty pcre pool");
}
static pool* oidc_pcre_malloc_init(pool *new_pool)
{
pool* old_pool;
if (pcre_malloc != oidc_pcre_malloc) {
oidc_pcre_pool = new_pool;
old_pcre_malloc = pcre_malloc;
old_pcre_free = pcre_free;
pcre_malloc = oidc_pcre_malloc;
pcre_free = oidc_pcre_free;
return NULL;
}
old_pool = oidc_pcre_pool;
oidc_pcre_pool = new_pool;
return old_pool;
}
static void oidc_pcre_malloc_done(pool *old_pool)
{
oidc_pcre_pool = old_pool;
if (old_pool == NULL) {
pcre_malloc = old_pcre_malloc;
pcre_free = old_pcre_free;
}
}
#endif /* NGX_TCREWRITE_PCRE */
|
tarachandverma/ngx-openidc
|
src/common-utils/common_utils.h
|
/*
* Created by <NAME> on 01/04/14.
*
*/
#ifndef __TCREWRITE_COMMON_UTILS__H_
#define __TCREWRITE_COMMON_UTILS__H_
#ifdef __cplusplus
extern "C" {
#endif
#include <apr_general.h>
#include <apr_pools.h>
#include <apr_tables.h>
#include <apr_hash.h>
#include <apr_strings.h>
#include <sys/types.h>
#include <time.h>
#include <string.h>
#define SAFESTR(str) (str!=NULL?str:"NULL")
#define SAFESTRBLANK(str) (str!=NULL?str:"")
#define SAFESTRELSE(str,elstr) (str!=NULL?str:elstr)
#define SAFESTRLEN(str) (str!=NULL?strlen(str):0)
#define BOOLTOSTR(bol) (bol!=1?"FALSE":"TRUE")
#define STRTOBOOL(str) ((str!=NULL&&(strcmp(str,"true")==0||strcmp(str,"TRUE")==0||strcmp(str,"on")==0))?1:0)
#define SAFEDUP(p,str) (str==NULL?NULL:apr_pstrdup(p,str))
// Use this macro instead of cu_getElement
#ifndef APR_ARRAY_IDX
#define APR_ARRAY_IDX(ary,i,type) (((type *)(ary)->elts)[i])
#endif
// Use this macro instead of apr_array_push
#ifndef APR_ARRAY_PUSH
#define APR_ARRAY_PUSH(ary,type) (*((type *)apr_array_push(ary)))
#endif
// Use this macro instead of cu_getElementRef
#ifndef APR_ARRAY_REF_IDX
#define APR_ARRAY_REF_IDX(ary,i,type) (((type *)(ary)->elts)+i)
#endif
// Use this macro instead of cu_getElementCount
#ifndef APR_ARRAY_NUM_ELTS
#define APR_ARRAY_NUM_ELTS(ary) ( (ary!=NULL) ? (ary)->nelts : 0 )
#endif
int cu_getElementCount(apr_array_header_t* data);
char* cu_getElement(apr_array_header_t* data, int element);
void** cu_getElementRef(apr_array_header_t* data, int element);
char* cu_getNodeDetails(apr_pool_t* p,unsigned int defaultHttpPort);
char* cu_templateString(apr_pool_t* p, char* src, apr_hash_t* vals);
time_t cu_dateStringToSeconds(const char* dateString);
char* cu_nonHtmlToHtmlChar(apr_pool_t*p, char*src);
char* cu_getCurrentDateByFormat2(apr_pool_t* p, const char* format);
char* cu_getFormattedUrl(apr_pool_t *p, char* cur, char* namespaceid);
char* cu_getTrimmedStr(apr_pool_t* p, char* str);
apr_array_header_t* cu_parseStringArrayFromCsv(apr_pool_t* p, int arraySz, const char* delim, char* src);
char* cu_serializeCsvFromStringArray(apr_pool_t* p, apr_array_header_t* arr);
apr_table_t* cu_parseNvpTableFromCsv(apr_pool_t* p,const char* itemDelim,const char* nvpDelim, char* src);
//
// RSA implementation
//
// by key
char* comu_rsa256Sign(apr_pool_t*p, unsigned char * data,int dataLen,unsigned char * privateKey, char** error);
int comu_rsa256Verify(apr_pool_t*p, unsigned char * data,int dataLen, unsigned char * publicKey, char* encodedSign, char** error);
int comu_rsaVerifyByModulus(apr_pool_t*p, const char* algorithm, unsigned char * data,int dataLen, const char* modulus, const char* exponent, char* encodedSign, char** error);
char* comu_rsaEncrypt(apr_pool_t*p, unsigned char * data,int data_len,unsigned char * publicKey, char** error);
char* comu_rsaDecrypt(apr_pool_t*p, unsigned char * encrypted, unsigned char * privateKey, char** error);
// by keyFile
char* comu_rsa256SignFromFile(apr_pool_t*p, unsigned char * data,int dataLen,unsigned char * privateKeyFile, char** error);
int comu_rsa256VerifyFromFile(apr_pool_t*p, unsigned char * data,int dataLen, unsigned char * publicKeyFile, char* encodedSign, char** error);
char* comu_rsaEncryptFromFile(apr_pool_t*p, unsigned char * data,int data_len,unsigned char * publicKeyFile, char** error);
char* comu_rsaDecryptFromFile(apr_pool_t*p, unsigned char * encrypted, unsigned char * privateKeyFile, char** error);
char* comu_rsaPrintModulusFromFile(apr_pool_t*p, unsigned char * publicKeyFile, int isPublic);
// AES encryption/decryption
typedef struct oidc_cipher_cfg{
apr_pool_t*p;
char* crypto_passphrase;
void* encrypt_ctx;
void* decrypt_ctx;
}oidc_cipher_cfg;
apr_byte_t comu_aesCryptoInit(apr_pool_t*p, oidc_cipher_cfg *cfg,
char** error);
unsigned char *comu_aesEncrypt(apr_pool_t*p, oidc_cipher_cfg *cfg,
unsigned char *plaintext, int *len, char** error);
unsigned char *comu_aesDecrypt(apr_pool_t*p, oidc_cipher_cfg *cfg,
unsigned char *ciphertext, int *len, char** error);
apr_byte_t comu_aesCryptoDestroy(oidc_cipher_cfg *cfg);
int cu_encryptAndBase64urlEncode(apr_pool_t*p, oidc_cipher_cfg*cfg, char **dst,
const char *src, char** error);
int cu_base64urlDecodeAndDecrypt(apr_pool_t*p, oidc_cipher_cfg*cfg, char **dst,
const char *src, char** error);
// uuid function
char* cu_generateGuid(apr_pool_t* p);
// base64 functions
int cu_base64urlEncode(apr_pool_t*p, char **dst, const char *src,
int src_len, int remove_padding);
int cu_base64urlDecode(apr_pool_t*p, char **dst, const char *src);
#ifdef __cplusplus
}
#endif
#endif//__TCREWRITE_COMMON_UTILS__H_
|
tarachandverma/ngx-openidc
|
src/oidc-core/rewrite_core.h
|
#ifndef __TCREWRITE_REWRITE_CORE__H_
#define __TCREWRITE_REWRITE_CORE__H_
#include <apr_general.h>
#include <apr_pools.h>
#include <apr_tables.h>
#include <apr_strings.h>
#include <apr_lib.h>
#include <apache_typedefs.h>
#define REWRITE_CORE_VERSION "1.0"
char* rc_getInfo(pool* p);
int rc_matchByStrings(pool* p, char* regex, char* value);
int rc_matchByStringsIgnoreCase(pool* p, char* regex, char* value);
char* rc_matchByStringsReturnDetails(pool* p, char* regex, char* value);
int rc_matchByStringsPattern(pool* p, char* regex, char* value, array_header** matches);
char* rc_matchByStringsPatternReturnDetails(pool* p, char* regex, char* value, array_header** matches);
int rc_isRegexValid(pool* p,char* regex);
#endif
|
tarachandverma/ngx-openidc
|
src/apache-utils/apache_mappings.h
|
/*
* Created by <NAME> on 01/04/14.
*
*/
#ifndef __TCREWRITE_APACHE_MAPPINGS__H_
#define __TCREWRITE_APACHE_MAPPINGS__H_
#ifdef NGX_HTTP_OPENIDC
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
#include <nginx.h>
#else
#include "httpd.h"
#include "http_config.h"
#include "http_log.h"
#include "ap_compat.h"
#endif
#endif
|
tarachandverma/ngx-openidc
|
src/config-core/config_core.h
|
#ifndef __TCREWRITE_CONFIG_CORE__H_
#define __TCREWRITE_CONFIG_CORE__H_
#include <sys/types.h>
#include "apache_typedefs.h"
#include "shm_apr.h"
#include "config_bindings.h"
#include "oidc_config_core.h"
#include "config_messaging.h"
#include "config_bindings_shm.h"
#include "common_utils.h"
typedef struct config_core{
cfg_globals* globals;
cfg_service_descriptor* service;
shared_heap* sheap;
char* sheapMapFile;
int sheapPageSize;
void* serviceConfig;
char* passPhrase;
char* refreshLogFile;
int disableProcessRecovery;
char* oidcHeaderPrefix;
int refreshWaitSeconds;
char* oidcConfigFile;
oidc_cipher_cfg* cipherConfig;
}config_core;
config_core* configcore_newConfigCoreObj(pool* p);
char* configcore_loadConfigCoreFile(pool* p, char* file, config_core* conf);
char* configcore_initializeConfigCore(pool* p,config_core* conf);
void configcore_printConfigCoreDetails(pool* p,config_core* conf);
int cfg_syncSelf(apr_pool_t* pool,config_core* configCore);
void* configcore_getModuleConfigByName(config_core* conf,char* name);
#endif
|
tarachandverma/ngx-openidc
|
src/oidc-core/oidc_config_core.c
|
<filename>src/oidc-core/oidc_config_core.c
#include "oidc_config.h"
#include "oidc_config_core.h"
#define PARAM_CONFIG_XML "config-xml"
#define PARAM_IS_REFRESH "initialized"
char* amc_initialize(pool* p,shared_heap* sheap,cbs_globals* globals,cfg_service_descriptor* svcdesc,void** userdata){
char* result=NULL;
char* error=NULL;
char* isRefresh=NULL;
char* configFile=NULL;
char* param_configFile=(char*)apr_hash_get(svcdesc->params,PARAM_CONFIG_XML,APR_HASH_KEY_STRING);
if(param_configFile==NULL){
return apr_pstrcat(p,"Missing service param:",PARAM_CONFIG_XML,NULL);
}
//get Latest Action Mappings Resource
configFile=cbs_getRemoteResourcePath(p,globals,param_configFile,&error);
if(configFile==NULL){
configFile=cbs_getLocalResourcePath(p, globals,param_configFile,NULL);
}
result=am_build(p,sheap,(apr_hash_get(svcdesc->params,PARAM_IS_REFRESH,APR_HASH_KEY_STRING)!=NULL),globals,configFile);
if(result!=NULL){
return apr_pstrcat(p,"Problem loading action-mappings : ",result,NULL);
}
apr_hash_set(svcdesc->params,PARAM_IS_REFRESH,APR_HASH_KEY_STRING,apr_pstrdup(p,"TRUE"));
return NULL;
}
char* amc_refresh(pool* p,shared_heap* sheap,cbs_globals* globals,cfg_service_descriptor* svcdesc,void** userdata){
return amc_initialize(p,sheap,globals,svcdesc,userdata);
}
char* amc_postRefresh(pool* p,shared_heap* sheap, cfg_globals* globals,cfg_service_descriptor* svcdesc,void** userdata){
oidc_config* mappings=NULL;
mappings=am_fetchFromSheap(sheap);
if(mappings==NULL){
return apr_pstrdup(p,"Action Mappings unable to be retrieved from sheap");
}
*userdata=mappings;
return NULL;
}
|
tarachandverma/ngx-openidc
|
src/oidc-core/unit-test/oidc_core_unit_test.c
|
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <apr_general.h>
#include <apr_pools.h>
#include <rewrite_core.h>
#include <CuTest.h>
#include <common_utils.h>
#include <oidc_config_xml.h>
#include <shm_data.h>
#include <match_list.h>
#include "config-core/config_bindings_shm.h"
#include "doc_parser_utils.h"
#include "http-utils/http_client.h"
#include "template_engine.h"
#include "oidc_globals.h"
#include "oidc_config_core.h"
#include "oidc_config.h"
void rc_getInfoTest(mm_logger* logger, CuTest*tc){
// char* version = rc_getInfo(logger->p);
// CuAssertPtrNotNull(tc,version);
}
void rc_matchByStringsTest(mm_logger* logger, CuTest*tc){
int matched = rc_matchByStrings(logger->p, "^/company", "/company/");
CuAssert(tc, "rc_matchByStrings failed to match ", matched==0);
}
void rc_matchByStringsIgnoreCaseTest(mm_logger* logger, CuTest*tc){
int matched = rc_matchByStringsIgnoreCase(logger->p, "^/company", "/Company/");
CuAssert(tc, "rc_matchByStringsIgnoreCase failed to match ", matched==0);
}
void rc_matchByStringsReturnDetailsTest(mm_logger* logger, CuTest*tc){
char* details = rc_matchByStringsReturnDetails(logger->p, "^/company", "/company/");
CuAssertPtrEquals(tc,NULL,details); // null expected
}
void rc_matchByStringsPatternTest(mm_logger* logger, CuTest*tc){
//http://proto.wsj.com/wsjacl/qa/rewrite-match?valueParam=%2Fdemographic%2Fuser%2Ftara®exParam=%2Fuser%2F%28.*%29&templateParam=
char* value ="/demographic/user/tara";
char* regex = "/user/(.*)";
array_header* matches=NULL;
char* elt=NULL;
int i=0;
int ret=0;
ret=rc_matchByStringsPattern(logger->p,regex,value,&matches);
if(matches!=NULL){
logging_printf(logger,"Found Matches (%d)\n",matches->nelts);
if(matches->nelts>0){
for(i=0;i<matches->nelts;i++){
elt=cu_getElement(matches,i);
logging_printf(logger,"$%d: %s\n",i,elt);
}
}
}
}
void rc_isRegexValidTest(mm_logger* logger, CuTest*tc){
int result = rc_isRegexValid(logger->p,"^/test");
CuAssertIntEquals(tc,1,result);
}
static oauth_jwk* oauth_getSignatureValidationKey(pool*p, oauth_jwt_header* header, const char* issuer, void* data, char** error) {
oidc_config* oauthConfig = (oidc_config *)data;
int i;
if(header==NULL||header->algorithm==NULL||oauthConfig==NULL) {
if(error!=NULL) { *error = apr_pstrdup(p, "header or jwsKeys null"); }
return NULL;
}
oauth_jwk* jwk =oauthutil_newJWKObj(p);
if(header->keyID!=NULL) {
oauth_jwskey* jwsKey = am_getJWSKeyByKeyID(oauthConfig->oidcProvider->jwsKeys, header->keyID);
if(jwsKey==NULL) {
if(error!=NULL) { *error = apr_pstrdup(p, "jwsKey by keyID not found"); }
return NULL;
}
jwk->keyID = apr_pstrdup(p, jwsKey->id);
jwk->use = apr_pstrdup(p, jwsKey->use);
jwk->modulus = apr_pstrdup(p, jwsKey->modulus);
jwk->exponent = apr_pstrdup(p, jwsKey->exponent);
}else if(issuer!=NULL){
relying_party* relyingParty = am_getRelyingPartyByClientID(oauthConfig->relyingPartyHash, issuer);
if(relyingParty==NULL) {
if(error!=NULL) { *error = apr_pstrdup(p, "relyingParty not configured"); }
return NULL;
}
jwk->key = apr_pstrdup(p, relyingParty->clientSecret);
}
return jwk;
}
void oidc_loadConfFile_test(mm_logger* logger, CuTest*tc){
pool* p=logger->p;
shared_heap* sheap=NULL;
char* error=NULL;
int handlerResponseCode=-1;
cbs_globals* globals=NULL;
cfg_service_descriptor *rs=NULL; // in pool
cfg_service_descriptor* svcdesc = cb_newServiceDescriptorObj(p);
apr_hash_set(svcdesc->params, "config-xml", APR_HASH_KEY_STRING, "oidc-config.xml");
void* userdata = NULL;
djrglobals_setEnableUnnamedSHM("true");
// create resource service.
rs=cb_newServiceDescriptorObj(p);
rs->uri=apr_pstrdup(p,"https://raw.githubusercontent.com/tarachandverma/nginx-openidc/master/example-conf/");
rs->timeoutSeconds=5;
sheap=shdata_sheap_make(p,200000,"./unit-test/oidc.shm");
shdata_BeginTagging(sheap);
shdata_OpenItemTag(sheap,"oidc_test");
//build globals
globals=(cbs_globals*)shdata_shpcalloc(sheap,sizeof(cbs_globals));
globals->homeDir=shdata_32BitString_copy(sheap,"./unit-test");
globals->resourceService=cbs_copyServiceDescripterOnSheap(p,sheap,rs);
error=amc_initialize(p,sheap,globals,svcdesc, &userdata);
CuAssertPtrEquals_Msg(tc,error,NULL,error);
shdata_PublishBackSeg(sheap);
shdata_syncself(p,sheap,NULL,NULL);
oidc_config* actmap = NULL;
error=amc_postRefresh(p,sheap, NULL, svcdesc,(void**)&actmap);
CuAssertPtrNotNullMsg(tc,"Error : oidcConfig is null", actmap);
am_printAll(p, actmap);
const char* id_token = "<KEY>";
if(id_token!=NULL) {
oauth_jwt* jwt = oauthutil_parseIDToken(p, id_token, NULL, &error);
CuAssert(tc,error, jwt!=NULL);
oauthutil_printIDToken(p, jwt);
oidc_cipher_cfg* cipherConfig = (oidc_cipher_cfg*)apr_palloc(p, sizeof(oidc_cipher_cfg));
cipherConfig->crypto_passphrase = apr_pstrdup(p, "<PASSWORD>");
cipherConfig->decrypt_ctx=NULL;
cipherConfig->encrypt_ctx=NULL;
cipherConfig->p = p;
const char* serializedClaim = "tarachandverma";
int crypted_len = strlen(serializedClaim) + 1;
// encrypt
char *encrypted = "";
int status = cu_encryptAndBase64urlEncode(p, cipherConfig, &encrypted, (unsigned char *) serializedClaim, &error);
if(status>0){
char* decrypted = "";
status = cu_base64urlDecodeAndDecrypt(p, cipherConfig, &decrypted, encrypted, &error);
printf("decrypted=%s\r\n", decrypted);
}
}
apr_table_t* headers_in = apr_table_make(p, 1);
char* sessionID = cookie_getCookie(p, headers_in, actmap->oidcSession);
if(sessionID==NULL) {
sessionID = cu_generateGuid(p);
char* cookieDrop = cookie_cookieTemplate(p, actmap->oidcSession, sessionID, NULL);
if(cookieDrop!=NULL){
printf("cookieDrop=%s", cookieDrop);
apr_table_add(headers_in, "Set-Cookie", cookieDrop);
}
}
}
static const char* oauthtest_getPublicKey(pool*p, oauth_jwt_header* header, const char* issuer, void* data, char** error) {
const char* publicKey =
"-----BEGIN PUBLIC KEY-----\n"\
"<KEY>
"<KEY>
"<KEY>
"<KEY>"\
"-----END PUBLIC KEY-----\n"
;
oauth_jwk* jwk =oauthutil_newJWKObj(p);
jwk->key = apr_pstrdup(p, publicKey);
return jwk;
}
static void oauthutil_generateAndParseAndValidateIDToken_test(mm_logger* logger,CuTest*tc) {
pool*p = logger->p;
char* error = NULL;
const char* privateKey =
"-----BEGIN RSA PRIVATE KEY-----\n"\
"<KEY>
"<KEY>
"<KEY>"\
"<KEY>"\
"<KEY>"\
"<KEY>
"<KEY>
"<KEY>"\
"<KEY>"\
"<KEY>"\
"<KEY>"\
"<KEY>"\
"<KEY>"\
"-----END RSA PRIVATE KEY-----\n"
;
oauth_jwt_header* header = oauthutil_newJWTHeaderObj(p);
header->algorithm = apr_pstrdup(p, "RS256");
oauth_jwt_claim* claim = oauthutil_newJWTClaimObj(p);
claim->issuer = apr_pstrdup(p, "https://login.wsj.com");
claim->subject = apr_pstrdup(p, "<EMAIL>");
claim->audience = apr_pstrdup(p, "test123");
claim->issuedAt = time(NULL);
claim->expiry = 600+time(NULL);
// set optional params
claim->options = apr_hash_make(p);
apr_hash_set(claim->options,"nonce", APR_HASH_KEY_STRING, "n-0S6_WzA2Mj");
char* IDTokenSerial = oauthutil_generateIDToken(p, header, claim, privateKey);
CuAssert(tc,"Error: unable to generate IDToken ", IDTokenSerial!=NULL);
printf("IDTokenSerial=%s\r\n", IDTokenSerial);
// parse and test
oauth_jwt* IDToken = oauthutil_parseAndValidateIDToken(p, IDTokenSerial, oauthtest_getPublicKey, NULL, &error);
CuAssert(tc,error, IDToken!=NULL);
oauthutil_printIDToken(p, IDToken);
}
static void oauthutil_parseAndValidateExpiredIDToken_test(mm_logger* logger,CuTest*tc) {
pool*p = logger->p;
char* error = NULL;
const char* IDTokenSerial = "<KEY>";
oauth_jwt* IDToken = oauthutil_parseAndValidateIDToken(p, IDTokenSerial, oauthtest_getPublicKey, NULL, &error);
CuAssert(tc,error, IDToken==NULL);
}
typedef struct oauth_jws_uri{
char* uri;
int timeout;
}oauth_jws_uri;
static oauth_jwk* oauthtest_getGooglePublicKey(pool*p, oauth_jwt_header* header, const char* issuer, void* data, char** error) {
oauth_jws_uri* jwsUri = (oauth_jws_uri*)data;
int i;
if(header==NULL||jwsUri==NULL||jwsUri->uri==NULL) {
if(error!=NULL) { *error = apr_pstrdup(p, "header or jwsUri null"); }
return NULL;
}
http_util_result* httpResult=hc_get_verbose(p, jwsUri->uri, jwsUri->timeout, NULL, NULL, error);
if(httpResult==NULL) {
if(error!=NULL) { *error = apr_pstrdup(p, "jwsUri response null"); }
return NULL;
}
oauth_jwk* jwk =oauthutil_newJWKObj(p);
Value* json = JSON_Parse(p, httpResult->data);
if(json!=NULL){
Value* array = JSON_GetObjectItem(json, "keys");
if(array==NULL||JSON_GetItemType(array)!=JSON_Array) {
if(error!=NULL) { *error = apr_pstrdup(p, "keys object is not array"); }
return NULL;
}
int arrSz = JSON_GetArraySize(array);
// Retrieve item number "item" from array "array". Returns NULL if unsuccessful.
for (i=0; i<arrSz; i++) {
Value* element = JSON_GetArrayItem(array, i);
Value* keyIDObj = JSON_GetObjectItem(element, "kid");
const char* keyID = (keyIDObj) ? (char*)JSON_GetStringFromStringItem(keyIDObj) : NULL;
if(keyID!=NULL&&(strcmp(keyID,header->keyID)==0)) {
jwk->keyID = keyID;
Value* val = JSON_GetObjectItem(element, "use");
jwk->use = (val) ? (char*)JSON_GetStringFromStringItem(val) : NULL;
val = JSON_GetObjectItem(element, "n");
jwk->modulus = (val) ? (char*)JSON_GetStringFromStringItem(val) : NULL;
val = JSON_GetObjectItem(element, "e");
jwk->exponent = (val) ? (char*)JSON_GetStringFromStringItem(val) : NULL;
}
}
}
return jwk;
}
static void oauthutil_parseAndValidateGoogleIDToken_test(mm_logger* logger,CuTest*tc) {
pool*p = logger->p;
char* error = NULL;
const char* googleIDToken = "<KEY>";
oauth_jws_uri* jwsUri=(oauth_jws_uri*)apr_pcalloc(p, sizeof(oauth_jws_uri));
jwsUri->uri = apr_pstrdup(p, "https://www.googleapis.com/oauth2/v3/certs");
jwsUri->timeout = 10;
oauth_jwt* jwt = oauthutil_parseAndValidateIDToken(p, googleIDToken, oauthtest_getGooglePublicKey, jwsUri, &error);
CuAssert(tc, error, jwt==NULL); // expired ID token
// oauthutil_printIDToken(p, jwt);
}
CuSuite* oidccore_GetSuite() {
CuSuite* suite = CuSuiteNew();
// SUITE_ADD_TEST(suite, rc_getInfoTest);
// SUITE_ADD_TEST(suite, rc_matchByStringsTest);
// SUITE_ADD_TEST(suite, rc_matchByStringsIgnoreCaseTest);
// SUITE_ADD_TEST(suite, rc_matchByStringsReturnDetailsTest);
// SUITE_ADD_TEST(suite, rc_matchByStringsPatternTest);
// SUITE_ADD_TEST(suite, rc_isRegexValidTest);
SUITE_ADD_TEST(suite, oidc_loadConfFile_test);
// SUITE_ADD_TEST(suite, oauthutil_generateAndParseAndValidateIDToken_test);
// SUITE_ADD_TEST(suite, oauthutil_parseAndValidateExpiredIDToken_test);
// SUITE_ADD_TEST(suite, oauthutil_parseAndValidateGoogleIDToken_test);
return suite;
}
|
tarachandverma/ngx-openidc
|
src/oidc-core/oidc_config_xml.c
|
#include <xml_core.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <common_utils.h>
#include <oidc-core/oidc_config_xml.h>
#include <oidc-core/rewrite_core.h>
#include <oidc-core/match_list.h>
#define CONST_INIT_PAGE_ACTIONS_ELTS 4
#define CONST_INIT_MATCH_LIST_ELTS 4
#define CONST_INIT_OIDC_PROVIDERS_ELTS 2
typedef struct actmap_tmp{
oidc_config_xml* conf;
void* tmp;
void* tmp2;
void* tmp3;
void* tmp4;
void* tmp5;
void* tmp6;
void* tmp7;
void* tmp8;
void* tmp9;
void* tmp10;
void* tmp11;
void* tmp12;
void* tmp13;
void* tmp14;
void* tmp15;
char* str, *errorStr;
}actmap_tmp;
static int doc_uid=0;
oidc_config_xml* amx_newObj(pool* p){
oidc_config_xml* ret=apr_palloc(p,sizeof(oidc_config_xml));
ret->uid=0;
ret->page_actions_hash=apr_hash_make (p);
ret->path_mappings_arr=apr_array_make (p,CONST_INIT_PAGE_ACTIONS_ELTS,sizeof(path_mapping_xml*));
ret->match_list_arr=apr_array_make (p,CONST_INIT_MATCH_LIST_ELTS,sizeof(mlx_matchlist*));
ret->rpSession=cookie_newObj(p);
cookie_setCookieName(p, ret->rpSession, (char*)"rp_session");
ret->oidcSession=cookie_newObj(p);
cookie_setCookieName(p, ret->oidcSession, (char*)"oidc_session");
ret->relyingPartyHash=apr_hash_make (p);
ret->oidcProviders=apr_array_make (p,CONST_INIT_OIDC_PROVIDERS_ELTS,sizeof(oidc_provider_xml*));
ret->accessToken=NULL;
return ret;
}
static void amx_printPathMappingMatchList(pool* p, array_header* arr){
int i=0;
char* match=NULL;
if(arr!=NULL&&arr->nelts>0){
printf("\r\n\t\t -- MatchLists[%d]: ",arr->nelts);
for(i=0;i<arr->nelts;i++){
match=(char*)cu_getElement(arr,i);
if(i!=0){printf(",");}
printf("%s",match);
}
}
}
void amx_printActions(pool*p, char*type, array_header* actions){
int i;
if(actions!=NULL&&actions->nelts>0){
printf("\t* %s={",type);
for(i=0;i<actions->nelts;i++){
pathmapping_action_xml* action=(pathmapping_action_xml*)cu_getElement(actions,i);
if(i!=0){printf(",");}
printf("id=%s matchList=%s",action->id,action->matchList);
}
printf("}\r\n");
}
}
void amx_printAll(pool* p,oidc_config_xml* conf){
int x=0, i=0;
page_action_xml* pa=NULL;
apr_hash_index_t * hi=NULL;
void *val=NULL;
const void *key=NULL;
path_mapping_xml* pmx=NULL;
mlx_matchlist* mlist=NULL;
char* includeXml=NULL;
printf("<OIDC Configuration XML>\r\n");
printf("Page Actions (%d)\r\n",apr_hash_count (conf->page_actions_hash));
for (hi = apr_hash_first(p,conf->page_actions_hash); hi; hi = apr_hash_next(hi)) {
apr_hash_this(hi, &key, NULL, &val);
printf("\t* %s",key);
if(val!=NULL){
pa=(page_action_xml*)val;
printf("uri:%s",pa->uri);
if(pa->handler!=NULL){
printf(",handler:%s",pa->handler);
}
if(pa->type){
printf(",type:%d",pa->type);
}
if(pa->oidcProvider!=NULL){
printf(",OidcProvider:%s",pa->oidcProvider);
}
if(pa->relyingParty!=NULL){
printf(",RelyingParty:%s",pa->relyingParty);
}
printf(", isForward:%d,description:%s}",pa->isForward,pa->description);
if(pa->requestHeaders!=NULL&&pa->requestHeaders->nelts>0){
printf("\r\n\t\t>Request headers [%d]\n", pa->requestHeaders->nelts);
for (i=0; i < pa->requestHeaders->nelts; i++){
action_header_xml* hdr =
(action_header_xml*)cu_getElement(pa->requestHeaders, i);
printf("\t\t\tHeader{name:%s, value:%s}\r\n", hdr->name, (hdr->value)?hdr->value:"null");
}
}
if(pa->responseHeaders!=NULL&&pa->responseHeaders->nelts>0){
printf("\r\n\t\t>Response headers [%d]\n", pa->responseHeaders->nelts);
for (i=0; i < pa->responseHeaders->nelts; i++){
action_header_xml* hdr =
(action_header_xml*)cu_getElement(pa->responseHeaders, i);
printf("\t\t\tHeader{name:%s, value:%s}\r\n", hdr->name, (hdr->value)?hdr->value:"null");
}
}
}
printf("\r\n");
}
printf("Match Lists (%d):\r\n",conf->match_list_arr->nelts);
for(x=0;x<conf->match_list_arr->nelts;x++){
mlist=(mlx_matchlist*)cu_getElement(conf->match_list_arr,x);
printf("\t* %s",mlist->name);
if(mlist->matches->nelts>0){
ml_printMatchList(p,mlist->matches);
}
printf("\r\n");
}
printf("Path Mappings (%d):\r\n",conf->path_mappings_arr->nelts);
for(x=0;x<conf->path_mappings_arr->nelts;x++){
pmx=(path_mapping_xml*)cu_getElement(conf->path_mappings_arr,x);
printf("\t* %s",pmx->pathRegex);
if(pmx->ignoreCase==TRUE){ printf("\t* ignoreCase=true"); }
if(pmx->postAuthActions!=NULL){
//printf(", PostAuth:%s",pmx->oidcAction);
amx_printActions(p,"PostAuth", pmx->postAuthActions);
}
amx_printPathMappingMatchList(p,pmx->matchLists);
printf("\r\n");
}
if(conf->relyingPartyHash!=NULL) {
printf("RelyingParties (%d):\r\n",apr_hash_count (conf->relyingPartyHash));
for(hi = apr_hash_first(p,conf->relyingPartyHash); hi; hi = apr_hash_next(hi)){
apr_hash_this(hi, &key, NULL, &val);
relying_party_xml* relyingRarty=(relying_party_xml*)val;
printf("\t\r\nID=%s",relyingRarty->id);
printf("\t\r\nclientID=%s",relyingRarty->clientID);
printf("\t\t\r\n* clientSecret=%s",relyingRarty->clientSecret);
printf("\t\t\r\n* description=%s",relyingRarty->description);
printf("\t\t\r\n* issuer=%s",relyingRarty->issuer);
printf("\t\t\r\n* postLoginDefaultLandingPage=%s",relyingRarty->postLoginDefaultLandingPage);
printf("\r\n");
}
}
if(conf->oidcProviders!=NULL) {
printf("OidcProviders (%d):\r\n",conf->oidcProviders->nelts);
for(x=0;x<conf->oidcProviders->nelts;x++){
oidc_provider_xml* oidcProviderX=(oidc_provider_xml*)cu_getElement(conf->oidcProviders,x);
printf("\t\r\nID=%s[%d]", SAFESTR(oidcProviderX->id), x);
printf("\t\r\nIssuer=%s[%d]", SAFESTR(oidcProviderX->issuer), x);
printf("\t\r\nMetadataUrl=%s[%d]", SAFESTR(oidcProviderX->metadataUrl), x);
printf("\r\n");
}
}
}
static page_action_xml* amx_newPageActionXml(pool* p){
page_action_xml* ret;
ret=apr_palloc(p,sizeof(page_action_xml));
ret->id=NULL;
ret->directory=NULL;
ret->description=NULL;
ret->isForward=1;
ret->isPermanent=0;
ret->type=action_authorize;
ret->regex=NULL;
ret->handler=NULL;
ret->isDebug=0;
ret->advancedTemplate=FALSE;
ret->requestHeaders = apr_array_make(p, 1, sizeof(action_header_xml*));
ret->responseHeaders = apr_array_make(p, 1, sizeof(action_header_xml*));
ret->uri =NULL;
ret->response = NULL;
ret->oidcProvider=NULL;
ret->relyingParty=NULL;
return ret;
}
static int amx_oidcConfigAttributes(pool* p,char* xPath,int type,const char ** attributes,void* userdata){
int i;
//page_action_xml* pax=NULL;
actmap_tmp* ctmp=(actmap_tmp*)userdata;
return 1;
}
static int amx_newPageAction(pool* p,char* xPath,int type,const char ** attributes,void* userdata){
int i;
page_action_xml* pax=NULL;
actmap_tmp* ctmp=(actmap_tmp*)userdata;
pax=(void*)amx_newPageActionXml(p);
ctmp->tmp=pax;
for(i=0;attributes[i]; i += 2) {
if(strcmp(attributes[i],"id")==0){
pax->id=apr_pstrdup(p,(char*)attributes[i + 1]);
if(ctmp->conf->uid!=0){
pax->id=apr_psprintf(p,"%s_%d",pax->id,ctmp->conf->uid);
}
}else if(strcmp(attributes[i],"debug")==0){
pax->isDebug=STRTOBOOL((char*)attributes[i + 1]);
}else if(strcmp(attributes[i],"type")==0){
if (strcmp((char*)attributes[i + 1], "login")==0)
pax->type = action_login;
else if (strcmp((char*)attributes[i + 1], "callback")==0)
pax->type = action_callback;
else if (strcmp((char*)attributes[i + 1], "authorize")==0)
pax->type = action_authorize;
else if (strcmp((char*)attributes[i + 1], "denial")==0)
pax->type = action_denial;
}
}
return 1;
}
static int amx_setPageActionId(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
page_action_xml* pa=(page_action_xml*)ctmp->tmp;
if(pa!=NULL&&pa->id==NULL){
pa->id=apr_pstrdup(p,body);
if(ctmp->conf->uid!=0){
pa->id=apr_psprintf(p,"%s_%d",pa->id,ctmp->conf->uid);
}
}
return 1;
}
static int amx_setPageActionDescription(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
page_action_xml* pa=(page_action_xml*)ctmp->tmp;
pa->description=apr_pstrdup(p,body);
return 1;
}
static int amx_setPageActionRegex(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
page_action_xml* pa=(page_action_xml*)ctmp->tmp;
pa->regex=apr_pstrdup(p,body);
return 1;
}
static int amx_setPageActionHandler(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
page_action_xml* pa=(page_action_xml*)ctmp->tmp;
pa->handler=apr_pstrdup(p,body);
return 1;
}
static int amx_setPageActionUri(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
page_action_xml* pa=(page_action_xml*)ctmp->tmp;
if(pa!=NULL){
pa->uri=apr_pstrdup(p,body);
}
return 1;
}
static int amx_setPageActionOidcProvider(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
page_action_xml* pa=(page_action_xml*)ctmp->tmp;
if(pa!=NULL){
pa->oidcProvider=apr_pstrdup(p,body);
}
return 1;
}
static int amx_setPageActionRelyingParty(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
page_action_xml* pa=(page_action_xml*)ctmp->tmp;
if(pa!=NULL){
pa->relyingParty=apr_pstrdup(p,body);
}
return 1;
}
static int amx_setPageActionIsForward(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
page_action_xml* pa=(page_action_xml*)ctmp->tmp;
pa->isForward=strcmp(body,"true")==0?1:0;
return 1;
}
static int amx_setPageActionIsPermanent(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
page_action_xml* pa=(page_action_xml*)ctmp->tmp;
pa->isPermanent=strcmp(body,"true")==0?1:0;
return 1;
}
static int amx_setPageActionAdvancedTemplate(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
page_action_xml* pa=(page_action_xml*)ctmp->tmp;
pa->advancedTemplate=STRTOBOOL(body);
return 1;
}
static int amx_setPageActionBase64UrlEncodeState(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
page_action_xml* pa=(page_action_xml*)ctmp->tmp;
pa->base64UrlEncodeState=STRTOBOOL(body);
return 1;
}
static int amx_addPageAction(pool* p,char* xPath,int type,void* userdata){
oidc_config_xml* amx=NULL;
page_action_xml* pageact=NULL;
actmap_tmp* ctmp=(actmap_tmp*)userdata;
amx=(oidc_config_xml*)ctmp->conf;
if(amx!=NULL&&ctmp->tmp!=NULL){
pageact=(page_action_xml*)ctmp->tmp;
apr_hash_set (amx->page_actions_hash,pageact->id,APR_HASH_KEY_STRING,ctmp->tmp);
// loginRedirect means always 302 meaning isForward false
if(pageact->type==action_login||pageact->response!=NULL) { pageact->isForward = FALSE; }
}
ctmp->tmp=NULL;
return 1;
}
//path mapping handlers
static path_mapping_xml* amx_newPathMappingXml(pool* p){
path_mapping_xml* ret;
ret=apr_palloc(p,sizeof(path_mapping_xml));
ret->pathRegex=NULL;
ret->ignoreCase=FALSE;// Case sensitive by default
ret->postAuthActions=apr_array_make(p,1,sizeof(pathmapping_action_xml*));
ret->matchLists=apr_array_make(p,1,sizeof(char*));
return ret;
}
static void amx_appendMatchListsToMatchListArray(pool*p,char* matchListsStr,int uniqueId,array_header*matchLists){
array_header* arr;
char* tmp,**pos;
int i;
if(matchListsStr==NULL) return;
arr=cu_parseStringArrayFromCsv(p,4,",",matchListsStr);
if(arr==NULL||arr->nelts<1) return;
for(i=0;i<arr->nelts;i++){
tmp=(char*)cu_getElement(arr,i);
if(uniqueId!=0){tmp=apr_psprintf(p,"%s_%d",tmp,uniqueId);}
pos=apr_array_push(matchLists);
*pos=tmp;
}
return;
}
static int amx_newPathMapping(pool* p,char* xPath,int type,const char ** attributes,void* userdata){\
int i;
path_mapping_xml* map=NULL;
actmap_tmp* ctmp=(actmap_tmp*)userdata;
map=amx_newPathMappingXml(p);
ctmp->tmp=(void*)map;
char*matchListsStr;
for(i=0;attributes[i]; i += 2) {
if(strcmp(attributes[i],"path")==0){
map->pathRegex=apr_pstrdup(p,(char*)attributes[i + 1]);
}else if(strcmp(attributes[i],"matchLists")==0){
matchListsStr=apr_pstrdup(p,(char*)attributes[i + 1]);
amx_appendMatchListsToMatchListArray(p,matchListsStr,ctmp->conf->uid,map->matchLists);
}else if(strcmp(attributes[i],"ignoreCase")==0){
map->ignoreCase=STRTOBOOL((char*)attributes[i + 1]);
}
}
return 1;
}
static int amx_addPathMapping(pool* p,char* xPath,int type,void* userdata){
oidc_config_xml* amx=NULL;
path_mapping_xml* pm=NULL, **placepm=NULL;
actmap_tmp* ctmp=(actmap_tmp*)userdata;
amx=(oidc_config_xml*)ctmp->conf;
if(amx!=NULL&&ctmp->tmp!=NULL){
pm=(path_mapping_xml*)ctmp->tmp;
placepm=(path_mapping_xml**)apr_array_push (amx->path_mappings_arr);
*placepm=pm;
}
ctmp->tmp=NULL;
return 1;
}
static int amx_setPath(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
path_mapping_xml* pa=(path_mapping_xml*)ctmp->tmp;
if(pa!=NULL){
pa->pathRegex=apr_pstrdup(p,body);
}
return 1;
}
static int amx_newPathMappingAction(pool* p,char* xPath,int type,const char ** attributes,void* userdata){
int i;
actmap_tmp* ctmp=(actmap_tmp*)userdata;
pathmapping_action_xml* action=apr_palloc(p,sizeof(pathmapping_action_xml));
action->id=NULL;
action->matchList=NULL;
for(i=0;attributes[i]; i += 2) {
if(strcmp(attributes[i],"matchList")==0){
action->matchList=apr_pstrdup(p,(char*)attributes[i + 1]);
if(ctmp->conf->uid!=0){
action->matchList=apr_psprintf(p,"%s_%d",action->matchList,ctmp->conf->uid);
}
}
}
ctmp->tmp6=(void*)action;
return 1;
}
static int amx_setPathMappingAction(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
pathmapping_action_xml* action=(pathmapping_action_xml*)ctmp->tmp6;
if(action!=NULL){
if(ctmp->conf->uid!=0){
action->id=apr_psprintf(p,"%s_%d",body,ctmp->conf->uid);
}else{
action->id=apr_pstrdup(p,body);
}
}
return 1;
}
static int amx_addPathMappingAction(pool* p,void* userdata,array_header* actions){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
path_mapping_xml* pa=(path_mapping_xml*)ctmp->tmp;
pathmapping_action_xml* action=(pathmapping_action_xml*)ctmp->tmp6, **pos=NULL;
if(actions!=NULL){
pos=(pathmapping_action_xml**)apr_array_push(actions);
*pos=action;
printf("matchlist=%s id=%s \r\n",action->matchList, action->id);
}
ctmp->tmp6=NULL;
return 1;
}
static int amx_addPathMappingPostAuth(pool* p,char* xPath,int type,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
path_mapping_xml* pa=(path_mapping_xml*)ctmp->tmp;
if(pa!=NULL){
amx_addPathMappingAction(p,userdata,pa->postAuthActions);
}
return 1;
}
static int amx_addPathMappingMatchList(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
path_mapping_xml* pa=(path_mapping_xml*)ctmp->tmp;
char** pos=NULL, *tmp;
if(pa!=NULL){
pos=apr_array_push(pa->matchLists);
tmp=apr_pstrdup(p,body);
if(ctmp->conf->uid!=0){
tmp=apr_psprintf(p,"%s_%d",tmp,ctmp->conf->uid);
}
*pos=tmp;
}
return 1;
}
static int amx_newPathMappingMatchHeader(pool* p,char* xPath,int type,const char ** attributes,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
mlx_ml_match* match=(mlx_ml_match*)ctmp->tmp2;
int i=0;
mlx_match_header* hdr=NULL;
if(match!=NULL){
hdr=ml_newMatchHeaderObj(p);
for(i=0;attributes[i]; i += 2) {
if(strcmp(attributes[i],"name")==0){
hdr->name=apr_pstrdup(p,(char*)attributes[i + 1]);
}else if(strcmp(attributes[i],"delimAnd")==0){
hdr->delimAnd=apr_pstrdup(p,(char*)attributes[i + 1]);
}else if(strcmp(attributes[i],"negate")==0){
hdr->negate=STRTOBOOL(apr_pstrdup(p,(char*)attributes[i + 1]));
}else if(strcmp(attributes[i],"isregex")==0){
hdr->isRegex=STRTOBOOL(apr_pstrdup(p,(char*)attributes[i + 1]));
}
}
ctmp->tmp5=(void*)hdr;
}
return 1;
}
static char* amx_getGlobalPrefixedParam(pool* p, const char* key){
if(key==NULL) return NULL;
if(strstr(key,"global:")==key){
return apr_pstrdup(p,key+7);
}
return NULL;
}
time_t amx_dateStringToSeconds(const char* dateString){
//Functionality moved to common_utils.c
return cu_dateStringToSeconds(dateString);
}
static int amx_newPathMappingMatchEvent(pool* p,char* xPath,int type,const char ** attributes,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
mlx_ml_match* match=(mlx_ml_match*)ctmp->tmp2;
int i=0;
mlx_match_event* e=NULL;
if(match!=NULL){
e=ml_newMatchEventObj(p);
for(i=0;attributes[i]; i += 2) {
if(strcmp(attributes[i],"start")==0){
e->start=amx_dateStringToSeconds(apr_pstrdup(p,(char*)attributes[i + 1]));
}else if(strcmp(attributes[i],"end")==0){
e->end=amx_dateStringToSeconds(apr_pstrdup(p,(char*)attributes[i + 1]));
}
}
match->event=e;
}
return 1;
}
static int amx_setPathMappingMatchHeader(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
mlx_ml_match* match=(mlx_ml_match*)ctmp->tmp2;
mlx_match_header* hdr=(mlx_match_header*)ctmp->tmp5, **headerPlace;
if(match!=NULL&&hdr!=NULL){
hdr->value=apr_pstrdup(p,body);
headerPlace=(mlx_match_header**)apr_array_push(match->headerList);
*headerPlace=hdr;
if(ctmp->errorStr==NULL&&!rc_isRegexValid(p,hdr->value)){
ctmp->errorStr=apr_pstrcat(p,"Header Regex not valid: (",hdr->name,"=",hdr->value,")",NULL);
}
ctmp->tmp5=NULL;
}
return 1;
}
static action_header_xml* amx_newActionHeaderObj(pool* p){
action_header_xml* ret=apr_palloc(p,sizeof(action_header_xml));
ret->name=NULL;
ret->value=NULL;
ret->regex=NULL;
ret->action=header_set;
return ret;
}
static header_actions amx_getHeaderAction(const char* action) {
header_actions header_action;
if(action==NULL) return header_set;
if (!strcasecmp(action, "set"))
header_action = header_set;
else if (!strcasecmp(action, "add"))
header_action = header_add;
else if (!strcasecmp(action, "append"))
header_action = header_append;
else if (!strcasecmp(action, "merge"))
header_action = header_merge;
else if (!strcasecmp(action, "unset"))
header_action = header_unset;
else if (!strcasecmp(action, "echo"))
header_action = header_echo;
else if (!strcasecmp(action, "edit"))
header_action = header_edit;
else header_action = header_set;
return header_action;
}
static int amx_newActionHeader(pool* p,char* xPath,int type,const char ** attributes,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
action_header_xml* hdr = amx_newActionHeaderObj(p);
int i;
for(i=0;attributes[i]; i += 2) {
if(strcmp(attributes[i],"name")==0){
hdr->name=apr_pstrdup(p,(char*)attributes[i + 1]);
}
else if(strcmp(attributes[i],"regex")==0) {
hdr->regex = apr_pstrdup(p,(char*)attributes[i + 1]);
}
else if(strcmp(attributes[i],"do")==0) {
hdr->action = amx_getHeaderAction((char*)attributes[i + 1]);
}
}
ctmp->tmp8=(void*)hdr;
return 1;
}
static int amx_setActionResponseHeader(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
page_action_xml* pa=(page_action_xml*)ctmp->tmp;
action_header_xml* hdr=(action_header_xml*)ctmp->tmp8, **headerPlace;
if(pa!=NULL&&pa->responseHeaders!=NULL&&hdr!=NULL){
hdr->value=apr_pstrdup(p,body);
headerPlace=(action_header_xml**)apr_array_push(pa->responseHeaders);
*headerPlace=hdr;
//printf("responseheaders=%s:%s\n", hdr->name, hdr->value);
ctmp->tmp8=NULL;
}
return 1;
}
static int amx_setActionRequestHeader(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
page_action_xml* pa=(page_action_xml*)ctmp->tmp;
action_header_xml* hdr=(action_header_xml*)ctmp->tmp8, **headerPlace;
if(pa!=NULL&&pa->requestHeaders!=NULL&&hdr!=NULL){
hdr->value=apr_pstrdup(p,body);
headerPlace=(action_header_xml**)apr_array_push(pa->requestHeaders);
*headerPlace=hdr;
//printf("requestHeaders=%s:%s\n", hdr->name, hdr->value);
ctmp->tmp8=NULL;
}
return 1;
}
static int amx_newMatchList(pool* p,char* xPath,int type,const char ** attributes,void* userdata){\
int i;
actmap_tmp* ctmp=(actmap_tmp*)userdata;
mlx_matchlist* mlist=apr_palloc(p,sizeof(mlx_matchlist));
mlist->name=NULL;
mlist->matches=apr_array_make(p,2,sizeof(mlx_ml_match*));
for(i=0;attributes[i]; i += 2) {
if(strcmp(attributes[i],"name")==0){
mlist->name=apr_pstrdup(p,(char*)attributes[i + 1]);
if(ctmp->conf->uid!=0){
mlist->name=apr_psprintf(p,"%s_%d",mlist->name,ctmp->conf->uid);
}
ctmp->tmp=(void*)mlist;
}
}
return 1;
}
static int amx_addMatchList(pool* p,char* xPath,int type,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
oidc_config_xml* amx=(oidc_config_xml*)ctmp->conf;
mlx_matchlist* mlist=(mlx_matchlist*)ctmp->tmp, **mlistPos=NULL;
if(ctmp!=NULL&&mlist!=NULL&&mlist->name!=NULL){
mlistPos=(mlx_matchlist**)apr_array_push(amx->match_list_arr);
*mlistPos=mlist;
}
ctmp->tmp=NULL;
return 1;
}
static int amx_newPathMappingMatch(pool* p,char* xPath,int type,const char ** attributes,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
mlx_ml_match* match=ml_newMatchListMatchObj(p);
int i;
if(match!=NULL){
for(i=0;attributes[i]; i += 2){
if(strcmp(attributes[i],"host")==0){
match->host=apr_pstrdup(p,(char*)attributes[i + 1]);
}else if(strcmp(attributes[i],"cascade")==0){
match->cascade=STRTOBOOL((char*)attributes[i + 1]);
}
}
}
ctmp->tmp2=(void*)match;
return 1;
}
static int amx_addPathMappingMatch(pool* p,char* xPath,int type,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
mlx_matchlist* matchlist=(mlx_matchlist*)ctmp->tmp;
mlx_ml_match* match=(mlx_ml_match*)ctmp->tmp2, **matchPos=NULL;
if(match!=NULL&&matchlist!=NULL){
matchPos=(mlx_ml_match**)apr_array_push(matchlist->matches);
*matchPos=match;
ctmp->tmp2=NULL;
}
return 1;
}
static int amx_setMatchHost(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
mlx_ml_match* match=(mlx_ml_match*)ctmp->tmp2;
if(match!=NULL){
match->host=apr_pstrdup(p,body);
}
return 1;
}
static int amx_newMatchListMatchIp(pool* p,char* xPath,int type,const char ** attributes,void* userdata){
int i;
actmap_tmp* ctmp=(actmap_tmp*)userdata;
mlx_match_ip* ip=ml_newMatchIpObj(p);
for(i=0;attributes[i]; i += 2){
if(strcmp(attributes[i],"isregex")==0){
ip->isRegex=STRTOBOOL((char*)attributes[i + 1]);
}else if(strcmp(attributes[i],"negate")==0){
ip->negate=STRTOBOOL((char*)attributes[i + 1]);
}
}
ctmp->tmp6=(void*)ip;
return 1;
}
static int amx_setPathMappingMatchIp(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
mlx_ml_match* match=(mlx_ml_match*)ctmp->tmp2;
mlx_match_ip* ip=(mlx_match_ip*)ctmp->tmp6;
if(match!=NULL&&ip!=NULL){
ip->ip=apr_pstrdup(p,body);
if(ctmp->errorStr==NULL&&ip->isRegex==TRUE&&!rc_isRegexValid(p,ip->ip)){
ctmp->errorStr=apr_pstrcat(p,"IP Regex not valid:",ip->ip,NULL);
}
match->ip=ip;
}
ctmp->tmp6=NULL;
return 1;
}
static int amx_newMatchListMatchPath(pool* p,char* xPath,int type,const char ** attributes,void* userdata){
int i;
actmap_tmp* ctmp=(actmap_tmp*)userdata;
mlx_match_path* path=ml_newMatchPathObj(p);
for(i=0;attributes[i]; i += 2){
if(strcmp(attributes[i],"negate")==0){
path->negate=STRTOBOOL((char*)attributes[i + 1]);
}
}
ctmp->tmp7=(void*)path;
return 1;
}
static int amx_setPathMappingMatchPath(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
mlx_ml_match* match=(mlx_ml_match*)ctmp->tmp2;
mlx_match_path* path=(mlx_match_path*)ctmp->tmp7;
if(match!=NULL&&path!=NULL){
path->path=apr_pstrdup(p,body);
if(ctmp->errorStr==NULL&&!rc_isRegexValid(p,path->path)){
ctmp->errorStr=apr_pstrcat(p,"IP Regex not valid:",path->path,NULL);
}
match->path=path;
}
ctmp->tmp7=NULL;
return 1;
}
static int amx_newInclude(pool* p,char* xPath,int type,const char ** attributes,void* userdata){
int i;
actmap_tmp* ctmp=(actmap_tmp*)userdata;
for(i=0;attributes[i]; i += 2) {
if(strcmp(attributes[i],"path")==0){
ctmp->tmp4=apr_pstrdup(p,(char*)attributes[i + 1]);
}
}
return 1;
}
static action_response_xml* actionmapxml_newPageActionResponseObj(pool* p){
action_response_xml* ret=(action_response_xml*)apr_palloc(p,sizeof(action_response_xml));
ret->code=200;
ret->contentType=NULL;
ret->body=NULL;
return ret;
}
static int amx_newPageActionResponse(pool* p,char* xPath,int type,const char ** attributes,void* userdata){
int i;
actmap_tmp* ctmp=(actmap_tmp*)userdata;
action_response_xml* response=actionmapxml_newPageActionResponseObj(p);
for(i=0;attributes[i]; i += 2) {
if(strcmp(attributes[i],"code")==0){
response->code=atoi(attributes[i + 1]);
}else if(strcmp(attributes[i],"contentType")==0){
response->contentType=apr_pstrdup(p, attributes[i + 1]);
}
}
ctmp->tmp11=(void*)response;
return 1;
}
static int amx_setPageActionResponseBody(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
action_response_xml* response=(action_response_xml*)ctmp->tmp11;
if(response!=NULL){
response->body = apr_pstrdup(p,body);
}
return 1;
}
static int amx_addPageActionResponse(pool* p,char* xPath,int type,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
if(ctmp->tmp!=NULL&&ctmp->tmp11!=NULL){
page_action_xml* pa=(page_action_xml*)ctmp->tmp;
if(pa!=NULL) {
pa->response=(action_response_xml*)ctmp->tmp11;
}
}
ctmp->tmp11=NULL;
return 1;
}
static int cc_setACCSessionCookieAttributes(pool* p,char* xPath,int type,const char ** attributes,void* userdata){
int i;
actmap_tmp* stmp=(actmap_tmp*)userdata;
oidc_config_xml* conf=(oidc_config_xml*)stmp->conf;
for (i = 0; attributes[i]; i += 2) {
if(strcmp(attributes[i],"name")==0){
cookie_setCookieName(p, conf->rpSession, (char*)attributes[i + 1]);
}else if(strcmp(attributes[i],"lifetime")==0){
cookie_setCookieLifeTime(conf->rpSession,atoi(attributes[i + 1]));
}else if(strcmp(attributes[i],"httpOnly")==0){
cookie_setCookieHttpOnlyflag(conf->rpSession,
STRTOBOOL(attributes[i + 1]));
}else if(strcmp(attributes[i],"secureHttpOnly")==0){
cookie_setCookieSecureHttpOnlyflag(conf->rpSession,
STRTOBOOL(attributes[i + 1]));
}
}
return 1;
}
static int cc_setACCPermCookieAttributes(pool* p,char* xPath,int type,const char ** attributes,void* userdata){
int i;
actmap_tmp* stmp=(actmap_tmp*)userdata;
oidc_config_xml* conf=(oidc_config_xml*)stmp->conf;
for (i = 0; attributes[i]; i += 2) {
if(strcmp(attributes[i],"name")==0){
cookie_setCookieName(p, conf->oidcSession,(char*)attributes[i + 1]);
}else if(strcmp(attributes[i],"lifetime")==0){
cookie_setCookieLifeTime(conf->oidcSession,atoi(attributes[i + 1]));
}else if(strcmp(attributes[i],"httpOnly")==0){
cookie_setCookieHttpOnlyflag(conf->oidcSession,STRTOBOOL(attributes[i + 1]));
}else if(strcmp(attributes[i],"secureHttpOnly")==0){
cookie_setCookieSecureHttpOnlyflag(conf->oidcSession,
STRTOBOOL(attributes[i + 1]));
}
}
return 1;
}
static int cc_setACCAccessTokenCookieAttributes(pool* p,char* xPath,int type,const char ** attributes,void* userdata){
int i;
actmap_tmp* stmp=(actmap_tmp*)userdata;
oidc_config_xml* conf=(oidc_config_xml*)stmp->conf;
conf->accessToken = cookie_newObj(p);
cookie_setCookieName(p, conf->accessToken, (char*)"access_token");
for (i = 0; attributes[i]; i += 2) {
if(strcmp(attributes[i],"name")==0){
cookie_setCookieName(p, conf->accessToken,(char*)attributes[i + 1]);
}else if(strcmp(attributes[i],"lifetime")==0){
cookie_setCookieLifeTime(conf->accessToken,atoi(attributes[i + 1]));
}else if(strcmp(attributes[i],"httpOnly")==0){
cookie_setCookieHttpOnlyflag(conf->accessToken,STRTOBOOL(attributes[i + 1]));
}else if(strcmp(attributes[i],"secureHttpOnly")==0){
cookie_setCookieSecureHttpOnlyflag(conf->accessToken,
STRTOBOOL(attributes[i + 1]));
}
}
return 1;
}
static relying_party_xml* amx_newRelyingPartyXml(pool* p){
relying_party_xml* ret;
ret=apr_palloc(p,sizeof(relying_party_xml));
ret->clientID=NULL;
ret->clientSecret=NULL;
ret->description=NULL;
ret->issuer=NULL;
ret->validateNonce=TRUE;
ret->redirectUri=NULL;
ret->id=NULL;
ret->postLoginDefaultLandingPage=NULL;
return ret;
}
static int amx_defaultRelyingParty(pool* p,char* xPath,int type,const char ** attributes,void* userdata){
int i;
actmap_tmp* ctmp=(actmap_tmp*)userdata;
oidc_config_xml* amx=(oidc_config_xml*)ctmp->conf;
return 1;
}
static int amx_newRelyingParty(pool* p,char* xPath,int type,const char ** attributes,void* userdata){
int i;
actmap_tmp* ctmp=(actmap_tmp*)userdata;
relying_party_xml* rpX=(relying_party_xml*)amx_newRelyingPartyXml(p);
for(i=0;attributes[i]; i += 2) {
if(strcmp(attributes[i],"id")==0){
rpX->id=apr_pstrdup(p,(char*)attributes[i + 1]);
}else if(strcmp(attributes[i],"clientID")==0){
rpX->clientID=apr_pstrdup(p,(char*)attributes[i + 1]);
}else if(strcmp(attributes[i],"clientSecret")==0){
rpX->clientSecret=apr_pstrdup(p,(char*)attributes[i + 1]);
}else if(strcmp(attributes[i],"validateNonce")==0){
rpX->validateNonce=STRTOBOOL(attributes[i + 1]);
}
}
ctmp->tmp14=rpX;
return 1;
}
static int amx_addRelyingParty(pool* p,char* xPath,int type,void* userdata){
oidc_config_xml* amx=NULL;
relying_party_xml* rpX=NULL;
actmap_tmp* ctmp=(actmap_tmp*)userdata;
amx=(oidc_config_xml*)ctmp->conf;
if(amx!=NULL&&ctmp->tmp14!=NULL){
rpX=(relying_party_xml*)ctmp->tmp14;
apr_hash_set (amx->relyingPartyHash,rpX->id,APR_HASH_KEY_STRING,rpX);
}
ctmp->tmp14=NULL;
return 1;
}
static int amx_setRelyingPartyClientID(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
relying_party_xml* rpX=(relying_party_xml*)ctmp->tmp14;
if(rpX!=NULL&&rpX->clientID==NULL){
rpX->clientID=apr_pstrdup(p,body);
}
return 1;
}
static int amx_setRelyingPartyDescription(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
relying_party_xml* rpX=(relying_party_xml*)ctmp->tmp14;
if(rpX!=NULL&&rpX->description==NULL){
rpX->description=apr_pstrdup(p,body);
}
return 1;
}
static int amx_setRelyingPartyClientSecret(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
relying_party_xml* rpX=(relying_party_xml*)ctmp->tmp14;
if(rpX!=NULL&&rpX->clientSecret==NULL){
rpX->clientSecret=apr_pstrdup(p,body);
}
return 1;
}
static int amx_setRelyingPartyIssuer(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
relying_party_xml* rpX=(relying_party_xml*)ctmp->tmp14;
if(rpX!=NULL&&rpX->issuer==NULL){
rpX->issuer=apr_pstrdup(p,body);
}
return 1;
}
static int amx_setRelyingPartyValidateNonce(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
relying_party_xml* rpX=(relying_party_xml*)ctmp->tmp14;
if(rpX!=NULL&&rpX->issuer==NULL){
rpX->validateNonce=STRTOBOOL(body);
}
return 1;
}
static int amx_setRelyingPartyRedirectUri(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
relying_party_xml* rpX=(relying_party_xml*)ctmp->tmp14;
if(rpX!=NULL&&rpX->redirectUri==NULL){
rpX->redirectUri=apr_pstrdup(p,body);
}
return 1;
}
static int amx_setRelyingPartyPostLoginDefaultLandingPage(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
relying_party_xml* rpX=(relying_party_xml*)ctmp->tmp14;
if(rpX!=NULL&&rpX->postLoginDefaultLandingPage==NULL){
rpX->postLoginDefaultLandingPage=apr_pstrdup(p,body);
}
return 1;
}
static oidc_provider_xml* amx_newOIDCProviderXml(pool* p){
oidc_provider_xml* ret;
ret=apr_pcalloc(p,sizeof(oidc_provider_xml));
ret->id=NULL;
ret->issuer=NULL;
ret->metadataUrl=NULL;
ret->isDefault=FALSE;
return ret;
}
static int amx_newOIDCProvider(pool* p,char* xPath,int type,const char ** attributes,void* userdata){
int i;
actmap_tmp* ctmp=(actmap_tmp*)userdata;
oidc_config_xml* amx=(oidc_config_xml*)ctmp->conf;
oidc_provider_xml* oidcProviderX=(oidc_provider_xml*)amx_newOIDCProviderXml(p);
for(i=0;attributes[i]; i += 2) {
if(strcmp(attributes[i],"id")==0){
oidcProviderX->id=apr_pstrdup(p,(char*)attributes[i + 1]);
}else if(strcmp(attributes[i],"issuer")==0){
oidcProviderX->issuer=apr_pstrdup(p,(char*)attributes[i + 1]);
}else if(strcmp(attributes[i],"isDefault")==0){
oidcProviderX->isDefault=STRTOBOOL(attributes[i + 1]);
}
}
ctmp->tmp15=oidcProviderX;
return 1;
}
static int amx_addOIDCProvider(pool* p,char* xPath,int type,void* userdata){
oidc_config_xml* amx=NULL;
oidc_provider_xml* oidcProviderX=NULL, **position;
actmap_tmp* ctmp=(actmap_tmp*)userdata;
amx=(oidc_config_xml*)ctmp->conf;
if(amx!=NULL&&ctmp->tmp15!=NULL){
oidcProviderX=(oidc_provider_xml*)ctmp->tmp15;
position=(oidc_provider_xml**)apr_array_push(amx->oidcProviders);
*position=oidcProviderX;
}
ctmp->tmp15=NULL;
return 1;
}
static int amx_setOIDCProviderMetadataUrl(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
oidc_provider_xml* oidcProviderX=(oidc_provider_xml*)ctmp->tmp15;
if(oidcProviderX!=NULL) {
oidcProviderX->metadataUrl=apr_pstrdup(p,body);
}
return 1;
}
static int amx_setOIDCProviderIssuer(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
oidc_provider_xml* oidcProviderX=(oidc_provider_xml*)ctmp->tmp15;
if(oidcProviderX!=NULL) {
oidcProviderX->issuer=apr_pstrdup(p,body);
}
return 1;
}
static int amx_setOIDCProviderAuthorizationEndpoint(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
oidc_provider_xml* oidcProviderX=(oidc_provider_xml*)ctmp->tmp15;
if(oidcProviderX!=NULL) {
oidcProviderX->authorizationEndpoint=apr_pstrdup(p,body);
}
return 1;
}
static int amx_setOIDCProviderTokenEndpoint(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
oidc_provider_xml* oidcProviderX=(oidc_provider_xml*)ctmp->tmp15;
if(oidcProviderX!=NULL) {
oidcProviderX->tokenEndpoint=apr_pstrdup(p,body);
}
return 1;
}
static int amx_setOIDCProviderJwksUri(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
oidc_provider_xml* oidcProviderX=(oidc_provider_xml*)ctmp->tmp15;
if(oidcProviderX!=NULL) {
oidcProviderX->jwksUri=apr_pstrdup(p,body);
}
return 1;
}
static int amx_setOIDCProviderJwksJson(pool* p,char* xPath,int type,const char *body,void* userdata){
actmap_tmp* ctmp=(actmap_tmp*)userdata;
oidc_provider_xml* oidcProviderX=(oidc_provider_xml*)ctmp->tmp15;
if(oidcProviderX!=NULL) {
oidcProviderX->jwksJson=apr_pstrdup(p,body);
}
return 1;
}
char* amx_loadConfFile(pool* p, char* file, oidc_config_xml* conf){
XmlCore* xCore;
actmap_tmp tmp;
char* result=NULL;
tmp.conf=conf;
tmp.tmp=NULL;
tmp.tmp2=NULL;
tmp.tmp3=NULL;
tmp.tmp4=NULL;
tmp.tmp5=NULL;
tmp.tmp6=NULL;
tmp.tmp7=NULL;
tmp.tmp8=NULL;
tmp.tmp9=NULL;
tmp.tmp10=NULL;
tmp.tmp11=NULL;
tmp.tmp12=NULL;
tmp.tmp13=NULL;
tmp.tmp14=NULL;
tmp.tmp15=NULL;
tmp.str=NULL;
tmp.errorStr=NULL;
xCore=xc_getXmlCore(p);
xc_addXPathHandler(xCore,"/oidcConfig",0,amx_oidcConfigAttributes,NULL,NULL, &tmp);
//page action stuff
xc_addXPathHandler(xCore,"/oidcConfig/oidcActions/action",0,amx_newPageAction,NULL,amx_addPageAction, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/oidcActions/action/id",0,NULL,amx_setPageActionId,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/oidcActions/action/description",0,NULL,amx_setPageActionDescription,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/oidcActions/action/isForward",0,NULL,amx_setPageActionIsForward,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/oidcActions/action/isPermanent",0,NULL,amx_setPageActionIsPermanent,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/oidcActions/action/advancedTemplate",0,NULL,amx_setPageActionAdvancedTemplate,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/oidcActions/action/uri",0,NULL,amx_setPageActionUri,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/oidcActions/action/regex",0,NULL,amx_setPageActionRegex,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/oidcActions/action/handler",0,NULL,amx_setPageActionHandler,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/oidcActions/action/requestHeaders/header",0,amx_newActionHeader,amx_setActionRequestHeader,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/oidcActions/action/responseHeaders/header",0,amx_newActionHeader,amx_setActionResponseHeader,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/oidcActions/action/response",0,amx_newPageActionResponse,amx_setPageActionResponseBody,amx_addPageActionResponse, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/oidcActions/action/oidcProvider",0,NULL,amx_setPageActionOidcProvider,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/oidcActions/action/relyingParty",0,NULL,amx_setPageActionRelyingParty,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/oidcActions/action/base64UrlEncodeState",0,NULL,amx_setPageActionBase64UrlEncodeState,NULL, &tmp);
//path mapping stuff
xc_addXPathHandler(xCore,"/oidcConfig/locations/location",0,amx_newPathMapping,NULL,amx_addPathMapping, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/locations/location/path",0,NULL,amx_setPath,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/locations/location/oidcAction",0,amx_newPathMappingAction,amx_setPathMappingAction,amx_addPathMappingPostAuth, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/locations/location/matchList",0,NULL,amx_addPathMappingMatchList,NULL, &tmp);
//match list stuff
xc_addXPathHandler(xCore,"/oidcConfig/matchLists/matchList",0,amx_newMatchList,NULL,amx_addMatchList, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/matchLists/matchList/match",0,amx_newPathMappingMatch,NULL,amx_addPathMappingMatch, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/matchLists/matchList/match/host",0,NULL,amx_setMatchHost,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/matchLists/matchList/match/ip",0,amx_newMatchListMatchIp,amx_setPathMappingMatchIp,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/matchLists/matchList/match/path",0,amx_newMatchListMatchPath,amx_setPathMappingMatchPath,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/matchLists/matchList/match/header",0,amx_newPathMappingMatchHeader,amx_setPathMappingMatchHeader,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/matchLists/matchList/match/event",0,amx_newPathMappingMatchEvent,NULL,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/rpSession",0,cc_setACCSessionCookieAttributes,NULL,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/oidcSession",0,cc_setACCPermCookieAttributes,NULL,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/accessToken",0,cc_setACCAccessTokenCookieAttributes,NULL,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/relyingParties",0,amx_defaultRelyingParty,NULL,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/relyingParties/relyingParty",0,amx_newRelyingParty,NULL,amx_addRelyingParty, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/relyingParties/relyingParty/clientID",0,NULL,amx_setRelyingPartyClientID,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/relyingParties/relyingParty/description",0,NULL,amx_setRelyingPartyDescription,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/relyingParties/relyingParty/clientSecret",0,NULL,amx_setRelyingPartyClientSecret,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/relyingParties/relyingParty/issuer",0,NULL,amx_setRelyingPartyIssuer,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/relyingParties/relyingParty/validateNonce",0,NULL,amx_setRelyingPartyValidateNonce,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/relyingParties/relyingParty/redirectUri",0,NULL,amx_setRelyingPartyRedirectUri,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/relyingParties/relyingParty/postLoginDefaultLandingPage",0,NULL,amx_setRelyingPartyPostLoginDefaultLandingPage,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/oidcProviders/oidcProvider",0,amx_newOIDCProvider,NULL,amx_addOIDCProvider, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/oidcProviders/oidcProvider/metadataUrl",0,NULL,amx_setOIDCProviderMetadataUrl,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/oidcProviders/oidcProvider/issuer",0,NULL,amx_setOIDCProviderIssuer,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/oidcProviders/oidcProvider/authorizationEndpoint",0,NULL,amx_setOIDCProviderAuthorizationEndpoint,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/oidcProviders/oidcProvider/tokenEndpoint",0,NULL,amx_setOIDCProviderTokenEndpoint,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/oidcProviders/oidcProvider/jwksUri",0,NULL,amx_setOIDCProviderJwksUri,NULL, &tmp);
xc_addXPathHandler(xCore,"/oidcConfig/oidcProviders/oidcProvider/jwksJson",0,NULL,amx_setOIDCProviderJwksJson,NULL, &tmp);
result=xc_beginParsingTextResponse(xCore,file);
return result;
}
|
tarachandverma/ngx-openidc
|
src/service-utils/http-utils/http_client.h
|
<filename>src/service-utils/http-utils/http_client.h
#ifndef HTTP_CLIENT_H_
#define HTTP_CLIENT_H_
#ifdef __cplusplus
extern "C" {
#endif
//apr stuff
#include <apr_general.h>
#include <apr_pools.h>
#include <apr_strings.h>
#include <apr_tables.h>
#define HTTP_USER_AGENT "openidc-libcurl"
typedef struct http_util_result {
char *data;
char *content_type;
size_t size;
double totalTime;
long responseCode;
apr_pool_t *p;
apr_table_t* headers_out;
}http_util_result;
typedef struct http_ssl_options {
char* certType;
char* certFile;
char* passPhrase;
char* keyType;
char* keyName;
char* caCertFile;
}http_ssl_options;
http_ssl_options* hc_createNewHttpSSLOptions(apr_pool_t *p);
void hc_cleanup();
void hc_init();
http_util_result* hc_post_verbose(apr_pool_t *p,char* uri,long timeout,char* userColonPass,const char* postData,int postDataLen, apr_table_t * headers_in);
http_util_result* hc_ssl_post_verbose(apr_pool_t *p,char* uri,long timeout,char* userColonPass,const char* postData,int postDataLen, http_ssl_options* sslOptions, apr_table_t * headers_in);
http_util_result* hc_get_verbose(apr_pool_t *p,char* uri,long timeout,char* userColonPass, apr_table_t * headers_in,char** error);
http_util_result* hc_get_verbose2(apr_pool_t *p,char* uri,long timeout,long connectionTimeout,char* userColonPass, apr_table_t * headers_in,char** error);
http_util_result* hc_ssl_get_verbose(apr_pool_t *p,char* uri,long timeout,long connectionTimeout,char* userColonPass, http_ssl_options* sslOptions, apr_table_t * headers_in, char** error);
http_util_result* hc_put_verbose(apr_pool_t *p,char* uri,long timeout,char* userColonPass, char* putData);
http_util_result* hc_put_verbose2(apr_pool_t *p,char* uri,long timeout,char* userColonPass, const char* putData,int putDataLen, apr_table_t * headers_in);
http_util_result* hc_method(apr_pool_t *p,const char* methodName,char* uri,long timeout,char* userColonPass,const char* data,int dataLen, apr_table_t * headers_in);
http_util_result* hc_delete_verbose(apr_pool_t *p,char* uri,long timeout,char* userColonPass);
http_util_result* hc_head_verbose(apr_pool_t *p,char* uri,long timeout,char* userColonPass,char** error);
char* hc_getInfo(apr_pool_t* p);
http_util_result* hc_get(apr_pool_t *p,char* uri,long timeout);
int hc_is200_OK(http_util_result* ret);
#ifdef __cplusplus
}
#endif
#endif /*HTTP_CLIENT_H_*/
|
tarachandverma/ngx-openidc
|
src/doc-parser-core/doc_parser_utils.c
|
#include <doc_parser_utils.h>
#include "apr_lib.h"
#include "apr_strings.h"
char* docp_getRemoteResourcePath(pool* p, char* resource,
cbs_service_descriptor *rs,char* homeDir,char**details){
char* ret=NULL,*reqUri;
apr_pool_t* tp;
char* fileName=NULL;
if(resource==NULL) return NULL;
if(rs!=NULL){
//setup filepool
if(apr_pool_create(&tp,p)!=APR_SUCCESS){
if(details!=NULL){
*details=apr_pstrdup(p,"Failure to create subpool");
}
return NULL;
}
//load remote path.
reqUri=apr_pstrcat(p,rs->uri,"/",resource,NULL);
fileName=(char*)apr_filepath_name_get(resource);
ret=cb_writeRemoteResourceToDisk(p,homeDir,reqUri,fileName,rs->timeoutSeconds,rs->userColonPass,tp,details,NULL);
apr_pool_destroy(tp);
}
return ret;
}
char* docp_getRemoteResourcePathEx(pool* p, char* resourceUri, char* homeDir,char**details){
char* ret=NULL,*reqUri;
apr_pool_t* tp;
char* fileName=NULL;
apr_finfo_t finfo;
apr_status_t rv;
char* localPath=NULL;
if(resourceUri!=NULL){
//setup filepool
if(apr_pool_create(&tp,p)!=APR_SUCCESS){
if(details!=NULL){
*details=apr_pstrdup(p,"Failure to create subpool");
}
return NULL;
}
//load remote path.
fileName=(char*)apr_filepath_name_get(resourceUri);
ret=cb_writeRemoteResourceToDisk(p, homeDir,resourceUri,fileName,20,NULL,tp,details,NULL);
apr_pool_destroy(tp);
}
return ret;
}
char* docp_getLocalResourcePath(pool*p,char* resource,char* homeDir){
if(resource==NULL){return NULL;}
return apr_pstrcat(p,homeDir,"/",apr_filepath_name_get(resource),NULL);
}
|
tarachandverma/ngx-openidc
|
src/shm_core/shm_apr.c
|
<reponame>tarachandverma/ngx-openidc
#include "shm_apr.h"
#include "shm_data.h"
#include "common_utils.h"
static void shapr_make_array_core(array_header *res, shared_heap* sheap,int nelts, int elt_size, int clear){
/*
* Assure sanity if someone asks for
* array of zero elts.
*/
if (nelts < 1) {
nelts = 1;
}
if (clear) {
res->elts = shdata_shpcalloc(sheap, nelts * elt_size);
}else {
res->elts = shdata_shpalloc(sheap, nelts * elt_size);
}
res->pool = NULL;
res->elt_size = elt_size;
res->nelts = 0; /* No active elements yet... */
res->nalloc = nelts; /* ...but this many allocated */
}
array_header* shapr_array_make(shared_heap* sheap, int nelts, int elt_size){
array_header *res;
res = (array_header*) shdata_shpalloc(sheap,sizeof(array_header));
shapr_make_array_core(res, sheap, nelts, elt_size, 1);
return res;
}
void * shapr_array_push(shared_heap* sheap, array_header *arr){
int new_size;
char *new_data;
if (arr->nelts == arr->nalloc) {
new_size = (arr->nalloc <= 0) ? 1 : arr->nalloc * 2;
new_data = shdata_shpalloc(sheap, arr->elt_size * new_size);
memcpy(new_data, arr->elts, arr->nalloc * arr->elt_size);
memset(new_data + arr->nalloc * arr->elt_size, 0, arr->elt_size * (new_size - arr->nalloc));
arr->elts = new_data;
arr->nalloc = new_size;
}
++arr->nelts;
return arr->elts + (arr->elt_size * (arr->nelts - 1));
}
array_header* shapr_parseLongArrayFromCsv(shared_heap* sheap, int arraySz, const char* delim, char* src){
char *srccpy=NULL, *prodStr=NULL, *p1=NULL;
long *prodId=NULL, prodlook=0;
char* end=NULL;
array_header* arr=(array_header*)shapr_array_make(sheap,arraySz,sizeof(long));
if(src==NULL){return arr;}
srccpy=shdata_32BitString_copy(sheap,src);
if(arr==NULL){
return NULL;
}
prodStr=apr_strtok(srccpy,delim,&p1);
while(prodStr!=NULL){
// prodId= (long *) shapr_array_push(sheap,arr);
// *prodId = (long) atol(prodStr);
prodlook = strtol(prodStr,&end,10);
if(*end=='\0'){
prodId= (long *) shapr_array_push(sheap,arr);
*prodId=prodlook;
}
prodStr =strtok_r(NULL,delim,&p1);
}
return arr;
}
// Copies source array of char* to sheap array.
array_header* shapr_copyStringArrayToSheap(shared_heap* sheap, array_header* sarray){
int i;
char**place;
array_header* dstArr;
if(sarray==NULL||sarray->nelts<1) return NULL;
dstArr=shapr_array_make(sheap,sarray->nelts,sizeof(char*));
for(i=0;i<sarray->nelts;i++){
place=(char**)shapr_array_push(sheap,dstArr);
*place=shdata_32BitString_copy(sheap,(char*)cu_getElement(sarray,i));
}
return dstArr;
}
array_header* shapr_parseStringArrayFromCsv(shared_heap* sheap, int arraySz, const char* delim, char* src){
char *srccpy=NULL, *prodStr=NULL, *p1=NULL;
char **val=NULL;
array_header* arr=(array_header*)shapr_array_make(sheap,arraySz,sizeof(char*));
if(src==NULL){return arr;}
srccpy=shdata_32BitString_copy(sheap,src);
if(arr==NULL){
return NULL;
}
prodStr=apr_strtok(srccpy,delim,&p1);
while(prodStr!=NULL){
val= (char**) shapr_array_push(sheap,arr);
*val = prodStr;
prodStr =strtok_r(NULL,delim,&p1);
}
return arr;
}
typedef struct shapr_hash_entry_t shapr_hash_entry_t;
struct shapr_hash_entry_t {
shapr_hash_entry_t *next;
unsigned int hash;
const void *key;
apr_ssize_t klen;
const void *val;
};
/*
* Data structure for iterating through a hash table.
*
* We keep a pointer to the next hash entry here to allow the current
* hash entry to be freed or otherwise mangled between calls to
* apr_hash_next().
*/
struct shapr_hash_index_t {
shapr_hash_t *ht;
shapr_hash_entry_t *this, *next;
unsigned int index;
};
/*
* The size of the array is always a power of two. We use the maximum
* index rather than the size so that we can use bitwise-AND for
* modular arithmetic.
* The count of hash entries may be greater depending on the chosen
* collision rate.
*/
struct shapr_hash_t {
shapr_hash_entry_t **array;
shapr_hash_index_t iterator; /* For apr_hash_first(NULL, ...) */
unsigned int count, max;
shapr_hash_entry_t *free; /* List of recycled entries */
};
#define INITIAL_MAX 127 /* tunable == 2^n - 1 */
static shapr_hash_entry_t **shapr_alloc_array(shared_heap* sheap, shapr_hash_t *ht, unsigned int max){
return (shapr_hash_entry_t **)shdata_shpcalloc(sheap, sizeof(*ht->array) * (max + 1));
}
shapr_hash_t* shapr_hash_make(shared_heap* sheap){
shapr_hash_t *ht;
ht = (shapr_hash_t*)shdata_shpalloc(sheap, sizeof(shapr_hash_t));
ht->free = NULL;
ht->count = 0;
ht->max = INITIAL_MAX;
ht->array = shapr_alloc_array(sheap,ht, ht->max);
return ht;
}
void shapr_hash_this(shapr_hash_index_t *hi,
const void **key,
apr_ssize_t *klen,
void **val){
if (key) *key = hi->this->key;
if (klen) *klen = hi->this->klen;
if (val) *val = (void *)hi->this->val;
}
/*
* This is where we keep the details of the hash function and control
* the maximum collision rate.
*
* If val is non-NULL it creates and initializes a new hash entry if
* there isn't already one there; it returns an updatable pointer so
* that hash entries can be removed.
*/
static shapr_hash_entry_t **shapr_find_entry(shared_heap* sheap,shapr_hash_t *ht,const void *key,apr_ssize_t klen,const void *val){
shapr_hash_entry_t **hep, *he;
const unsigned char *p;
unsigned int hash;
apr_ssize_t i;
/*
* This is the popular `times 33' hash algorithm which is used by
* perl and also appears in Berkeley DB. This is one of the best
* known hash functions for strings because it is both computed
* very fast and distributes very well.
*
* The originator may be <NAME> but the code in Berkeley DB
* cites <NAME> as the source. The best citation I have found
* is "<NAME>, Hash function for text in C, Usenet message
* <<EMAIL>> in comp.lang.c , October, 1990." in Rich
* Salz's USENIX 1992 paper about INN which can be found at
* <http://citeseer.nj.nec.com/salz92internetnews.html>.
*
* The magic of number 33, i.e. why it works better than many other
* constants, prime or not, has never been adequately explained by
* anyone. So I try an explanation: if one experimentally tests all
* multipliers between 1 and 256 (as I did while writing a low-level
* data structure library some time ago) one detects that even
* numbers are not useable at all. The remaining 128 odd numbers
* (except for the number 1) work more or less all equally well.
* They all distribute in an acceptable way and this way fill a hash
* table with an average percent of approx. 86%.
*
* If one compares the chi^2 values of the variants (see
* <NAME> ``Hashing Frequently Asked Questions'' at
* http://burtleburtle.net/bob/hash/hashfaq.html for a description
* of chi^2), the number 33 not even has the best value. But the
* number 33 and a few other equally good numbers like 17, 31, 63,
* 127 and 129 have nevertheless a great advantage to the remaining
* numbers in the large set of possible multipliers: their multiply
* operation can be replaced by a faster operation based on just one
* shift plus either a single addition or subtraction operation. And
* because a hash function has to both distribute good _and_ has to
* be very fast to compute, those few numbers should be preferred.
*
* -- <NAME> <<EMAIL>>
*/
hash = 0;
if (klen == APR_HASH_KEY_STRING) {
for (p = key; *p; p++) {
hash = hash * 33 + *p;
}
klen = p - (const unsigned char *)key;
}else {
for (p = key, i = klen; i; i--, p++) {
hash = hash * 33 + *p;
}
}
/* scan linked list */
for (hep = &ht->array[hash & ht->max], he = *hep;
he; hep = &he->next, he = *hep) {
if (he->hash == hash
&& he->klen == klen
&& memcmp(he->key, key, klen) == 0)
break;
}
if (he || !val)
return hep;
/* add a new entry for non-NULL values */
if ((he = ht->free) != NULL)
ht->free = he->next;
else
he = (shapr_hash_entry_t*)shdata_shpalloc(sheap, sizeof(*he));
he->next = NULL;
he->hash = hash;
/*allocate shared memory for key
* this used to be he->key=key;
**/
he->key = shdata_32BitString_copy(sheap,(char*)key);
he->klen = klen;
he->val = val;
*hep = he;
ht->count++;
return hep;
}
shapr_hash_index_t * shapr_hash_next(shapr_hash_index_t *hi){
hi->this = hi->next;
while (!hi->this) {
if (hi->index > hi->ht->max)
return NULL;
hi->this = hi->ht->array[hi->index++];
}
hi->next = hi->this->next;
return hi;
}
shapr_hash_index_t * shapr_hash_first(apr_pool_t* pool, shapr_hash_t *ht){
shapr_hash_index_t *hi;
if (pool)
hi = (shapr_hash_index_t*)apr_palloc(pool, sizeof(*hi));
else
hi = &ht->iterator;
hi->ht = ht;
hi->index = 0;
hi->this = NULL;
hi->next = NULL;
return shapr_hash_next(hi);
}
/*
* Expanding a hash table
*/
static void shapr_expand_array(shared_heap* sheap,shapr_hash_t *ht){
shapr_hash_index_t *hi;
shapr_hash_entry_t **new_array;
unsigned int new_max;
new_max = ht->max * 2 + 1;
new_array = shapr_alloc_array(sheap,ht, new_max);
for (hi = shapr_hash_first(NULL, ht); hi; hi = shapr_hash_next(hi)) {
unsigned int i = hi->this->hash & new_max;
hi->this->next = new_array[i];
new_array[i] = hi->this;
}
ht->array = new_array;
ht->max = new_max;
}
void shapr_hash_set(shared_heap* sheap,shapr_hash_t *ht,const void *key,apr_ssize_t klen,const void *val){
shapr_hash_entry_t **hep;
if(key==NULL) return;
hep = shapr_find_entry(sheap,ht, key, klen, val);
if (*hep) {
if (!val) {
/* delete entry */
shapr_hash_entry_t *old = *hep;
*hep = (*hep)->next;
old->next = ht->free;
ht->free = old;
--ht->count;
}else {
/* replace entry */
(*hep)->val = val;
/* check that the collision rate isn't too high */
if (ht->count > ht->max) {
shapr_expand_array(sheap,ht);
}
}
}
/* else key not present and val==NULL */
}
void* shapr_hash_get(shapr_hash_t *ht,const void *key,apr_ssize_t klen){
shapr_hash_entry_t *he, **he_p;
he_p=shapr_find_entry(NULL,ht, key, klen, NULL);
he = *he_p;
if (he)
return (void *)he->val;
else
return NULL;
}
unsigned int shapr_hash_count(shapr_hash_t *ht){
return ht->count;
}
|
tarachandverma/ngx-openidc
|
src/template-core/template_engine.c
|
#include "template_engine.h"
#include "common_utils.h"
#include <apr_lib.h>
static int templatecore_templateCount(){
return sizeof(template_eng_templates)/sizeof(template_eng_template);
}
static template_eng_template* templatecore_findTemplate(char* id){
int x;
int len=templatecore_templateCount();
for(x=0;x<len;x++){
if(template_eng_templates[x].id!=NULL&&strcmp(template_eng_templates[x].id,id)==0){
return (template_eng_template*)&(template_eng_templates[x]);
}
}
return NULL;
}
template_engine* te_newEngineObj(shared_heap* sheap){
template_engine* ret=NULL;
ret=(template_engine*)shdata_shpcalloc(sheap,sizeof(template_engine));
ret->templateHash=shapr_hash_make(sheap);
return ret;
}
static template_eng_livetemplate* te_newLiveTemplate(shared_heap* sheap,template_eng_template* etemplate){
template_eng_livetemplate* ret=NULL;
ret=(template_eng_livetemplate*)shdata_shpcalloc(sheap,sizeof(template_eng_livetemplate));
ret->engineTemplate=etemplate;
return ret;
}
char* te_initialize(pool* p,shared_heap* sheap,cbs_globals* globals,template_engine* teng){
char* ret=NULL;
void* config=NULL;
int x=0;
template_eng_livetemplate* ltemplate=NULL;
int len=templatecore_templateCount();
for(x=0;x<len;x++){
ltemplate=te_newLiveTemplate(sheap,(template_eng_template*)&(template_eng_templates[x]));
//initialize template
if(template_eng_templates[x].initFunc!=NULL){
ret=(*template_eng_templates[x].initFunc)(p,sheap,globals,&config);
if(ret!=NULL){
return ret;
}
ltemplate->config=config;
}
//attach template to live template hash
if(teng!=NULL){
shapr_hash_set(sheap,teng->templateHash,template_eng_templates[x].id,APR_HASH_KEY_STRING,ltemplate);
}
}
return ret;
}
char* te_getToken(pool* p, template_engine* tengine,char* tid, char* src){
template_eng_livetemplate* ltemplate=NULL;
char* ret=NULL;
ltemplate=shapr_hash_get(tengine->templateHash,tid,APR_HASH_KEY_STRING);
if(ltemplate!=NULL&<emplate->engineTemplate!=NULL&<emplate->engineTemplate->tokenFunc!=NULL){
ret=(*ltemplate->engineTemplate->tokenFunc)(p,ltemplate->config,src);
}
return ret;
}
static int te_isToken(pool* p, char* token,template_engine* tengine){
shapr_hash_index_t* hi;
void* val, * key;
if(tengine!=NULL&&token!=NULL){
for(hi=shapr_hash_first(p,tengine->templateHash);hi;hi=shapr_hash_next(hi)){
shapr_hash_this(hi,(const void**)&key,NULL,&val);
if(strncmp(token,(char*)key,1)==0){
return 1;
}
}
}
return 0;
}
typedef struct template_token{
int num;
char* prefix;
char* postfix;
char* id;
} template_token;
static te_zeroToken(template_token* token){
token->num=-1;
token->prefix=NULL;
token->postfix=NULL;
token->id=NULL;
}
static char* te_append(pool* p, char* base, char* add1, char* add2){
char* ret=NULL;
if(base==NULL){
ret=apr_pstrcat(p,add1,add2,NULL);
}else{
ret=apr_pstrcat(p,base,add1,add2,NULL);
}
return ret;
}
static char* te_appendToken(pool* p, array_header* matches,char* base,char* space,template_token* token,template_engine* tengine){
char* ret=NULL;
char* el=NULL;
char* tmp=NULL;
int dlen=0;
if(matches!=NULL&&token!=NULL&&token->num>=0&&token->num<matches->nelts){
el=cu_getElement(matches,token->num);
if(token->id!=NULL){
el=te_getToken(p,tengine,token->id,el);
}
// if(token->urlEncode==1){
// dlen=(strlen(el)*3)+1;
// tmp=apr_pcalloc(p,dlen);
// url_encode(el,tmp,dlen);
// el=tmp;
// }else if (token->urlEncode==2){
// dlen=strlen(el)+1;
// tmp=apr_pcalloc(p,dlen);
// url_decode(el,tmp,dlen);
// el=tmp;
// }
}
if(token!=NULL){
ret=apr_pstrcat(p,SAFESTRBLANK(base),SAFESTRBLANK(space),SAFESTRBLANK(token->prefix),SAFESTRBLANK(el),SAFESTRBLANK(token->postfix),NULL);
}else{
ret=apr_pstrcat(p,SAFESTRBLANK(base),SAFESTRBLANK(space),NULL);
}
return ret;
}
char* te_templateString(pool* p,template_engine* tengine,char* sourcestr,array_header* matches){
char* ret=NULL;
char* num=NULL;
char code='\0';
template_token token;
char* match,*start=NULL, *str=NULL, *end=NULL,*begin=NULL,*cursor=NULL;
str=apr_pstrdup(p,sourcestr);
begin=str;
cursor=str;
match=strstr(begin,"($");
while(match!=NULL){
te_zeroToken(&token);
//find number
start=match+2;
end=start;
while(apr_isdigit(*end)){
end++;
}
if(*end==')'||*end=='^'||*end=='$' || te_isToken(p,end,tengine)){ ///replace with IS TOKEN FROM TOKEN ENGINE!!!
num=apr_pstrndup(p,start, (end-start));
token.num=atoi(num);
}
if(te_isToken(p,end,tengine)){
token.id=apr_pstrndup(p,end,1);
end++;
}
//get pre/postfix stuff
if(*end=='^'||*end=='$'){
code=*end;
start=end+1;
end=start;
while(*end!='\0'&&*end!=')'){
end++;
}
if(*end==')'){
if(code=='^'){
token.prefix=apr_pstrndup(p,start, (end-start));
}else if(code=='$'){
token.postfix=apr_pstrndup(p,start, (end-start));
}
}
}
if(*end==')'){
*match='\0';
if(matches!=NULL&&token.num<matches->nelts){
//do template
ret=te_appendToken(p,matches,ret,cursor,&token,tengine);
}else{
ret=te_appendToken(p,NULL,ret,cursor,NULL,tengine);
}
cursor=end+1;
}
begin=end+1;
match=strstr(begin,"($");
}
if(cursor!=NULL&&*cursor!='\0'){
ret=te_append(p,ret,cursor,NULL);
}
return ret;
}
|
tarachandverma/ngx-openidc
|
src/template-core/template_handler_url.c
|
<gh_stars>10-100
#include "template_handler_url.h"
#include "url_utils.h"
char* temphand_url_encodeToken(pool* p,void* config,char* src){
return url_encode2(p,src);
}
char* temphand_url_decodeToken(pool* p,void* config,char* src){
return url_decode2(p,src);
}
// base64 encode decode
char* temphand_base64_encodeToken(pool* p,void* config,char* src){
char encoded[2048];
if(src==NULL) return "(null)";
base64_encode(encoded, (char*)src, strlen(src));
return apr_pstrdup(p, encoded);
}
char* temphand_base64_decodeToken(pool* p,void* config,char* src){
char decoded[2048];
if(src==NULL) return "(null)";
base64_decode(decoded, (char*)src, strlen(src));
return apr_pstrdup(p, decoded);
}
|
gramado/miniyacc
|
y.tab.c
|
short yyini = 0;
short yyntoks = 83;
short yyr1[] = {
2, 1, 2, 1, 1, 1, 3, 1, 3, 1,
4, 3, 4, 3, 3, 2, 2, 1, 3, 1,
3, 1, 2, 2, 2, 2, 4, 1, 1, 1,
1, 1, 1, 1, 4, 1, 2, 1, 3, 3,
3, 1, 3, 3, 1, 3, 3, 1, 3, 3,
3, 3, 1, 3, 3, 1, 3, 1, 3, 1,
3, 1, 3, 1, 3, 1, 5, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
3, 1, 2, 1, 2, 1, 2, 1, 3, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 3,
2, 1, 1, 3, 4, 5, 4, 2, 4, 5,
2, 1, 1, 1, 2, 3, 2, 1, 2, 1,
1, 3, 1, 2, 3, 1, 3, 1, 3, 1,
2, 2, 3, 1, 3, 4, 3, 4, 4, 3,
1, 3, 1, 3, 1, 2, 1, 3, 2, 2,
1, 1, 1, 2, 3, 2, 3, 3, 4, 2,
3, 3, 4, 1, 3, 1, 1, 1, 1, 1,
1, 3, 4, 3, 2, 3, 3, 4, 1, 2,
5, 7, 5, 5, 7, 6, 7, 3, 2, 2,
2, 3, 1, 2, 1, 2, 1, 1, 4, 3,
3, 2
};
short yyr2[] = {
0, 1, 1, 2, 2, 2, 2, 3, 3, 4,
4, 4, 4, 4, 4, 4, 4, 5, 5, 6,
6, 7, 7, 7, 7, 7, 7, 8, 8, 8,
8, 8, 8, 9, 9, 10, 10, 11, 11, 11,
11, 12, 12, 12, 13, 13, 13, 14, 14, 14,
14, 14, 15, 15, 15, 16, 16, 17, 17, 18,
18, 19, 19, 20, 20, 21, 21, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 23, 24,
24, 25, 25, 25, 25, 25, 25, 26, 26, 27,
27, 27, 27, 27, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 29, 29, 30, 30,
31, 31, 32, 32, 32, 33, 33, 33, 34, 34,
34, 35, 35, 36, 36, 37, 38, 38, 38, 38,
39, 39, 40, 40, 40, 41, 41, 42, 42, 43,
43, 43, 43, 44, 44, 44, 44, 44, 44, 44,
45, 45, 46, 46, 47, 47, 48, 48, 49, 49,
49, 50, 50, 50, 51, 51, 51, 51, 51, 51,
51, 51, 51, 52, 52, 53, 53, 53, 53, 53,
53, 54, 54, 54, 55, 55, 55, 55, 56, 56,
57, 57, 57, 58, 58, 58, 58, 59, 59, 59,
59, 59, 60, 60, 61, 61, 62, 62, 63, 63,
63, 63
};
short yyadef[] = {
-1, -1, 0, 1, 2, 3, 3, 4, 5, -1,
-1, -1, -1, 6, 7, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 8, 9, 21, -1, 10,
-1, 11, -1, 12, -1, 13, -1, 14, 15, 16,
17, -1, 18, 19, 33, -1, 20, -1, 22, -1,
23, -1, 24, -1, 25, -1, 26, 27, 28, 29,
30, 31, 32, 33, -1, -1, 34, 35, 36, 37,
41, 42, 43, -1, 38, -1, 39, -1, 40, 44,
45, 46, -1, -1, 47, 48, 49, 50, 51, -1,
-1, 52, 53, 54, -1, -1, -1, -1, 55, 56,
-1, -1, 57, 58, -1, 59, 60, -1, 61, 62,
-1, 63, 64, -1, 65, -1, -1, -1, 66, 67,
68, 69, 70, 71, 72, 73, 74, 75, 76, 77,
78, -1, -1, 79, -1, 80, 81, 82, 83, 84,
85, 86, 87, -1, 88, 89, 90, 91, 92, 93,
94, 95, 96, 97, 98, 99, 100, 101, 102, 103,
104, 105, 106, 107, 108, 108, -1, 109, -1, 161,
110, 111, 112, -1, -1, 113, -1, 114, -1, 117,
-1, -1, 115, -1, -1, 116, -1, -1, -1, 118,
120, -1, -1, 119, 121, 122, 123, 124, -1, -1,
125, 127, 126, 129, 128, 130, -1, 131, 132, -1,
133, -1, 134, 135, -1, 136, 137, -1, 138, 139,
140, 141, 142, 143, -1, -1, -1, 144, -1, -1,
145, 146, -1, -1, 147, -1, 148, 149, 150, -1,
151, 152, -1, 153, 154, 155, 156, 157, 160, 158,
159, 161, 162, 163, -1, -1, 164, -1, 165, -1,
166, -1, 167, -1, 168, 169, -1, 170, -1, 171,
-1, 172, 173, 174, 175, 176, 177, 178, 179, 180,
-1, 181, -1, -1, -1, 182, -1, -1, 183, -1,
184, -1, 185, -1, 186, -1, 187, 188, 189, -1,
-1, -1, 190, -1, 191, -1, -1, -1, 192, -1,
-1, -1, 193, -1, -1, -1, -1, -1, 194, -1,
-1, -1, -1, -1, 195, -1, 196, -1, -1, 197,
-1, 198, -1, 199, -1, 200, 201, 202, 203, 204,
-1, -1, 205, 206, 207, 208, 209, -1, 210, 211
};
short yygdef[] = {
-1, 1, 26, 17, 27, 32, 14, 44, 51, 69,
55, 70, 79, 84, 91, 98, 102, 105, 108, 111,
114, 43, 45, 210, 339, 131, 134, 136, 138, 140,
142, 347, 167, 159, 160, 178, 181, 196, 198, 199,
205, 188, 213, 168, 171, 266, 235, 220, 238, 246,
255, 252, 174, 337, 274, 275, 276, 277, 278, 279,
291, 340, 3, 343
};
short yyadsp[] = {
447, 361, -83, -83, -83, -83, -19, -83, -83, 871,
139, 139, -15, -83, -83, -55, 55, -56, 14, 84,
106, 135, 137, 136, 871, -83, -83, 151, 871, -83,
495, -83, 155, -83, 62, -83, 114, -83, -83, -83,
-83, 871, -83, -83, 68, 871, -83, 883, -83, 883,
-83, 871, -83, 902, -83, 72, -83, -83, -83, -83,
-83, -83, -83, -83, 104, 871, -83, 101, -83, -83,
11, 11, 11, 871, -83, 871, -83, 871, -83, -6,
-6, -6, 871, 871, 194, 194, 194, 194, 194, 871,
871, 119, 119, 119, 871, 871, 871, 871, 216, 216,
871, 871, 96, 96, 871, 142, 142, 871, 180, 180,
871, 266, 266, 871, 148, 871, 871, 871, -83, -83,
-83, -83, -83, -83, -83, -83, -83, -83, -83, -83,
-83, 154, 154, -83, 181, -83, 620, -83, 620, -83,
620, -83, -83, 130, -83, -83, -83, -83, -83, -83,
-83, -83, -83, -83, -83, -83, -83, -83, -83, -83,
-83, -83, -83, -83, 204, 488, 715, -83, 247, 269,
185, 185, -83, 715, 217, -83, 668, -83, 246, 203,
670, -22, -83, 670, 650, -83, 254, 292, 300, -83,
215, 292, 301, -83, -83, -83, -83, -83, 152, 218,
-83, 670, -83, 670, -83, -83, 152, -83, 219, 871,
-83, 871, -83, -83, 292, -83, 239, 871, -83, 128,
128, -83, -83, -83, 130, 315, 260, -83, 738, 267,
-83, -83, 508, 271, -83, 231, -83, -83, 268, 544,
-83, -83, 332, -83, -83, -83, -83, -83, 93, -83,
-83, 233, 258, 258, 402, 274, -83, 750, -83, 276,
-83, 762, -83, 277, -83, -83, 280, -83, 565, -83,
303, -83, -83, -83, -83, -83, -83, -83, -83, -83,
256, -83, 871, 288, 256, -83, 289, 256, -83, -1,
-83, 184, -83, 69, -83, 220, -83, -83, -83, 309,
871, 256, 319, 256, -83, 311, 871, 256, -83, 312,
871, 256, -83, 256, 320, 314, 871, 297, -83, 321,
785, 785, 832, 256, -83, 256, -83, 377, 299, -83,
304, -83, 305, -83, 855, -83, -83, -83, -83, -83,
600, 600, -83, -83, -83, -83, -83, 600, -83, -83
};
short yygdsp[] = {
-350,-350,-350, 750,-350,-350, 955, 909,-350, 998,
375, 331, 326, 315, 317, 350, 349, 347, 345, 344,
-350, 766,-350, 841, 407, 915,-350,-350, 908, 884,
317, 814, 250,-350,-350,-350, 281, 268, 411,-350,
259, 275, 253, 782, 256, 187,-350,-350,-350, 230,
550, 446,-350, 734,-350, 454, 130,-350,-350,-350,
177, 164, 470,-350
};
short yyact[] = {
6, 7, 8, 53, 161, 47, 49, 29, 24, 24,
151, 152, 153, 154, 157, 158, 155, 156, 162, 163,
150, 194, 195, 186, 298, 161, 145, 146, 147, 148,
149, 151, 152, 153, 154, 157, 158, 155, 156, 162,
163, 150, 194, 195, 186, 13, 282, 286, 299, 24,
305, 309, 313, 319, 327, 330, 332, 334, 11, 280,
182, 82, 83, 35, 57, 58, 59, 60, 61, 62,
6, 7, 8, 53, 301, 47, 49, 73, 24, 297,
289, 290, 75, 77, 120, 121, 122, 123, 124, 125,
126, 127, 128, 129, 223, 161, 145, 146, 147, 148,
149, 151, 152, 153, 154, 157, 158, 155, 156, 162,
163, 150, 194, 195, 186, 37, 282, 286, 299, 24,
305, 309, 313, 319, 327, 330, 332, 334, 11, 96,
97, 223, 56, 117, 57, 58, 59, 60, 61, 62,
5, 7, 8, 53, 307, 47, 49, 119, 24, 297,
289, 294, 225, 223, 257, 223, 36, 38, 39, 219,
254, 104, 257, 115, 65, 161, 311, 219, 162, 163,
24, 151, 152, 153, 154, 157, 158, 155, 156, 162,
163, 150, 194, 195, 186, 6, 7, 8, 53, 224,
47, 49, 94, 95, 219, 317, 219, 325, 11, 24,
24, 24, 89, 90, 57, 58, 59, 60, 61, 62,
30, 224, 28, 224, 34, 33, 336, 107, 219, 41,
219, 6, 7, 8, 53, 116, 47, 49, 100, 101,
209, 282, 286, 299, 133, 305, 309, 313, 319, 327,
330, 332, 334, 11, 232, 143, 228, 179, 223, 57,
58, 59, 60, 61, 62, 190, 110, 6, 7, 8,
53, 135, 47, 49, 297, 289, 292, 282, 286, 299,
223, 305, 309, 313, 319, 327, 330, 332, 334, 11,
113, 176, 206, 166, 180, 57, 58, 59, 60, 61,
62, 236, 254, 216, 257, 242, 191, 211, 200, 175,
297, 289, 296, 282, 286, 299, 224, 305, 309, 313,
319, 327, 330, 332, 334, 11, 223, 268, 217, 261,
227, 57, 58, 59, 60, 61, 62, 183, 225, 230,
257, 234, 239, 243, 256, 187, 297, 289, 260, 264,
267, 161, 145, 146, 147, 148, 149, 151, 152, 153,
154, 157, 158, 155, 156, 162, 163, 150, 194, 195,
186, 2, 223, 271, 214, 214, 284, 287, 300, 303,
306, 310, 315, 316, 225, 265, 257, 318, 328, 329,
320, 219, 189, 193, 331, 333, 64, 161, 145, 146,
147, 148, 149, 151, 152, 153, 154, 157, 158, 155,
156, 162, 163, 150, 194, 195, 186, 344, 344, 85,
86, 87, 88, 71, 72, 80, 81, 92, 93, 233,
224, 67, 67, 272, 170, 170, 273, 219, 161, 145,
146, 147, 148, 149, 151, 152, 153, 154, 157, 158,
155, 156, 162, 163, 150, 194, 195, 186, 223, 197,
321, 322, 197, 293, 99, 270, 103, 106, 109, 112,
144, 254, 265, 257, 184, 207, 192, 215, 219, 247,
295, 4, -1, 161, 145, 146, 147, 148, 149, 151,
152, 153, 154, 157, 158, 155, 156, 162, 163, 150,
194, 195, 186, -1, -1, -1, 5, 7, 8, 53,
-1, 47, 49, -1, -1, -1, 224, -1, -1, 241,
-1, 341, -1, 219, 161, 145, 146, 147, 148, 149,
151, 152, 153, 154, 157, 158, 155, 156, 162, 163,
150, 194, 195, 186, 161, 145, 146, 147, 148, 149,
151, 152, 153, 154, 157, 158, 155, 156, 162, 163,
150, 194, 195, 186, 11, 31, -1, -1, -1, -1,
57, 58, 59, 60, 61, 62, -1, 166, 237, 289,
161, 145, 146, 147, 148, 149, 151, 152, 153, 154,
157, 158, 155, 156, 162, 163, 150, 194, 195, 186,
240, 161, 145, 146, 147, 148, 149, 151, 152, 153,
154, 157, 158, 155, 156, 162, 163, 150, 194, 195,
186, -1, 202, -1, 204, 253, -1, 68, -1, 346,
-1, -1, -1, -1, -1, 269, 161, 145, 146, 147,
148, 149, 151, 152, 153, 154, 157, 158, 155, 156,
162, 163, 150, 194, 195, 186, 161, 145, 146, 147,
148, 149, 151, 152, 153, 154, 157, 158, 155, 156,
162, 163, 150, 194, 195, 186, -1, -1, -1, 5,
7, 8, 53, -1, 47, 49, 161, -1, -1, -1,
-1, 289, 151, 152, 153, 154, 157, 158, 155, 156,
162, 163, 150, 194, 195, 186, 161, 253, -1, -1,
342, -1, 151, 152, 153, 154, 157, 158, 155, 156,
162, 163, 150, 194, 195, 186, 5, 7, 8, 53,
-1, 47, 49, -1, -1, -1, -1, 11, -1, -1,
-1, -1, 185, 57, 58, 59, 60, 61, 62, 5,
7, 8, 53, -1, 47, 49, -1, 342, 342, 173,
177, 5, 7, 8, 53, -1, 47, 49, -1, 12,
12, 12, -1, 5, 7, 8, 53, -1, 47, 49,
-1, -1, -1, -1, 11, -1, -1, -1, 15, -1,
57, 58, 59, 60, 61, 62, 5, 7, 8, 53,
-1, 47, 49, -1, 345, 348, 173, 11, 250, -1,
231, 349, -1, 57, 58, 59, 60, 61, 62, 11,
-1, -1, 258, -1, -1, 57, 58, 59, 60, 61,
62, 11, -1, -1, 262, -1, -1, 57, 58, 59,
60, 61, 62, 5, 7, 8, 53, -1, 47, 49,
-1, -1, -1, -1, 11, -1, -1, -1, -1, 251,
57, 58, 59, 60, 61, 62, 5, 7, 8, 53,
-1, 47, 49, -1, -1, 297, 16, -1, -1, -1,
-1, -1, 5, 7, 8, 53, -1, 47, 49, -1,
-1, -1, -1, 118, 5, 7, 8, 53, -1, 47,
49, 11, 323, -1, 203, 203, -1, 57, 58, 59,
60, 61, 62, 5, 7, 8, 53, -1, 47, 49,
-1, -1, -1, -1, 11, 132, 132, -1, 201, 201,
57, 58, 59, 60, 61, 62, -1, -1, -1, -1,
11, -1, -1, -1, -1, 335, 57, 58, 59, 60,
61, 62, 9, -1, -1, 164, 165, -1, 57, 58,
59, 60, 61, 62, -1, -1, 48, 164, 50, -1,
63, 10, 54, -1, -1, -1, -1, 57, 58, 59,
60, 61, 62, -1, 63, 130, -1, 130, -1, 25,
-1, -1, 63, 130, 63, 40, 63, -1, -1, -1,
-1, 63, 63, -1, 130, -1, 42, -1, 63, 63,
46, 221, 222, 63, 63, 63, 63, 169, -1, 63,
63, -1, 208, 63, 281, -1, 63, -1, 285, 63,
208, 288, 63, 130, 63, 338, 63, 130, -1, 338,
169, -1, -1, -1, -1, 302, 251, 304, 226, 226,
-1, 308, -1, -1, -1, 312, -1, 314, 130, 52,
18, 137, 212, 139, -1, 141, 19, 324, 218, 326,
20, -1, 249, 66, 203, 203, 21, 203, 203, 229,
-1, 74, 22, 76, -1, 78, -1, -1, -1, -1,
-1, -1, -1, -1, 23, 203, -1, 203, 201, 201,
-1, 201, 201, -1, -1, -1, -1, -1, 259, -1,
-1, -1, 263, 244, 245, -1, -1, -1, -1, 201,
-1, 201, -1, -1, -1, -1, -1, -1, 63, -1,
63, 172, -1, 283, -1, -1, 63, -1, 172, -1,
-1, 172, -1, -1, -1, -1, -1, 63, -1, -1,
248, -1, -1, -1, -1, -1, -1, 248, -1, -1,
-1, -1, -1, -1, 248, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, 63, -1, -1, 248,
63, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 248, -1, -1, -1, -1, -1, -1,
-1, 63
};
short yychk[] = {
1, 2, 3, 4, 26, 6, 7, 62, 64, 64,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
42, 43, 44, 45, 80, 26, 27, 28, 29, 30,
31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 60, 47, 48, 49, 64,
51, 52, 53, 54, 55, 56, 57, 58, 59, 78,
82, 67, 68, 1, 65, 66, 67, 68, 69, 70,
1, 2, 3, 4, 60, 6, 7, 66, 64, 80,
81, 82, 71, 72, 16, 17, 18, 19, 20, 21,
22, 23, 24, 25, 1, 26, 27, 28, 29, 30,
31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 1, 47, 48, 49, 64,
51, 52, 53, 54, 55, 56, 57, 58, 59, 10,
11, 1, 60, 78, 65, 66, 67, 68, 69, 70,
1, 2, 3, 4, 60, 6, 7, 79, 64, 80,
81, 82, 59, 1, 61, 1, 5, 6, 7, 66,
59, 65, 61, 15, 60, 26, 60, 66, 40, 41,
64, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 1, 2, 3, 4, 59,
6, 7, 73, 74, 66, 60, 66, 60, 59, 64,
64, 64, 8, 9, 65, 66, 67, 68, 69, 70,
59, 59, 61, 59, 63, 60, 80, 75, 66, 64,
66, 1, 2, 3, 4, 77, 6, 7, 12, 13,
78, 47, 48, 49, 80, 51, 52, 53, 54, 55,
56, 57, 58, 59, 59, 64, 61, 1, 1, 65,
66, 67, 68, 69, 70, 1, 76, 1, 2, 3,
4, 80, 6, 7, 80, 81, 82, 47, 48, 49,
1, 51, 52, 53, 54, 55, 56, 57, 58, 59,
14, 64, 64, 79, 81, 65, 66, 67, 68, 69,
70, 60, 59, 1, 61, 64, 81, 78, 80, 82,
80, 81, 82, 47, 48, 49, 59, 51, 52, 53,
54, 55, 56, 57, 58, 59, 1, 59, 79, 61,
60, 65, 66, 67, 68, 69, 70, 81, 59, 62,
61, 60, 64, 1, 60, 81, 80, 81, 62, 62,
60, 26, 27, 28, 29, 30, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
45, 0, 1, 60, 64, 64, 78, 78, 59, 50,
59, 59, 52, 59, 59, 60, 61, 80, 1, 80,
59, 66, 82, 82, 80, 80, 93, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
39, 40, 41, 42, 43, 44, 45, 107, 107, 96,
96, 96, 96, 94, 94, 95, 95, 97, 97, 128,
59, 121, 121, 115, 127, 127, 115, 66, 26, 27,
28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
38, 39, 40, 41, 42, 43, 44, 45, 1, 120,
139, 139, 120, 144, 98, 128, 99, 100, 101, 102,
113, 59, 60, 61, 119, 123, 124, 125, 66, 132,
143, 145, -1, 26, 27, 28, 29, 30, 31, 32,
33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
43, 44, 45, -1, -1, -1, 1, 2, 3, 4,
-1, 6, 7, -1, -1, -1, 59, -1, -1, 1,
-1, 144, -1, 66, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
42, 43, 44, 45, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
42, 43, 44, 45, 59, 60, -1, -1, -1, -1,
65, 66, 67, 68, 69, 70, -1, 79, 60, 81,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
36, 37, 38, 39, 40, 41, 42, 43, 44, 45,
46, 26, 27, 28, 29, 30, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
45, -1, 121, -1, 121, 134, -1, 133, -1, 138,
-1, -1, -1, -1, -1, 60, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, -1, -1, -1, 1,
2, 3, 4, -1, 6, 7, 26, -1, -1, -1,
-1, 81, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 26, 134, -1, -1,
107, -1, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 1, 2, 3, 4,
-1, 6, 7, -1, -1, -1, -1, 59, -1, -1,
-1, -1, 82, 65, 66, 67, 68, 69, 70, 1,
2, 3, 4, -1, 6, 7, -1, 107, 107, 81,
82, 1, 2, 3, 4, -1, 6, 7, -1, 86,
86, 86, -1, 1, 2, 3, 4, -1, 6, 7,
-1, -1, -1, -1, 59, -1, -1, -1, 86, -1,
65, 66, 67, 68, 69, 70, 1, 2, 3, 4,
-1, 6, 7, -1, 138, 138, 81, 59, 133, -1,
62, 138, -1, 65, 66, 67, 68, 69, 70, 59,
-1, -1, 62, -1, -1, 65, 66, 67, 68, 69,
70, 59, -1, -1, 62, -1, -1, 65, 66, 67,
68, 69, 70, 1, 2, 3, 4, -1, 6, 7,
-1, -1, -1, -1, 59, -1, -1, -1, -1, 126,
65, 66, 67, 68, 69, 70, 1, 2, 3, 4,
-1, 6, 7, -1, -1, 80, 86, -1, -1, -1,
-1, -1, 1, 2, 3, 4, -1, 6, 7, -1,
-1, -1, -1, 104, 1, 2, 3, 4, -1, 6,
7, 59, 60, -1, 112, 112, -1, 65, 66, 67,
68, 69, 70, 1, 2, 3, 4, -1, 6, 7,
-1, -1, -1, -1, 59, 108, 108, -1, 111, 111,
65, 66, 67, 68, 69, 70, -1, -1, -1, -1,
59, -1, -1, -1, -1, 80, 65, 66, 67, 68,
69, 70, 59, -1, -1, 114, 114, -1, 65, 66,
67, 68, 69, 70, -1, -1, 90, 114, 90, -1,
90, 59, 90, -1, -1, -1, -1, 65, 66, 67,
68, 69, 70, -1, 90, 104, -1, 104, -1, 89,
-1, -1, 90, 104, 90, 89, 90, -1, -1, -1,
-1, 90, 90, -1, 104, -1, 89, -1, 90, 90,
89, 126, 126, 90, 90, 90, 90, 126, -1, 90,
90, -1, 114, 90, 136, -1, 90, -1, 136, 90,
114, 136, 90, 104, 90, 136, 90, 104, -1, 136,
126, -1, -1, -1, -1, 136, 126, 136, 114, 114,
-1, 136, -1, -1, -1, 136, -1, 136, 104, 92,
86, 108, 106, 108, -1, 108, 86, 136, 106, 136,
86, -1, 114, 92, 112, 112, 86, 112, 112, 106,
-1, 92, 86, 92, -1, 92, -1, -1, -1, -1,
-1, -1, -1, -1, 86, 112, -1, 112, 111, 111,
-1, 111, 111, -1, -1, -1, -1, -1, 106, -1,
-1, -1, 106, 112, 112, -1, -1, -1, -1, 111,
-1, 111, -1, -1, -1, -1, -1, -1, 90, -1,
90, 89, -1, 106, -1, -1, 90, -1, 89, -1,
-1, 89, -1, -1, -1, -1, -1, 90, -1, -1,
108, -1, -1, -1, -1, -1, -1, 108, -1, -1,
-1, -1, -1, -1, 108, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, 90, -1, -1, 108,
90, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 108, -1, -1, -1, -1, -1, -1,
-1, 90
};
#define IDENTIFIER 128
#define CONSTANT 129
#define STRING_LITERAL 130
#define SIZEOF 131
#define PTR_OP 132
#define INC_OP 133
#define DEC_OP 134
#define LEFT_OP 135
#define RIGHT_OP 136
#define LE_OP 137
#define GE_OP 138
#define EQ_OP 139
#define NE_OP 140
#define AND_OP 141
#define OR_OP 142
#define MUL_ASSIGN 143
#define DIV_ASSIGN 144
#define MOD_ASSIGN 145
#define ADD_ASSIGN 146
#define SUB_ASSIGN 147
#define LEFT_ASSIGN 148
#define RIGHT_ASSIGN 149
#define AND_ASSIGN 150
#define XOR_ASSIGN 151
#define OR_ASSIGN 152
#define TYPE_NAME 153
#define TYPEDEF 154
#define EXTERN 155
#define STATIC 156
#define AUTO 157
#define REGISTER 158
#define CHAR 159
#define SHORT 160
#define INT 161
#define LONG 162
#define SIGNED 163
#define UNSIGNED 164
#define FLOAT 165
#define DOUBLE 166
#define CONST 167
#define VOLATILE 168
#define VOID 169
#define STRUCT 170
#define UNION 171
#define ENUM 172
#define ELLIPSIS 173
#define CASE 174
#define DEFAULT 175
#define IF 176
#define ELSE 177
#define SWITCH 178
#define WHILE 179
#define DO 180
#define FOR 181
#define GOTO 182
#define CONTINUE 183
#define BREAK 184
#define RETURN 185
short yytrns[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 70, 0, 0, 0, 72, 65, 0,
59, 60, 66, 67, 64, 68, 63, 71, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 78, 80,
73, 79, 74, 77, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 61, 0, 62, 75, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 81, 76, 82, 69, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
53, 54, 55, 56, 57, 58
};
#ifndef YYSTYPE
#define YYSTYPE int
#endif
YYSTYPE yylval;
int
yyparse()
{
enum {
StackSize = 100,
ActSz = sizeof yyact / sizeof yyact[0],
};
struct {
YYSTYPE val;
int state;
} stk[StackSize], *ps;
int r, h, n, s, tk;
YYSTYPE yyval;
ps = stk;
ps->state = s = yyini;
tk = -1;
loop:
n = yyadsp[s];
if (tk < 0 && n > -yyntoks)
tk = yytrns[yylex()];
n += tk;
if (n < 0 || n >= ActSz || yychk[n] != tk) {
r = yyadef[s];
if (r < 0)
return -1;
goto reduce;
}
n = yyact[n];
if (n == -1)
return -1;
if (n < 0) {
r = - (n+2);
goto reduce;
}
tk = -1;
yyval = yylval;
stack:
ps++;
if (ps-stk >= StackSize)
return -2;
s = n;
ps->state = s;
ps->val = yyval;
goto loop;
reduce:
ps -= yyr1[r];
h = yyr2[r];
s = ps->state;
n = yygdsp[h] + s;
if (n < 0 || n >= ActSz || yychk[n] != yyntoks+h)
n = yygdef[h];
else
n = yyact[n];
switch (r) {
case 0:
#line 0 "testfiles/c89.y"
yyval = ps[1].val; return 0;
break;
case 1:
#line 0 "testfiles/c89.y"
break;
case 2:
#line 0 "testfiles/c89.y"
break;
case 3:
#line 0 "testfiles/c89.y"
break;
case 4:
#line 0 "testfiles/c89.y"
break;
case 5:
#line 0 "testfiles/c89.y"
break;
case 6:
#line 0 "testfiles/c89.y"
break;
case 7:
#line 0 "testfiles/c89.y"
break;
case 8:
#line 0 "testfiles/c89.y"
break;
case 9:
#line 0 "testfiles/c89.y"
break;
case 10:
#line 0 "testfiles/c89.y"
break;
case 11:
#line 0 "testfiles/c89.y"
break;
case 12:
#line 0 "testfiles/c89.y"
break;
case 13:
#line 0 "testfiles/c89.y"
break;
case 14:
#line 0 "testfiles/c89.y"
break;
case 15:
#line 0 "testfiles/c89.y"
break;
case 16:
#line 0 "testfiles/c89.y"
break;
case 17:
#line 0 "testfiles/c89.y"
break;
case 18:
#line 0 "testfiles/c89.y"
break;
case 19:
#line 0 "testfiles/c89.y"
break;
case 20:
#line 0 "testfiles/c89.y"
break;
case 21:
#line 0 "testfiles/c89.y"
break;
case 22:
#line 0 "testfiles/c89.y"
break;
case 23:
#line 0 "testfiles/c89.y"
break;
case 24:
#line 0 "testfiles/c89.y"
break;
case 25:
#line 0 "testfiles/c89.y"
break;
case 26:
#line 0 "testfiles/c89.y"
break;
case 27:
#line 0 "testfiles/c89.y"
break;
case 28:
#line 0 "testfiles/c89.y"
break;
case 29:
#line 0 "testfiles/c89.y"
break;
case 30:
#line 0 "testfiles/c89.y"
break;
case 31:
#line 0 "testfiles/c89.y"
break;
case 32:
#line 0 "testfiles/c89.y"
break;
case 33:
#line 0 "testfiles/c89.y"
break;
case 34:
#line 0 "testfiles/c89.y"
break;
case 35:
#line 0 "testfiles/c89.y"
break;
case 36:
#line 0 "testfiles/c89.y"
break;
case 37:
#line 0 "testfiles/c89.y"
break;
case 38:
#line 0 "testfiles/c89.y"
break;
case 39:
#line 0 "testfiles/c89.y"
break;
case 40:
#line 0 "testfiles/c89.y"
break;
case 41:
#line 0 "testfiles/c89.y"
break;
case 42:
#line 0 "testfiles/c89.y"
break;
case 43:
#line 0 "testfiles/c89.y"
break;
case 44:
#line 0 "testfiles/c89.y"
break;
case 45:
#line 0 "testfiles/c89.y"
break;
case 46:
#line 0 "testfiles/c89.y"
break;
case 47:
#line 0 "testfiles/c89.y"
break;
case 48:
#line 0 "testfiles/c89.y"
break;
case 49:
#line 0 "testfiles/c89.y"
break;
case 50:
#line 0 "testfiles/c89.y"
break;
case 51:
#line 0 "testfiles/c89.y"
break;
case 52:
#line 0 "testfiles/c89.y"
break;
case 53:
#line 0 "testfiles/c89.y"
break;
case 54:
#line 0 "testfiles/c89.y"
break;
case 55:
#line 0 "testfiles/c89.y"
break;
case 56:
#line 0 "testfiles/c89.y"
break;
case 57:
#line 0 "testfiles/c89.y"
break;
case 58:
#line 0 "testfiles/c89.y"
break;
case 59:
#line 0 "testfiles/c89.y"
break;
case 60:
#line 0 "testfiles/c89.y"
break;
case 61:
#line 0 "testfiles/c89.y"
break;
case 62:
#line 0 "testfiles/c89.y"
break;
case 63:
#line 0 "testfiles/c89.y"
break;
case 64:
#line 0 "testfiles/c89.y"
break;
case 65:
#line 0 "testfiles/c89.y"
break;
case 66:
#line 0 "testfiles/c89.y"
break;
case 67:
#line 0 "testfiles/c89.y"
break;
case 68:
#line 0 "testfiles/c89.y"
break;
case 69:
#line 0 "testfiles/c89.y"
break;
case 70:
#line 0 "testfiles/c89.y"
break;
case 71:
#line 0 "testfiles/c89.y"
break;
case 72:
#line 0 "testfiles/c89.y"
break;
case 73:
#line 0 "testfiles/c89.y"
break;
case 74:
#line 0 "testfiles/c89.y"
break;
case 75:
#line 0 "testfiles/c89.y"
break;
case 76:
#line 0 "testfiles/c89.y"
break;
case 77:
#line 0 "testfiles/c89.y"
break;
case 78:
#line 0 "testfiles/c89.y"
break;
case 79:
#line 0 "testfiles/c89.y"
break;
case 80:
#line 0 "testfiles/c89.y"
break;
case 81:
#line 0 "testfiles/c89.y"
break;
case 82:
#line 0 "testfiles/c89.y"
break;
case 83:
#line 0 "testfiles/c89.y"
break;
case 84:
#line 0 "testfiles/c89.y"
break;
case 85:
#line 0 "testfiles/c89.y"
break;
case 86:
#line 0 "testfiles/c89.y"
break;
case 87:
#line 0 "testfiles/c89.y"
break;
case 88:
#line 0 "testfiles/c89.y"
break;
case 89:
#line 0 "testfiles/c89.y"
break;
case 90:
#line 0 "testfiles/c89.y"
break;
case 91:
#line 0 "testfiles/c89.y"
break;
case 92:
#line 0 "testfiles/c89.y"
break;
case 93:
#line 0 "testfiles/c89.y"
break;
case 94:
#line 0 "testfiles/c89.y"
break;
case 95:
#line 0 "testfiles/c89.y"
break;
case 96:
#line 0 "testfiles/c89.y"
break;
case 97:
#line 0 "testfiles/c89.y"
break;
case 98:
#line 0 "testfiles/c89.y"
break;
case 99:
#line 0 "testfiles/c89.y"
break;
case 100:
#line 0 "testfiles/c89.y"
break;
case 101:
#line 0 "testfiles/c89.y"
break;
case 102:
#line 0 "testfiles/c89.y"
break;
case 103:
#line 0 "testfiles/c89.y"
break;
case 104:
#line 0 "testfiles/c89.y"
break;
case 105:
#line 0 "testfiles/c89.y"
break;
case 106:
#line 0 "testfiles/c89.y"
break;
case 107:
#line 0 "testfiles/c89.y"
break;
case 108:
#line 0 "testfiles/c89.y"
break;
case 109:
#line 0 "testfiles/c89.y"
break;
case 110:
#line 0 "testfiles/c89.y"
break;
case 111:
#line 0 "testfiles/c89.y"
break;
case 112:
#line 0 "testfiles/c89.y"
break;
case 113:
#line 0 "testfiles/c89.y"
break;
case 114:
#line 0 "testfiles/c89.y"
break;
case 115:
#line 0 "testfiles/c89.y"
break;
case 116:
#line 0 "testfiles/c89.y"
break;
case 117:
#line 0 "testfiles/c89.y"
break;
case 118:
#line 0 "testfiles/c89.y"
break;
case 119:
#line 0 "testfiles/c89.y"
break;
case 120:
#line 0 "testfiles/c89.y"
break;
case 121:
#line 0 "testfiles/c89.y"
break;
case 122:
#line 0 "testfiles/c89.y"
break;
case 123:
#line 0 "testfiles/c89.y"
break;
case 124:
#line 0 "testfiles/c89.y"
break;
case 125:
#line 0 "testfiles/c89.y"
break;
case 126:
#line 0 "testfiles/c89.y"
break;
case 127:
#line 0 "testfiles/c89.y"
break;
case 128:
#line 0 "testfiles/c89.y"
break;
case 129:
#line 0 "testfiles/c89.y"
break;
case 130:
#line 0 "testfiles/c89.y"
break;
case 131:
#line 0 "testfiles/c89.y"
break;
case 132:
#line 0 "testfiles/c89.y"
break;
case 133:
#line 0 "testfiles/c89.y"
break;
case 134:
#line 0 "testfiles/c89.y"
break;
case 135:
#line 0 "testfiles/c89.y"
break;
case 136:
#line 0 "testfiles/c89.y"
break;
case 137:
#line 0 "testfiles/c89.y"
break;
case 138:
#line 0 "testfiles/c89.y"
break;
case 139:
#line 0 "testfiles/c89.y"
break;
case 140:
#line 0 "testfiles/c89.y"
break;
case 141:
#line 0 "testfiles/c89.y"
break;
case 142:
#line 0 "testfiles/c89.y"
break;
case 143:
#line 0 "testfiles/c89.y"
break;
case 144:
#line 0 "testfiles/c89.y"
break;
case 145:
#line 0 "testfiles/c89.y"
break;
case 146:
#line 0 "testfiles/c89.y"
break;
case 147:
#line 0 "testfiles/c89.y"
break;
case 148:
#line 0 "testfiles/c89.y"
break;
case 149:
#line 0 "testfiles/c89.y"
break;
case 150:
#line 0 "testfiles/c89.y"
break;
case 151:
#line 0 "testfiles/c89.y"
break;
case 152:
#line 0 "testfiles/c89.y"
break;
case 153:
#line 0 "testfiles/c89.y"
break;
case 154:
#line 0 "testfiles/c89.y"
break;
case 155:
#line 0 "testfiles/c89.y"
break;
case 156:
#line 0 "testfiles/c89.y"
break;
case 157:
#line 0 "testfiles/c89.y"
break;
case 158:
#line 0 "testfiles/c89.y"
break;
case 159:
#line 0 "testfiles/c89.y"
break;
case 160:
#line 0 "testfiles/c89.y"
break;
case 161:
#line 0 "testfiles/c89.y"
break;
case 162:
#line 0 "testfiles/c89.y"
break;
case 163:
#line 0 "testfiles/c89.y"
break;
case 164:
#line 0 "testfiles/c89.y"
break;
case 165:
#line 0 "testfiles/c89.y"
break;
case 166:
#line 0 "testfiles/c89.y"
break;
case 167:
#line 0 "testfiles/c89.y"
break;
case 168:
#line 0 "testfiles/c89.y"
break;
case 169:
#line 0 "testfiles/c89.y"
break;
case 170:
#line 0 "testfiles/c89.y"
break;
case 171:
#line 0 "testfiles/c89.y"
break;
case 172:
#line 0 "testfiles/c89.y"
break;
case 173:
#line 0 "testfiles/c89.y"
break;
case 174:
#line 0 "testfiles/c89.y"
break;
case 175:
#line 0 "testfiles/c89.y"
break;
case 176:
#line 0 "testfiles/c89.y"
break;
case 177:
#line 0 "testfiles/c89.y"
break;
case 178:
#line 0 "testfiles/c89.y"
break;
case 179:
#line 0 "testfiles/c89.y"
break;
case 180:
#line 0 "testfiles/c89.y"
break;
case 181:
#line 0 "testfiles/c89.y"
break;
case 182:
#line 0 "testfiles/c89.y"
break;
case 183:
#line 0 "testfiles/c89.y"
break;
case 184:
#line 0 "testfiles/c89.y"
break;
case 185:
#line 0 "testfiles/c89.y"
break;
case 186:
#line 0 "testfiles/c89.y"
break;
case 187:
#line 0 "testfiles/c89.y"
break;
case 188:
#line 0 "testfiles/c89.y"
break;
case 189:
#line 0 "testfiles/c89.y"
break;
case 190:
#line 0 "testfiles/c89.y"
break;
case 191:
#line 0 "testfiles/c89.y"
break;
case 192:
#line 0 "testfiles/c89.y"
break;
case 193:
#line 0 "testfiles/c89.y"
break;
case 194:
#line 0 "testfiles/c89.y"
break;
case 195:
#line 0 "testfiles/c89.y"
break;
case 196:
#line 0 "testfiles/c89.y"
break;
case 197:
#line 0 "testfiles/c89.y"
break;
case 198:
#line 0 "testfiles/c89.y"
break;
case 199:
#line 0 "testfiles/c89.y"
break;
case 200:
#line 0 "testfiles/c89.y"
break;
case 201:
#line 0 "testfiles/c89.y"
break;
case 202:
#line 0 "testfiles/c89.y"
break;
case 203:
#line 0 "testfiles/c89.y"
break;
case 204:
#line 0 "testfiles/c89.y"
break;
case 205:
#line 0 "testfiles/c89.y"
break;
case 206:
#line 0 "testfiles/c89.y"
break;
case 207:
#line 0 "testfiles/c89.y"
break;
case 208:
#line 0 "testfiles/c89.y"
break;
case 209:
#line 0 "testfiles/c89.y"
break;
case 210:
#line 0 "testfiles/c89.y"
break;
case 211:
#line 0 "testfiles/c89.y"
break;
}
goto stack;
}
#line 417 "testfiles/c89.y"
#include <stdio.h>
extern char yytext[];
extern int column;
yyerror(s)
char *s;
{
fflush(stdout);
printf("\n%*s\n%*s\n", column, "^", column, s);
}
|
DieracDelta/cbat_tools
|
wp/resources/sample_binaries/nested_ifs/main.c
|
<gh_stars>0
#include <assert.h>
#include <stdlib.h>
#define STRING_MAX 10
void gotoExample()
{
char *string1, *string2, *string3, *string4, *string5;
if ( !(string1 = (char*) calloc(STRING_MAX, sizeof(char))) )
goto gotoExample_string1;
if ( !(string2 = (char*) calloc(STRING_MAX, sizeof(char))) )
goto gotoExample_string2;
if ( !(string3 = (char*) calloc(STRING_MAX, sizeof(char))) )
goto gotoExample_string3;
if ( !(string4 = (char*) calloc(STRING_MAX, sizeof(char))) )
goto gotoExample_string4;
if ( !(string5 = (char*) calloc(STRING_MAX, sizeof(char))) )
goto gotoExample_string5;
//important code goes here
assert(string1 && string2 && string3 && string4 && string5);
gotoExample_string5:
free(string5);
gotoExample_string4:
free(string4);
gotoExample_string3:
free(string3);
gotoExample_string2:
free(string2);
gotoExample_string1:
free(string1);
}
void nestedIfExample()
{
char *string1, *string2, *string3, *string4, *string5;
if (string1 = (char*) calloc(STRING_MAX, sizeof(char)))
{
if (string2 = (char*) calloc(STRING_MAX, sizeof(char)))
{
if (string3 = (char*) calloc(STRING_MAX, sizeof(char)))
{
if (string4 = (char*) calloc(STRING_MAX, sizeof(char)))
{
if (string5 = (char*) calloc(STRING_MAX, sizeof(char)))
{
//important code here
assert(string1
&& string2
&& string3
&& string4
&& string5);
free(string5);
}
free(string4);
}
free(string3);
}
free(string2);
}
free(string1);
}
}
int main(int argc, char* argv[])
{
nestedIfExample();
gotoExample();
return 0;
}
|
DieracDelta/cbat_tools
|
wp/resources/sample_binaries/equiv_null_check/main_2.c
|
<reponame>DieracDelta/cbat_tools<gh_stars>0
#include<stdlib.h>
#include<assert.h>
int main(void) {
char * p = malloc(10);
if( p == NULL ) assert(0);
* (p + 3) = 0;
return * (p + 3);
}
|
onea7351/hackingtober
|
largest_of_three.c
|
<filename>largest_of_three.c
# Python program to find the largest number among the three input numbers
# take three numbers from user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
if (num1 > num2) and (num1 > num3):
largest = num1
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3
print("The largest number is",largest)
|
Made4Dev/SFBL
|
sfbl.h
|
<reponame>Made4Dev/SFBL
#ifndef SFBL_H
#define SFBL_H
#include <Box2D\Box2D.h>
#include <iostream>
#include <SFML\Graphics.hpp>
#include <SFML\OpenGL.hpp>
#include <functional>
#define MIN_RAYS 3
#define MAX_RAYS 0xFFFF // 65535
class RaysCastCallback : public b2RayCastCallback
{
public:
RaysCastCallback(b2Vec2 startPoint) : m_hit(false), startPoint(startPoint){
}
float32 ReportFixture(b2Fixture*, const b2Vec2& point, const b2Vec2&, float32 fraction) {
float dist = b2Distance(startPoint, point);
if(dist > this->dist){// get the farthest intersection point
this->dist = dist;
m_point = point;
m_fraction = fraction;
m_hit = true;
}
return 1;// keep going to get all intersection points
}
bool m_hit;
b2Vec2 m_point;
float32 m_fraction;
private:
b2Vec2 startPoint;
float dist = 0.0f;
};
namespace sfbl{
struct Light{
Light(float radius, sf::Vector2f position, sf::Color color){
this->radius = radius;
this->position = position;
this->color = color;
}
float radius;
sf::Vector2f position;
sf::Color color;
};
class WorldLight
{
public:
///add movable PointLight
///\param pointer to the specific light
///\param number of rays
void addAsPointLight(Light*light, sf::Uint16 rays);
/// add static PointLight
///\param number of rays
///\param radius of light
///\param position of light
///\param color of light
void addAsPointLight(sf::Uint16 rays, float radius, sf::Vector2f position, sf::Color color);
/// add movable SpotLight
///\param pointer to the specific light
///\param number of rays
void addAsSpotLight(Light*light, sf::Uint16 rays);
/// add static SpotLight
///\param number of rays
///\param radius of light
///\param position of light
///\param color of light
void addAsSpotLight(sf::Uint16 rays, float radius, sf::Vector2f position, sf::Color color);
///add movable ConeLight
///\param pointer to the specific light
///\param number of rays
///\param cutOffAngle in degres
///\param rotation in degres
void addAsConeLight(Light*light, sf::Uint16 rays, float cutOffAngle, float rotation);
///add static ConeLight
///\param number of rays
///\param cutOffAngle in degres
///\param rotation in degres
///\param radius of light
///\param position of light
///\param color of light
void addAsConeLight(sf::Uint16 rays, float cutOffAngle, float rotation, float radius, sf::Vector2f position, sf::Color color);
/// apply the params that you've changed manually
void updatePointLight(Light*light);
/// apply the params that you've changed manually
void updateSpotLight(Light*light);
/// apply the params that you've changed manually
void updateConeLight(Light*light, float cutOffAngle, float rotation);
/// update and render lights
void updateNrender();
/// update lights
void update();
/// render lights
void render();
/// move viewport of lights by x , y
void moveViewport(int x, int y);
/// set viewport of lights into specific position
void setViewportPos(int x, int y);
/// set viewport of lights into specific position
void setViewportPos(sf::Vector2i pos);
/// get viewport of lights
const sf::Vector2f& getViewportPos();
/// set the darkness of scene
/// \param the darkness of scene 0 -> 255
void setDarkness(sf::Uint8 darkness);
/// get darkness
sf::Uint8 getDarkness();
/// remove light
/// \param the index of light
/// \note "index" its existence is not verified.
void removeLight(int index);
/// remove dynamic light
/// \param pointer to light
void removeLight(Light*light);
WorldLight(b2World* world, sf::RenderWindow* window);
~WorldLight();
private:
sf::Vector2f _viewPort;
sf::Vector2u initSize;
b2World* _world;
sf::RenderWindow* _window;
sf::RenderTexture _render;
std::vector<Light*>_lights;
std::vector<bool>isPointLight;
std::vector<sf::VertexArray>lightMesh,fixedMesh;
sf::Shader lightShader;
sf::Color darkness = sf::Color::Black;
};
}// sfbl namespace
#endif // SFBL_H
|
maruinen/FullereneViewer
|
src/Carbon.h
|
<gh_stars>0
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __CARBON_H__
#define __CARBON_H__
#include <stdio.h>
#include "ErrorCode.h"
#include "InteractiveRegularPolygon.h"
#include "Queue.h"
#include "List.h"
class Bond;
class Ring;
class Path;
class Representation;
class Automorphism;
class CarbonAllotrope;
class Carbon : public InteractiveRegularPolygon {
// friend classes & functions
friend class Ring;
// members
private:
double p_radius;
int p_color;
Bond* p_bond_0;
Ring* p_ring_01;
Bond* p_bond_1;
Ring* p_ring_12;
Bond* p_bond_2;
Ring* p_ring_20;
int p_distance_to_set;
// private tools
private:
int p_calc_clockwise(Carbon* from, Carbon* to);
// constructors & the destructor
public:
Carbon(CarbonAllotrope* ca);
virtual ~Carbon();
Carbon& operator = (const Carbon& you); /* dont use */
void copy_from(const CarbonAllotrope* ca, const Carbon* you);
bool connect_to(CarbonAllotrope* ca, Carbon* carbon);
bool connect_to(CarbonAllotrope* ca, Bond* bond);
void remove_bond(Bond* bond);
bool set_ring(Bond* bond_before, Ring* ring, Bond* bond_after);
void remove_ring(Ring* ring);
// comparators
public:
int compare(const Carbon* you) const;
// distance
public:
void calculate_distance_around(Queue<Carbon>& operations);
int distance_to_set() { return p_distance_to_set; }
void set_distance_to_set(int distance) { p_distance_to_set = distance; }
void reset_distance_to_set();
// determining normal vector
public:
bool check_clockwise(Carbon* from, Carbon* to);
void set_clockwise(Carbon* from, Carbon* to, bool locally);
// interactions
// representation
public:
void write_representation(Representation& representation, Bond* from);
void write_automorphism(Automorphism& automorphism, Bond* from);
// I/O
public:
void print_structure(int indent = 0, bool deep = true) const;
void print_POVRay_scene_description(const CarbonAllotrope* ca, FILE* fptr) const;
void print_POVRay_scene_description(const CarbonAllotrope* ca, FILE* fptr,
const Matrix3& rot, const Vector3& move,
bool clipped_by_Z_non_negative) const;
virtual void draw_opaque_by_OpenGL(bool selection) const;
Vector3 carbon_location() const;
Vector3 bond_location(Bond* bond) const;
// member accessing methods
public:
int number_of_rings() const;
Ring* get_ring(int index) const;
int number_of_bonds() const;
Bond* get_bond(int index) const;
bool connected_with(Bond* bond) const;
Bond* bond_between(Carbon* carbon) const;
Carbon* carbon_beyond(Bond* bond) const;
Ring* ring_between(Bond* bond_before, Bond* bond_after) const;
Bond* bond_between(Ring* ring_before, Ring* ring_after) const;
bool open_side_bond(Bond* bond, Bond*& result) const;
Bond* boundary_bond(Bond* bond = 0) const;
Bond* inner_bond() const;
void set_color(int color) { p_color = color; }
ErrorCode concave_boundary_segment(int n_members, int& length, Bond*& end_bond);
bool has_pentagon() const;
bool has_non_hexagon() const;
};
#endif /* __CARBON_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/StringPair.h
|
<reponame>maruinen/FullereneViewer<filename>src/StringPair.h<gh_stars>0
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __STRINGPAIR_H__
#define __STRINGPAIR_H__
#include "Object.h"
#include "MyString.h"
class StringPair : public Object {
// friend classes & functions
// members
private:
MyString p_my_string;
MyString p_your_string;
// private tools
// constructors & the destructor
public:
StringPair(const char* my_string, const char* your_string);
virtual ~StringPair();
StringPair& operator = (const StringPair& you); /* dont use */
// type converters
// comparators
public:
int compare(const StringPair* you) const;
// math operators
// I/O
// class decision
// member accessing methods
const char* my_string() const { return p_my_string; }
const char* your_string() const { return p_your_string; }
};
#endif /* __STRINGPAIR_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/RepresentationInfo.h
|
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __REPRESENTATIONINFO_H__
#define __REPRESENTATIONINFO_H__
#include "Object.h"
struct RepresentationInfo : public Object {
// members
public:
int clockwise;
int carbon_sequence_no;
int bond_sequence_no;
// constructors & the destructor
public:
RepresentationInfo();
virtual ~RepresentationInfo();
RepresentationInfo& operator = (const RepresentationInfo& you); /* dont use */
};
#endif /* __REPRESENTATIONINFO_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
maruinen/FullereneViewer
|
src/ReflectionPair.h
|
/*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __REFLECTIONPAIR_H__
#define __REFLECTIONPAIR_H__
#include "Object.h"
#include "MyString.h"
class Fullerene;
class ReflectionPair : public Object {
// friend classes & functions
// members
private:
bool p_symmetric;
MyString p_my_repres;
MyString p_my_generator_formula;
MyString p_your_repres;
MyString p_your_generator_formula;
// private tools
// constructors & the destructor
public:
ReflectionPair(const char* generator_formula, const Fullerene* fullerene);
virtual ~ReflectionPair();
ReflectionPair& operator = (const ReflectionPair& you); /* dont use */
// comparators
public:
int compare(const ReflectionPair* you) const;
// I/O
// member accessing methods
void merge(const ReflectionPair* with);
bool symmetric() const { return p_symmetric; }
const char* ones_generator_formula() { return p_my_generator_formula; }
const char* the_others_generator_formula() { return p_your_generator_formula; }
};
#endif /* __REFLECTIONPAIR_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.